From: bors Date: Mon, 24 Mar 2014 19:06:58 +0000 (-0700) Subject: auto merge of #13049 : alexcrichton/rust/io-fill, r=huonw X-Git-Url: https://git.lizzy.rs/?a=commitdiff_plain;h=e06348ea5516eb18f1b33d3ca19e3f0867bdf6df;hp=02dab5a3e79a48c77d28c9aa6dcfea173584933b;p=rust.git auto merge of #13049 : alexcrichton/rust/io-fill, r=huonw This method can be used to fill a byte slice of data entirely, and it's considered an error if any error happens before its entirely filled. --- diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index eef1a1ac241..3b8c86b7c41 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -337,7 +337,7 @@ fn run_debuginfo_test(config: &config, props: &TestProps, testfile: &Path) { } } - if tool_path.equals(&~"") { + if tool_path.is_empty() { fatal(~"cannot found android cross path"); } @@ -452,7 +452,7 @@ fn cleanup_debug_info_options(options: &Option<~str>) -> Option<~str> { let options_to_remove = [~"-O", ~"-g", ~"--debuginfo"]; let new_options = split_maybe_args(options).move_iter() .filter(|x| !options_to_remove.contains(x)) - .to_owned_vec() + .collect::<~[~str]>() .connect(" "); Some(new_options) } diff --git a/src/doc/guide-tasks.md b/src/doc/guide-tasks.md index 969ade289d3..9f8e5c727bd 100644 --- a/src/doc/guide-tasks.md +++ b/src/doc/guide-tasks.md @@ -493,14 +493,14 @@ Here is the function that implements the child task: ~~~ extern crate sync; # fn main() { - fn stringifier(channel: &sync::DuplexStream<~str, uint>) { - let mut value: uint; - loop { - value = channel.recv(); - channel.send(value.to_str()); - if value == 0 { break; } - } +fn stringifier(channel: &sync::DuplexStream<~str, uint>) { + let mut value: uint; + loop { + value = channel.recv(); + channel.send(value.to_str()); + if value == 0 { break; } } +} # } ~~~~ diff --git a/src/doc/rust.md b/src/doc/rust.md index deb26610ada..ef66fc7abe2 100644 --- a/src/doc/rust.md +++ b/src/doc/rust.md @@ -1019,7 +1019,7 @@ never invoking this behaviour or exposing an API making it possible for it to oc * Data races * Dereferencing a null/dangling raw pointer -* Mutating an immutable value/reference, if it is not marked as non-`Freeze` +* Mutating an immutable value/reference * Reads of [undef](http://llvm.org/docs/LangRef.html#undefined-values) (uninitialized) memory * Breaking the [pointer aliasing rules](http://llvm.org/docs/LangRef.html#pointer-aliasing-rules) with raw pointers (a subset of the rules used by C) @@ -3434,10 +3434,6 @@ call to the method `make_string`. Types in Rust are categorized into kinds, based on various properties of the components of the type. The kinds are: -`Freeze` - : Types of this kind are deeply immutable; - they contain no mutable memory locations - directly or indirectly via pointers. `Send` : Types of this kind can be safely sent between tasks. This kind includes scalars, owning pointers, owned closures, and @@ -3450,8 +3446,9 @@ The kinds are: This kind includes scalars and immutable references, as well as structural types containing other `Pod` types. `'static` - : Types of this kind do not contain any references; - this can be a useful guarantee for code + : Types of this kind do not contain any references (except for + references with the `static` lifetime, which are allowed). + This can be a useful guarantee for code that breaks borrowing assumptions using [`unsafe` operations](#unsafe-functions). `Drop` diff --git a/src/doc/tutorial.md b/src/doc/tutorial.md index 5d180cdfab5..bfa1a3a2a29 100644 --- a/src/doc/tutorial.md +++ b/src/doc/tutorial.md @@ -2099,10 +2099,6 @@ unless they contain managed boxes, managed closures, or references. These are types that are safe to be used across several threads with access to a `&T` pointer. `MutexArc` is an example of a *sharable* type with internal mutable data. -* `Freeze` - Constant (immutable) types. -These are types that do not contain anything intrinsically mutable. -Intrinsically mutable values include `Cell` in the standard library. - * `'static` - Non-borrowed types. These are types that do not contain any data whose lifetime is bound to a particular stack frame. These are types that do not contain any @@ -2152,7 +2148,7 @@ We say that the `Printable` trait _provides_ a `print` method with the given signature. This means that we can call `print` on an argument of any type that implements the `Printable` trait. -Rust's built-in `Send` and `Freeze` types are examples of traits that +Rust's built-in `Send` and `Share` types are examples of traits that don't provide any methods. Traits may be implemented for specific types with [impls]. An impl for @@ -2444,15 +2440,15 @@ Consequently, the trait objects themselves automatically fulfill their respective kind bounds. However, this default behavior can be overridden by specifying a list of bounds on the trait type, for example, by writing `~Trait:` (which indicates that the contents of the owned trait need not fulfill any -bounds), or by writing `~Trait:Send+Freeze`, which indicates that in addition -to fulfilling `Send`, contents must also fulfill `Freeze`, and as a consequence, -the trait itself fulfills `Freeze`. +bounds), or by writing `~Trait:Send+Share`, which indicates that in addition +to fulfilling `Send`, contents must also fulfill `Share`, and as a consequence, +the trait itself fulfills `Share`. * `~Trait:Send` is equivalent to `~Trait`. * `&Trait:` is equivalent to `&Trait`. Builtin kind bounds can also be specified on closure types in the same way (for -example, by writing `fn:Freeze()`), and the default behaviours are the same as +example, by writing `fn:Send()`), and the default behaviours are the same as for traits of the same storage class. ## Trait inheritance diff --git a/src/driver/driver.rs b/src/driver/driver.rs index bd7096cda03..5fd08793ce7 100644 --- a/src/driver/driver.rs +++ b/src/driver/driver.rs @@ -8,10 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#[no_uv]; // remove this after stage0 -#[allow(attribute_usage)]; // remove this after stage0 -extern crate native; // remove this after stage0 - #[cfg(rustdoc)] extern crate this = "rustdoc"; diff --git a/src/libarena/lib.rs b/src/libarena/lib.rs index 6ed72cc3713..94e340368fe 100644 --- a/src/libarena/lib.rs +++ b/src/libarena/lib.rs @@ -24,7 +24,6 @@ html_root_url = "http://static.rust-lang.org/doc/master")]; #[allow(missing_doc)]; #[feature(managed_boxes)]; -#[allow(deprecated_owned_vector)]; // NOTE: remove after stage0 extern crate collections; @@ -37,7 +36,6 @@ use std::ptr::read; use std::cmp; use std::num; -use std::kinds::marker; use std::rc::Rc; use std::rt::global_heap; use std::intrinsics::{TyDesc, get_tydesc}; @@ -54,11 +52,11 @@ struct Chunk { } impl Chunk { fn capacity(&self) -> uint { - self.data.deref().borrow().get().capacity() + self.data.borrow().capacity() } unsafe fn as_ptr(&self) -> *u8 { - self.data.deref().borrow().get().as_ptr() + self.data.borrow().as_ptr() } } @@ -90,7 +88,6 @@ pub struct Arena { priv head: Chunk, priv pod_head: Chunk, priv chunks: RefCell<@List>, - priv no_freeze: marker::NoFreeze, } impl Arena { @@ -103,7 +100,6 @@ pub fn new_with_size(initial_size: uint) -> Arena { head: chunk(initial_size, false), pod_head: chunk(initial_size, true), chunks: RefCell::new(@Nil), - no_freeze: marker::NoFreeze, } } } diff --git a/src/libcollections/btree.rs b/src/libcollections/btree.rs index 6411b6bc974..3f53ede6027 100644 --- a/src/libcollections/btree.rs +++ b/src/libcollections/btree.rs @@ -94,17 +94,12 @@ fn clone(&self) -> BTree { impl Eq for BTree { fn eq(&self, other: &BTree) -> bool { - self.equals(other) - } -} - -impl TotalEq for BTree { - ///Testing equality on BTrees by comparing the root. - fn equals(&self, other: &BTree) -> bool { self.root.cmp(&other.root) == Equal } } +impl TotalEq for BTree {} + impl Ord for BTree { fn lt(&self, other: &BTree) -> bool { self.cmp(other) == Less @@ -204,14 +199,6 @@ fn clone(&self) -> Node { impl Eq for Node { fn eq(&self, other: &Node) -> bool { - self.equals(other) - } -} - -impl TotalEq for Node { - ///Returns whether two nodes are equal based on the keys of each element. - ///Two nodes are equal if all of their keys are the same. - fn equals(&self, other: &Node) -> bool{ match *self{ BranchNode(ref branch) => { if other.is_leaf() { @@ -232,6 +219,8 @@ fn equals(&self, other: &Node) -> bool{ } } +impl TotalEq for Node {} + impl Ord for Node { fn lt(&self, other: &Node) -> bool { self.cmp(other) == Less @@ -405,16 +394,11 @@ fn clone(&self) -> Leaf { impl Eq for Leaf { fn eq(&self, other: &Leaf) -> bool { - self.equals(other) + self.elts == other.elts } } -impl TotalEq for Leaf { - ///Implementation of equals function for leaves that compares LeafElts. - fn equals(&self, other: &Leaf) -> bool { - self.elts.equals(&other.elts) - } -} +impl TotalEq for Leaf {} impl Ord for Leaf { fn lt(&self, other: &Leaf) -> bool { @@ -639,16 +623,11 @@ fn clone(&self) -> Branch { impl Eq for Branch { fn eq(&self, other: &Branch) -> bool { - self.equals(other) + self.elts == other.elts } } -impl TotalEq for Branch { - ///Equals function for Branches--compares all the elements in each branch - fn equals(&self, other: &Branch) -> bool { - self.elts.equals(&other.elts) - } -} +impl TotalEq for Branch {} impl Ord for Branch { fn lt(&self, other: &Branch) -> bool { @@ -712,16 +691,11 @@ fn clone(&self) -> LeafElt { impl Eq for LeafElt { fn eq(&self, other: &LeafElt) -> bool { - self.equals(other) + self.key == other.key && self.value == other.value } } -impl TotalEq for LeafElt { - ///TotalEq for LeafElts - fn equals(&self, other: &LeafElt) -> bool { - self.key.equals(&other.key) && self.value.equals(&other.value) - } -} +impl TotalEq for LeafElt {} impl Ord for LeafElt { fn lt(&self, other: &LeafElt) -> bool { @@ -766,16 +740,11 @@ fn clone(&self) -> BranchElt { impl Eq for BranchElt{ fn eq(&self, other: &BranchElt) -> bool { - self.equals(other) + self.key == other.key && self.value == other.value } } -impl TotalEq for BranchElt{ - ///TotalEq for BranchElts - fn equals(&self, other: &BranchElt) -> bool { - self.key.equals(&other.key)&&self.value.equals(&other.value) - } -} +impl TotalEq for BranchElt{} impl Ord for BranchElt { fn lt(&self, other: &BranchElt) -> bool { @@ -900,7 +869,7 @@ fn get_test() { fn btree_clone_test() { let b = BTree::new(1, ~"abc", 2); let b2 = b.clone(); - assert!(b.root.equals(&b2.root)) + assert!(b.root == b2.root) } //Tests the BTree's cmp() method when one node is "less than" another. diff --git a/src/libcollections/enum_set.rs b/src/libcollections/enum_set.rs index 7fda99d8d2c..07f3181d218 100644 --- a/src/libcollections/enum_set.rs +++ b/src/libcollections/enum_set.rs @@ -15,7 +15,7 @@ use std::num::Bitwise; -#[deriving(Clone, Eq, Hash, Show)] +#[deriving(Clone, Eq, TotalEq, Hash, Show)] /// A specialized Set implementation to use enum types. pub struct EnumSet { // We must maintain the invariant that no bits are set diff --git a/src/libcollections/hashmap.rs b/src/libcollections/hashmap.rs index a1f815df72e..5ec5db45f27 100644 --- a/src/libcollections/hashmap.rs +++ b/src/libcollections/hashmap.rs @@ -12,7 +12,7 @@ use std::container::{Container, Mutable, Map, MutableMap, Set, MutableSet}; use std::clone::Clone; -use std::cmp::{Eq, Equiv, max}; +use std::cmp::{Eq, TotalEq, Equiv, max}; use std::default::Default; use std::fmt; use std::fmt::Show; @@ -140,6 +140,7 @@ pub enum BucketState { } /// A hash that is not zero, since we use that to represent empty buckets. + #[deriving(Eq)] pub struct SafeHash { priv hash: u64, } @@ -149,10 +150,6 @@ impl SafeHash { pub fn inspect(&self) -> u64 { self.hash } } - impl Eq for SafeHash { - fn eq(&self, other: &SafeHash) -> bool { self.hash == other.hash } - } - /// We need to remove hashes of 0. That's reserved for empty buckets. /// This function wraps up `hash_keyed` to be the only way outside this /// module to generate a SafeHash. @@ -698,7 +695,7 @@ fn grow_at(capacity: uint, load_factor: Fraction) -> uint { fraction_mul(capacity, load_factor) } -impl, V, S, H: Hasher> HashMap { +impl, V, S, H: Hasher> HashMap { /// Get the number of elements which will force the capacity to shrink. /// When size == self.shrink_at(), we halve the capacity. fn shrink_at(&self) -> uint { @@ -799,12 +796,12 @@ fn search(&self, k: &K) -> Option { } } -impl, V, S, H: Hasher> Container for HashMap { +impl, V, S, H: Hasher> Container for HashMap { /// Return the number of elements in the map fn len(&self) -> uint { self.table.size() } } -impl, V, S, H: Hasher> Mutable for HashMap { +impl, V, S, H: Hasher> Mutable for HashMap { /// Clear the map, removing all key-value pairs. fn clear(&mut self) { self.minimum_capacity = self.table.size(); @@ -819,7 +816,7 @@ fn clear(&mut self) { } -impl, V, S, H: Hasher> Map for HashMap { +impl, V, S, H: Hasher> Map for HashMap { fn find<'a>(&'a self, k: &K) -> Option<&'a V> { self.search(k).map(|idx| { let (_, v) = self.table.read(&idx); @@ -832,7 +829,7 @@ fn contains_key(&self, k: &K) -> bool { } } -impl, V, S, H: Hasher> MutableMap for HashMap { +impl, V, S, H: Hasher> MutableMap for HashMap { fn find_mut<'a>(&'a mut self, k: &K) -> Option<&'a mut V> { match self.search(k) { None => None, @@ -969,7 +966,7 @@ fn pop(&mut self, k: &K) -> Option { } } -impl HashMap { +impl HashMap { /// Create an empty HashMap. pub fn new() -> HashMap { HashMap::with_capacity(INITIAL_CAPACITY) @@ -984,7 +981,7 @@ pub fn with_capacity(capacity: uint) -> HashMap { } } -impl, V, S, H: Hasher> HashMap { +impl, V, S, H: Hasher> HashMap { pub fn with_hasher(hasher: H) -> HashMap { HashMap::with_capacity_and_hasher(INITIAL_CAPACITY, hasher) } @@ -1296,7 +1293,7 @@ pub fn move_iter(self) -> MoveEntries { } } -impl, V: Clone, S, H: Hasher> HashMap { +impl, V: Clone, S, H: Hasher> HashMap { /// Like `find`, but returns a copy of the value. pub fn find_copy(&self, k: &K) -> Option { self.find(k).map(|v| (*v).clone()) @@ -1308,7 +1305,7 @@ pub fn get_copy(&self, k: &K) -> V { } } -impl, V: Eq, S, H: Hasher> Eq for HashMap { +impl, V: Eq, S, H: Hasher> Eq for HashMap { fn eq(&self, other: &HashMap) -> bool { if self.len() != other.len() { return false; } @@ -1321,7 +1318,7 @@ fn eq(&self, other: &HashMap) -> bool { } } -impl + Show, V: Show, S, H: Hasher> Show for HashMap { +impl + Show, V: Show, S, H: Hasher> Show for HashMap { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f.buf, r"\{")); @@ -1334,7 +1331,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl, V, S, H: Hasher + Default> Default for HashMap { +impl, V, S, H: Hasher + Default> Default for HashMap { fn default() -> HashMap { HashMap::with_capacity_and_hasher(INITIAL_CAPACITY, Default::default()) } @@ -1358,7 +1355,7 @@ fn default() -> HashMap { pub type Values<'a, K, V> = iter::Map<'static, (&'a K, &'a V), &'a V, Entries<'a, K, V>>; -impl, V, S, H: Hasher + Default> FromIterator<(K, V)> for HashMap { +impl, V, S, H: Hasher + Default> FromIterator<(K, V)> for HashMap { fn from_iterator>(iter: &mut T) -> HashMap { let (lower, _) = iter.size_hint(); let mut map = HashMap::with_capacity_and_hasher(lower, Default::default()); @@ -1367,7 +1364,7 @@ fn from_iterator>(iter: &mut T) -> HashMap { } } -impl, V, S, H: Hasher + Default> Extendable<(K, V)> for HashMap { +impl, V, S, H: Hasher + Default> Extendable<(K, V)> for HashMap { fn extend>(&mut self, iter: &mut T) { for (k, v) in *iter { self.insert(k, v); @@ -1391,7 +1388,7 @@ pub struct HashSet { priv map: HashMap } -impl, S, H: Hasher> Eq for HashSet { +impl, S, H: Hasher> Eq for HashSet { // FIXME #11998: Since the value is a (), and `find` returns a Some(&()), // we trigger #11998 when matching on it. I've fallen back to manual // iteration until this is fixed. @@ -1402,17 +1399,17 @@ fn eq(&self, other: &HashSet) -> bool { } } -impl, S, H: Hasher> Container for HashSet { +impl, S, H: Hasher> Container for HashSet { /// Return the number of elements in the set fn len(&self) -> uint { self.map.len() } } -impl, S, H: Hasher> Mutable for HashSet { +impl, S, H: Hasher> Mutable for HashSet { /// Clear the set, removing all values. fn clear(&mut self) { self.map.clear() } } -impl, S, H: Hasher> Set for HashSet { +impl, S, H: Hasher> Set for HashSet { /// Return true if the set contains a value fn contains(&self, value: &T) -> bool { self.map.search(value).is_some() } @@ -1433,7 +1430,7 @@ fn is_superset(&self, other: &HashSet) -> bool { } } -impl, S, H: Hasher> MutableSet for HashSet { +impl, S, H: Hasher> MutableSet for HashSet { /// Add a value to the set. Return true if the value was not already /// present in the set. fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()) } @@ -1443,7 +1440,7 @@ fn insert(&mut self, value: T) -> bool { self.map.insert(value, ()) } fn remove(&mut self, value: &T) -> bool { self.map.remove(value) } } -impl HashSet { +impl HashSet { /// Create an empty HashSet pub fn new() -> HashSet { HashSet::with_capacity(INITIAL_CAPACITY) @@ -1456,7 +1453,7 @@ pub fn with_capacity(capacity: uint) -> HashSet { } } -impl, S, H: Hasher> HashSet { +impl, S, H: Hasher> HashSet { pub fn with_hasher(hasher: H) -> HashSet { HashSet::with_capacity_and_hasher(INITIAL_CAPACITY, hasher) } @@ -1529,7 +1526,7 @@ pub fn union<'a>(&'a self, other: &'a HashSet) } -impl + fmt::Show, S, H: Hasher> fmt::Show for HashSet { +impl + fmt::Show, S, H: Hasher> fmt::Show for HashSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f.buf, r"\{")); @@ -1542,7 +1539,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl, S, H: Hasher + Default> FromIterator for HashSet { +impl, S, H: Hasher + Default> FromIterator for HashSet { fn from_iterator>(iter: &mut I) -> HashSet { let (lower, _) = iter.size_hint(); let mut set = HashSet::with_capacity_and_hasher(lower, Default::default()); @@ -1551,7 +1548,7 @@ fn from_iterator>(iter: &mut I) -> HashSet { } } -impl, S, H: Hasher + Default> Extendable for HashSet { +impl, S, H: Hasher + Default> Extendable for HashSet { fn extend>(&mut self, iter: &mut I) { for k in *iter { self.insert(k); @@ -1559,7 +1556,7 @@ fn extend>(&mut self, iter: &mut I) { } } -impl Default for HashSet { +impl Default for HashSet { fn default() -> HashSet { HashSet::new() } } @@ -1601,7 +1598,7 @@ fn test_insert() { local_data_key!(drop_vector: vec::Vec) - #[deriving(Hash, Eq)] + #[deriving(Hash, Eq, TotalEq)] struct Dropable { k: int } diff --git a/src/libcollections/lib.rs b/src/libcollections/lib.rs index ec57173ff19..fba85b05231 100644 --- a/src/libcollections/lib.rs +++ b/src/libcollections/lib.rs @@ -21,7 +21,6 @@ html_root_url = "http://static.rust-lang.org/doc/master")]; #[feature(macro_rules, managed_boxes, default_type_params, phase)]; -#[allow(deprecated_owned_vector)]; // NOTE: remove after stage0 extern crate rand; diff --git a/src/libcollections/lru_cache.rs b/src/libcollections/lru_cache.rs index 28ea36fa231..e328b41cc0f 100644 --- a/src/libcollections/lru_cache.rs +++ b/src/libcollections/lru_cache.rs @@ -74,6 +74,8 @@ fn eq(&self, other: &KeyRef) -> bool { } } +impl TotalEq for KeyRef {} + impl LruEntry { fn new() -> LruEntry { LruEntry { @@ -94,7 +96,7 @@ fn with_key_value(k: K, v: V) -> LruEntry { } } -impl LruCache { +impl LruCache { /// Create an LRU Cache that holds at most `capacity` items. pub fn new(capacity: uint) -> LruCache { let cache = LruCache { @@ -218,7 +220,7 @@ fn attach(&mut self, node: *mut LruEntry) { } } -impl fmt::Show for LruCache { +impl fmt::Show for LruCache { /// Return a string that lists the key-value pairs from most-recently /// used to least-recently used. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { @@ -247,14 +249,14 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -impl Container for LruCache { +impl Container for LruCache { /// Return the number of key-value pairs in the cache. fn len(&self) -> uint { self.map.len() } } -impl Mutable for LruCache { +impl Mutable for LruCache { /// Clear the cache of all key-value pairs. fn clear(&mut self) { self.map.clear(); diff --git a/src/libglob/lib.rs b/src/libglob/lib.rs index f4591c9fc19..1411fe89e6b 100644 --- a/src/libglob/lib.rs +++ b/src/libglob/lib.rs @@ -223,7 +223,7 @@ impl Pattern { */ pub fn new(pattern: &str) -> Pattern { - let chars = pattern.chars().to_owned_vec(); + let chars = pattern.chars().collect::<~[_]>(); let mut tokens = Vec::new(); let mut i = 0; diff --git a/src/libgreen/lib.rs b/src/libgreen/lib.rs index 926b9028a7a..d586d08bd0d 100644 --- a/src/libgreen/lib.rs +++ b/src/libgreen/lib.rs @@ -174,7 +174,6 @@ // NB this does *not* include globs, please keep it that way. #[feature(macro_rules, phase)]; #[allow(visible_private_types)]; -#[allow(deprecated_owned_vector)]; // NOTE: remove after stage0 #[cfg(test)] #[phase(syntax, link)] extern crate log; extern crate rand; diff --git a/src/libnative/lib.rs b/src/libnative/lib.rs index afe440cc1e0..da8f2ea139d 100644 --- a/src/libnative/lib.rs +++ b/src/libnative/lib.rs @@ -50,7 +50,6 @@ html_root_url = "http://static.rust-lang.org/doc/master")]; #[deny(unused_result, unused_must_use)]; #[allow(non_camel_case_types)]; -#[allow(deprecated_owned_vector)]; // NOTE: remove after stage0 // NB this crate explicitly does *not* allow glob imports, please seriously // consider whether they're needed before adding that feature here (the diff --git a/src/libnum/bigint.rs b/src/libnum/bigint.rs index 5716a1dedf3..89ad2b5d1bc 100644 --- a/src/libnum/bigint.rs +++ b/src/libnum/bigint.rs @@ -92,15 +92,11 @@ pub struct BigUint { impl Eq for BigUint { #[inline] - fn eq(&self, other: &BigUint) -> bool { self.equals(other) } -} - -impl TotalEq for BigUint { - #[inline] - fn equals(&self, other: &BigUint) -> bool { + fn eq(&self, other: &BigUint) -> bool { match self.cmp(other) { Equal => true, _ => false } } } +impl TotalEq for BigUint {} impl Ord for BigUint { #[inline] @@ -852,31 +848,9 @@ fn get_radix_base(radix: uint) -> (uint, uint) { } /// A Sign is a `BigInt`'s composing element. -#[deriving(Eq, Clone, Show)] +#[deriving(Eq, Ord, TotalEq, TotalOrd, Clone, Show)] pub enum Sign { Minus, Zero, Plus } -impl Ord for Sign { - #[inline] - fn lt(&self, other: &Sign) -> bool { - match self.cmp(other) { Less => true, _ => false} - } -} - -impl TotalEq for Sign { - #[inline] - fn equals(&self, other: &Sign) -> bool { *self == *other } -} -impl TotalOrd for Sign { - #[inline] - fn cmp(&self, other: &Sign) -> Ordering { - match (*self, *other) { - (Minus, Minus) | (Zero, Zero) | (Plus, Plus) => Equal, - (Minus, Zero) | (Minus, Plus) | (Zero, Plus) => Less, - _ => Greater - } - } -} - impl Neg for Sign { /// Negate Sign value. #[inline] @@ -898,16 +872,13 @@ pub struct BigInt { impl Eq for BigInt { #[inline] - fn eq(&self, other: &BigInt) -> bool { self.equals(other) } -} - -impl TotalEq for BigInt { - #[inline] - fn equals(&self, other: &BigInt) -> bool { + fn eq(&self, other: &BigInt) -> bool { match self.cmp(other) { Equal => true, _ => false } } } +impl TotalEq for BigInt {} + impl Ord for BigInt { #[inline] fn lt(&self, other: &BigInt) -> bool { diff --git a/src/libnum/rational.rs b/src/libnum/rational.rs index a71674c4122..6fb3d492432 100644 --- a/src/libnum/rational.rs +++ b/src/libnum/rational.rs @@ -147,20 +147,20 @@ macro_rules! cmp_impl { cmp_impl!(impl $imp, $($method -> bool),+) }; // return something other than a Ratio - (impl $imp:ident, $($method:ident -> $res:ty),+) => { + (impl $imp:ident, $($method:ident -> $res:ty),*) => { impl + $imp> $imp for Ratio { $( #[inline] fn $method(&self, other: &Ratio) -> $res { (self.numer * other.denom). $method (&(self.denom*other.numer)) } - )+ + )* } }; } cmp_impl!(impl Eq, eq, ne) -cmp_impl!(impl TotalEq, equals) cmp_impl!(impl Ord, lt, gt, le, ge) +cmp_impl!(impl TotalEq, ) cmp_impl!(impl TotalOrd, cmp -> cmp::Ordering) /* Arithmetic */ diff --git a/src/librand/lib.rs b/src/librand/lib.rs index 1d0070ea477..e405ace3867 100644 --- a/src/librand/lib.rs +++ b/src/librand/lib.rs @@ -71,7 +71,6 @@ html_root_url = "http://static.rust-lang.org/doc/master")]; #[feature(macro_rules, managed_boxes, phase)]; -#[allow(deprecated_owned_vector)]; // NOTE: remove after stage0 #[cfg(test)] #[phase(syntax, link)] extern crate log; @@ -826,7 +825,7 @@ fn test_sample() { let max_val = 100; let mut r = task_rng(); - let vals = range(min_val, max_val).to_owned_vec(); + let vals = range(min_val, max_val).collect::<~[int]>(); let small_sample = r.sample(vals.iter(), 5); let large_sample = r.sample(vals.iter(), vals.len() + 5); diff --git a/src/librustc/back/archive.rs b/src/librustc/back/archive.rs index aa561333756..33b79b213d2 100644 --- a/src/librustc/back/archive.rs +++ b/src/librustc/back/archive.rs @@ -206,12 +206,8 @@ fn find_library(&self, name: &str) -> Path { let mut rustpath = filesearch::rust_path(); rustpath.push(self.sess.filesearch().get_target_lib_path()); - let addl_lib_search_paths = self.sess - .opts - .addl_lib_search_paths - .borrow(); - let path = addl_lib_search_paths.get().iter(); - for path in path.chain(rustpath.iter()) { + let search = self.sess.opts.addl_lib_search_paths.borrow(); + for path in search.iter().chain(rustpath.iter()) { debug!("looking for {} inside {}", name, path.display()); let test = path.join(oslibname.as_slice()); if test.exists() { return test } diff --git a/src/librustc/back/link.rs b/src/librustc/back/link.rs index b363b06fbdc..f198a41af65 100644 --- a/src/librustc/back/link.rs +++ b/src/librustc/back/link.rs @@ -209,9 +209,8 @@ pub fn run_passes(sess: &Session, // Emit the bytecode if we're either saving our temporaries or // emitting an rlib. Whenever an rlib is created, the bytecode is // inserted into the archive in order to allow LTO against it. - let crate_types = sess.crate_types.borrow(); if sess.opts.cg.save_temps || - (crate_types.get().contains(&session::CrateTypeRlib) && + (sess.crate_types.borrow().contains(&session::CrateTypeRlib) && sess.opts.output_types.contains(&OutputTypeExe)) { output.temp_path(OutputTypeBitcode).with_c_str(|buf| { llvm::LLVMWriteBitcodeToFile(llmod, buf); @@ -550,15 +549,14 @@ fn symbol_hash(tcx: &ty::ctxt, symbol_hasher: &mut Sha256, } fn get_symbol_hash(ccx: &CrateContext, t: ty::t) -> ~str { - match ccx.type_hashcodes.borrow().get().find(&t) { + match ccx.type_hashcodes.borrow().find(&t) { Some(h) => return h.to_str(), None => {} } - let mut type_hashcodes = ccx.type_hashcodes.borrow_mut(); let mut symbol_hasher = ccx.symbol_hasher.borrow_mut(); - let hash = symbol_hash(ccx.tcx(), symbol_hasher.get(), t, &ccx.link_meta); - type_hashcodes.get().insert(t, hash.clone()); + let hash = symbol_hash(ccx.tcx(), &mut *symbol_hasher, t, &ccx.link_meta); + ccx.type_hashcodes.borrow_mut().insert(t, hash.clone()); hash } @@ -779,8 +777,7 @@ pub fn link_binary(sess: &Session, outputs: &OutputFilenames, id: &CrateId) -> Vec { let mut out_filenames = Vec::new(); - let crate_types = sess.crate_types.borrow(); - for &crate_type in crate_types.get().iter() { + for &crate_type in sess.crate_types.borrow().iter() { let out_file = link_binary_output(sess, trans, crate_type, outputs, id); out_filenames.push(out_file); } @@ -887,9 +884,7 @@ fn link_rlib<'a>(sess: &'a Session, out_filename: &Path) -> Archive<'a> { let mut a = Archive::create(sess, out_filename, obj_filename); - let used_libraries = sess.cstore.get_used_libraries(); - let used_libraries = used_libraries.borrow(); - for &(ref l, kind) in used_libraries.get().iter() { + for &(ref l, kind) in sess.cstore.get_used_libraries().borrow().iter() { match kind { cstore::NativeStatic => { a.add_native_library(l.as_slice()).unwrap(); @@ -942,8 +937,9 @@ fn link_rlib<'a>(sess: &'a Session, // For LTO purposes, the bytecode of this library is also inserted // into the archive. let bc = obj_filename.with_extension("bc"); + let bc_deflated = obj_filename.with_extension("bc.deflate"); match fs::File::open(&bc).read_to_end().and_then(|data| { - fs::File::create(&bc).write(flate::deflate_bytes(data).as_slice()) + fs::File::create(&bc_deflated).write(flate::deflate_bytes(data).as_slice()) }) { Ok(()) => {} Err(e) => { @@ -951,7 +947,8 @@ fn link_rlib<'a>(sess: &'a Session, sess.abort_if_errors() } } - a.add_file(&bc, false); + a.add_file(&bc_deflated, false); + remove(sess, &bc_deflated); if !sess.opts.cg.save_temps && !sess.opts.output_types.contains(&OutputTypeBitcode) { remove(sess, &bc); @@ -1227,9 +1224,7 @@ fn link_args(sess: &Session, // Finally add all the linker arguments provided on the command line along // with any #[link_args] attributes found inside the crate args.push_all(sess.opts.cg.link_args.as_slice()); - let used_link_args = sess.cstore.get_used_link_args(); - let used_link_args = used_link_args.borrow(); - for arg in used_link_args.get().iter() { + for arg in sess.cstore.get_used_link_args().borrow().iter() { args.push(arg.clone()); } return args; @@ -1247,8 +1242,7 @@ fn link_args(sess: &Session, // in the current crate. Upstream crates with native library dependencies // may have their native library pulled in above. fn add_local_native_libraries(args: &mut Vec<~str>, sess: &Session) { - let addl_lib_search_paths = sess.opts.addl_lib_search_paths.borrow(); - for path in addl_lib_search_paths.get().iter() { + for path in sess.opts.addl_lib_search_paths.borrow().iter() { // FIXME (#9639): This needs to handle non-utf8 paths args.push("-L" + path.as_str().unwrap().to_owned()); } @@ -1259,9 +1253,7 @@ fn add_local_native_libraries(args: &mut Vec<~str>, sess: &Session) { args.push("-L" + path.as_str().unwrap().to_owned()); } - let used_libraries = sess.cstore.get_used_libraries(); - let used_libraries = used_libraries.borrow(); - for &(ref l, kind) in used_libraries.get().iter() { + for &(ref l, kind) in sess.cstore.get_used_libraries().borrow().iter() { match kind { cstore::NativeUnknown | cstore::NativeStatic => { args.push("-l" + *l); diff --git a/src/librustc/back/lto.rs b/src/librustc/back/lto.rs index b42e8f1b92e..ef3496f113b 100644 --- a/src/librustc/back/lto.rs +++ b/src/librustc/back/lto.rs @@ -27,8 +27,7 @@ pub fn run(sess: &session::Session, llmod: ModuleRef, } // Make sure we actually can run LTO - let crate_types = sess.crate_types.borrow(); - for crate_type in crate_types.get().iter() { + for crate_type in sess.crate_types.borrow().iter() { match *crate_type { session::CrateTypeExecutable | session::CrateTypeStaticlib => {} _ => { @@ -53,9 +52,9 @@ pub fn run(sess: &session::Session, llmod: ModuleRef, let archive = ArchiveRO::open(&path).expect("wanted an rlib"); debug!("reading {}", name); - let bc = time(sess.time_passes(), format!("read {}.bc", name), (), |_| - archive.read(format!("{}.bc", name))); - let bc = bc.expect("missing bytecode in archive!"); + let bc = time(sess.time_passes(), format!("read {}.bc.deflate", name), (), |_| + archive.read(format!("{}.bc.deflate", name))); + let bc = bc.expect("missing compressed bytecode in archive!"); let bc = time(sess.time_passes(), format!("inflate {}.bc", name), (), |_| flate::inflate_bytes(bc)); let ptr = bc.as_slice().as_ptr(); diff --git a/src/librustc/driver/driver.rs b/src/librustc/driver/driver.rs index 14244d7d2e9..fb0de959489 100644 --- a/src/librustc/driver/driver.rs +++ b/src/librustc/driver/driver.rs @@ -512,8 +512,7 @@ fn write_out_deps(sess: &Session, let file = outputs.path(*output_type); match *output_type { link::OutputTypeExe => { - let crate_types = sess.crate_types.borrow(); - for output in crate_types.get().iter() { + for output in sess.crate_types.borrow().iter() { let p = link::filename_for_input(sess, *output, &id, &file); out_filenames.push(p); } @@ -542,10 +541,10 @@ fn write_out_deps(sess: &Session, // Build a list of files used to compile the output and // write Makefile-compatible dependency rules - let files: Vec<~str> = sess.codemap().files.borrow().get() + let files: Vec<~str> = sess.codemap().files.borrow() .iter().filter_map(|fmap| { - if fmap.deref().is_real_file() { - Some(fmap.deref().name.clone()) + if fmap.is_real_file() { + Some(fmap.name.clone()) } else { None } @@ -683,7 +682,7 @@ pub fn pretty_print_input(sess: Session, }; let src_name = source_name(input); - let src = sess.codemap().get_filemap(src_name).deref().src.as_bytes().to_owned(); + let src = sess.codemap().get_filemap(src_name).src.as_bytes().to_owned(); let mut rdr = MemReader::new(src); match ppm { diff --git a/src/librustc/driver/session.rs b/src/librustc/driver/session.rs index 113906f570b..772d92a4f85 100644 --- a/src/librustc/driver/session.rs +++ b/src/librustc/driver/session.rs @@ -253,11 +253,11 @@ pub fn add_lint(&self, sp: Span, msg: ~str) { let mut lints = self.lints.borrow_mut(); - match lints.get().find_mut(&id) { + match lints.find_mut(&id) { Some(arr) => { arr.push((lint, sp, msg)); return; } None => {} } - lints.get().insert(id, vec!((lint, sp, msg))); + lints.insert(id, vec!((lint, sp, msg))); } pub fn next_node_id(&self) -> ast::NodeId { self.reserve_node_ids(1) diff --git a/src/librustc/front/test.rs b/src/librustc/front/test.rs index be9e9ea0bf6..cb6b5eefade 100644 --- a/src/librustc/front/test.rs +++ b/src/librustc/front/test.rs @@ -88,10 +88,7 @@ fn fold_crate(&mut self, c: ast::Crate) -> ast::Crate { } fn fold_item(&mut self, i: @ast::Item) -> SmallVector<@ast::Item> { - { - let mut path = self.cx.path.borrow_mut(); - path.get().push(i.ident); - } + self.cx.path.borrow_mut().push(i.ident); debug!("current path: {}", ast_util::path_name_i(self.cx.path.get().as_slice())); @@ -112,10 +109,7 @@ fn fold_item(&mut self, i: @ast::Item) -> SmallVector<@ast::Item> { ignore: is_ignored(&self.cx, i), should_fail: should_fail(i) }; - { - let mut testfns = self.cx.testfns.borrow_mut(); - testfns.get().push(test); - } + self.cx.testfns.borrow_mut().push(test); // debug!("have {} test/bench functions", // cx.testfns.len()); } @@ -123,10 +117,7 @@ fn fold_item(&mut self, i: @ast::Item) -> SmallVector<@ast::Item> { } let res = fold::noop_fold_item(i, self); - { - let mut path = self.cx.path.borrow_mut(); - path.get().pop(); - } + self.cx.path.borrow_mut().pop(); res } @@ -414,12 +405,9 @@ fn is_test_crate(krate: &ast::Crate) -> bool { fn mk_test_descs(cx: &TestCtxt) -> @ast::Expr { let mut descs = Vec::new(); - { - let testfns = cx.testfns.borrow(); - debug!("building test vector from {} tests", testfns.get().len()); - for test in testfns.get().iter() { - descs.push(mk_test_desc_and_fn_rec(cx, test)); - } + debug!("building test vector from {} tests", cx.testfns.borrow().len()); + for test in cx.testfns.borrow().iter() { + descs.push(mk_test_desc_and_fn_rec(cx, test)); } let inner_expr = @ast::Expr { diff --git a/src/librustc/lib.rs b/src/librustc/lib.rs index b3e40bd71f3..6aff1530104 100644 --- a/src/librustc/lib.rs +++ b/src/librustc/lib.rs @@ -30,7 +30,6 @@ #[allow(deprecated)]; #[feature(macro_rules, globs, struct_variant, managed_boxes, quote, default_type_params, phase)]; -#[allow(deprecated_owned_vector)]; // NOTE: remove after stage0 extern crate flate; extern crate arena; diff --git a/src/librustc/lib/llvm.rs b/src/librustc/lib/llvm.rs index b98f3f6fd5d..36ebb3d5139 100644 --- a/src/librustc/lib/llvm.rs +++ b/src/librustc/lib/llvm.rs @@ -1831,13 +1831,11 @@ pub fn new() -> TypeNames { } pub fn associate_type(&self, s: &str, t: &Type) { - let mut named_types = self.named_types.borrow_mut(); - assert!(named_types.get().insert(s.to_owned(), t.to_ref())); + assert!(self.named_types.borrow_mut().insert(s.to_owned(), t.to_ref())); } pub fn find_type(&self, s: &str) -> Option { - let named_types = self.named_types.borrow(); - named_types.get().find_equiv(&s).map(|x| Type::from_ref(*x)) + self.named_types.borrow().find_equiv(&s).map(|x| Type::from_ref(*x)) } pub fn type_to_str(&self, ty: Type) -> ~str { diff --git a/src/librustc/metadata/creader.rs b/src/librustc/metadata/creader.rs index 8d48403b6e5..958c6373a8c 100644 --- a/src/librustc/metadata/creader.rs +++ b/src/librustc/metadata/creader.rs @@ -51,11 +51,10 @@ pub fn read_crates(sess: &Session, }; visit_crate(&e, krate); visit::walk_crate(&mut e, krate, ()); - let crate_cache = e.crate_cache.borrow(); - dump_crates(crate_cache.get().as_slice()); + dump_crates(e.crate_cache.borrow().as_slice()); warn_if_multiple_versions(&mut e, sess.diagnostic(), - crate_cache.get().as_slice()); + e.crate_cache.borrow().as_slice()); } impl<'a> visit::Visitor<()> for Env<'a> { @@ -198,7 +197,7 @@ fn visit_item(e: &Env, i: &ast::Item) { } else { None }) - .to_owned_vec(); + .collect::<~[&ast::Attribute]>(); for m in link_args.iter() { match m.value_str() { Some(linkarg) => e.sess.cstore.add_used_link_args(linkarg.get()), @@ -213,7 +212,7 @@ fn visit_item(e: &Env, i: &ast::Item) { } else { None }) - .to_owned_vec(); + .collect::<~[&ast::Attribute]>(); for m in link_args.iter() { match m.meta_item_list() { Some(items) => { @@ -268,8 +267,7 @@ fn visit_item(e: &Env, i: &ast::Item) { fn existing_match(e: &Env, crate_id: &CrateId, hash: Option<&Svh>) -> Option { - let crate_cache = e.crate_cache.borrow(); - for c in crate_cache.get().iter() { + for c in e.crate_cache.borrow().iter() { if !crate_id.matches(&c.crate_id) { continue } match hash { Some(hash) if *hash != c.hash => {} @@ -309,15 +307,12 @@ fn resolve_crate(e: &mut Env, // Claim this crate number and cache it let cnum = e.next_crate_num; - { - let mut crate_cache = e.crate_cache.borrow_mut(); - crate_cache.get().push(cache_entry { - cnum: cnum, - span: span, - hash: hash, - crate_id: crate_id, - }); - } + e.crate_cache.borrow_mut().push(cache_entry { + cnum: cnum, + span: span, + hash: hash, + crate_id: crate_id, + }); e.next_crate_num += 1; // Maintain a reference to the top most crate. diff --git a/src/librustc/metadata/cstore.rs b/src/librustc/metadata/cstore.rs index f1089891ea5..02c092ca508 100644 --- a/src/librustc/metadata/cstore.rs +++ b/src/librustc/metadata/cstore.rs @@ -89,8 +89,7 @@ pub fn new(intr: @IdentInterner) -> CStore { } pub fn get_crate_data(&self, cnum: ast::CrateNum) -> @crate_metadata { - let metas = self.metas.borrow(); - *metas.get().get(&cnum) + *self.metas.borrow().get(&cnum) } pub fn get_crate_hash(&self, cnum: ast::CrateNum) -> Svh { @@ -104,33 +103,30 @@ pub fn get_crate_id(&self, cnum: ast::CrateNum) -> CrateId { } pub fn set_crate_data(&self, cnum: ast::CrateNum, data: @crate_metadata) { - let mut metas = self.metas.borrow_mut(); - metas.get().insert(cnum, data); + self.metas.borrow_mut().insert(cnum, data); } pub fn have_crate_data(&self, cnum: ast::CrateNum) -> bool { - let metas = self.metas.borrow(); - metas.get().contains_key(&cnum) + self.metas.borrow().contains_key(&cnum) } pub fn iter_crate_data(&self, i: |ast::CrateNum, @crate_metadata|) { - let metas = self.metas.borrow(); - for (&k, &v) in metas.get().iter() { + for (&k, &v) in self.metas.borrow().iter() { i(k, v); } } pub fn add_used_crate_source(&self, src: CrateSource) { let mut used_crate_sources = self.used_crate_sources.borrow_mut(); - if !used_crate_sources.get().contains(&src) { - used_crate_sources.get().push(src); + if !used_crate_sources.contains(&src) { + used_crate_sources.push(src); } } pub fn get_used_crate_source(&self, cnum: ast::CrateNum) -> Option { - let mut used_crate_sources = self.used_crate_sources.borrow_mut(); - used_crate_sources.get().iter().find(|source| source.cnum == cnum) + self.used_crate_sources.borrow_mut() + .iter().find(|source| source.cnum == cnum) .map(|source| source.clone()) } @@ -158,18 +154,17 @@ fn visit(cstore: &CStore, cnum: ast::CrateNum, ordering: &mut Vec) { if ordering.as_slice().contains(&cnum) { return } let meta = cstore.get_crate_data(cnum); - for (_, &dep) in meta.cnum_map.borrow().get().iter() { + for (_, &dep) in meta.cnum_map.borrow().iter() { visit(cstore, dep, ordering); } ordering.push(cnum); }; - for (&num, _) in self.metas.borrow().get().iter() { + for (&num, _) in self.metas.borrow().iter() { visit(self, num, &mut ordering); } ordering.as_mut_slice().reverse(); let ordering = ordering.as_slice(); - let used_crate_sources = self.used_crate_sources.borrow(); - let mut libs = used_crate_sources.get() + let mut libs = self.used_crate_sources.borrow() .iter() .map(|src| (src.cnum, match prefer { RequireDynamic => src.dylib.clone(), @@ -184,8 +179,7 @@ fn visit(cstore: &CStore, cnum: ast::CrateNum, pub fn add_used_library(&self, lib: ~str, kind: NativeLibaryKind) { assert!(!lib.is_empty()); - let mut used_libraries = self.used_libraries.borrow_mut(); - used_libraries.get().push((lib, kind)); + self.used_libraries.borrow_mut().push((lib, kind)); } pub fn get_used_libraries<'a>(&'a self) @@ -194,9 +188,8 @@ pub fn get_used_libraries<'a>(&'a self) } pub fn add_used_link_args(&self, args: &str) { - let mut used_link_args = self.used_link_args.borrow_mut(); for s in args.split(' ') { - used_link_args.get().push(s.to_owned()); + self.used_link_args.borrow_mut().push(s.to_owned()); } } @@ -207,14 +200,12 @@ pub fn get_used_link_args<'a>(&'a self) -> &'a RefCell > { pub fn add_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId, cnum: ast::CrateNum) { - let mut extern_mod_crate_map = self.extern_mod_crate_map.borrow_mut(); - extern_mod_crate_map.get().insert(emod_id, cnum); + self.extern_mod_crate_map.borrow_mut().insert(emod_id, cnum); } pub fn find_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option { - let extern_mod_crate_map = self.extern_mod_crate_map.borrow(); - extern_mod_crate_map.get().find(&emod_id).map(|x| *x) + self.extern_mod_crate_map.borrow().find(&emod_id).map(|x| *x) } } diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index 61d6b1d9d75..3387c47842a 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -1187,8 +1187,7 @@ pub fn translate_def_id(cdata: Cmd, did: ast::DefId) -> ast::DefId { return ast::DefId { krate: cdata.cnum, node: did.node }; } - let cnum_map = cdata.cnum_map.borrow(); - match cnum_map.get().find(&did.krate) { + match cdata.cnum_map.borrow().find(&did.krate) { Some(&n) => { ast::DefId { krate: n, diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 9faa5610887..d97e9f2b3e1 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -270,8 +270,7 @@ fn encode_symbol(ecx: &EncodeContext, ebml_w: &mut writer::Encoder, id: NodeId) { ebml_w.start_tag(tag_items_data_item_symbol); - let item_symbols = ecx.item_symbols.borrow(); - match item_symbols.get().find(&id) { + match ecx.item_symbols.borrow().find(&id) { Some(x) => { debug!("encode_symbol(id={:?}, str={})", id, *x); ebml_w.writer.write(x.as_bytes()); @@ -334,13 +333,10 @@ fn encode_enum_variant_info(ecx: &EncodeContext, ast::DefId { krate: LOCAL_CRATE, node: id }); for variant in variants.iter() { let def_id = local_def(variant.node.id); - { - let mut index = index.borrow_mut(); - index.get().push(entry { - val: variant.node.id as i64, - pos: ebml_w.writer.tell().unwrap(), - }); - } + index.borrow_mut().push(entry { + val: variant.node.id as i64, + pos: ebml_w.writer.tell().unwrap(), + }); ebml_w.start_tag(tag_items_data_item); encode_def_id(ebml_w, def_id); match variant.node.kind { @@ -415,11 +411,9 @@ fn encode_reexported_static_base_methods(ecx: &EncodeContext, ebml_w: &mut writer::Encoder, exp: &middle::resolve::Export2) -> bool { - let inherent_impls = ecx.tcx.inherent_impls.borrow(); - match inherent_impls.get().find(&exp.def_id) { + match ecx.tcx.inherent_impls.borrow().find(&exp.def_id) { Some(implementations) => { - let implementations = implementations.borrow(); - for &base_impl in implementations.get().iter() { + for &base_impl in implementations.borrow().iter() { for &m in base_impl.methods.iter() { if m.explicit_self == ast::SelfStatic { encode_reexported_static_method(ebml_w, exp, m.def_id, m.ident); @@ -437,8 +431,7 @@ fn encode_reexported_static_trait_methods(ecx: &EncodeContext, ebml_w: &mut writer::Encoder, exp: &middle::resolve::Export2) -> bool { - let trait_methods_cache = ecx.tcx.trait_methods_cache.borrow(); - match trait_methods_cache.get().find(&exp.def_id) { + match ecx.tcx.trait_methods_cache.borrow().find(&exp.def_id) { Some(methods) => { for &m in methods.iter() { if m.explicit_self == ast::SelfStatic { @@ -538,8 +531,7 @@ fn encode_reexports(ecx: &EncodeContext, id: NodeId, path: PathElems) { debug!("(encoding info for module) encoding reexports for {}", id); - let reexports2 = ecx.reexports2.borrow(); - match reexports2.get().find(&id) { + match ecx.reexports2.borrow().find(&id) { Some(ref exports) => { debug!("(encoding info for module) found reexports for {}", id); for exp in exports.iter() { @@ -703,13 +695,10 @@ fn encode_info_for_struct(ecx: &EncodeContext, let id = field.node.id; index.push(entry {val: id as i64, pos: ebml_w.writer.tell().unwrap()}); - { - let mut global_index = global_index.borrow_mut(); - global_index.get().push(entry { - val: id as i64, - pos: ebml_w.writer.tell().unwrap(), - }); - } + global_index.borrow_mut().push(entry { + val: id as i64, + pos: ebml_w.writer.tell().unwrap(), + }); ebml_w.start_tag(tag_items_data_item); debug!("encode_info_for_struct: doing {} {}", token::get_ident(nm), id); @@ -728,13 +717,10 @@ fn encode_info_for_struct_ctor(ecx: &EncodeContext, ctor_id: NodeId, index: @RefCell> >, struct_id: NodeId) { - { - let mut index = index.borrow_mut(); - index.get().push(entry { - val: ctor_id as i64, - pos: ebml_w.writer.tell().unwrap(), - }); - } + index.borrow_mut().push(entry { + val: ctor_id as i64, + pos: ebml_w.writer.tell().unwrap(), + }); ebml_w.start_tag(tag_items_data_item); encode_def_id(ebml_w, local_def(ctor_id)); @@ -746,8 +732,7 @@ fn encode_info_for_struct_ctor(ecx: &EncodeContext, ecx.tcx.map.with_path(ctor_id, |path| encode_path(ebml_w, path)); encode_parent_item(ebml_w, local_def(struct_id)); - let item_symbols = ecx.item_symbols.borrow(); - if item_symbols.get().contains_key(&ctor_id) { + if ecx.item_symbols.borrow().contains_key(&ctor_id) { encode_symbol(ecx, ebml_w, ctor_id); } @@ -853,12 +838,10 @@ fn should_inline(attrs: &[Attribute]) -> bool { fn encode_inherent_implementations(ecx: &EncodeContext, ebml_w: &mut writer::Encoder, def_id: DefId) { - let inherent_impls = ecx.tcx.inherent_impls.borrow(); - match inherent_impls.get().find(&def_id) { + match ecx.tcx.inherent_impls.borrow().find(&def_id) { None => {} Some(&implementations) => { - let implementations = implementations.borrow(); - for implementation in implementations.get().iter() { + for implementation in implementations.borrow().iter() { ebml_w.start_tag(tag_items_data_item_inherent_impl); encode_def_id(ebml_w, implementation.did); ebml_w.end_tag(); @@ -871,12 +854,10 @@ fn encode_inherent_implementations(ecx: &EncodeContext, fn encode_extension_implementations(ecx: &EncodeContext, ebml_w: &mut writer::Encoder, trait_def_id: DefId) { - let trait_impls = ecx.tcx.trait_impls.borrow(); - match trait_impls.get().find(&trait_def_id) { + match ecx.tcx.trait_impls.borrow().find(&trait_def_id) { None => {} Some(&implementations) => { - let implementations = implementations.borrow(); - for implementation in implementations.get().iter() { + for implementation in implementations.borrow().iter() { ebml_w.start_tag(tag_items_data_item_extension_impl); encode_def_id(ebml_w, implementation.did); ebml_w.end_tag(); @@ -895,8 +876,7 @@ fn encode_info_for_item(ecx: &EncodeContext, fn add_to_index(item: &Item, ebml_w: &writer::Encoder, index: @RefCell> >) { - let mut index = index.borrow_mut(); - index.get().push(entry { + index.borrow_mut().push(entry { val: item.id as i64, pos: ebml_w.writer.tell().unwrap(), }); @@ -921,7 +901,7 @@ fn add_to_index(item: &Item, ebml_w: &writer::Encoder, encode_name(ebml_w, item.ident.name); encode_path(ebml_w, path); - let inlineable = !ecx.non_inlineable_statics.borrow().get().contains(&item.id); + let inlineable = !ecx.non_inlineable_statics.borrow().contains(&item.id); if inlineable { (ecx.encode_inlined_item)(ecx, ebml_w, IIItemRef(item)); @@ -1065,7 +1045,7 @@ fn add_to_index(item: &Item, ebml_w: &writer::Encoder, // We need to encode information about the default methods we // have inherited, so we drive this based on the impl structure. let impls = tcx.impls.borrow(); - let imp = impls.get().get(&def_id); + let imp = impls.get(&def_id); add_to_index(item, ebml_w, index); ebml_w.start_tag(tag_items_data_item); @@ -1108,13 +1088,10 @@ fn add_to_index(item: &Item, ebml_w: &writer::Encoder, Some(*ast_methods.get(i)) } else { None }; - { - let mut index = index.borrow_mut(); - index.get().push(entry { - val: m.def_id.node as i64, - pos: ebml_w.writer.tell().unwrap(), - }); - } + index.borrow_mut().push(entry { + val: m.def_id.node as i64, + pos: ebml_w.writer.tell().unwrap(), + }); encode_info_for_method(ecx, ebml_w, *m, @@ -1169,13 +1146,10 @@ fn add_to_index(item: &Item, ebml_w: &writer::Encoder, let method_ty = ty::method(tcx, method_def_id); - { - let mut index = index.borrow_mut(); - index.get().push(entry { - val: method_def_id.node as i64, - pos: ebml_w.writer.tell().unwrap(), - }); - } + index.borrow_mut().push(entry { + val: method_def_id.node as i64, + pos: ebml_w.writer.tell().unwrap(), + }); ebml_w.start_tag(tag_items_data_item); @@ -1242,13 +1216,10 @@ fn encode_info_for_foreign_item(ecx: &EncodeContext, index: @RefCell> >, path: PathElems, abi: AbiSet) { - { - let mut index = index.borrow_mut(); - index.get().push(entry { - val: nitem.id as i64, - pos: ebml_w.writer.tell().unwrap(), - }); - } + index.borrow_mut().push(entry { + val: nitem.id as i64, + pos: ebml_w.writer.tell().unwrap(), + }); ebml_w.start_tag(tag_items_data_item); encode_def_id(ebml_w, local_def(nitem.id)); @@ -1347,13 +1318,10 @@ fn encode_info_for_items(ecx: &EncodeContext, -> Vec> { let index = @RefCell::new(Vec::new()); ebml_w.start_tag(tag_items_data); - { - let mut index = index.borrow_mut(); - index.get().push(entry { - val: CRATE_NODE_ID as i64, - pos: ebml_w.writer.tell().unwrap(), - }); - } + index.borrow_mut().push(entry { + val: CRATE_NODE_ID as i64, + pos: ebml_w.writer.tell().unwrap(), + }); encode_info_for_mod(ecx, ebml_w, &krate.module, @@ -1390,8 +1358,7 @@ fn create_index( } for elt in index.iter() { let h = hash::hash(&elt.val) as uint; - let mut bucket = buckets.get_mut(h % 256).borrow_mut(); - bucket.get().push((*elt).clone()); + buckets.get_mut(h % 256).borrow_mut().push((*elt).clone()); } let mut buckets_frozen = Vec::new(); @@ -1584,9 +1551,8 @@ fn encode_lang_items(ecx: &EncodeContext, ebml_w: &mut writer::Encoder) { fn encode_native_libraries(ecx: &EncodeContext, ebml_w: &mut writer::Encoder) { ebml_w.start_tag(tag_native_libraries); - let used_libraries = ecx.tcx.sess.cstore.get_used_libraries(); - let used_libraries = used_libraries.borrow(); - for &(ref lib, kind) in used_libraries.get().iter() { + for &(ref lib, kind) in ecx.tcx.sess.cstore.get_used_libraries() + .borrow().iter() { match kind { cstore::NativeStatic => {} // these libraries are not propagated cstore::NativeFramework | cstore::NativeUnknown => { @@ -1609,8 +1575,7 @@ fn encode_native_libraries(ecx: &EncodeContext, ebml_w: &mut writer::Encoder) { } fn encode_macro_registrar_fn(ecx: &EncodeContext, ebml_w: &mut writer::Encoder) { - let ptr = ecx.tcx.sess.macro_registrar_fn.borrow(); - match *ptr.get() { + match *ecx.tcx.sess.macro_registrar_fn.borrow() { Some(did) => { ebml_w.start_tag(tag_macro_registrar_fn); encode_def_id(ebml_w, did); @@ -1665,8 +1630,7 @@ fn visit_item(&mut self, item: &Item, _: ()) { match item.node { ItemImpl(_, Some(ref trait_ref), _, _) => { let def_map = self.ecx.tcx.def_map; - let def_map = def_map.borrow(); - let trait_def = def_map.get().get_copy(&trait_ref.ref_id); + let trait_def = def_map.borrow().get_copy(&trait_ref.ref_id); let def_id = ast_util::def_id_of_def(trait_def); // Load eagerly if this is an implementation of the Drop trait diff --git a/src/librustc/metadata/filesearch.rs b/src/librustc/metadata/filesearch.rs index f9ef4ebabdc..fa794c88345 100644 --- a/src/librustc/metadata/filesearch.rs +++ b/src/librustc/metadata/filesearch.rs @@ -36,10 +36,9 @@ pub fn for_each_lib_search_path(&self, f: |&Path| -> FileMatch) { let mut visited_dirs = HashSet::new(); let mut found = false; - let addl_lib_search_paths = self.addl_lib_search_paths.borrow(); debug!("filesearch: searching additional lib search paths [{:?}]", - addl_lib_search_paths.get().len()); - for path in addl_lib_search_paths.get().iter() { + self.addl_lib_search_paths.borrow().len()); + for path in self.addl_lib_search_paths.borrow().iter() { match f(path) { FileMatches => found = true, FileDoesntMatch => () diff --git a/src/librustc/metadata/tydecode.rs b/src/librustc/metadata/tydecode.rs index c8ab6818697..9ee2779079c 100644 --- a/src/librustc/metadata/tydecode.rs +++ b/src/librustc/metadata/tydecode.rs @@ -382,23 +382,17 @@ fn parse_ty(st: &mut PState, conv: conv_did) -> ty::t { pos: pos, len: len }; - let tt_opt = { - let rcache = st.tcx.rcache.borrow(); - rcache.get().find_copy(&key) - }; - match tt_opt { + match st.tcx.rcache.borrow().find_copy(&key) { Some(tt) => return tt, - None => { - let mut ps = PState { - pos: pos, - .. *st - }; - let tt = parse_ty(&mut ps, |x,y| conv(x,y)); - let mut rcache = st.tcx.rcache.borrow_mut(); - rcache.get().insert(key, tt); - return tt; - } + None => {} } + let mut ps = PState { + pos: pos, + .. *st + }; + let tt = parse_ty(&mut ps, |x,y| conv(x,y)); + st.tcx.rcache.borrow_mut().insert(key, tt); + return tt; } '"' => { let _ = parse_def(st, TypeWithId, |x,y| conv(x,y)); @@ -590,9 +584,6 @@ fn parse_bounds(st: &mut PState, conv: conv_did) -> ty::ParamBounds { 'S' => { param_bounds.builtin_bounds.add(ty::BoundSend); } - 'K' => { - param_bounds.builtin_bounds.add(ty::BoundFreeze); - } 'O' => { param_bounds.builtin_bounds.add(ty::BoundStatic); } diff --git a/src/librustc/metadata/tyencode.rs b/src/librustc/metadata/tyencode.rs index 35014d4085a..5b3c2962ac0 100644 --- a/src/librustc/metadata/tyencode.rs +++ b/src/librustc/metadata/tyencode.rs @@ -63,37 +63,27 @@ fn mywrite(w: &mut MemWriter, fmt: &fmt::Arguments) { pub fn enc_ty(w: &mut MemWriter, cx: &ctxt, t: ty::t) { match cx.abbrevs { ac_no_abbrevs => { - let result_str_opt; - { - let short_names_cache = cx.tcx.short_names_cache.borrow(); - result_str_opt = short_names_cache.get() - .find(&t) - .map(|result| { - (*result).clone() - }); - } + let result_str_opt = cx.tcx.short_names_cache.borrow() + .find(&t) + .map(|result| { + (*result).clone() + }); let result_str = match result_str_opt { Some(s) => s, None => { let wr = &mut MemWriter::new(); enc_sty(wr, cx, &ty::get(t).sty); let s = str::from_utf8(wr.get_ref()).unwrap(); - let mut short_names_cache = cx.tcx - .short_names_cache - .borrow_mut(); - short_names_cache.get().insert(t, s.to_str()); + cx.tcx.short_names_cache.borrow_mut().insert(t, s.to_str()); s.to_str() } }; w.write(result_str.as_bytes()); } ac_use_abbrevs(abbrevs) => { - { - let mut abbrevs = abbrevs.borrow_mut(); - match abbrevs.get().find(&t) { - Some(a) => { w.write(a.s.as_bytes()); return; } - None => {} - } + match abbrevs.borrow_mut().find(&t) { + Some(a) => { w.write(a.s.as_bytes()); return; } + None => {} } let pos = w.tell().unwrap(); enc_sty(w, cx, &ty::get(t).sty); @@ -112,10 +102,7 @@ fn estimate_sz(u: u64) -> u64 { let a = ty_abbrev { pos: pos as uint, len: len as uint, s: s }; - { - let mut abbrevs = abbrevs.borrow_mut(); - abbrevs.get().insert(t, a); - } + abbrevs.borrow_mut().insert(t, a); } return; } @@ -405,7 +392,6 @@ fn enc_bounds(w: &mut MemWriter, cx: &ctxt, bs: &ty::ParamBounds) { for bound in bs.builtin_bounds.iter() { match bound { ty::BoundSend => mywrite!(w, "S"), - ty::BoundFreeze => mywrite!(w, "K"), ty::BoundStatic => mywrite!(w, "O"), ty::BoundSized => mywrite!(w, "Z"), ty::BoundPod => mywrite!(w, "P"), diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index 9abb35d5738..94947b95cd3 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -581,41 +581,48 @@ fn tr(&self, xcx: &ExtendedDecodeContext) -> moves::CaptureVar { // Encoding and decoding of MethodCallee trait read_method_callee_helper { - fn read_method_callee(&mut self, xcx: &ExtendedDecodeContext) -> MethodCallee; + fn read_method_callee(&mut self, xcx: &ExtendedDecodeContext) -> (u32, MethodCallee); } fn encode_method_callee(ecx: &e::EncodeContext, ebml_w: &mut writer::Encoder, + autoderef: u32, method: &MethodCallee) { - ebml_w.emit_struct("MethodCallee", 3, |ebml_w| { - ebml_w.emit_struct_field("origin", 0u, |ebml_w| { + ebml_w.emit_struct("MethodCallee", 4, |ebml_w| { + ebml_w.emit_struct_field("autoderef", 0u, |ebml_w| { + autoderef.encode(ebml_w); + }); + ebml_w.emit_struct_field("origin", 1u, |ebml_w| { method.origin.encode(ebml_w); }); - ebml_w.emit_struct_field("ty", 1u, |ebml_w| { + ebml_w.emit_struct_field("ty", 2u, |ebml_w| { ebml_w.emit_ty(ecx, method.ty); }); - ebml_w.emit_struct_field("substs", 2u, |ebml_w| { + ebml_w.emit_struct_field("substs", 3u, |ebml_w| { ebml_w.emit_substs(ecx, &method.substs); }); }) } impl<'a> read_method_callee_helper for reader::Decoder<'a> { - fn read_method_callee(&mut self, xcx: &ExtendedDecodeContext) -> MethodCallee { - self.read_struct("MethodCallee", 3, |this| { - MethodCallee { - origin: this.read_struct_field("origin", 0, |this| { + fn read_method_callee(&mut self, xcx: &ExtendedDecodeContext) -> (u32, MethodCallee) { + self.read_struct("MethodCallee", 4, |this| { + let autoderef = this.read_struct_field("autoderef", 0, |this| { + Decodable::decode(this) + }); + (autoderef, MethodCallee { + origin: this.read_struct_field("origin", 1, |this| { let method_origin: MethodOrigin = Decodable::decode(this); method_origin.tr(xcx) }), - ty: this.read_struct_field("ty", 1, |this| { + ty: this.read_struct_field("ty", 2, |this| { this.read_ty(xcx) }), - substs: this.read_struct_field("substs", 2, |this| { + substs: this.read_struct_field("substs", 3, |this| { this.read_substs(xcx) }) - } + }) }) } } @@ -647,6 +654,20 @@ fn tr(&self, xcx: &ExtendedDecodeContext) -> MethodOrigin { // ______________________________________________________________________ // Encoding and decoding vtable_res +fn encode_vtable_res_with_key(ecx: &e::EncodeContext, + ebml_w: &mut writer::Encoder, + autoderef: u32, + dr: typeck::vtable_res) { + ebml_w.emit_struct("VtableWithKey", 2, |ebml_w| { + ebml_w.emit_struct_field("autoderef", 0u, |ebml_w| { + autoderef.encode(ebml_w); + }); + ebml_w.emit_struct_field("vtable_res", 1u, |ebml_w| { + encode_vtable_res(ecx, ebml_w, dr); + }); + }) +} + pub fn encode_vtable_res(ecx: &e::EncodeContext, ebml_w: &mut writer::Encoder, dr: typeck::vtable_res) { @@ -701,6 +722,10 @@ pub fn encode_vtable_origin(ecx: &e::EncodeContext, } pub trait vtable_decoder_helpers { + fn read_vtable_res_with_key(&mut self, + tcx: &ty::ctxt, + cdata: @cstore::crate_metadata) + -> (u32, typeck::vtable_res); fn read_vtable_res(&mut self, tcx: &ty::ctxt, cdata: @cstore::crate_metadata) -> typeck::vtable_res; @@ -713,6 +738,20 @@ fn read_vtable_origin(&mut self, } impl<'a> vtable_decoder_helpers for reader::Decoder<'a> { + fn read_vtable_res_with_key(&mut self, + tcx: &ty::ctxt, + cdata: @cstore::crate_metadata) + -> (u32, typeck::vtable_res) { + self.read_struct("VtableWithKey", 2, |this| { + let autoderef = this.read_struct_field("autoderef", 0, |this| { + Decodable::decode(this) + }); + (autoderef, this.read_struct_field("vtable_res", 1, |this| { + this.read_vtable_res(tcx, cdata) + })) + }) + } + fn read_vtable_res(&mut self, tcx: &ty::ctxt, cdata: @cstore::crate_metadata) -> typeck::vtable_res { @@ -958,129 +997,121 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext, debug!("Encoding side tables for id {}", id); - { - let def_map = tcx.def_map.borrow(); - let r = def_map.get().find(&id); - for def in r.iter() { - ebml_w.tag(c::tag_table_def, |ebml_w| { - ebml_w.id(id); - ebml_w.tag(c::tag_table_val, |ebml_w| (*def).encode(ebml_w)); - }) - } + for def in tcx.def_map.borrow().find(&id).iter() { + ebml_w.tag(c::tag_table_def, |ebml_w| { + ebml_w.id(id); + ebml_w.tag(c::tag_table_val, |ebml_w| (*def).encode(ebml_w)); + }) } - { - let node_types = tcx.node_types.borrow(); - let r = node_types.get().find(&(id as uint)); - for &ty in r.iter() { - ebml_w.tag(c::tag_table_node_type, |ebml_w| { - ebml_w.id(id); - ebml_w.tag(c::tag_table_val, |ebml_w| { - ebml_w.emit_ty(ecx, *ty); - }) + for &ty in tcx.node_types.borrow().find(&(id as uint)).iter() { + ebml_w.tag(c::tag_table_node_type, |ebml_w| { + ebml_w.id(id); + ebml_w.tag(c::tag_table_val, |ebml_w| { + ebml_w.emit_ty(ecx, *ty); }) - } + }) } - { - let node_type_substs = tcx.node_type_substs.borrow(); - let r = node_type_substs.get().find(&id); - for tys in r.iter() { - ebml_w.tag(c::tag_table_node_type_subst, |ebml_w| { - ebml_w.id(id); - ebml_w.tag(c::tag_table_val, |ebml_w| { - ebml_w.emit_tys(ecx, tys.as_slice()) - }) + for tys in tcx.node_type_substs.borrow().find(&id).iter() { + ebml_w.tag(c::tag_table_node_type_subst, |ebml_w| { + ebml_w.id(id); + ebml_w.tag(c::tag_table_val, |ebml_w| { + ebml_w.emit_tys(ecx, tys.as_slice()) }) - } + }) } - { - let freevars = tcx.freevars.borrow(); - let r = freevars.get().find(&id); - for &fv in r.iter() { - ebml_w.tag(c::tag_table_freevars, |ebml_w| { - ebml_w.id(id); - ebml_w.tag(c::tag_table_val, |ebml_w| { - ebml_w.emit_from_vec(fv.as_slice(), |ebml_w, fv_entry| { - encode_freevar_entry(ebml_w, *fv_entry) - }) + for &fv in tcx.freevars.borrow().find(&id).iter() { + ebml_w.tag(c::tag_table_freevars, |ebml_w| { + ebml_w.id(id); + ebml_w.tag(c::tag_table_val, |ebml_w| { + ebml_w.emit_from_vec(fv.as_slice(), |ebml_w, fv_entry| { + encode_freevar_entry(ebml_w, *fv_entry) }) }) - } + }) } let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id }; - { - let tcache = tcx.tcache.borrow(); - let r = tcache.get().find(&lid); - for &tpbt in r.iter() { - ebml_w.tag(c::tag_table_tcache, |ebml_w| { - ebml_w.id(id); - ebml_w.tag(c::tag_table_val, |ebml_w| { - ebml_w.emit_tpbt(ecx, tpbt.clone()); - }) + for &tpbt in tcx.tcache.borrow().find(&lid).iter() { + ebml_w.tag(c::tag_table_tcache, |ebml_w| { + ebml_w.id(id); + ebml_w.tag(c::tag_table_val, |ebml_w| { + ebml_w.emit_tpbt(ecx, tpbt.clone()); }) - } + }) } - { - let r = { - let ty_param_defs = tcx.ty_param_defs.borrow(); - ty_param_defs.get().find(&id).map(|def| *def) - }; - for type_param_def in r.iter() { - ebml_w.tag(c::tag_table_param_defs, |ebml_w| { - ebml_w.id(id); - ebml_w.tag(c::tag_table_val, |ebml_w| { - ebml_w.emit_type_param_def(ecx, type_param_def) - }) + for &type_param_def in tcx.ty_param_defs.borrow().find(&id).iter() { + ebml_w.tag(c::tag_table_param_defs, |ebml_w| { + ebml_w.id(id); + ebml_w.tag(c::tag_table_val, |ebml_w| { + ebml_w.emit_type_param_def(ecx, type_param_def) }) - } + }) } let method_call = MethodCall::expr(id); - for &method in maps.method_map.borrow().get().find(&method_call).iter() { + for &method in maps.method_map.borrow().find(&method_call).iter() { ebml_w.tag(c::tag_table_method_map, |ebml_w| { ebml_w.id(id); ebml_w.tag(c::tag_table_val, |ebml_w| { - encode_method_callee(ecx, ebml_w, method) + encode_method_callee(ecx, ebml_w, method_call.autoderef, method) }) }) } - { - let vtable_map = maps.vtable_map.borrow(); - let r = vtable_map.get().find(&id); - for &dr in r.iter() { - ebml_w.tag(c::tag_table_vtable_map, |ebml_w| { - ebml_w.id(id); - ebml_w.tag(c::tag_table_val, |ebml_w| { - encode_vtable_res(ecx, ebml_w, *dr); - }) + for &dr in maps.vtable_map.borrow().find(&method_call).iter() { + ebml_w.tag(c::tag_table_vtable_map, |ebml_w| { + ebml_w.id(id); + ebml_w.tag(c::tag_table_val, |ebml_w| { + encode_vtable_res_with_key(ecx, ebml_w, method_call.autoderef, *dr); }) - } + }) } - { - let adjustments = tcx.adjustments.borrow(); - let r = adjustments.get().find(&id); - for adj in r.iter() { - ebml_w.tag(c::tag_table_adjustments, |ebml_w| { - ebml_w.id(id); - ebml_w.tag(c::tag_table_val, |ebml_w| { - ebml_w.emit_auto_adjustment(ecx, **adj); - }) - }) + for adj in tcx.adjustments.borrow().find(&id).iter() { + match ***adj { + ty::AutoDerefRef(adj) => { + for autoderef in range(0, adj.autoderefs) { + let method_call = MethodCall::autoderef(id, autoderef as u32); + for &method in maps.method_map.borrow().find(&method_call).iter() { + ebml_w.tag(c::tag_table_method_map, |ebml_w| { + ebml_w.id(id); + ebml_w.tag(c::tag_table_val, |ebml_w| { + encode_method_callee(ecx, ebml_w, method_call.autoderef, method) + }) + }) + } + + for &dr in maps.vtable_map.borrow().find(&method_call).iter() { + ebml_w.tag(c::tag_table_vtable_map, |ebml_w| { + ebml_w.id(id); + ebml_w.tag(c::tag_table_val, |ebml_w| { + encode_vtable_res_with_key(ecx, ebml_w, + method_call.autoderef, *dr); + }) + }) + } + } + } + _ => {} } + + ebml_w.tag(c::tag_table_adjustments, |ebml_w| { + ebml_w.id(id); + ebml_w.tag(c::tag_table_val, |ebml_w| { + ebml_w.emit_auto_adjustment(ecx, **adj); + }) + }) } - for &cap_vars in maps.capture_map.borrow().get().find(&id).iter() { + for &cap_vars in maps.capture_map.borrow().find(&id).iter() { ebml_w.tag(c::tag_table_capture_map, |ebml_w| { ebml_w.id(id); ebml_w.tag(c::tag_table_val, |ebml_w| { - ebml_w.emit_from_vec(cap_vars.deref().as_slice(), - |ebml_w, cap_var| { + ebml_w.emit_from_vec(cap_vars.as_slice(), |ebml_w, cap_var| { cap_var.encode(ebml_w); }) }) @@ -1343,71 +1374,61 @@ fn decode_side_tables(xcx: &ExtendedDecodeContext, match value { c::tag_table_def => { let def = decode_def(xcx, val_doc); - let mut def_map = dcx.tcx.def_map.borrow_mut(); - def_map.get().insert(id, def); + dcx.tcx.def_map.borrow_mut().insert(id, def); } c::tag_table_node_type => { let ty = val_dsr.read_ty(xcx); debug!("inserting ty for node {:?}: {}", id, ty_to_str(dcx.tcx, ty)); - let mut node_types = dcx.tcx.node_types.borrow_mut(); - node_types.get().insert(id as uint, ty); + dcx.tcx.node_types.borrow_mut().insert(id as uint, ty); } c::tag_table_node_type_subst => { let tys = val_dsr.read_tys(xcx); - let mut node_type_substs = dcx.tcx - .node_type_substs - .borrow_mut(); - node_type_substs.get().insert(id, tys); + dcx.tcx.node_type_substs.borrow_mut().insert(id, tys); } c::tag_table_freevars => { let fv_info = @val_dsr.read_to_vec(|val_dsr| { @val_dsr.read_freevar_entry(xcx) }).move_iter().collect(); - let mut freevars = dcx.tcx.freevars.borrow_mut(); - freevars.get().insert(id, fv_info); + dcx.tcx.freevars.borrow_mut().insert(id, fv_info); } c::tag_table_tcache => { let tpbt = val_dsr.read_ty_param_bounds_and_ty(xcx); let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id }; - let mut tcache = dcx.tcx.tcache.borrow_mut(); - tcache.get().insert(lid, tpbt); + dcx.tcx.tcache.borrow_mut().insert(lid, tpbt); } c::tag_table_param_defs => { let bounds = val_dsr.read_type_param_def(xcx); - let mut ty_param_defs = dcx.tcx - .ty_param_defs - .borrow_mut(); - ty_param_defs.get().insert(id, bounds); + dcx.tcx.ty_param_defs.borrow_mut().insert(id, bounds); } c::tag_table_method_map => { - let method = val_dsr.read_method_callee(xcx); - let method_call = MethodCall::expr(id); - dcx.maps.method_map.borrow_mut().get().insert(method_call, method); + let (autoderef, method) = val_dsr.read_method_callee(xcx); + let method_call = MethodCall { + expr_id: id, + autoderef: autoderef + }; + dcx.maps.method_map.borrow_mut().insert(method_call, method); } c::tag_table_vtable_map => { - let vtable_res = - val_dsr.read_vtable_res(xcx.dcx.tcx, - xcx.dcx.cdata); - let mut vtable_map = dcx.maps.vtable_map.borrow_mut(); - vtable_map.get().insert(id, vtable_res); + let (autoderef, vtable_res) = + val_dsr.read_vtable_res_with_key(xcx.dcx.tcx, + xcx.dcx.cdata); + let vtable_key = MethodCall { + expr_id: id, + autoderef: autoderef + }; + dcx.maps.vtable_map.borrow_mut().insert(vtable_key, vtable_res); } c::tag_table_adjustments => { let adj: @ty::AutoAdjustment = @val_dsr.read_auto_adjustment(xcx); - let mut adjustments = dcx.tcx - .adjustments - .borrow_mut(); - adjustments.get().insert(id, adj); + dcx.tcx.adjustments.borrow_mut().insert(id, adj); } c::tag_table_capture_map => { let cvars = val_dsr.read_to_vec(|val_dsr| val_dsr.read_capture_var(xcx)) .move_iter() .collect(); - let mut capture_map = dcx.maps - .capture_map - .borrow_mut(); - capture_map.get().insert(id, Rc::new(cvars)); + dcx.maps.capture_map.borrow_mut().insert(id, Rc::new(cvars)); } _ => { xcx.dcx.tcx.sess.bug( diff --git a/src/librustc/middle/borrowck/check_loans.rs b/src/librustc/middle/borrowck/check_loans.rs index 6b8af3cbc53..eaef50307ef 100644 --- a/src/librustc/middle/borrowck/check_loans.rs +++ b/src/librustc/middle/borrowck/check_loans.rs @@ -378,11 +378,7 @@ pub fn check_if_path_is_moved(&self, pub fn check_assignment(&self, expr: &ast::Expr) { // We don't use cat_expr() here because we don't want to treat // auto-ref'd parameters in overloaded operators as rvalues. - let adj = { - let adjustments = self.bccx.tcx.adjustments.borrow(); - adjustments.get().find_copy(&expr.id) - }; - let cmt = match adj { + let cmt = match self.bccx.tcx.adjustments.borrow().find_copy(&expr.id) { None => self.bccx.cat_expr_unadjusted(expr), Some(adj) => self.bccx.cat_expr_autoderefd(expr, adj) }; @@ -452,10 +448,7 @@ fn mark_variable_as_used_mut(this: &CheckLoanCtxt, cmt.repr(this.tcx())); match cmt.cat { mc::cat_local(id) | mc::cat_arg(id) => { - let mut used_mut_nodes = this.tcx() - .used_mut_nodes - .borrow_mut(); - used_mut_nodes.get().insert(id); + this.tcx().used_mut_nodes.borrow_mut().insert(id); return; } @@ -717,7 +710,7 @@ fn check_move_out_from_id(&self, id: ast::NodeId, span: Span) { fn check_captured_variables(&self, closure_id: ast::NodeId, span: Span) { - for cap_var in self.bccx.capture_map.get(&closure_id).deref().iter() { + for cap_var in self.bccx.capture_map.get(&closure_id).iter() { let var_id = ast_util::def_id_of_def(cap_var.def).node; let var_path = @LpVar(var_id); self.check_if_path_is_moved(closure_id, span, @@ -839,11 +832,11 @@ fn check_loans_in_expr<'a>(this: &mut CheckLoanCtxt<'a>, this.check_call(expr, None, expr.span, args.as_slice()); } ast::ExprIndex(_, rval) | ast::ExprBinary(_, _, rval) - if method_map.get().contains_key(&MethodCall::expr(expr.id)) => { + if method_map.contains_key(&MethodCall::expr(expr.id)) => { this.check_call(expr, None, expr.span, [rval]); } ast::ExprUnary(_, _) | ast::ExprIndex(_, _) - if method_map.get().contains_key(&MethodCall::expr(expr.id)) => { + if method_map.contains_key(&MethodCall::expr(expr.id)) => { this.check_call(expr, None, expr.span, []); } ast::ExprInlineAsm(ref ia) => { diff --git a/src/librustc/middle/borrowck/gather_loans/gather_moves.rs b/src/librustc/middle/borrowck/gather_loans/gather_moves.rs index 3d5ea0e89b2..d07d6a066b0 100644 --- a/src/librustc/middle/borrowck/gather_loans/gather_moves.rs +++ b/src/librustc/middle/borrowck/gather_loans/gather_moves.rs @@ -47,7 +47,7 @@ pub fn gather_move_from_pat(bccx: &BorrowckCtxt, pub fn gather_captures(bccx: &BorrowckCtxt, move_data: &MoveData, closure_expr: &ast::Expr) { - for captured_var in bccx.capture_map.get(&closure_expr.id).deref().iter() { + for captured_var in bccx.capture_map.get(&closure_expr.id).iter() { match captured_var.mode { moves::CapMove => { let cmt = bccx.cat_captured_var(closure_expr.id, diff --git a/src/librustc/middle/borrowck/gather_loans/lifetime.rs b/src/librustc/middle/borrowck/gather_loans/lifetime.rs index 7f810aabf0f..a04afd6d5f3 100644 --- a/src/librustc/middle/borrowck/gather_loans/lifetime.rs +++ b/src/librustc/middle/borrowck/gather_loans/lifetime.rs @@ -237,8 +237,7 @@ fn check_root(&self, let rm_key = root_map_key {id: cmt_deref.id, derefs: derefs}; let root_info = RootInfo {scope: root_scope}; - let mut root_map = self.bccx.root_map.borrow_mut(); - root_map.get().insert(rm_key, root_info); + self.bccx.root_map.borrow_mut().insert(rm_key, root_info); debug!("root_key: {:?} root_info: {:?}", rm_key, root_info); Ok(()) diff --git a/src/librustc/middle/borrowck/gather_loans/mod.rs b/src/librustc/middle/borrowck/gather_loans/mod.rs index 8ecac0a60be..be86d387b20 100644 --- a/src/librustc/middle/borrowck/gather_loans/mod.rs +++ b/src/librustc/middle/borrowck/gather_loans/mod.rs @@ -195,7 +195,7 @@ fn gather_loans_in_expr(this: &mut GatherLoanCtxt, this.id_range.add(ex.id); // If this expression is borrowed, have to ensure it remains valid: - for &adjustments in tcx.adjustments.borrow().get().find(&ex.id).iter() { + for &adjustments in tcx.adjustments.borrow().find(&ex.id).iter() { this.guarantee_adjustments(ex, *adjustments); } @@ -255,7 +255,7 @@ fn gather_loans_in_expr(this: &mut GatherLoanCtxt, ast::ExprIndex(_, arg) | ast::ExprBinary(_, _, arg) - if method_map.get().contains_key(&MethodCall::expr(ex.id)) => { + if method_map.contains_key(&MethodCall::expr(ex.id)) => { // Arguments in method calls are always passed by ref. // // Currently these do not use adjustments, so we have to @@ -343,7 +343,7 @@ pub fn guarantee_autoderefs(&mut self, autoderefs: uint) { let method_map = self.bccx.method_map.borrow(); for i in range(0, autoderefs) { - match method_map.get().find(&MethodCall::autoderef(expr.id, i as u32)) { + match method_map.find(&MethodCall::autoderef(expr.id, i as u32)) { Some(method) => { // Treat overloaded autoderefs as if an AutoRef adjustment // was applied on the base type, as that is always the case. @@ -452,7 +452,7 @@ pub fn guarantee_adjustments(&mut self, fn guarantee_captures(&mut self, closure_expr: &ast::Expr) { - for captured_var in self.bccx.capture_map.get(&closure_expr.id).deref().iter() { + for captured_var in self.bccx.capture_map.get(&closure_expr.id).iter() { match captured_var.mode { moves::CapCopy | moves::CapMove => { continue; } moves::CapRef => { } @@ -466,8 +466,8 @@ fn guarantee_captures(&mut self, // Lookup the kind of borrow the callee requires let upvar_id = ty::UpvarId { var_id: var_id, closure_expr_id: closure_expr.id }; - let upvar_borrow_map = self.tcx().upvar_borrow_map.borrow(); - let upvar_borrow = upvar_borrow_map.get().get_copy(&upvar_id); + let upvar_borrow = self.tcx().upvar_borrow_map.borrow() + .get_copy(&upvar_id); self.guarantee_valid_kind(closure_expr.id, closure_expr.span, @@ -750,10 +750,7 @@ pub fn mark_loan_path_as_mutated(&self, loan_path: @LoanPath) { match *loan_path { LpVar(local_id) => { - let mut used_mut_nodes = self.tcx() - .used_mut_nodes - .borrow_mut(); - used_mut_nodes.get().insert(local_id); + self.tcx().used_mut_nodes.borrow_mut().insert(local_id); } LpExtend(base, mc::McInherited, _) => { self.mark_loan_path_as_mutated(base); diff --git a/src/librustc/middle/borrowck/mod.rs b/src/librustc/middle/borrowck/mod.rs index 362553ccbf1..d7d936a7048 100644 --- a/src/librustc/middle/borrowck/mod.rs +++ b/src/librustc/middle/borrowck/mod.rs @@ -205,7 +205,7 @@ pub struct BorrowStats { // // Note that there is no entry with derefs:3---the type of that expression // is T, which is not a box. -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] pub struct root_map_key { id: ast::NodeId, derefs: uint @@ -243,13 +243,13 @@ pub enum LoanCause { RefBinding, } -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] pub enum LoanPath { LpVar(ast::NodeId), // `x` in doc.rs LpExtend(@LoanPath, mc::MutabilityCategory, LoanPathElem) } -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] pub enum LoanPathElem { LpDeref(mc::PointerKind), // `*LV` in doc.rs LpInterior(mc::InteriorKind) // `LV.f` in doc.rs @@ -574,7 +574,7 @@ pub fn report_use_of_moved_value(&self, let (expr_ty, expr_span) = match self.tcx.map.find(move.id) { Some(ast_map::NodeExpr(expr)) => { (ty::expr_ty_adjusted(self.tcx, expr, - self.method_map.borrow().get()), expr.span) + &*self.method_map.borrow()), expr.span) } r => self.tcx.sess.bug(format!("MoveExpr({:?}) maps to {:?}, not Expr", move.id, r)) @@ -601,7 +601,7 @@ pub fn report_use_of_moved_value(&self, let (expr_ty, expr_span) = match self.tcx.map.find(move.id) { Some(ast_map::NodeExpr(expr)) => { (ty::expr_ty_adjusted(self.tcx, expr, - self.method_map.borrow().get()), expr.span) + &*self.method_map.borrow()), expr.span) } r => self.tcx.sess.bug(format!("Captured({:?}) maps to {:?}, not Expr", move.id, r)) @@ -942,16 +942,15 @@ fn node_ty(&mut self, id: ast::NodeId) -> mc::McResult { } fn node_method_ty(&self, method_call: typeck::MethodCall) -> Option { - self.method_map.borrow().get().find(&method_call).map(|method| method.ty) + self.method_map.borrow().find(&method_call).map(|method| method.ty) } fn adjustment(&mut self, id: ast::NodeId) -> Option<@ty::AutoAdjustment> { - let adjustments = self.tcx.adjustments.borrow(); - adjustments.get().find_copy(&id) + self.tcx.adjustments.borrow().find_copy(&id) } fn is_method_call(&mut self, id: ast::NodeId) -> bool { - self.method_map.borrow().get().contains_key(&typeck::MethodCall::expr(id)) + self.method_map.borrow().contains_key(&typeck::MethodCall::expr(id)) } fn temporary_scope(&mut self, id: ast::NodeId) -> Option { @@ -959,7 +958,6 @@ fn temporary_scope(&mut self, id: ast::NodeId) -> Option { } fn upvar_borrow(&mut self, id: ty::UpvarId) -> ty::UpvarBorrow { - let upvar_borrow_map = self.tcx.upvar_borrow_map.borrow(); - upvar_borrow_map.get().get_copy(&id) + self.tcx.upvar_borrow_map.borrow().get_copy(&id) } } diff --git a/src/librustc/middle/borrowck/move_data.rs b/src/librustc/middle/borrowck/move_data.rs index 93a1ba309c2..22bacca5485 100644 --- a/src/librustc/middle/borrowck/move_data.rs +++ b/src/librustc/middle/borrowck/move_data.rs @@ -183,48 +183,40 @@ pub fn new() -> MoveData { } fn path_loan_path(&self, index: MovePathIndex) -> @LoanPath { - let paths = self.paths.borrow(); - paths.get().get(index.get()).loan_path + self.paths.borrow().get(index.get()).loan_path } fn path_parent(&self, index: MovePathIndex) -> MovePathIndex { - let paths = self.paths.borrow(); - paths.get().get(index.get()).parent + self.paths.borrow().get(index.get()).parent } fn path_first_move(&self, index: MovePathIndex) -> MoveIndex { - let paths = self.paths.borrow(); - paths.get().get(index.get()).first_move + self.paths.borrow().get(index.get()).first_move } fn path_first_child(&self, index: MovePathIndex) -> MovePathIndex { - let paths = self.paths.borrow(); - paths.get().get(index.get()).first_child + self.paths.borrow().get(index.get()).first_child } fn path_next_sibling(&self, index: MovePathIndex) -> MovePathIndex { - let paths = self.paths.borrow(); - paths.get().get(index.get()).next_sibling + self.paths.borrow().get(index.get()).next_sibling } fn set_path_first_move(&self, index: MovePathIndex, first_move: MoveIndex) { - let mut paths = self.paths.borrow_mut(); - paths.get().get_mut(index.get()).first_move = first_move + self.paths.borrow_mut().get_mut(index.get()).first_move = first_move } fn set_path_first_child(&self, index: MovePathIndex, first_child: MovePathIndex) { - let mut paths = self.paths.borrow_mut(); - paths.get().get_mut(index.get()).first_child = first_child + self.paths.borrow_mut().get_mut(index.get()).first_child = first_child } fn move_next_move(&self, index: MoveIndex) -> MoveIndex { //! Type safe indexing operator - let moves = self.moves.borrow(); - moves.get().get(index.get()).next_move + self.moves.borrow().get(index.get()).next_move } fn is_var_path(&self, index: MovePathIndex) -> bool { @@ -241,22 +233,18 @@ pub fn move_path(&self, * base paths that do not yet have an index. */ - { - let path_map = self.path_map.borrow(); - match path_map.get().find(&lp) { - Some(&index) => { - return index; - } - None => {} + match self.path_map.borrow().find(&lp) { + Some(&index) => { + return index; } + None => {} } let index = match *lp { LpVar(..) => { - let mut paths = self.paths.borrow_mut(); - let index = MovePathIndex(paths.get().len()); + let index = MovePathIndex(self.paths.borrow().len()); - paths.get().push(MovePath { + self.paths.borrow_mut().push(MovePath { loan_path: lp, parent: InvalidMovePathIndex, first_move: InvalidMoveIndex, @@ -270,24 +258,18 @@ pub fn move_path(&self, LpExtend(base, _, _) => { let parent_index = self.move_path(tcx, base); - let index = { - let paths = self.paths.borrow(); - MovePathIndex(paths.get().len()) - }; + let index = MovePathIndex(self.paths.borrow().len()); let next_sibling = self.path_first_child(parent_index); self.set_path_first_child(parent_index, index); - { - let mut paths = self.paths.borrow_mut(); - paths.get().push(MovePath { - loan_path: lp, - parent: parent_index, - first_move: InvalidMoveIndex, - first_child: InvalidMovePathIndex, - next_sibling: next_sibling, - }); - } + self.paths.borrow_mut().push(MovePath { + loan_path: lp, + parent: parent_index, + first_move: InvalidMoveIndex, + first_child: InvalidMovePathIndex, + next_sibling: next_sibling, + }); index } @@ -297,19 +279,15 @@ pub fn move_path(&self, lp.repr(tcx), index); - let paths = self.paths.borrow(); - assert_eq!(index.get(), paths.get().len() - 1); - - let mut path_map = self.path_map.borrow_mut(); - path_map.get().insert(lp, index); + assert_eq!(index.get(), self.paths.borrow().len() - 1); + self.path_map.borrow_mut().insert(lp, index); return index; } fn existing_move_path(&self, lp: @LoanPath) -> Option { - let path_map = self.path_map.borrow(); - path_map.get().find_copy(&lp) + self.path_map.borrow().find_copy(&lp) } fn existing_base_paths(&self, @@ -328,11 +306,7 @@ fn add_existing_base_paths(&self, * paths of `lp` to `result`, but does not add new move paths */ - let index_opt = { - let path_map = self.path_map.borrow(); - path_map.get().find_copy(&lp) - }; - match index_opt { + match self.path_map.borrow().find_copy(&lp) { Some(index) => { self.each_base_path(index, |p| { result.push(p); @@ -367,23 +341,17 @@ pub fn add_move(&self, kind); let path_index = self.move_path(tcx, lp); - let move_index = { - let moves = self.moves.borrow(); - MoveIndex(moves.get().len()) - }; + let move_index = MoveIndex(self.moves.borrow().len()); let next_move = self.path_first_move(path_index); self.set_path_first_move(path_index, move_index); - { - let mut moves = self.moves.borrow_mut(); - moves.get().push(Move { - path: path_index, - id: id, - kind: kind, - next_move: next_move - }); - } + self.moves.borrow_mut().push(Move { + path: path_index, + id: id, + kind: kind, + next_move: next_move + }); } pub fn add_assignment(&self, @@ -404,8 +372,7 @@ pub fn add_assignment(&self, let path_index = self.move_path(tcx, lp); if !is_also_move { - let mut assignee_ids = self.assignee_ids.borrow_mut(); - assignee_ids.get().insert(assignee_id); + self.assignee_ids.borrow_mut().insert(assignee_id); } let assignment = Assignment { @@ -415,19 +382,15 @@ pub fn add_assignment(&self, }; if self.is_var_path(path_index) { - let mut var_assignments = self.var_assignments.borrow_mut(); debug!("add_assignment[var](lp={}, assignment={}, path_index={:?})", - lp.repr(tcx), var_assignments.get().len(), path_index); + lp.repr(tcx), self.var_assignments.borrow().len(), path_index); - var_assignments.get().push(assignment); + self.var_assignments.borrow_mut().push(assignment); } else { debug!("add_assignment[path](lp={}, path_index={:?})", lp.repr(tcx), path_index); - { - let mut path_assignments = self.path_assignments.borrow_mut(); - path_assignments.get().push(assignment); - } + self.path_assignments.borrow_mut().push(assignment); } } @@ -443,60 +406,42 @@ fn add_gen_kills(&self, * killed by scoping. See `doc.rs` for more details. */ - { - let moves = self.moves.borrow(); - for (i, move) in moves.get().iter().enumerate() { - dfcx_moves.add_gen(move.id, i); - } + for (i, move) in self.moves.borrow().iter().enumerate() { + dfcx_moves.add_gen(move.id, i); } - { - let var_assignments = self.var_assignments.borrow(); - for (i, assignment) in var_assignments.get().iter().enumerate() { - dfcx_assign.add_gen(assignment.id, i); - self.kill_moves(assignment.path, assignment.id, dfcx_moves); - } + for (i, assignment) in self.var_assignments.borrow().iter().enumerate() { + dfcx_assign.add_gen(assignment.id, i); + self.kill_moves(assignment.path, assignment.id, dfcx_moves); } - { - let path_assignments = self.path_assignments.borrow(); - for assignment in path_assignments.get().iter() { - self.kill_moves(assignment.path, assignment.id, dfcx_moves); - } + for assignment in self.path_assignments.borrow().iter() { + self.kill_moves(assignment.path, assignment.id, dfcx_moves); } // Kill all moves related to a variable `x` when it goes out // of scope: - { - let paths = self.paths.borrow(); - for path in paths.get().iter() { - match *path.loan_path { - LpVar(id) => { - let kill_id = tcx.region_maps.var_scope(id); - let path = { - let path_map = self.path_map.borrow(); - *path_map.get().get(&path.loan_path) - }; - self.kill_moves(path, kill_id, dfcx_moves); - } - LpExtend(..) => {} + for path in self.paths.borrow().iter() { + match *path.loan_path { + LpVar(id) => { + let kill_id = tcx.region_maps.var_scope(id); + let path = *self.path_map.borrow().get(&path.loan_path); + self.kill_moves(path, kill_id, dfcx_moves); } + LpExtend(..) => {} } } // Kill all assignments when the variable goes out of scope: - { - let var_assignments = self.var_assignments.borrow(); - for (assignment_index, assignment) in - var_assignments.get().iter().enumerate() { - match *self.path_loan_path(assignment.path) { - LpVar(id) => { - let kill_id = tcx.region_maps.var_scope(id); - dfcx_assign.add_kill(kill_id, assignment_index); - } - LpExtend(..) => { - tcx.sess.bug("var assignment for non var path"); - } + for (assignment_index, assignment) in + self.var_assignments.borrow().iter().enumerate() { + match *self.path_loan_path(assignment.path) { + LpVar(id) => { + let kill_id = tcx.region_maps.var_scope(id); + dfcx_assign.add_kill(kill_id, assignment_index); + } + LpExtend(..) => { + tcx.sess.bug("var assignment for non var path"); } } } @@ -570,22 +515,18 @@ pub fn new(move_data: MoveData, id_range: ast_util::IdRange, body: &ast::Block) -> FlowedMoveData<'a> { - let mut dfcx_moves = { - let moves = move_data.moves.borrow(); + let mut dfcx_moves = DataFlowContext::new(tcx, method_map, MoveDataFlowOperator, id_range, - moves.get().len()) - }; - let mut dfcx_assign = { - let var_assignments = move_data.var_assignments.borrow(); + move_data.moves.borrow().len()); + let mut dfcx_assign = DataFlowContext::new(tcx, method_map, AssignDataFlowOperator, id_range, - var_assignments.get().len()) - }; + move_data.var_assignments.borrow().len()); move_data.add_gen_kills(tcx, &mut dfcx_moves, &mut dfcx_assign); dfcx_moves.propagate(body); dfcx_assign.propagate(body); @@ -605,8 +546,8 @@ pub fn each_path_moved_by(&self, */ self.dfcx_moves.each_gen_bit_frozen(id, |index| { - let moves = self.move_data.moves.borrow(); - let move = moves.get().get(index); + let move = self.move_data.moves.borrow(); + let move = move.get(index); let moved_path = move.path; f(move, self.move_data.path_loan_path(moved_path)) }) @@ -644,8 +585,8 @@ pub fn each_move_of(&self, let mut ret = true; self.dfcx_moves.each_bit_on_entry_frozen(id, |index| { - let moves = self.move_data.moves.borrow(); - let move = moves.get().get(index); + let move = self.move_data.moves.borrow(); + let move = move.get(index); let moved_path = move.path; if base_indices.iter().any(|x| x == &moved_path) { // Scenario 1 or 2: `loan_path` or some base path of @@ -675,9 +616,7 @@ pub fn is_assignee(&self, id: ast::NodeId) -> bool { //! True if `id` is the id of the LHS of an assignment - - let assignee_ids = self.move_data.assignee_ids.borrow(); - assignee_ids.get().iter().any(|x| x == &id) + self.move_data.assignee_ids.borrow().iter().any(|x| x == &id) } pub fn each_assignment_of(&self, @@ -702,8 +641,8 @@ pub fn each_assignment_of(&self, }; self.dfcx_assign.each_bit_on_entry_frozen(id, |index| { - let var_assignments = self.move_data.var_assignments.borrow(); - let assignment = var_assignments.get().get(index); + let assignment = self.move_data.var_assignments.borrow(); + let assignment = assignment.get(index); if assignment.path == loan_path_index && !f(assignment) { false } else { diff --git a/src/librustc/middle/cfg/construct.rs b/src/librustc/middle/cfg/construct.rs index b84e923f77d..a66e9191b33 100644 --- a/src/librustc/middle/cfg/construct.rs +++ b/src/librustc/middle/cfg/construct.rs @@ -497,8 +497,7 @@ fn find_scope(&self, } Some(_) => { - let def_map = self.tcx.def_map.borrow(); - match def_map.get().find(&expr.id) { + match self.tcx.def_map.borrow().find(&expr.id) { Some(&ast::DefLabel(loop_id)) => { for l in self.loop_scopes.iter() { if l.loop_id == loop_id { @@ -522,6 +521,6 @@ fn find_scope(&self, fn is_method_call(&self, expr: &ast::Expr) -> bool { let method_call = typeck::MethodCall::expr(expr.id); - self.method_map.borrow().get().contains_key(&method_call) + self.method_map.borrow().contains_key(&method_call) } } diff --git a/src/librustc/middle/check_const.rs b/src/librustc/middle/check_const.rs index 6bec35665fb..6d95202d2c1 100644 --- a/src/librustc/middle/check_const.rs +++ b/src/librustc/middle/check_const.rs @@ -103,7 +103,7 @@ fn check_expr(v: &mut CheckCrateVisitor, e: &Expr, is_const: bool) { ExprLit(lit) if ast_util::lit_is_str(lit) => {} ExprBinary(..) | ExprUnary(..) => { let method_call = typeck::MethodCall::expr(e.id); - if v.method_map.borrow().get().contains_key(&method_call) { + if v.method_map.borrow().contains_key(&method_call) { v.tcx.sess.span_err(e.span, "user-defined operators are not \ allowed in constant expressions"); } @@ -127,7 +127,7 @@ fn check_expr(v: &mut CheckCrateVisitor, e: &Expr, is_const: bool) { "paths in constants may only refer to \ items without type parameters"); } - match v.def_map.borrow().get().find(&e.id) { + match v.def_map.borrow().find(&e.id) { Some(&DefStatic(..)) | Some(&DefFn(_, _)) | Some(&DefVariant(_, _, _)) | @@ -145,7 +145,7 @@ fn check_expr(v: &mut CheckCrateVisitor, e: &Expr, is_const: bool) { } } ExprCall(callee, _) => { - match v.def_map.borrow().get().find(&callee.id) { + match v.def_map.borrow().find(&callee.id) { Some(&DefStruct(..)) => {} // OK. Some(&DefVariant(..)) => {} // OK. _ => { @@ -221,8 +221,7 @@ fn visit_item(&mut self, it: &Item, _: ()) { fn visit_expr(&mut self, e: &Expr, _: ()) { match e.node { ExprPath(..) => { - let def_map = self.def_map.borrow(); - match def_map.get().find(&e.id) { + match self.def_map.borrow().find(&e.id) { Some(&DefStatic(def_id, _)) if ast_util::is_local(def_id) => { self.visit_item(self.ast_map.expect_item(def_id.node), ()); diff --git a/src/librustc/middle/check_match.rs b/src/librustc/middle/check_match.rs index 9e74e9605da..12c22edcd2e 100644 --- a/src/librustc/middle/check_match.rs +++ b/src/librustc/middle/check_match.rs @@ -121,10 +121,7 @@ fn check_arms(cx: &MatchCheckCtxt, arms: &[Arm]) { // Check that we do not match against a static NaN (#6804) let pat_matches_nan: |&Pat| -> bool = |p| { - let opt_def = { - let def_map = cx.tcx.def_map.borrow(); - def_map.get().find_copy(&p.id) - }; + let opt_def = cx.tcx.def_map.borrow().find_copy(&p.id); match opt_def { Some(DefStatic(did, false)) => { let const_expr = lookup_const_by_id(cx.tcx, did).unwrap(); @@ -351,10 +348,7 @@ fn pat_ctor_id(cx: &MatchCheckCtxt, p: @Pat) -> Option { match pat.node { PatWild | PatWildMulti => { None } PatIdent(_, _, _) | PatEnum(_, _) => { - let opt_def = { - let def_map = cx.tcx.def_map.borrow(); - def_map.get().find_copy(&pat.id) - }; + let opt_def = cx.tcx.def_map.borrow().find_copy(&pat.id); match opt_def { Some(DefVariant(_, id, _)) => Some(variant(id)), Some(DefStatic(did, false)) => { @@ -369,8 +363,7 @@ fn pat_ctor_id(cx: &MatchCheckCtxt, p: @Pat) -> Option { Some(range(eval_const_expr(cx.tcx, lo), eval_const_expr(cx.tcx, hi))) } PatStruct(..) => { - let def_map = cx.tcx.def_map.borrow(); - match def_map.get().find(&pat.id) { + match cx.tcx.def_map.borrow().find(&pat.id) { Some(&DefVariant(_, id, _)) => Some(variant(id)), _ => Some(single) } @@ -392,8 +385,7 @@ fn is_wild(cx: &MatchCheckCtxt, p: @Pat) -> bool { match pat.node { PatWild | PatWildMulti => { true } PatIdent(_, _, _) => { - let def_map = cx.tcx.def_map.borrow(); - match def_map.get().find(&pat.id) { + match cx.tcx.def_map.borrow().find(&pat.id) { Some(&DefVariant(_, _, _)) | Some(&DefStatic(..)) => { false } _ => { true } } @@ -575,10 +567,7 @@ fn specialize(cx: &MatchCheckCtxt, r.tail())) } PatIdent(_, _, _) => { - let opt_def = { - let def_map = cx.tcx.def_map.borrow(); - def_map.get().find_copy(&pat_id) - }; + let opt_def = cx.tcx.def_map.borrow().find_copy(&pat_id); match opt_def { Some(DefVariant(_, id, _)) => { if variant(id) == *ctor_id { @@ -636,11 +625,8 @@ fn specialize(cx: &MatchCheckCtxt, } } PatEnum(_, args) => { - let opt_def = { - let def_map = cx.tcx.def_map.borrow(); - def_map.get().get_copy(&pat_id) - }; - match opt_def { + let def = cx.tcx.def_map.borrow().get_copy(&pat_id); + match def { DefStatic(did, _) => { let const_expr = lookup_const_by_id(cx.tcx, did).unwrap(); @@ -701,11 +687,8 @@ fn specialize(cx: &MatchCheckCtxt, } PatStruct(_, ref pattern_fields, _) => { // Is this a struct or an enum variant? - let opt_def = { - let def_map = cx.tcx.def_map.borrow(); - def_map.get().get_copy(&pat_id) - }; - match opt_def { + let def = cx.tcx.def_map.borrow().get_copy(&pat_id); + match def { DefVariant(_, variant_id, _) => { if variant(variant_id) == *ctor_id { let struct_fields = ty::lookup_struct_fields(cx.tcx, variant_id); @@ -891,10 +874,7 @@ fn check_fn(cx: &mut MatchCheckCtxt, } fn is_refutable(cx: &MatchCheckCtxt, pat: &Pat) -> bool { - let opt_def = { - let def_map = cx.tcx.def_map.borrow(); - def_map.get().find_copy(&pat.id) - }; + let opt_def = cx.tcx.def_map.borrow().find_copy(&pat.id); match opt_def { Some(DefVariant(enum_id, _, _)) => { if ty::enum_variants(cx.tcx, enum_id).len() != 1u { diff --git a/src/librustc/middle/const_eval.rs b/src/librustc/middle/const_eval.rs index 5f0db7b3821..8d7cff98f42 100644 --- a/src/librustc/middle/const_eval.rs +++ b/src/librustc/middle/const_eval.rs @@ -83,10 +83,7 @@ pub fn join_all>(mut cs: It) -> constness { } pub fn lookup_const(tcx: &ty::ctxt, e: &Expr) -> Option<@Expr> { - let opt_def = { - let def_map = tcx.def_map.borrow(); - def_map.get().find_copy(&e.id) - }; + let opt_def = tcx.def_map.borrow().find_copy(&e.id); match opt_def { Some(ast::DefStatic(def_id, false)) => { lookup_const_by_id(tcx, def_id) @@ -125,14 +122,14 @@ fn variant_expr(variants: &[ast::P], id: ast::NodeId) -> Option<@E } } } else { - match tcx.extern_const_variants.borrow().get().find(&variant_def) { + match tcx.extern_const_variants.borrow().find(&variant_def) { Some(&e) => return e, None => {} } let maps = astencode::Maps { root_map: @RefCell::new(HashMap::new()), method_map: @RefCell::new(FnvHashMap::new()), - vtable_map: @RefCell::new(NodeMap::new()), + vtable_map: @RefCell::new(FnvHashMap::new()), capture_map: RefCell::new(NodeMap::new()) }; let e = match csearch::maybe_get_item_ast(tcx, enum_def, @@ -145,7 +142,7 @@ fn variant_expr(variants: &[ast::P], id: ast::NodeId) -> Option<@E }, _ => None }; - tcx.extern_const_variants.borrow_mut().get().insert(variant_def, e); + tcx.extern_const_variants.borrow_mut().insert(variant_def, e); return e; } } @@ -166,17 +163,14 @@ pub fn lookup_const_by_id(tcx: &ty::ctxt, def_id: ast::DefId) } } } else { - { - let extern_const_statics = tcx.extern_const_statics.borrow(); - match extern_const_statics.get().find(&def_id) { - Some(&e) => return e, - None => {} - } + match tcx.extern_const_statics.borrow().find(&def_id) { + Some(&e) => return e, + None => {} } let maps = astencode::Maps { root_map: @RefCell::new(HashMap::new()), method_map: @RefCell::new(FnvHashMap::new()), - vtable_map: @RefCell::new(NodeMap::new()), + vtable_map: @RefCell::new(FnvHashMap::new()), capture_map: RefCell::new(NodeMap::new()) }; let e = match csearch::maybe_get_item_ast(tcx, def_id, @@ -187,12 +181,8 @@ pub fn lookup_const_by_id(tcx: &ty::ctxt, def_id: ast::DefId) }, _ => None }; - { - let mut extern_const_statics = tcx.extern_const_statics - .borrow_mut(); - extern_const_statics.get().insert(def_id, e); - return e; - } + tcx.extern_const_statics.borrow_mut().insert(def_id, e); + return e; } } @@ -500,7 +490,7 @@ pub fn lit_to_const(lit: &Lit) -> const_val { match lit.node { LitStr(ref s, _) => const_str((*s).clone()), LitBinary(ref data) => { - const_binary(Rc::new(data.deref().iter().map(|x| *x).collect())) + const_binary(Rc::new(data.iter().map(|x| *x).collect())) } LitChar(n) => const_uint(n as u64), LitInt(n, _) => const_int(n), diff --git a/src/librustc/middle/dataflow.rs b/src/librustc/middle/dataflow.rs index 114bf3bae2c..178688917e8 100644 --- a/src/librustc/middle/dataflow.rs +++ b/src/librustc/middle/dataflow.rs @@ -782,8 +782,7 @@ fn find_scope<'a,'b>( } Some(_) => { - let def_map = self.tcx().def_map.borrow(); - match def_map.get().find(&expr.id) { + match self.tcx().def_map.borrow().find(&expr.id) { Some(&ast::DefLabel(loop_id)) => { match loop_scopes.iter().position(|l| l.loop_id == loop_id) { Some(i) => i, @@ -809,7 +808,7 @@ fn find_scope<'a,'b>( fn is_method_call(&self, expr: &ast::Expr) -> bool { let method_call = typeck::MethodCall::expr(expr.id); - self.dfcx.method_map.borrow().get().contains_key(&method_call) + self.dfcx.method_map.borrow().contains_key(&method_call) } fn reset(&mut self, bits: &mut [uint]) { diff --git a/src/librustc/middle/dead.rs b/src/librustc/middle/dead.rs index 7004ce3f0d4..1d23218583f 100644 --- a/src/librustc/middle/dead.rs +++ b/src/librustc/middle/dead.rs @@ -75,8 +75,7 @@ fn check_def_id(&mut self, def_id: ast::DefId) { } fn lookup_and_handle_definition(&mut self, id: &ast::NodeId) { - let def_map = self.tcx.def_map.borrow(); - let def = match def_map.get().find(id) { + let def = match self.tcx.def_map.borrow().find(id) { Some(&def) => def, None => return }; @@ -94,7 +93,7 @@ fn lookup_and_handle_definition(&mut self, id: &ast::NodeId) { fn lookup_and_handle_method(&mut self, id: ast::NodeId, span: codemap::Span) { let method_call = typeck::MethodCall::expr(id); - match self.method_map.borrow().get().find(&method_call) { + match self.method_map.borrow().find(&method_call) { Some(method) => { match method.origin { typeck::MethodStatic(def_id) => { @@ -342,12 +341,10 @@ fn symbol_is_live(&mut self, id: ast::NodeId, // method of a private type is used, but the type itself is never // called directly. let def_id = local_def(id); - let inherent_impls = self.tcx.inherent_impls.borrow(); - match inherent_impls.get().find(&def_id) { + match self.tcx.inherent_impls.borrow().find(&def_id) { None => (), Some(ref impl_list) => { - let impl_list = impl_list.borrow(); - for impl_ in impl_list.get().iter() { + for impl_ in impl_list.borrow().iter() { for method in impl_.methods.iter() { if self.live_symbols.contains(&method.def_id.node) { return true; diff --git a/src/librustc/middle/effect.rs b/src/librustc/middle/effect.rs index 592c4f7e29e..5cec239783e 100644 --- a/src/librustc/middle/effect.rs +++ b/src/librustc/middle/effect.rs @@ -56,8 +56,7 @@ fn require_unsafe(&mut self, span: Span, description: &str) { UnsafeBlock(block_id) => { // OK, but record this. debug!("effect: recording unsafe block as used: {:?}", block_id); - let mut used_unsafe = self.tcx.used_unsafe.borrow_mut(); - let _ = used_unsafe.get().insert(block_id); + self.tcx.used_unsafe.borrow_mut().insert(block_id); } UnsafeFn => {} } @@ -139,7 +138,7 @@ fn visit_expr(&mut self, expr: &ast::Expr, _:()) { match expr.node { ast::ExprMethodCall(_, _, _) => { let method_call = MethodCall::expr(expr.id); - let base_type = self.method_map.borrow().get().get(&method_call).ty; + let base_type = self.method_map.borrow().get(&method_call).ty; debug!("effect: method call case, base type is {}", ppaux::ty_to_str(self.tcx, base_type)); if type_is_unsafe_function(base_type) { diff --git a/src/librustc/middle/freevars.rs b/src/librustc/middle/freevars.rs index d836f8e332b..84a3bb525af 100644 --- a/src/librustc/middle/freevars.rs +++ b/src/librustc/middle/freevars.rs @@ -51,8 +51,7 @@ fn visit_expr(&mut self, expr: &ast::Expr, depth: int) { } ast::ExprPath(..) => { let mut i = 0; - let def_map = self.def_map.borrow(); - match def_map.get().find(&expr.id) { + match self.def_map.borrow().find(&expr.id) { None => fail!("path not found"), Some(&df) => { let mut def = df; @@ -141,8 +140,7 @@ pub fn annotate_freevars(def_map: resolve::DefMap, krate: &ast::Crate) -> } pub fn get_freevars(tcx: &ty::ctxt, fid: ast::NodeId) -> freevar_info { - let freevars = tcx.freevars.borrow(); - match freevars.get().find(&fid) { + match tcx.freevars.borrow().find(&fid) { None => fail!("get_freevars: {} has no freevars", fid), Some(&d) => return d } diff --git a/src/librustc/middle/kind.rs b/src/librustc/middle/kind.rs index 9d8f35eb980..fd53c2e544d 100644 --- a/src/librustc/middle/kind.rs +++ b/src/librustc/middle/kind.rs @@ -30,20 +30,14 @@ // kind is noncopyable. The noncopyable kind can be extended with any number // of the following attributes. // -// send: Things that can be sent on channels or included in spawned closures. -// freeze: Things thare are deeply immutable. They are guaranteed never to -// change, and can be safely shared without copying between tasks. +// Send: Things that can be sent on channels or included in spawned closures. It +// includes scalar types as well as classes and unique types containing only +// sendable types. // 'static: Things that do not contain references. // -// Send includes scalar types as well as classes and unique types containing -// only sendable types. -// -// Freeze include scalar types, things without non-const fields, and pointers -// to freezable things. -// // This pass ensures that type parameters are only instantiated with types // whose kinds are equal or less general than the way the type parameter was -// annotated (with the `Send` or `Freeze` bound). +// annotated (with the `Send` bound). // // It also verifies that noncopyable kinds are not copied. Sendability is not // applied, since none of our language primitives send. Instead, the sending @@ -117,18 +111,13 @@ fn check_struct_safe_for_destructor(cx: &mut Context, } fn check_impl_of_trait(cx: &mut Context, it: &Item, trait_ref: &TraitRef, self_type: &Ty) { - let def_map = cx.tcx.def_map.borrow(); - let ast_trait_def = def_map.get() - .find(&trait_ref.ref_id) - .expect("trait ref not in def map!"); - let trait_def_id = ast_util::def_id_of_def(*ast_trait_def); - let trait_def; - { - let trait_defs = cx.tcx.trait_defs.borrow(); - trait_def = *trait_defs.get() - .find(&trait_def_id) - .expect("trait def not in trait-defs map!"); - } + let ast_trait_def = *cx.tcx.def_map.borrow() + .find(&trait_ref.ref_id) + .expect("trait ref not in def map!"); + let trait_def_id = ast_util::def_id_of_def(ast_trait_def); + let trait_def = *cx.tcx.trait_defs.borrow() + .find(&trait_def_id) + .expect("trait def not in trait-defs map!"); // If this trait has builtin-kind supertraits, meet them. let self_ty: ty::t = ty::node_id_to_type(cx.tcx, it.id); @@ -147,7 +136,7 @@ fn check_impl_of_trait(cx: &mut Context, it: &Item, trait_ref: &TraitRef, self_t match self_type.node { TyPath(_, ref bounds, path_node_id) => { assert!(bounds.is_none()); - let struct_def = def_map.get().get_copy(&path_node_id); + let struct_def = cx.tcx.def_map.borrow().get_copy(&path_node_id); let struct_did = ast_util::def_id_of_def(struct_def); check_struct_safe_for_destructor(cx, self_type.span, struct_did); } @@ -266,18 +255,17 @@ pub fn check_expr(cx: &mut Context, e: &Expr) { // Handle any kind bounds on type parameters { let method_map = cx.method_map.borrow(); - let method = method_map.get().find(&typeck::MethodCall::expr(e.id)); + let method = method_map.find(&typeck::MethodCall::expr(e.id)); let node_type_substs = cx.tcx.node_type_substs.borrow(); let r = match method { Some(method) => Some(&method.substs.tps), - None => node_type_substs.get().find(&e.id) + None => node_type_substs.find(&e.id) }; for ts in r.iter() { let def_map = cx.tcx.def_map.borrow(); let type_param_defs = match e.node { ExprPath(_) => { - let did = ast_util::def_id_of_def(def_map.get() - .get_copy(&e.id)); + let did = ast_util::def_id_of_def(def_map.get_copy(&e.id)); ty::lookup_item_type(cx.tcx, did).generics.type_param_defs.clone() } _ => { @@ -297,7 +285,6 @@ pub fn check_expr(cx: &mut Context, e: &Expr) { } } }; - let type_param_defs = type_param_defs.deref(); if ts.len() != type_param_defs.len() { // Fail earlier to make debugging easier fail!("internal error: in kind::check_expr, length \ @@ -334,14 +321,13 @@ pub fn check_expr(cx: &mut Context, e: &Expr) { } // Search for auto-adjustments to find trait coercions. - let adjustments = cx.tcx.adjustments.borrow(); - match adjustments.get().find(&e.id) { + match cx.tcx.adjustments.borrow().find(&e.id) { Some(adjustment) => { match **adjustment { ty::AutoObject(..) => { let source_ty = ty::expr_ty(cx.tcx, e); let target_ty = ty::expr_ty_adjusted(cx.tcx, e, - cx.method_map.borrow().get()); + &*cx.method_map.borrow()); check_trait_cast(cx, source_ty, target_ty, e.span); } ty::AutoAddEnv(..) | @@ -368,10 +354,10 @@ fn check_ty(cx: &mut Context, aty: &Ty) { match aty.node { TyPath(_, _, id) => { let node_type_substs = cx.tcx.node_type_substs.borrow(); - let r = node_type_substs.get().find(&id); + let r = node_type_substs.find(&id); for ts in r.iter() { let def_map = cx.tcx.def_map.borrow(); - let did = ast_util::def_id_of_def(def_map.get().get_copy(&id)); + let did = ast_util::def_id_of_def(def_map.get_copy(&id)); let generics = ty::lookup_item_type(cx.tcx, did).generics; let type_param_defs = generics.type_param_defs(); for (&ty, type_param_def) in ts.iter().zip(type_param_defs.iter()) { diff --git a/src/librustc/middle/lang_items.rs b/src/librustc/middle/lang_items.rs index 2a1cb6f5a8f..67c597f927a 100644 --- a/src/librustc/middle/lang_items.rs +++ b/src/librustc/middle/lang_items.rs @@ -13,7 +13,7 @@ // Language items are items that represent concepts intrinsic to the language // itself. Examples are: // -// * Traits that specify "kinds"; e.g. "Freeze", "Send". +// * Traits that specify "kinds"; e.g. "Share", "Send". // // * Traits that represent operators; e.g. "Add", "Sub", "Index". // @@ -82,9 +82,7 @@ pub fn require(&self, it: LangItem) -> Result { } pub fn to_builtin_kind(&self, id: ast::DefId) -> Option { - if Some(id) == self.freeze_trait() { - Some(ty::BoundFreeze) - } else if Some(id) == self.send_trait() { + if Some(id) == self.send_trait() { Some(ty::BoundSend) } else if Some(id) == self.sized_trait() { Some(ty::BoundSized) @@ -210,7 +208,6 @@ pub fn collect_language_items(krate: &ast::Crate, lets_do_this! { // Variant name, Name, Method name; - FreezeTraitLangItem, "freeze", freeze_trait; SendTraitLangItem, "send", send_trait; SizedTraitLangItem, "sized", sized_trait; PodTraitLangItem, "pod", pod_trait; @@ -275,7 +272,6 @@ pub fn collect_language_items(krate: &ast::Crate, ContravariantLifetimeItem, "contravariant_lifetime", contravariant_lifetime; InvariantLifetimeItem, "invariant_lifetime", invariant_lifetime; - NoFreezeItem, "no_freeze_bound", no_freeze_bound; NoSendItem, "no_send_bound", no_send_bound; NoPodItem, "no_pod_bound", no_pod_bound; NoShareItem, "no_share_bound", no_share_bound; diff --git a/src/librustc/middle/lint.rs b/src/librustc/middle/lint.rs index 286ecbd6c8f..2ba8121b479 100644 --- a/src/librustc/middle/lint.rs +++ b/src/librustc/middle/lint.rs @@ -848,8 +848,7 @@ fn check_item_ctypes(cx: &Context, it: &ast::Item) { fn check_ty(cx: &Context, ty: &ast::Ty) { match ty.node { ast::TyPath(_, _, id) => { - let def_map = cx.tcx.def_map.borrow(); - match def_map.get().get_copy(&id) { + match cx.tcx.def_map.borrow().get_copy(&id) { ast::DefPrimTy(ast::TyInt(ast::TyI)) => { cx.span_lint(CTypes, ty.span, "found rust type `int` in foreign module, while \ @@ -1182,8 +1181,7 @@ fn check_item_non_uppercase_statics(cx: &Context, it: &ast::Item) { fn check_pat_non_uppercase_statics(cx: &Context, p: &ast::Pat) { // Lint for constants that look like binding identifiers (#7526) - let def_map = cx.tcx.def_map.borrow(); - match (&p.node, def_map.get().find(&p.id)) { + match (&p.node, cx.tcx.def_map.borrow().find(&p.id)) { (&ast::PatIdent(_, ref path, _), Some(&ast::DefStatic(_, false))) => { // last identifier alone is right choice for this lint. let ident = path.segments.last().unwrap().identifier; @@ -1198,10 +1196,9 @@ fn check_pat_non_uppercase_statics(cx: &Context, p: &ast::Pat) { } fn check_pat_uppercase_variable(cx: &Context, p: &ast::Pat) { - let def_map = cx.tcx.def_map.borrow(); match &p.node { &ast::PatIdent(_, ref path, _) => { - match def_map.get().find(&p.id) { + match cx.tcx.def_map.borrow().find(&p.id) { Some(&ast::DefLocal(_, _)) | Some(&ast::DefBinding(_, _)) | Some(&ast::DefArg(_, _)) => { // last identifier alone is right choice for this lint. @@ -1279,9 +1276,8 @@ fn check_unused_unsafe(cx: &Context, e: &ast::Expr) { match e.node { // Don't warn about generated blocks, that'll just pollute the output. ast::ExprBlock(ref blk) => { - let used_unsafe = cx.tcx.used_unsafe.borrow(); if blk.rules == ast::UnsafeBlock(ast::UserProvided) && - !used_unsafe.get().contains(&blk.id) { + !cx.tcx.used_unsafe.borrow().contains(&blk.id) { cx.span_lint(UnusedUnsafe, blk.span, "unnecessary `unsafe` block"); } @@ -1315,8 +1311,8 @@ fn check_unused_mut_pat(cx: &Context, p: &ast::Pat) { of exactly one segment") }; - let used_mut_nodes = cx.tcx.used_mut_nodes.borrow(); - if !initial_underscore && !used_mut_nodes.get().contains(&p.id) { + if !initial_underscore && + !cx.tcx.used_mut_nodes.borrow().contains(&p.id) { cx.span_lint(UnusedMut, p.span, "variable does not need to be mutable"); } @@ -1353,11 +1349,7 @@ fn check_unnecessary_allocation(cx: &Context, e: &ast::Expr) { cx.span_lint(UnnecessaryAllocation, e.span, msg); }; - let adjustment = { - let adjustments = cx.tcx.adjustments.borrow(); - adjustments.get().find_copy(&e.id) - }; - match adjustment { + match cx.tcx.adjustments.borrow().find_copy(&e.id) { Some(adjustment) => { match *adjustment { ty::AutoDerefRef(ty::AutoDerefRef { autoref, .. }) => { @@ -1439,13 +1431,7 @@ fn check_missing_doc_method(cx: &Context, m: &ast::Method) { node: m.id }; - let method_opt; - { - let methods = cx.tcx.methods.borrow(); - method_opt = methods.get().find(&did).map(|method| *method); - } - - match method_opt { + match cx.tcx.methods.borrow().find(&did).map(|method| *method) { None => cx.tcx.sess.span_bug(m.span, "missing method descriptor?!"), Some(md) => { match md.container { @@ -1503,15 +1489,14 @@ fn check_missing_doc_variant(cx: &Context, v: &ast::Variant) { fn check_stability(cx: &Context, e: &ast::Expr) { let id = match e.node { ast::ExprPath(..) | ast::ExprStruct(..) => { - let def_map = cx.tcx.def_map.borrow(); - match def_map.get().find(&e.id) { + match cx.tcx.def_map.borrow().find(&e.id) { Some(&def) => ast_util::def_id_of_def(def), None => return } } ast::ExprMethodCall(..) => { let method_call = typeck::MethodCall::expr(e.id); - match cx.method_map.borrow().get().find(&method_call) { + match cx.method_map.borrow().find(&method_call) { Some(method) => { match method.origin { typeck::MethodStatic(def_id) => { @@ -1736,8 +1721,7 @@ fn visit_ty(&mut self, _t: &ast::Ty, _: ()) {} impl<'a> IdVisitingOperation for Context<'a> { fn visit_id(&self, id: ast::NodeId) { - let mut lints = self.tcx.sess.lints.borrow_mut(); - match lints.get().pop(&id) { + match self.tcx.sess.lints.borrow_mut().pop(&id) { None => {} Some(l) => { for (lint, span, msg) in l.move_iter() { @@ -1793,8 +1777,7 @@ pub fn check_crate(tcx: &ty::ctxt, // If we missed any lints added to the session, then there's a bug somewhere // in the iteration code. - let lints = tcx.sess.lints.borrow(); - for (id, v) in lints.get().iter() { + for (id, v) in tcx.sess.lints.borrow().iter() { for &(lint, span, ref msg) in v.iter() { tcx.sess.span_bug(span, format!("unprocessed lint {:?} at {}: {}", lint, tcx.map.node_to_str(*id), *msg)) diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index 5e8bee803f3..42b7260a4ae 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -455,7 +455,7 @@ fn visit_expr(ir: &mut IrMaps, expr: &Expr) { match expr.node { // live nodes required for uses or definitions of variables: ExprPath(_) => { - let def = ir.tcx.def_map.borrow().get().get_copy(&expr.id); + let def = ir.tcx.def_map.borrow().get_copy(&expr.id); debug!("expr {}: path that leads to {:?}", expr.id, def); if moves::moved_variable_node_id_from_def(def).is_some() { ir.add_live_node_for_node(expr.id, ExprNode(expr.span)); @@ -472,7 +472,7 @@ fn visit_expr(ir: &mut IrMaps, expr: &Expr) { // in better error messages than just pointing at the closure // construction site. let mut call_caps = Vec::new(); - for cv in ir.capture_map.get(&expr.id).deref().iter() { + for cv in ir.capture_map.get(&expr.id).iter() { match moves::moved_variable_node_id_from_def(cv.def) { Some(rv) => { let cv_ln = ir.add_live_node(FreeVarNode(cv.span)); @@ -707,7 +707,7 @@ fn find_loop_scope(&self, Some(_) => { // Refers to a labeled loop. Use the results of resolve // to find with one - match self.ir.tcx.def_map.borrow().get().find(&id) { + match self.ir.tcx.def_map.borrow().find(&id) { Some(&DefLabel(loop_id)) => loop_id, _ => self.ir.tcx.sess.span_bug(sp, "label on break/loop \ doesn't refer to a loop") @@ -979,7 +979,7 @@ fn propagate_through_expr(&mut self, expr: &Expr, succ: LiveNode) this.ir.tcx.sess.span_bug(expr.span, "no registered caps"); } }; - caps.deref().iter().rev().fold(succ, |succ, cap| { + caps.iter().rev().fold(succ, |succ, cap| { this.init_from_succ(cap.ln, succ); let var = this.variable(cap.var_nid, expr.span); this.acc(cap.ln, var, ACC_READ | ACC_USE); @@ -1274,7 +1274,7 @@ fn write_lvalue(&mut self, expr: &Expr, succ: LiveNode, acc: uint) fn access_path(&mut self, expr: &Expr, succ: LiveNode, acc: uint) -> LiveNode { - let def = self.ir.tcx.def_map.borrow().get().get_copy(&expr.id); + let def = self.ir.tcx.def_map.borrow().get_copy(&expr.id); match moves::moved_variable_node_id_from_def(def) { Some(nid) => { let ln = self.live_node(expr.id, expr.span); @@ -1490,7 +1490,7 @@ fn check_ret(&self, fn check_lvalue(&mut self, expr: &Expr) { match expr.node { ExprPath(_) => { - match self.ir.tcx.def_map.borrow().get().get_copy(&expr.id) { + match self.ir.tcx.def_map.borrow().get_copy(&expr.id) { DefLocal(nid, _) => { // Assignment to an immutable variable or argument: only legal // if there is no later assignment. If this local is actually diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index 895fff1df5c..1eb6ab4a8b8 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -95,7 +95,7 @@ pub struct CopiedUpvar { } // different kinds of pointers: -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] pub enum PointerKind { OwnedPtr, GcPtr, @@ -105,26 +105,26 @@ pub enum PointerKind { // We use the term "interior" to mean "something reachable from the // base without a pointer dereference", e.g. a field -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] pub enum InteriorKind { InteriorField(FieldName), InteriorElement(ElementKind), } -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] pub enum FieldName { NamedField(ast::Name), PositionalField(uint) } -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] pub enum ElementKind { VecElement, StrElement, OtherElement, } -#[deriving(Eq, Hash, Show)] +#[deriving(Eq, TotalEq, Hash, Show)] pub enum MutabilityCategory { McImmutable, // Immutable. McDeclared, // Directly declared as mutable. @@ -455,8 +455,7 @@ pub fn cat_expr_unadjusted(&mut self, expr: &ast::Expr) -> McResult { } ast::ExprPath(_) => { - let def_map = self.tcx().def_map.borrow(); - let def = def_map.get().get_copy(&expr.id); + let def = self.tcx().def_map.borrow().get_copy(&expr.id); self.cat_def(expr.id, expr.span, expr_ty, def) } @@ -1010,8 +1009,7 @@ pub fn cat_pattern(&mut self, // variant(..) } ast::PatEnum(_, Some(ref subpats)) => { - let def_map = self.tcx().def_map.borrow(); - match def_map.get().find(&pat.id) { + match self.tcx().def_map.borrow().find(&pat.id) { Some(&ast::DefVariant(enum_did, _, _)) => { // variant(x, y, z) @@ -1202,8 +1200,7 @@ pub fn field_mutbl(tcx: &ty::ctxt, } } ty::ty_enum(..) => { - let def_map = tcx.def_map.borrow(); - match def_map.get().get_copy(&node_id) { + match tcx.def_map.borrow().get_copy(&node_id) { ast::DefVariant(_, variant_id, _) => { let r = ty::lookup_struct_fields(tcx, variant_id); for fld in r.iter() { diff --git a/src/librustc/middle/moves.rs b/src/librustc/middle/moves.rs index fb0aa1e405c..b6cfff5c86f 100644 --- a/src/librustc/middle/moves.rs +++ b/src/librustc/middle/moves.rs @@ -275,7 +275,7 @@ pub fn consume_expr(&mut self, expr: &Expr) { expr.repr(self.tcx)); let expr_ty = ty::expr_ty_adjusted(self.tcx, expr, - self.method_map.borrow().get()); + &*self.method_map.borrow()); if ty::type_moves_by_default(self.tcx, expr_ty) { self.move_maps.moves_map.insert(expr.id); self.use_expr(expr, Move); @@ -316,20 +316,17 @@ pub fn use_expr(&mut self, // `expr_mode` refers to the post-adjustment value. If one of // those adjustments is to take a reference, then it's only // reading the underlying expression, not moving it. - let comp_mode = { - let adjustments = self.tcx.adjustments.borrow(); - match adjustments.get().find(&expr.id) { - Some(adjustment) => { - match **adjustment { - ty::AutoDerefRef(ty::AutoDerefRef { - autoref: Some(_), - .. - }) => Read, - _ => expr_mode, - } + let comp_mode = match self.tcx.adjustments.borrow().find(&expr.id) { + Some(adjustment) => { + match **adjustment { + ty::AutoDerefRef(ty::AutoDerefRef { + autoref: Some(_), + .. + }) => Read, + _ => expr_mode, } - _ => expr_mode, } + _ => expr_mode, }; debug!("comp_mode = {:?}", comp_mode); @@ -338,8 +335,7 @@ pub fn use_expr(&mut self, ExprPath(..) => { match comp_mode { Move => { - let def_map = self.tcx.def_map.borrow(); - let def = def_map.get().get_copy(&expr.id); + let def = self.tcx.def_map.borrow().get_copy(&expr.id); let r = moved_variable_node_id_from_def(def); for &id in r.iter() { self.move_maps.moved_variables_set.insert(id); @@ -581,7 +577,7 @@ pub fn use_overloaded_operator(&mut self, arg_exprs: &[@Expr]) -> bool { let method_call = MethodCall::expr(expr.id); - if !self.method_map.borrow().get().contains_key(&method_call) { + if !self.method_map.borrow().contains_key(&method_call) { return false; } diff --git a/src/librustc/middle/pat_util.rs b/src/librustc/middle/pat_util.rs index 36c6c190284..e9d01b9048f 100644 --- a/src/librustc/middle/pat_util.rs +++ b/src/librustc/middle/pat_util.rs @@ -31,8 +31,7 @@ pub fn pat_id_map(dm: resolve::DefMap, pat: &Pat) -> PatIdMap { pub fn pat_is_variant_or_struct(dm: resolve::DefMap, pat: &Pat) -> bool { match pat.node { PatEnum(_, _) | PatIdent(_, _, None) | PatStruct(..) => { - let dm = dm.borrow(); - match dm.get().find(&pat.id) { + match dm.borrow().find(&pat.id) { Some(&DefVariant(..)) | Some(&DefStruct(..)) => true, _ => false } @@ -44,8 +43,7 @@ pub fn pat_is_variant_or_struct(dm: resolve::DefMap, pat: &Pat) -> bool { pub fn pat_is_const(dm: resolve::DefMap, pat: &Pat) -> bool { match pat.node { PatIdent(_, _, None) | PatEnum(..) => { - let dm = dm.borrow(); - match dm.get().find(&pat.id) { + match dm.borrow().find(&pat.id) { Some(&DefStatic(_, false)) => true, _ => false } diff --git a/src/librustc/middle/privacy.rs b/src/librustc/middle/privacy.rs index 360d010ed67..0c2abfd23c3 100644 --- a/src/librustc/middle/privacy.rs +++ b/src/librustc/middle/privacy.rs @@ -252,8 +252,7 @@ fn visit_item(&mut self, item: &ast::Item, _: ()) { ast::ItemImpl(_, _, ref ty, ref methods) => { let public_ty = match ty.node { ast::TyPath(_, _, id) => { - let def_map = self.tcx.def_map.borrow(); - match def_map.get().get_copy(&id) { + match self.tcx.def_map.borrow().get_copy(&id) { ast::DefPrimTy(..) => true, def => { let did = def_id_of_def(def); @@ -328,8 +327,8 @@ fn visit_mod(&mut self, m: &ast::Mod, _sp: Span, id: ast::NodeId, _: ()) { // crate module gets processed as well. if self.prev_exported { let exp_map2 = self.exp_map2.borrow(); - assert!(exp_map2.get().contains_key(&id), "wut {:?}", id); - for export in exp_map2.get().get(&id).iter() { + assert!(exp_map2.contains_key(&id), "wut {:?}", id); + for export in exp_map2.get(&id).iter() { if is_local(export.def_id) { self.reexports.insert(export.def_id.node); } @@ -376,8 +375,7 @@ fn def_privacy(&self, did: ast::DefId) -> PrivacyResult { } debug!("privacy - is {:?} a public method", did); - let methods = self.tcx.methods.borrow(); - return match methods.get().find(&did) { + return match self.tcx.methods.borrow().find(&did) { Some(meth) => { debug!("privacy - well at least it's a method: {:?}", meth); match meth.container { @@ -639,8 +637,7 @@ fn check_static_method(&mut self, span: Span, method_id: ast::DefId, // Checks that a path is in scope. fn check_path(&mut self, span: Span, path_id: ast::NodeId, path: &ast::Path) { debug!("privacy - path {}", self.nodestr(path_id)); - let def_map = self.tcx.def_map.borrow(); - let orig_def = def_map.get().get_copy(&path_id); + let orig_def = self.tcx.def_map.borrow().get_copy(&path_id); let ck = |tyname: &str| { let ck_public = |def: ast::DefId| { let name = token::get_ident(path.segments @@ -722,8 +719,7 @@ fn check_path(&mut self, span: Span, path_id: ast::NodeId, path: &ast::Path) { // def map is not. Therefore the names we work out below will not always // be accurate and we can get slightly wonky error messages (but type // checking is always correct). - let def_map = self.tcx.def_map.borrow(); - match def_map.get().get_copy(&path_id) { + match self.tcx.def_map.borrow().get_copy(&path_id) { ast::DefStaticMethod(..) => ck("static method"), ast::DefFn(..) => ck("function"), ast::DefStatic(..) => ck("static"), @@ -772,7 +768,7 @@ fn visit_expr(&mut self, expr: &ast::Expr, _: ()) { match expr.node { ast::ExprField(base, ident, _) => { match ty::get(ty::expr_ty_adjusted(self.tcx, base, - self.method_map.borrow().get())).sty { + &*self.method_map.borrow())).sty { ty::ty_struct(id, _) => { self.check_field(expr.span, id, ident, None); } @@ -781,7 +777,7 @@ fn visit_expr(&mut self, expr: &ast::Expr, _: ()) { } ast::ExprMethodCall(ident, _, _) => { let method_call = MethodCall::expr(expr.id); - match self.method_map.borrow().get().find(&method_call) { + match self.method_map.borrow().find(&method_call) { None => { self.tcx.sess.span_bug(expr.span, "method call not in \ @@ -802,8 +798,7 @@ fn visit_expr(&mut self, expr: &ast::Expr, _: ()) { } } ty::ty_enum(_, _) => { - let def_map = self.tcx.def_map.borrow(); - match def_map.get().get_copy(&expr.id) { + match self.tcx.def_map.borrow().get_copy(&expr.id) { ast::DefVariant(enum_id, variant_id, _) => { for field in fields.iter() { self.check_field(expr.span, variant_id, @@ -877,8 +872,7 @@ fn visit_pat(&mut self, pattern: &ast::Pat, _: ()) { } } ty::ty_enum(_, _) => { - let def_map = self.tcx.def_map.borrow(); - match def_map.get().find(&pattern.id) { + match self.tcx.def_map.borrow().find(&pattern.id) { Some(&ast::DefVariant(enum_id, variant_id, _)) => { for field in fields.iter() { self.check_field(pattern.span, variant_id, @@ -1176,7 +1170,7 @@ struct CheckTypeForPrivatenessVisitor<'a, 'b> { impl<'a> VisiblePrivateTypesVisitor<'a> { fn path_is_private_type(&self, path_id: ast::NodeId) -> bool { - let did = match self.tcx.def_map.borrow().get().find_copy(&path_id) { + let did = match self.tcx.def_map.borrow().find_copy(&path_id) { // `int` etc. (None doesn't seem to occur.) None | Some(ast::DefPrimTy(..)) => return false, Some(def) => def_id_of_def(def) diff --git a/src/librustc/middle/reachable.rs b/src/librustc/middle/reachable.rs index 97f492ae73d..839f1d6039c 100644 --- a/src/librustc/middle/reachable.rs +++ b/src/librustc/middle/reachable.rs @@ -100,7 +100,7 @@ fn visit_expr(&mut self, expr: &ast::Expr, _: ()) { match expr.node { ast::ExprPath(_) => { - let def = match self.tcx.def_map.borrow().get().find(&expr.id) { + let def = match self.tcx.def_map.borrow().find(&expr.id) { Some(&def) => def, None => { self.tcx.sess.span_bug(expr.span, @@ -133,7 +133,7 @@ fn visit_expr(&mut self, expr: &ast::Expr, _: ()) { } ast::ExprMethodCall(..) => { let method_call = typeck::MethodCall::expr(expr.id); - match self.method_map.borrow().get().get(&method_call).origin { + match self.method_map.borrow().get(&method_call).origin { typeck::MethodStatic(def_id) => { if is_local(def_id) { if self.def_id_represents_local_inlined_item(def_id) { @@ -330,7 +330,7 @@ fn propagate_node(&mut self, node: &ast_map::Node, // this properly would result in the necessity of computing *type* // reachability, which might result in a compile time loss. fn mark_destructors_reachable(&mut self) { - for (_, destructor_def_id) in self.tcx.destructor_for_type.borrow().get().iter() { + for (_, destructor_def_id) in self.tcx.destructor_for_type.borrow().iter() { if destructor_def_id.krate == ast::LOCAL_CRATE { self.reachable_symbols.insert(destructor_def_id.node); } diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index a1f74aaee4e..16c513f16f3 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -100,8 +100,7 @@ struct RegionResolutionVisitor<'a> { impl RegionMaps { pub fn relate_free_regions(&self, sub: FreeRegion, sup: FreeRegion) { - let mut free_region_map = self.free_region_map.borrow_mut(); - match free_region_map.get().find_mut(&sub) { + match self.free_region_map.borrow_mut().find_mut(&sub) { Some(sups) => { if !sups.iter().any(|x| x == &sup) { sups.push(sup); @@ -112,32 +111,25 @@ pub fn relate_free_regions(&self, sub: FreeRegion, sup: FreeRegion) { } debug!("relate_free_regions(sub={:?}, sup={:?})", sub, sup); - - free_region_map.get().insert(sub, vec!(sup)); + self.free_region_map.borrow_mut().insert(sub, vec!(sup)); } pub fn record_encl_scope(&self, sub: ast::NodeId, sup: ast::NodeId) { debug!("record_encl_scope(sub={}, sup={})", sub, sup); assert!(sub != sup); - - let mut scope_map = self.scope_map.borrow_mut(); - scope_map.get().insert(sub, sup); + self.scope_map.borrow_mut().insert(sub, sup); } pub fn record_var_scope(&self, var: ast::NodeId, lifetime: ast::NodeId) { debug!("record_var_scope(sub={}, sup={})", var, lifetime); assert!(var != lifetime); - - let mut var_map = self.var_map.borrow_mut(); - var_map.get().insert(var, lifetime); + self.var_map.borrow_mut().insert(var, lifetime); } pub fn record_rvalue_scope(&self, var: ast::NodeId, lifetime: ast::NodeId) { debug!("record_rvalue_scope(sub={}, sup={})", var, lifetime); assert!(var != lifetime); - - let mut rvalue_scopes = self.rvalue_scopes.borrow_mut(); - rvalue_scopes.get().insert(var, lifetime); + self.rvalue_scopes.borrow_mut().insert(var, lifetime); } pub fn mark_as_terminating_scope(&self, scope_id: ast::NodeId) { @@ -149,22 +141,17 @@ pub fn mark_as_terminating_scope(&self, scope_id: ast::NodeId) { */ debug!("record_terminating_scope(scope_id={})", scope_id); - let mut terminating_scopes = self.terminating_scopes.borrow_mut(); - terminating_scopes.get().insert(scope_id); + self.terminating_scopes.borrow_mut().insert(scope_id); } pub fn opt_encl_scope(&self, id: ast::NodeId) -> Option { //! Returns the narrowest scope that encloses `id`, if any. - - let scope_map = self.scope_map.borrow(); - scope_map.get().find(&id).map(|x| *x) + self.scope_map.borrow().find(&id).map(|x| *x) } pub fn encl_scope(&self, id: ast::NodeId) -> ast::NodeId { //! Returns the narrowest scope that encloses `id`, if any. - - let scope_map = self.scope_map.borrow(); - match scope_map.get().find(&id) { + match self.scope_map.borrow().find(&id) { Some(&r) => r, None => { fail!("no enclosing scope for id {}", id); } } @@ -174,9 +161,7 @@ pub fn var_scope(&self, var_id: ast::NodeId) -> ast::NodeId { /*! * Returns the lifetime of the local variable `var_id` */ - - let var_map = self.var_map.borrow(); - match var_map.get().find(&var_id) { + match self.var_map.borrow().find(&var_id) { Some(&r) => r, None => { fail!("no enclosing scope for id {}", var_id); } } @@ -186,8 +171,7 @@ pub fn temporary_scope(&self, expr_id: ast::NodeId) -> Option { //! Returns the scope when temp created by expr_id will be cleaned up // check for a designated rvalue scope - let rvalue_scopes = self.rvalue_scopes.borrow(); - match rvalue_scopes.get().find(&expr_id) { + match self.rvalue_scopes.borrow().find(&expr_id) { Some(&s) => { debug!("temporary_scope({}) = {} [custom]", expr_id, s); return Some(s); @@ -204,8 +188,7 @@ pub fn temporary_scope(&self, expr_id: ast::NodeId) -> Option { None => { return None; } }; - let terminating_scopes = self.terminating_scopes.borrow(); - while !terminating_scopes.get().contains(&id) { + while !self.terminating_scopes.borrow().contains(&id) { match self.opt_encl_scope(id) { Some(p) => { id = p; @@ -249,8 +232,7 @@ pub fn is_subscope_of(&self, let mut s = subscope; while superscope != s { - let scope_map = self.scope_map.borrow(); - match scope_map.get().find(&s) { + match self.scope_map.borrow().find(&s) { None => { debug!("is_subscope_of({}, {}, s={})=false", subscope, superscope, s); @@ -286,8 +268,7 @@ pub fn sub_free_region(&self, sub: FreeRegion, sup: FreeRegion) -> bool { let mut queue = vec!(sub); let mut i = 0; while i < queue.len() { - let free_region_map = self.free_region_map.borrow(); - match free_region_map.get().find(queue.get(i)) { + match self.free_region_map.borrow().find(queue.get(i)) { Some(parents) => { for parent in parents.iter() { if *parent == sup { @@ -391,8 +372,7 @@ fn ancestors_of(this: &RegionMaps, scope: ast::NodeId) let mut result = vec!(scope); let mut scope = scope; loop { - let scope_map = this.scope_map.borrow(); - match scope_map.get().find(&scope) { + match this.scope_map.borrow().find(&scope) { None => return result, Some(&superscope) => { result.push(superscope); diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index 47f5e05fb8a..d86e05395b4 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -107,7 +107,7 @@ enum PatternBindingMode { ArgumentIrrefutableMode, } -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] enum Namespace { TypeNS, ValueNS @@ -499,8 +499,7 @@ fn new(parent_link: ParentLink, } fn all_imports_resolved(&self) -> bool { - let mut imports = self.imports.borrow_mut(); - return imports.get().len() == self.resolved_import_count.get(); + self.imports.borrow().len() == self.resolved_import_count.get() } } @@ -641,8 +640,7 @@ fn define_value(&self, def: Def, sp: Span, is_public: bool) { /// Returns the module node if applicable. fn get_module_if_available(&self) -> Option<@Module> { - let type_def = self.type_def.borrow(); - match *type_def.get() { + match *self.type_def.borrow() { Some(ref type_def) => (*type_def).module_def, None => None } @@ -1011,15 +1009,11 @@ fn add_child(&mut self, // Add or reuse the child. let new_parent = ModuleReducedGraphParent(module_); - let child_opt = { - let children = module_.children.borrow(); - children.get().find_copy(&name.name) - }; + let child_opt = module_.children.borrow().find_copy(&name.name); match child_opt { None => { let child = @NameBindings(); - let mut children = module_.children.borrow_mut(); - children.get().insert(name.name, child); + module_.children.borrow_mut().insert(name.name, child); return (child, new_parent); } Some(child) => { @@ -1258,11 +1252,9 @@ fn build_reduced_graph_for_item(&mut self, TyPath(ref path, _, _) if path.segments.len() == 1 => { let name = path_to_ident(path); - let existing_parent_opt = { - let children = parent.module().children.borrow(); - children.get().find_copy(&name.name) - }; - let new_parent = match existing_parent_opt { + let parent_opt = parent.module().children.borrow() + .find_copy(&name.name); + let new_parent = match parent_opt { // It already exists Some(child) if child.get_module_if_available() .is_some() && @@ -1393,10 +1385,10 @@ fn build_reduced_graph_for_item(&mut self, let def_id = local_def(item.id); for (name, _) in method_names.iter() { let mut method_map = self.method_map.borrow_mut(); - if !method_map.get().contains_key(name) { - method_map.get().insert(*name, HashSet::new()); + if !method_map.contains_key(name) { + method_map.insert(*name, HashSet::new()); } - match method_map.get().find_mut(name) { + match method_map.find_mut(name) { Some(s) => { s.insert(def_id); }, _ => fail!("can't happen"), } @@ -1530,13 +1522,9 @@ fn build_reduced_graph_for_view_item(&mut self, view_item: &ViewItem, false, true); - { - let mut external_module_children = - parent.module().external_module_children.borrow_mut(); - external_module_children.get().insert( - name.name, - external_module); - } + parent.module().external_module_children + .borrow_mut().insert(name.name, + external_module); self.build_reduced_graph_for_external_crate( external_module); @@ -1599,12 +1587,9 @@ fn build_reduced_graph_for_block(&mut self, AnonymousModuleKind, false, false); - { - let mut anonymous_children = parent_module.anonymous_children - .borrow_mut(); - anonymous_children.get().insert(block_id, new_module); - ModuleReducedGraphParent(new_module) - } + parent_module.anonymous_children.borrow_mut() + .insert(block_id, new_module); + ModuleReducedGraphParent(new_module) } else { parent } @@ -1711,10 +1696,10 @@ trait method '{}'", } for name in interned_method_names.iter() { let mut method_map = self.method_map.borrow_mut(); - if !method_map.get().contains_key(name) { - method_map.get().insert(*name, HashSet::new()); + if !method_map.contains_key(name) { + method_map.insert(*name, HashSet::new()); } - match method_map.get().find_mut(name) { + match method_map.find_mut(name) { Some(s) => { s.insert(def_id); }, _ => fail!("can't happen"), } @@ -1959,12 +1944,7 @@ fn build_import_directive(&mut self, let directive = @ImportDirective::new(module_path, subclass, span, id, is_public); - - { - let mut imports = module_.imports.borrow_mut(); - imports.get().push(directive); - } - + module_.imports.borrow_mut().push(directive); // Bump the reference count on the name. Or, if this is a glob, set // the appropriate flag. @@ -1977,7 +1957,7 @@ fn build_import_directive(&mut self, let mut import_resolutions = module_.import_resolutions .borrow_mut(); - match import_resolutions.get().find(&target.name) { + match import_resolutions.find(&target.name) { Some(&resolution) => { debug!("(building import directive) bumping \ reference"); @@ -1992,8 +1972,7 @@ fn build_import_directive(&mut self, debug!("(building import directive) creating new"); let resolution = @ImportResolution::new(id, is_public); resolution.outstanding_references.set(1); - import_resolutions.get().insert(target.name, - resolution); + import_resolutions.insert(target.name, resolution); } } } @@ -2052,22 +2031,18 @@ fn resolve_imports_for_module_subtree(&mut self, self.resolve_imports_for_module(module_); self.populate_module_if_necessary(module_); - { - let children = module_.children.borrow(); - for (_, &child_node) in children.get().iter() { - match child_node.get_module_if_available() { - None => { - // Nothing to do. - } - Some(child_module) => { - self.resolve_imports_for_module_subtree(child_module); - } + for (_, &child_node) in module_.children.borrow().iter() { + match child_node.get_module_if_available() { + None => { + // Nothing to do. + } + Some(child_module) => { + self.resolve_imports_for_module_subtree(child_module); } } } - let anonymous_children = module_.anonymous_children.borrow(); - for (_, &child_module) in anonymous_children.get().iter() { + for (_, &child_module) in module_.anonymous_children.borrow().iter() { self.resolve_imports_for_module_subtree(child_module); } } @@ -2082,10 +2057,10 @@ fn resolve_imports_for_module(&mut self, module: @Module) { } let mut imports = module.imports.borrow_mut(); - let import_count = imports.get().len(); + let import_count = imports.len(); while module.resolved_import_count.get() < import_count { let import_index = module.resolved_import_count.get(); - let import_directive = *imports.get().get(import_index); + let import_directive = *imports.get(import_index); match self.resolve_import_for_module(module, import_directive) { Failed => { // We presumably emitted an error. Continue. @@ -2296,21 +2271,18 @@ fn resolve_single_import(&mut self, // Search for direct children of the containing module. self.populate_module_if_necessary(containing_module); - { - let children = containing_module.children.borrow(); - match children.get().find(&source.name) { - None => { - // Continue. + match containing_module.children.borrow().find(&source.name) { + None => { + // Continue. + } + Some(child_name_bindings) => { + if child_name_bindings.defined_in_namespace(ValueNS) { + value_result = BoundResult(containing_module, + *child_name_bindings); } - Some(child_name_bindings) => { - if child_name_bindings.defined_in_namespace(ValueNS) { - value_result = BoundResult(containing_module, - *child_name_bindings); - } - if child_name_bindings.defined_in_namespace(TypeNS) { - type_result = BoundResult(containing_module, - *child_name_bindings); - } + if child_name_bindings.defined_in_namespace(TypeNS) { + type_result = BoundResult(containing_module, + *child_name_bindings); } } } @@ -2337,7 +2309,7 @@ fn resolve_single_import(&mut self, let import_resolutions = containing_module.import_resolutions .borrow(); - match import_resolutions.get().find(&source.name) { + match import_resolutions.find(&source.name) { None => { // The containing module definitely doesn't have an // exported import with the name in question. We can @@ -2411,13 +2383,8 @@ fn get_binding(this: &mut Resolver, match type_result { BoundResult(..) => {} _ => { - let module_opt = { - let mut external_module_children = - containing_module.external_module_children - .borrow_mut(); - external_module_children.get().find_copy(&source.name) - }; - match module_opt { + match containing_module.external_module_children.borrow_mut() + .find_copy(&source.name) { None => {} // Continue. Some(module) => { let name_bindings = @@ -2434,8 +2401,8 @@ fn get_binding(this: &mut Resolver, // We've successfully resolved the import. Write the results in. let import_resolution = { let import_resolutions = module_.import_resolutions.borrow(); - assert!(import_resolutions.get().contains_key(&target.name)); - import_resolutions.get().get_copy(&target.name) + assert!(import_resolutions.contains_key(&target.name)); + import_resolutions.get_copy(&target.name) }; match value_result { @@ -2488,8 +2455,7 @@ fn get_binding(this: &mut Resolver, let value_private = match import_resolution.value_target.get() { Some(target) => { let def = target.bindings.def_for_namespace(ValueNS).unwrap(); - let mut def_map = self.def_map.borrow_mut(); - def_map.get().insert(directive.id, def); + self.def_map.borrow_mut().insert(directive.id, def); let did = def_id_of_def(def); if value_used_public {Some(lp)} else {Some(DependsOn(did))} }, @@ -2500,8 +2466,7 @@ fn get_binding(this: &mut Resolver, let type_private = match import_resolution.type_target.get() { Some(target) => { let def = target.bindings.def_for_namespace(TypeNS).unwrap(); - let mut def_map = self.def_map.borrow_mut(); - def_map.get().insert(directive.id, def); + self.def_map.borrow_mut().insert(directive.id, def); let did = def_id_of_def(def); if type_used_public {Some(lp)} else {Some(DependsOn(did))} }, @@ -2545,8 +2510,7 @@ fn resolve_glob_import(&mut self, // Add all resolved imports from the containing module. let import_resolutions = containing_module.import_resolutions .borrow(); - for (ident, target_import_resolution) in import_resolutions.get() - .iter() { + for (ident, target_import_resolution) in import_resolutions.iter() { debug!("(resolving glob import) writing module resolution \ {:?} into `{}`", target_import_resolution.type_target.get().is_none(), @@ -2558,9 +2522,8 @@ fn resolve_glob_import(&mut self, } // Here we merge two import resolutions. - let mut import_resolutions = module_.import_resolutions - .borrow_mut(); - match import_resolutions.get().find(ident) { + let mut import_resolutions = module_.import_resolutions.borrow_mut(); + match import_resolutions.find(ident) { None => { // Simple: just copy the old import resolution. let new_import_resolution = @@ -2570,7 +2533,7 @@ fn resolve_glob_import(&mut self, new_import_resolution.type_target.set( target_import_resolution.type_target.get()); - import_resolutions.get().insert + import_resolutions.insert (*ident, new_import_resolution); } Some(&dest_import_resolution) => { @@ -2603,33 +2566,27 @@ fn resolve_glob_import(&mut self, // Add all children from the containing module. self.populate_module_if_necessary(containing_module); - { - let children = containing_module.children.borrow(); - for (&name, name_bindings) in children.get().iter() { - self.merge_import_resolution(module_, containing_module, - id, is_public, - name, *name_bindings); - } + for (&name, name_bindings) in containing_module.children + .borrow().iter() { + self.merge_import_resolution(module_, containing_module, + id, is_public, + name, *name_bindings); } // Add external module children from the containing module. - { - let external_module_children = - containing_module.external_module_children.borrow(); - for (&name, module) in external_module_children.get().iter() { - let name_bindings = - @Resolver::create_name_bindings_from_module(*module); - self.merge_import_resolution(module_, containing_module, - id, is_public, - name, name_bindings); - } + for (&name, module) in containing_module.external_module_children + .borrow().iter() { + let name_bindings = + @Resolver::create_name_bindings_from_module(*module); + self.merge_import_resolution(module_, containing_module, + id, is_public, + name, name_bindings); } // Record the destination of this import match containing_module.def_id.get() { Some(did) => { - let mut def_map = self.def_map.borrow_mut(); - def_map.get().insert(id, DefMod(did)); + self.def_map.borrow_mut().insert(id, DefMod(did)); self.last_private.insert(id, lp); } None => {} @@ -2648,12 +2605,12 @@ fn merge_import_resolution(&mut self, name_bindings: @NameBindings) { let dest_import_resolution; let mut import_resolutions = module_.import_resolutions.borrow_mut(); - match import_resolutions.get().find(&name) { + match import_resolutions.find(&name) { None => { // Create a new import resolution from this child. dest_import_resolution = @ImportResolution::new(id, is_public); - import_resolutions.get().insert(name, + import_resolutions.insert(name, dest_import_resolution); } Some(&existing_import_resolution) => { @@ -2919,25 +2876,21 @@ fn resolve_item_in_lexical_scope(&mut self, // its immediate children. self.populate_module_if_necessary(module_); - { - let children = module_.children.borrow(); - match children.get().find(&name.name) { - Some(name_bindings) - if name_bindings.defined_in_namespace(namespace) => { - debug!("top name bindings succeeded"); - return Success((Target::new(module_, *name_bindings), - false)); - } - Some(_) | None => { /* Not found; continue. */ } + match module_.children.borrow().find(&name.name) { + Some(name_bindings) + if name_bindings.defined_in_namespace(namespace) => { + debug!("top name bindings succeeded"); + return Success((Target::new(module_, *name_bindings), + false)); } + Some(_) | None => { /* Not found; continue. */ } } // Now check for its import directives. We don't have to have resolved // all its imports in the usual way; this is because chains of // adjacent import statements are processed as though they mutated the // current scope. - let import_resolutions = module_.import_resolutions.borrow(); - match import_resolutions.get().find(&name.name) { + match module_.import_resolutions.borrow().find(&name.name) { None => { // Not found; continue. } @@ -2961,12 +2914,7 @@ fn resolve_item_in_lexical_scope(&mut self, // Search for external modules. if namespace == TypeNS { - let module_opt = { - let external_module_children = - module_.external_module_children.borrow(); - external_module_children.get().find_copy(&name.name) - }; - match module_opt { + match module_.external_module_children.borrow().find_copy(&name.name) { None => {} Some(module) => { let name_bindings = @@ -3195,18 +3143,15 @@ fn resolve_name_in_module(&mut self, // First, check the direct children of the module. self.populate_module_if_necessary(module_); - { - let children = module_.children.borrow(); - match children.get().find(&name.name) { - Some(name_bindings) - if name_bindings.defined_in_namespace(namespace) => { - debug!("(resolving name in module) found node as child"); - return Success((Target::new(module_, *name_bindings), - false)); - } - Some(_) | None => { - // Continue. - } + match module_.children.borrow().find(&name.name) { + Some(name_bindings) + if name_bindings.defined_in_namespace(namespace) => { + debug!("(resolving name in module) found node as child"); + return Success((Target::new(module_, *name_bindings), + false)); + } + Some(_) | None => { + // Continue. } } @@ -3219,8 +3164,7 @@ fn resolve_name_in_module(&mut self, } // Check the list of resolved imports. - let import_resolutions = module_.import_resolutions.borrow(); - match import_resolutions.get().find(&name.name) { + match module_.import_resolutions.borrow().find(&name.name) { Some(import_resolution) => { if import_resolution.is_public.get() && import_resolution.outstanding_references.get() != 0 { @@ -3247,12 +3191,7 @@ fn resolve_name_in_module(&mut self, // Finally, search through external children. if namespace == TypeNS { - let module_opt = { - let external_module_children = - module_.external_module_children.borrow(); - external_module_children.get().find_copy(&name.name) - }; - match module_opt { + match module_.external_module_children.borrow().find_copy(&name.name) { None => {} Some(module) => { let name_bindings = @@ -3270,42 +3209,38 @@ fn resolve_name_in_module(&mut self, fn report_unresolved_imports(&mut self, module_: @Module) { let index = module_.resolved_import_count.get(); - let mut imports = module_.imports.borrow_mut(); - let import_count = imports.get().len(); + let imports = module_.imports.borrow(); + let import_count = imports.len(); if index != import_count { let sn = self.session .codemap() - .span_to_snippet(imports.get().get(index).span) + .span_to_snippet(imports.get(index).span) .unwrap(); if sn.contains("::") { - self.resolve_error(imports.get().get(index).span, + self.resolve_error(imports.get(index).span, "unresolved import"); } else { let err = format!("unresolved import (maybe you meant `{}::*`?)", sn.slice(0, sn.len())); - self.resolve_error(imports.get().get(index).span, err); + self.resolve_error(imports.get(index).span, err); } } // Descend into children and anonymous children. self.populate_module_if_necessary(module_); - { - let children = module_.children.borrow(); - for (_, &child_node) in children.get().iter() { - match child_node.get_module_if_available() { - None => { - // Continue. - } - Some(child_module) => { - self.report_unresolved_imports(child_module); - } + for (_, &child_node) in module_.children.borrow().iter() { + match child_node.get_module_if_available() { + None => { + // Continue. + } + Some(child_module) => { + self.report_unresolved_imports(child_module); } } } - let anonymous_children = module_.anonymous_children.borrow(); - for (_, &module_) in anonymous_children.get().iter() { + for (_, &module_) in module_.anonymous_children.borrow().iter() { self.report_unresolved_imports(module_); } } @@ -3354,22 +3289,18 @@ fn record_exports_for_module_subtree(&mut self, self.record_exports_for_module(module_); self.populate_module_if_necessary(module_); - { - let children = module_.children.borrow(); - for (_, &child_name_bindings) in children.get().iter() { - match child_name_bindings.get_module_if_available() { - None => { - // Nothing to do. - } - Some(child_module) => { - self.record_exports_for_module_subtree(child_module); - } + for (_, &child_name_bindings) in module_.children.borrow().iter() { + match child_name_bindings.get_module_if_available() { + None => { + // Nothing to do. + } + Some(child_module) => { + self.record_exports_for_module_subtree(child_module); } } } - let anonymous_children = module_.anonymous_children.borrow(); - for (_, &child_module) in anonymous_children.get().iter() { + for (_, &child_module) in module_.anonymous_children.borrow().iter() { self.record_exports_for_module_subtree(child_module); } } @@ -3380,8 +3311,7 @@ fn record_exports_for_module(&mut self, module_: @Module) { self.add_exports_for_module(&mut exports2, module_); match module_.def_id.get() { Some(def_id) => { - let mut export_map2 = self.export_map2.borrow_mut(); - export_map2.get().insert(def_id.node, exports2); + self.export_map2.borrow_mut().insert(def_id.node, exports2); debug!("(computing exports) writing exports for {} (some)", def_id.node); } @@ -3413,8 +3343,7 @@ fn add_exports_of_namebindings(&mut self, fn add_exports_for_module(&mut self, exports2: &mut Vec , module_: @Module) { - let import_resolutions = module_.import_resolutions.borrow(); - for (name, importresolution) in import_resolutions.get().iter() { + for (name, importresolution) in module_.import_resolutions.borrow().iter() { if !importresolution.is_public.get() { continue } @@ -3464,8 +3393,7 @@ fn with_scope(&mut self, name: Option, f: |&mut Resolver|) { Some(name) => { self.populate_module_if_necessary(orig_module); - let children = orig_module.children.borrow(); - match children.get().find(&name.name) { + match orig_module.children.borrow().find(&name.name) { None => { debug!("!!! (with scope) didn't find `{}` in `{}`", token::get_ident(name), @@ -3538,8 +3466,7 @@ fn upvarify(&mut self, // item, it's ok match def { DefTyParam(did, _) if { - let def_map = self.def_map.borrow(); - def_map.get().find(&did.node).map(|x| *x) + self.def_map.borrow().find(&did.node).map(|x| *x) == Some(DefTyParamBinder(item_id)) } => { // ok @@ -3621,10 +3548,7 @@ fn search_ribs(&mut self, let mut i = ribs.len(); while i != 0 { i -= 1; - let binding_opt = { - let bindings = ribs.get(i).bindings.borrow(); - bindings.get().find_copy(&name) - }; + let binding_opt = ribs.get(i).bindings.borrow().find_copy(&name); match binding_opt { Some(def_like) => { return self.upvarify(ribs, i, def_like, span); @@ -3699,16 +3623,11 @@ fn resolve_item(&mut self, item: &Item) { ItemTrait(ref generics, ref traits, ref methods) => { // Create a new rib for the self type. let self_type_rib = @Rib::new(NormalRibKind); - { - let mut type_ribs = self.type_ribs.borrow_mut(); - type_ribs.get().push(self_type_rib); - } + self.type_ribs.borrow_mut().push(self_type_rib); // plain insert (no renaming) let name = self.type_self_ident.name; - { - let mut bindings = self_type_rib.bindings.borrow_mut(); - bindings.get().insert(name, DlDef(DefSelfTy(item.id))); - } + self_type_rib.bindings.borrow_mut() + .insert(name, DlDef(DefSelfTy(item.id))); // Create a new rib for the trait-wide type parameters. self.with_type_parameter_rib(HasTypeParameters(generics, @@ -3760,8 +3679,7 @@ fn resolve_item(&mut self, item: &Item) { } }); - let mut type_ribs = self.type_ribs.borrow_mut(); - type_ribs.get().pop(); + self.type_ribs.borrow_mut().pop(); } ItemStruct(ref struct_def, ref generics) => { @@ -3831,10 +3749,7 @@ fn with_type_parameter_rib(&mut self, rib_kind) => { let function_type_rib = @Rib::new(rib_kind); - { - let mut type_ribs = self.type_ribs.borrow_mut(); - type_ribs.get().push(function_type_rib); - } + self.type_ribs.borrow_mut().push(function_type_rib); for (index, type_parameter) in generics.ty_params.iter().enumerate() { let ident = type_parameter.ident; @@ -3848,9 +3763,8 @@ fn with_type_parameter_rib(&mut self, self.record_def(type_parameter.id, (DefTyParamBinder(node_id), LastMod(AllPublic))); // plain insert (no renaming) - let mut bindings = function_type_rib.bindings - .borrow_mut(); - bindings.get().insert(ident.name, def_like); + function_type_rib.bindings.borrow_mut() + .insert(ident.name, def_like); } } @@ -3862,45 +3776,23 @@ fn with_type_parameter_rib(&mut self, f(self); match type_parameters { - HasTypeParameters(..) => { - let mut type_ribs = self.type_ribs.borrow_mut(); - type_ribs.get().pop(); - } - - NoTypeParameters => { - // Nothing to do. - } + HasTypeParameters(..) => { self.type_ribs.borrow_mut().pop(); } + NoTypeParameters => { } } } fn with_label_rib(&mut self, f: |&mut Resolver|) { - { - let mut label_ribs = self.label_ribs.borrow_mut(); - label_ribs.get().push(@Rib::new(NormalRibKind)); - } - + self.label_ribs.borrow_mut().push(@Rib::new(NormalRibKind)); f(self); - - { - let mut label_ribs = self.label_ribs.borrow_mut(); - label_ribs.get().pop(); - } + self.label_ribs.borrow_mut().pop(); } fn with_constant_rib(&mut self, f: |&mut Resolver|) { - { - let mut value_ribs = self.value_ribs.borrow_mut(); - let mut type_ribs = self.type_ribs.borrow_mut(); - value_ribs.get().push(@Rib::new(ConstantItemRibKind)); - type_ribs.get().push(@Rib::new(ConstantItemRibKind)); - } + self.value_ribs.borrow_mut().push(@Rib::new(ConstantItemRibKind)); + self.type_ribs.borrow_mut().push(@Rib::new(ConstantItemRibKind)); f(self); - { - let mut value_ribs = self.value_ribs.borrow_mut(); - let mut type_ribs = self.type_ribs.borrow_mut(); - type_ribs.get().pop(); - value_ribs.get().pop(); - } + self.type_ribs.borrow_mut().pop(); + self.value_ribs.borrow_mut().pop(); } fn resolve_function(&mut self, @@ -3910,17 +3802,11 @@ fn resolve_function(&mut self, block: P) { // Create a value rib for the function. let function_value_rib = @Rib::new(rib_kind); - { - let mut value_ribs = self.value_ribs.borrow_mut(); - value_ribs.get().push(function_value_rib); - } + self.value_ribs.borrow_mut().push(function_value_rib); // Create a label rib for the function. - { - let mut label_ribs = self.label_ribs.borrow_mut(); - let function_label_rib = @Rib::new(rib_kind); - label_ribs.get().push(function_label_rib); - } + let function_label_rib = @Rib::new(rib_kind); + self.label_ribs.borrow_mut().push(function_label_rib); // If this function has type parameters, add them now. self.with_type_parameter_rib(type_parameters, |this| { @@ -3961,11 +3847,8 @@ fn resolve_function(&mut self, debug!("(resolving function) leaving function"); }); - let mut label_ribs = self.label_ribs.borrow_mut(); - label_ribs.get().pop(); - - let mut value_ribs = self.value_ribs.borrow_mut(); - value_ribs.get().pop(); + self.label_ribs.borrow_mut().pop(); + self.value_ribs.borrow_mut().pop(); } fn resolve_type_parameters(&mut self, @@ -4097,12 +3980,9 @@ fn resolve_implementation(&mut self, // Record the current set of trait references. let mut new_trait_refs = Vec::new(); - { - let def_map = this.def_map.borrow(); - let r = def_map.get().find(&trait_reference.ref_id); - for &def in r.iter() { - new_trait_refs.push(def_id_of_def(*def)); - } + for &def in this.def_map.borrow() + .find(&trait_reference.ref_id).iter() { + new_trait_refs.push(def_id_of_def(*def)); } original_trait_refs = Some(replace( &mut this.current_trait_refs, @@ -4234,10 +4114,7 @@ fn check_consistent_bindings(&mut self, arm: &Arm) { } fn resolve_arm(&mut self, arm: &Arm) { - { - let mut value_ribs = self.value_ribs.borrow_mut(); - value_ribs.get().push(@Rib::new(NormalRibKind)); - } + self.value_ribs.borrow_mut().push(@Rib::new(NormalRibKind)); let mut bindings_list = HashMap::new(); for pattern in arm.pats.iter() { @@ -4253,23 +4130,19 @@ fn resolve_arm(&mut self, arm: &Arm) { visit::walk_expr_opt(self, arm.guard, ()); self.resolve_expr(arm.body); - let mut value_ribs = self.value_ribs.borrow_mut(); - value_ribs.get().pop(); + self.value_ribs.borrow_mut().pop(); } fn resolve_block(&mut self, block: &Block) { debug!("(resolving block) entering block"); - { - let mut value_ribs = self.value_ribs.borrow_mut(); - value_ribs.get().push(@Rib::new(NormalRibKind)); - } + self.value_ribs.borrow_mut().push(@Rib::new(NormalRibKind)); // Move down in the graph, if there's an anonymous module rooted here. let orig_module = self.current_module; let anonymous_children = self.current_module .anonymous_children .borrow(); - match anonymous_children.get().find(&block.id) { + match anonymous_children.find(&block.id) { None => { /* Nothing to do. */ } Some(&anonymous_module) => { debug!("(resolving block) found anonymous module, moving \ @@ -4284,8 +4157,7 @@ fn resolve_block(&mut self, block: &Block) { // Move back up. self.current_module = orig_module; - let mut value_ribs = self.value_ribs.borrow_mut(); - value_ribs.get().pop(); + self.value_ribs.borrow_mut().pop(); debug!("(resolving block) leaving block"); } @@ -4490,17 +4362,12 @@ struct in scope", Some(ref mut bindings_list) if !bindings_list.contains_key(&renamed) => { let this = &mut *self; - { - let mut value_ribs = - this.value_ribs.borrow_mut(); - let length = value_ribs.get().len(); - let last_rib = value_ribs.get().get( - length - 1); - let mut bindings = - last_rib.bindings.borrow_mut(); - bindings.get().insert(renamed, - DlDef(def)); - } + let value_ribs = this.value_ribs.borrow(); + let length = value_ribs.len(); + let last_rib = value_ribs.get( + length - 1); + last_rib.bindings.borrow_mut() + .insert(renamed, DlDef(def)); bindings_list.insert(renamed, pat_id); } Some(ref mut b) => { @@ -4518,15 +4385,12 @@ struct in scope", None => { let this = &mut *self; { - let mut value_ribs = - this.value_ribs.borrow_mut(); - let length = value_ribs.get().len(); - let last_rib = value_ribs.get().get( + let value_ribs = this.value_ribs.borrow(); + let length = value_ribs.len(); + let last_rib = value_ribs.get( length - 1); - let mut bindings = - last_rib.bindings.borrow_mut(); - bindings.get().insert(renamed, - DlDef(def)); + last_rib.bindings.borrow_mut() + .insert(renamed, DlDef(def)); } } } @@ -4774,31 +4638,26 @@ fn resolve_definition_of_name_in_module(&mut self, // First, search children. self.populate_module_if_necessary(containing_module); - { - let children = containing_module.children.borrow(); - match children.get().find(&name.name) { - Some(child_name_bindings) => { - match child_name_bindings.def_for_namespace(namespace) { - Some(def) => { - // Found it. Stop the search here. - let p = child_name_bindings.defined_in_public_namespace( - namespace); - let lp = if p {LastMod(AllPublic)} else { - LastMod(DependsOn(def_id_of_def(def))) - }; - return ChildNameDefinition(def, lp); - } - None => {} + match containing_module.children.borrow().find(&name.name) { + Some(child_name_bindings) => { + match child_name_bindings.def_for_namespace(namespace) { + Some(def) => { + // Found it. Stop the search here. + let p = child_name_bindings.defined_in_public_namespace( + namespace); + let lp = if p {LastMod(AllPublic)} else { + LastMod(DependsOn(def_id_of_def(def))) + }; + return ChildNameDefinition(def, lp); } + None => {} } - None => {} } + None => {} } // Next, search import resolutions. - let import_resolutions = containing_module.import_resolutions - .borrow(); - match import_resolutions.get().find(&name.name) { + match containing_module.import_resolutions.borrow().find(&name.name) { Some(import_resolution) if import_resolution.is_public.get() => { match (*import_resolution).target_for_namespace(namespace) { Some(target) => { @@ -4823,12 +4682,8 @@ fn resolve_definition_of_name_in_module(&mut self, // Finally, search through external children. if namespace == TypeNS { - let module_opt = { - let external_module_children = - containing_module.external_module_children.borrow(); - external_module_children.get().find_copy(&name.name) - }; - match module_opt { + match containing_module.external_module_children.borrow() + .find_copy(&name.name) { None => {} Some(module) => { match module.def_id.get() { @@ -4892,8 +4747,7 @@ fn resolve_module_relative_path(&mut self, }; match containing_module.kind.get() { TraitModuleKind | ImplModuleKind => { - let method_map = self.method_map.borrow(); - match method_map.get().find(&ident.name) { + match self.method_map.borrow().find(&ident.name) { Some(s) => { match containing_module.def_id.get() { Some(def_id) if s.contains(&def_id) => { @@ -4967,23 +4821,17 @@ fn resolve_identifier_in_local_ribs(&mut self, span: Span) -> Option { // Check the local set of ribs. - let search_result; - match namespace { + let search_result = match namespace { ValueNS => { let renamed = mtwt::resolve(ident); - let mut value_ribs = self.value_ribs.borrow_mut(); - search_result = self.search_ribs(value_ribs.get(), - renamed, - span); + self.search_ribs(&mut *self.value_ribs.borrow_mut(), + renamed, span) } TypeNS => { let name = ident.name; - let mut type_ribs = self.type_ribs.borrow_mut(); - search_result = self.search_ribs(type_ribs.get(), - name, - span); + self.search_ribs(&mut *self.type_ribs.borrow_mut(), name, span) } - } + }; match search_result { Some(DlDef(def)) => { @@ -5060,15 +4908,12 @@ fn find_best_match_for_name(&mut self, name: &str, max_distance: uint) let mut maybes: Vec = Vec::new(); let mut values: Vec = Vec::new(); - let mut j = { - let value_ribs = this.value_ribs.borrow(); - value_ribs.get().len() - }; + let mut j = this.value_ribs.borrow().len(); while j != 0 { j -= 1; let value_ribs = this.value_ribs.borrow(); - let bindings = value_ribs.get().get(j).bindings.borrow(); - for (&k, _) in bindings.get().iter() { + let bindings = value_ribs.get(j).bindings.borrow(); + for (&k, _) in bindings.iter() { maybes.push(token::get_name(k)); values.push(uint::MAX); } @@ -5213,13 +5058,13 @@ fn resolve_expr(&mut self, expr: &Expr) { ExprLoop(_, Some(label)) => { self.with_label_rib(|this| { let def_like = DlDef(DefLabel(expr.id)); + { - let mut label_ribs = this.label_ribs.borrow_mut(); - let length = label_ribs.get().len(); - let rib = label_ribs.get().get(length - 1); - let mut bindings = rib.bindings.borrow_mut(); + let label_ribs = this.label_ribs.borrow(); + let length = label_ribs.len(); + let rib = label_ribs.get(length - 1); let renamed = mtwt::resolve(label); - bindings.get().insert(renamed, def_like); + rib.bindings.borrow_mut().insert(renamed, def_like); } visit::walk_expr(this, expr, ()); @@ -5231,7 +5076,7 @@ fn resolve_expr(&mut self, expr: &Expr) { ExprBreak(Some(label)) | ExprAgain(Some(label)) => { let mut label_ribs = self.label_ribs.borrow_mut(); let renamed = mtwt::resolve(label); - match self.search_ribs(label_ribs.get(), renamed, expr.span) { + match self.search_ribs(&mut *label_ribs, renamed, expr.span) { None => self.resolve_error(expr.span, format!("use of undeclared label `{}`", @@ -5283,8 +5128,7 @@ fn search_for_traits_containing_method(&mut self, name: Ident) -> Vec { let mut found_traits = Vec::new(); let mut search_module = self.current_module; - let method_map = self.method_map.borrow(); - match method_map.get().find(&name.name) { + match self.method_map.borrow().find(&name.name) { Some(candidate_traits) => loop { // Look for the current trait. match self.current_trait_refs { @@ -5305,8 +5149,7 @@ fn search_for_traits_containing_method(&mut self, name: Ident) -> Vec { // Look for trait children. self.populate_module_if_necessary(search_module); - let children = search_module.children.borrow(); - for (_, &child_names) in children.get().iter() { + for (_, &child_names) in search_module.children.borrow().iter() { let def = match child_names.def_for_namespace(TypeNS) { Some(def) => def, None => continue @@ -5324,7 +5167,7 @@ fn search_for_traits_containing_method(&mut self, name: Ident) -> Vec { // Look for imports. let import_resolutions = search_module.import_resolutions .borrow(); - for (_, &import) in import_resolutions.get().iter() { + for (_, &import) in import_resolutions.iter() { let target = match import.target_for_namespace(TypeNS) { None => continue, Some(target) => target, @@ -5369,8 +5212,7 @@ fn record_def(&mut self, node_id: NodeId, (def, lp): (Def, LastPrivate)) { assert!(match lp {LastImport{..} => false, _ => true}, "Import should only be used for `use` directives"); self.last_private.insert(node_id, lp); - let mut def_map = self.def_map.borrow_mut(); - def_map.get().insert_or_update_with(node_id, def, |_, old_value| { + self.def_map.borrow_mut().insert_or_update_with(node_id, def, |_, old_value| { // Resolve appears to "resolve" the same ID multiple // times, so here is a sanity check it at least comes to // the same conclusion! - nmatsakis @@ -5531,14 +5373,13 @@ fn dump_module(&mut self, module_: @Module) { debug!("Children:"); self.populate_module_if_necessary(module_); - let children = module_.children.borrow(); - for (&name, _) in children.get().iter() { + for (&name, _) in module_.children.borrow().iter() { debug!("* {}", token::get_name(name)); } debug!("Import resolutions:"); let import_resolutions = module_.import_resolutions.borrow(); - for (&name, import_resolution) in import_resolutions.get().iter() { + for (&name, import_resolution) in import_resolutions.iter() { let value_repr; match import_resolution.target_for_namespace(ValueNS) { None => { value_repr = ~""; } diff --git a/src/librustc/middle/subst.rs b/src/librustc/middle/subst.rs index 0dd5c2ee10e..c6819dbc919 100644 --- a/src/librustc/middle/subst.rs +++ b/src/librustc/middle/subst.rs @@ -141,7 +141,7 @@ impl Subst for Rc { fn subst_spanned(&self, tcx: &ty::ctxt, substs: &ty::substs, span: Option) -> Rc { - Rc::new(self.deref().subst_spanned(tcx, substs, span)) + Rc::new((**self).subst_spanned(tcx, substs, span)) } } diff --git a/src/librustc/middle/trans/_match.rs b/src/librustc/middle/trans/_match.rs index 31296ba260b..ebb813f6d24 100644 --- a/src/librustc/middle/trans/_match.rs +++ b/src/librustc/middle/trans/_match.rs @@ -355,8 +355,8 @@ fn trans_opt<'a>(bcx: &'a Block<'a>, o: &Opt) -> opt_result<'a> { fn variant_opt(bcx: &Block, pat_id: ast::NodeId) -> Opt { let ccx = bcx.ccx(); - let def_map = ccx.tcx.def_map.borrow(); - match def_map.get().get_copy(&pat_id) { + let def = ccx.tcx.def_map.borrow().get_copy(&pat_id); + match def { ast::DefVariant(enum_id, var_id, _) => { let variants = ty::enum_variants(ccx.tcx(), enum_id); for v in (*variants).iter() { @@ -636,10 +636,7 @@ fn enter_opt<'r,'b>( let answer = match p.node { ast::PatEnum(..) | ast::PatIdent(_, _, None) if pat_is_const(tcx.def_map, p) => { - let const_def = { - let def_map = tcx.def_map.borrow(); - def_map.get().get_copy(&p.id) - }; + let const_def = tcx.def_map.borrow().get_copy(&p.id); let const_def_id = ast_util::def_id_of_def(const_def); if opt_eq(tcx, &lit(ConstLit(const_def_id)), opt) { Some(Vec::new()) @@ -678,11 +675,7 @@ fn enter_opt<'r,'b>( if opt_eq(tcx, &variant_opt(bcx, p.id), opt) { // Look up the struct variant ID. let struct_id; - let defn = { - let def_map = tcx.def_map.borrow(); - def_map.get().get_copy(&p.id) - }; - match defn { + match tcx.def_map.borrow().get_copy(&p.id) { ast::DefVariant(_, found_struct_id, _) => { struct_id = found_struct_id; } @@ -964,10 +957,7 @@ fn add_veclen_to_set(set: &mut Vec , i: uint, ast::PatIdent(..) => { // This is one of: an enum variant, a unit-like struct, or a // variable binding. - let opt_def = { - let def_map = ccx.tcx.def_map.borrow(); - def_map.get().find_copy(&cur.id) - }; + let opt_def = ccx.tcx.def_map.borrow().find_copy(&cur.id); match opt_def { Some(ast::DefVariant(..)) => { add_to_set(ccx.tcx(), &mut found, @@ -987,10 +977,7 @@ fn add_veclen_to_set(set: &mut Vec , i: uint, ast::PatEnum(..) | ast::PatStruct(..) => { // This could be one of: a tuple-like enum variant, a // struct-like enum variant, or a struct. - let opt_def = { - let def_map = ccx.tcx.def_map.borrow(); - def_map.get().find_copy(&cur.id) - }; + let opt_def = ccx.tcx.def_map.borrow().find_copy(&cur.id); match opt_def { Some(ast::DefFn(..)) | Some(ast::DefVariant(..)) => { @@ -1147,8 +1134,7 @@ fn pats_require_rooting(bcx: &Block, m: &[Match], col: uint) -> bool { m.iter().any(|br| { let pat_id = br.pats.get(col).id; let key = root_map_key {id: pat_id, derefs: 0u }; - let root_map = bcx.ccx().maps.root_map.borrow(); - root_map.get().contains_key(&key) + bcx.ccx().maps.root_map.borrow().contains_key(&key) }) } @@ -1184,8 +1170,7 @@ fn any_tuple_struct_pat(bcx: &Block, m: &[Match], col: uint) -> bool { let pat = *br.pats.get(col); match pat.node { ast::PatEnum(_, Some(_)) => { - let def_map = bcx.tcx().def_map.borrow(); - match def_map.get().find(&pat.id) { + match bcx.tcx().def_map.borrow().find(&pat.id) { Some(&ast::DefFn(..)) | Some(&ast::DefStruct(..)) => true, _ => false @@ -1200,7 +1185,7 @@ struct DynamicFailureHandler<'a> { bcx: &'a Block<'a>, sp: Span, msg: InternedString, - finished: @Cell>, + finished: Cell>, } impl<'a> DynamicFailureHandler<'a> { @@ -1387,13 +1372,10 @@ fn insert_lllocals<'a>(bcx: &'a Block<'a>, let datum = Datum(llval, binding_info.ty, Lvalue); fcx.schedule_drop_mem(cleanup_scope, llval, binding_info.ty); - { - debug!("binding {:?} to {}", - binding_info.id, - bcx.val_to_str(llval)); - let mut llmap = bcx.fcx.lllocals.borrow_mut(); - llmap.get().insert(binding_info.id, datum); - } + debug!("binding {:?} to {}", + binding_info.id, + bcx.val_to_str(llval)); + bcx.fcx.lllocals.borrow_mut().insert(binding_info.id, datum); if bcx.sess().opts.debuginfo == FullDebugInfo { debuginfo::create_match_binding_metadata(bcx, @@ -1458,8 +1440,7 @@ fn drop_bindings<'a>(bcx: &'a Block<'a>, data: &ArmData) } TrByRef => {} } - let mut lllocals = bcx.fcx.lllocals.borrow_mut(); - lllocals.get().remove(&binding_info.id); + bcx.fcx.lllocals.borrow_mut().remove(&binding_info.id); } return bcx; } @@ -1946,7 +1927,7 @@ fn trans_match_inner<'a>(scope_cx: &'a Block<'a>, let chk = { if ty::type_is_empty(tcx, t) { // Special case for empty types - let fail_cx = @Cell::new(None); + let fail_cx = Cell::new(None); let fail_handler = ~DynamicFailureHandler { bcx: scope_cx, sp: discr_expr.span, @@ -2096,8 +2077,8 @@ pub fn store_arg<'a>(mut bcx: &'a Block<'a>, // already put it in a temporary alloca and gave it up, unless // we emit extra-debug-info, which requires local allocas :(. let arg_val = arg.add_clean(bcx.fcx, arg_scope); - let mut llmap = bcx.fcx.llargs.borrow_mut(); - llmap.get().insert(pat.id, Datum(arg_val, arg_ty, Lvalue)); + bcx.fcx.llargs.borrow_mut() + .insert(pat.id, Datum(arg_val, arg_ty, Lvalue)); bcx } else { mk_binding_alloca( @@ -2143,7 +2124,7 @@ fn mk_binding_alloca<'a,A>(bcx: &'a Block<'a>, BindLocal => bcx.fcx.lllocals.borrow_mut(), BindArgument => bcx.fcx.llargs.borrow_mut() }; - llmap.get().insert(p_id, datum); + llmap.insert(p_id, datum); bcx } @@ -2219,9 +2200,9 @@ fn bind_irrefutable_pat<'a>( } } ast::PatEnum(_, ref sub_pats) => { - let def_map = bcx.tcx().def_map.borrow(); - match def_map.get().find(&pat.id) { - Some(&ast::DefVariant(enum_id, var_id, _)) => { + let opt_def = bcx.tcx().def_map.borrow().find_copy(&pat.id); + match opt_def { + Some(ast::DefVariant(enum_id, var_id, _)) => { let repr = adt::represent_node(bcx, pat.id); let vinfo = ty::enum_variant_with_id(ccx.tcx(), enum_id, @@ -2238,8 +2219,8 @@ fn bind_irrefutable_pat<'a>( } } } - Some(&ast::DefFn(..)) | - Some(&ast::DefStruct(..)) => { + Some(ast::DefFn(..)) | + Some(ast::DefStruct(..)) => { match *sub_pats { None => { // This is a unit-like struct. Nothing to do here. @@ -2257,7 +2238,7 @@ fn bind_irrefutable_pat<'a>( } } } - Some(&ast::DefStatic(_, false)) => { + Some(ast::DefStatic(_, false)) => { } _ => { // Nothing to do here. diff --git a/src/librustc/middle/trans/adt.rs b/src/librustc/middle/trans/adt.rs index 8ec061fc2f5..1215eba17d7 100644 --- a/src/librustc/middle/trans/adt.rs +++ b/src/librustc/middle/trans/adt.rs @@ -118,18 +118,14 @@ pub fn represent_node(bcx: &Block, node: ast::NodeId) -> @Repr { /// Decides how to represent a given type. pub fn represent_type(cx: &CrateContext, t: ty::t) -> @Repr { debug!("Representing: {}", ty_to_str(cx.tcx(), t)); - { - let adt_reprs = cx.adt_reprs.borrow(); - match adt_reprs.get().find(&t) { - Some(repr) => return *repr, - None => {} - } + match cx.adt_reprs.borrow().find(&t) { + Some(repr) => return *repr, + None => {} } let repr = @represent_type_uncached(cx, t); debug!("Represented as: {:?}", repr) - let mut adt_reprs = cx.adt_reprs.borrow_mut(); - adt_reprs.get().insert(t, repr); + cx.adt_reprs.borrow_mut().insert(t, repr); return repr; } diff --git a/src/librustc/middle/trans/base.rs b/src/librustc/middle/trans/base.rs index 3cdbc38ab07..a00bcdd7037 100644 --- a/src/librustc/middle/trans/base.rs +++ b/src/librustc/middle/trans/base.rs @@ -161,12 +161,9 @@ fn drop(&mut self) { let end = time::precise_time_ns(); let elapsed = ((end - self.start) / 1_000_000) as uint; let iend = self.ccx.stats.n_llvm_insns.get(); - { - let mut fn_stats = self.ccx.stats.fn_stats.borrow_mut(); - fn_stats.get().push((self.name.take_unwrap(), - elapsed, - iend - self.istart)); - } + self.ccx.stats.fn_stats.borrow_mut().push((self.name.take_unwrap(), + elapsed, + iend - self.istart)); self.ccx.stats.n_fns.set(self.ccx.stats.n_fns.get() + 1); // Reset LLVM insn count to avoid compound costs. self.ccx.stats.n_llvm_insns.set(self.istart); @@ -232,21 +229,17 @@ pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef, fn get_extern_rust_fn(ccx: &CrateContext, inputs: &[ty::t], output: ty::t, name: &str, did: ast::DefId) -> ValueRef { - { - let externs = ccx.externs.borrow(); - match externs.get().find_equiv(&name) { - Some(n) => return *n, - None => () - } + match ccx.externs.borrow().find_equiv(&name) { + Some(n) => return *n, + None => () } let f = decl_rust_fn(ccx, false, inputs, output, name); csearch::get_item_attrs(&ccx.sess().cstore, did, |meta_items| { - set_llvm_fn_attrs(meta_items.iter().map(|&x| attr::mk_attr(x)).to_owned_vec(), f) + set_llvm_fn_attrs(meta_items.iter().map(|&x| attr::mk_attr(x)).collect::<~[_]>(), f) }); - let mut externs = ccx.externs.borrow_mut(); - externs.get().insert(name.to_owned(), f); + ccx.externs.borrow_mut().insert(name.to_owned(), f); f } @@ -448,19 +441,15 @@ pub fn get_tydesc_simple(ccx: &CrateContext, t: ty::t) -> ValueRef { } pub fn get_tydesc(ccx: &CrateContext, t: ty::t) -> @tydesc_info { - { - let tydescs = ccx.tydescs.borrow(); - match tydescs.get().find(&t) { - Some(&inf) => return inf, - _ => { } - } + match ccx.tydescs.borrow().find(&t) { + Some(&inf) => return inf, + _ => { } } ccx.stats.n_static_tydescs.set(ccx.stats.n_static_tydescs.get() + 1u); let inf = glue::declare_tydesc(ccx, t); - let mut tydescs = ccx.tydescs.borrow_mut(); - tydescs.get().insert(t, inf); + ccx.tydescs.borrow_mut().insert(t, inf); return inf; } @@ -519,11 +508,10 @@ pub fn set_no_split_stack(f: ValueRef) { // Double-check that we never ask LLVM to declare the same symbol twice. It // silently mangles such symbols, breaking our linkage model. pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: ~str) { - let mut all_llvm_symbols = ccx.all_llvm_symbols.borrow_mut(); - if all_llvm_symbols.get().contains(&sym) { + if ccx.all_llvm_symbols.borrow().contains(&sym) { ccx.sess().bug(~"duplicate LLVM symbol: " + sym); } - all_llvm_symbols.get().insert(sym); + ccx.all_llvm_symbols.borrow_mut().insert(sym); } @@ -561,11 +549,8 @@ pub fn get_res_dtor(ccx: &CrateContext, ty::lookup_item_type(tcx, parent_id).ty); let llty = type_of_dtor(ccx, class_ty); - { - let mut externs = ccx.externs.borrow_mut(); - get_extern_fn(externs.get(), ccx.llmod, name, - lib::llvm::CCallConv, llty, ty::mk_nil()) - } + get_extern_fn(&mut *ccx.externs.borrow_mut(), ccx.llmod, name, + lib::llvm::CCallConv, llty, ty::mk_nil()) } } @@ -889,9 +874,8 @@ pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> Val let c = foreign::llvm_calling_convention(ccx, fn_ty.abis); let cconv = c.unwrap_or(lib::llvm::CCallConv); let llty = type_of_fn_from_ty(ccx, t); - let mut externs = ccx.externs.borrow_mut(); - get_extern_fn(externs.get(), ccx.llmod, name, - cconv, llty, fn_ty.sig.output) + get_extern_fn(&mut *ccx.externs.borrow_mut(), ccx.llmod, + name, cconv, llty, fn_ty.sig.output) } } } @@ -904,8 +888,8 @@ pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> Val } _ => { let llty = type_of(ccx, t); - let mut externs = ccx.externs.borrow_mut(); - get_extern_const(externs.get(), ccx.llmod, name, llty) + get_extern_const(&mut *ccx.externs.borrow_mut(), ccx.llmod, name, + llty) } } } @@ -1709,8 +1693,7 @@ pub fn trans_item(ccx: &CrateContext, item: &ast::Item) { static"); } - let const_values = ccx.const_values.borrow(); - let v = const_values.get().get_copy(&item.id); + let v = ccx.const_values.borrow().get_copy(&item.id); unsafe { if !(llvm::LLVMConstIntGetZExtValue(v) != 0) { ccx.sess().span_fatal(expr.span, "static assertion failed"); @@ -1766,7 +1749,7 @@ pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) { fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: ~str, node_id: ast::NodeId, llfn: ValueRef) { - ccx.item_symbols.borrow_mut().get().insert(node_id, sym); + ccx.item_symbols.borrow_mut().insert(node_id, sym); if !ccx.reachable.contains(&node_id) { lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage); @@ -1919,241 +1902,222 @@ fn exported_name(ccx: &CrateContext, id: ast::NodeId, pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef { debug!("get_item_val(id=`{:?}`)", id); - let val = { - let item_vals = ccx.item_vals.borrow(); - item_vals.get().find_copy(&id) - }; + match ccx.item_vals.borrow().find_copy(&id) { + Some(v) => return v, + None => {} + } - match val { - Some(v) => v, - None => { - let mut foreign = false; - let item = ccx.tcx.map.get(id); - let val = match item { - ast_map::NodeItem(i) => { - let ty = ty::node_id_to_type(ccx.tcx(), i.id); - let sym = exported_name(ccx, id, ty, i.attrs.as_slice()); - - let v = match i.node { - ast::ItemStatic(_, _, expr) => { - // If this static came from an external crate, then - // we need to get the symbol from csearch instead of - // using the current crate's name/version - // information in the hash of the symbol - debug!("making {}", sym); - let (sym, is_local) = { - let external_srcs = ccx.external_srcs - .borrow(); - match external_srcs.get().find(&i.id) { - Some(&did) => { - debug!("but found in other crate..."); - (csearch::get_symbol(&ccx.sess().cstore, - did), false) - } - None => (sym, true) - } - }; - - // We need the translated value here, because for enums the - // LLVM type is not fully determined by the Rust type. - let (v, inlineable) = consts::const_expr(ccx, expr, is_local); - { - let mut const_values = ccx.const_values - .borrow_mut(); - const_values.get().insert(id, v); - } - let mut inlineable = inlineable; - - unsafe { - let llty = llvm::LLVMTypeOf(v); - let g = sym.with_c_str(|buf| { - llvm::LLVMAddGlobal(ccx.llmod, llty, buf) - }); - - if !ccx.reachable.contains(&id) { - lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage); - } - - // Apply the `unnamed_addr` attribute if - // requested - if attr::contains_name(i.attrs.as_slice(), - "address_insignificant") { - if ccx.reachable.contains(&id) { - ccx.sess().span_bug(i.span, - "insignificant static is reachable"); - } - lib::llvm::SetUnnamedAddr(g, true); - - // This is a curious case where we must make - // all of these statics inlineable. If a - // global is tagged as - // address_insignificant, then LLVM won't - // coalesce globals unless they have an - // internal linkage type. This means that - // external crates cannot use this global. - // This is a problem for things like inner - // statics in generic functions, because the - // function will be inlined into another - // crate and then attempt to link to the - // static in the original crate, only to - // find that it's not there. On the other - // side of inlininig, the crates knows to - // not declare this static as - // available_externally (because it isn't) - inlineable = true; - } - - if attr::contains_name(i.attrs.as_slice(), - "thread_local") { - lib::llvm::set_thread_local(g, true); - } - - if !inlineable { - debug!("{} not inlined", sym); - let mut non_inlineable_statics = - ccx.non_inlineable_statics - .borrow_mut(); - non_inlineable_statics.get().insert(id); - } - - let mut item_symbols = ccx.item_symbols - .borrow_mut(); - item_symbols.get().insert(i.id, sym); - g + let mut foreign = false; + let item = ccx.tcx.map.get(id); + let val = match item { + ast_map::NodeItem(i) => { + let ty = ty::node_id_to_type(ccx.tcx(), i.id); + let sym = exported_name(ccx, id, ty, i.attrs.as_slice()); + + let v = match i.node { + ast::ItemStatic(_, _, expr) => { + // If this static came from an external crate, then + // we need to get the symbol from csearch instead of + // using the current crate's name/version + // information in the hash of the symbol + debug!("making {}", sym); + let (sym, is_local) = { + match ccx.external_srcs.borrow().find(&i.id) { + Some(&did) => { + debug!("but found in other crate..."); + (csearch::get_symbol(&ccx.sess().cstore, + did), false) } + None => (sym, true) } + }; - ast::ItemFn(_, purity, _, _, _) => { - let llfn = if purity != ast::ExternFn { - register_fn(ccx, i.span, sym, i.id, ty) - } else { - foreign::register_rust_fn_with_foreign_abi(ccx, - i.span, - sym, - i.id) - }; - set_llvm_fn_attrs(i.attrs.as_slice(), llfn); - llfn - } + // We need the translated value here, because for enums the + // LLVM type is not fully determined by the Rust type. + let (v, inlineable) = consts::const_expr(ccx, expr, is_local); + ccx.const_values.borrow_mut().insert(id, v); + let mut inlineable = inlineable; - _ => fail!("get_item_val: weird result in table") - }; + unsafe { + let llty = llvm::LLVMTypeOf(v); + let g = sym.with_c_str(|buf| { + llvm::LLVMAddGlobal(ccx.llmod, llty, buf) + }); - match attr::first_attr_value_str_by_name(i.attrs - .as_slice(), - "link_section") { - Some(sect) => unsafe { - sect.get().with_c_str(|buf| { - llvm::LLVMSetSection(v, buf); - }) - }, - None => () - } + if !ccx.reachable.contains(&id) { + lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage); + } - v - } + // Apply the `unnamed_addr` attribute if + // requested + if attr::contains_name(i.attrs.as_slice(), + "address_insignificant") { + if ccx.reachable.contains(&id) { + ccx.sess().span_bug(i.span, + "insignificant static is reachable"); + } + lib::llvm::SetUnnamedAddr(g, true); + + // This is a curious case where we must make + // all of these statics inlineable. If a + // global is tagged as + // address_insignificant, then LLVM won't + // coalesce globals unless they have an + // internal linkage type. This means that + // external crates cannot use this global. + // This is a problem for things like inner + // statics in generic functions, because the + // function will be inlined into another + // crate and then attempt to link to the + // static in the original crate, only to + // find that it's not there. On the other + // side of inlininig, the crates knows to + // not declare this static as + // available_externally (because it isn't) + inlineable = true; + } - ast_map::NodeTraitMethod(trait_method) => { - debug!("get_item_val(): processing a NodeTraitMethod"); - match *trait_method { - ast::Required(_) => { - ccx.sess().bug("unexpected variant: required trait method in \ - get_item_val()"); + if attr::contains_name(i.attrs.as_slice(), + "thread_local") { + lib::llvm::set_thread_local(g, true); } - ast::Provided(m) => { - register_method(ccx, id, m) + + if !inlineable { + debug!("{} not inlined", sym); + ccx.non_inlineable_statics.borrow_mut() + .insert(id); } + + ccx.item_symbols.borrow_mut().insert(i.id, sym); + g } } - ast_map::NodeMethod(m) => { - register_method(ccx, id, m) + ast::ItemFn(_, purity, _, _, _) => { + let llfn = if purity != ast::ExternFn { + register_fn(ccx, i.span, sym, i.id, ty) + } else { + foreign::register_rust_fn_with_foreign_abi(ccx, + i.span, + sym, + i.id) + }; + set_llvm_fn_attrs(i.attrs.as_slice(), llfn); + llfn } - ast_map::NodeForeignItem(ni) => { - foreign = true; + _ => fail!("get_item_val: weird result in table") + }; - match ni.node { - ast::ForeignItemFn(..) => { - let abis = ccx.tcx.map.get_foreign_abis(id); - foreign::register_foreign_item_fn(ccx, abis, ni) - } - ast::ForeignItemStatic(..) => { - foreign::register_static(ccx, ni) - } - } - } + match attr::first_attr_value_str_by_name(i.attrs.as_slice(), + "link_section") { + Some(sect) => unsafe { + sect.get().with_c_str(|buf| { + llvm::LLVMSetSection(v, buf); + }) + }, + None => () + } - ast_map::NodeVariant(ref v) => { - let llfn; - match v.node.kind { - ast::TupleVariantKind(ref args) => { - assert!(args.len() != 0u); - let ty = ty::node_id_to_type(ccx.tcx(), id); - let parent = ccx.tcx.map.get_parent(id); - let enm = ccx.tcx.map.expect_item(parent); - let sym = exported_name(ccx, - id, - ty, - enm.attrs.as_slice()); - - llfn = match enm.node { - ast::ItemEnum(_, _) => { - register_fn(ccx, (*v).span, sym, id, ty) - } - _ => fail!("NodeVariant, shouldn't happen") - }; - } - ast::StructVariantKind(_) => { - fail!("struct variant kind unexpected in get_item_val") - } - } - set_inline_hint(llfn); - llfn + v + } + + ast_map::NodeTraitMethod(trait_method) => { + debug!("get_item_val(): processing a NodeTraitMethod"); + match *trait_method { + ast::Required(_) => { + ccx.sess().bug("unexpected variant: required trait method in \ + get_item_val()"); + } + ast::Provided(m) => { + register_method(ccx, id, m) } + } + } - ast_map::NodeStructCtor(struct_def) => { - // Only register the constructor if this is a tuple-like struct. - match struct_def.ctor_id { - None => { - ccx.sess().bug("attempt to register a constructor of \ - a non-tuple-like struct") - } - Some(ctor_id) => { - let parent = ccx.tcx.map.get_parent(id); - let struct_item = ccx.tcx.map.expect_item(parent); - let ty = ty::node_id_to_type(ccx.tcx(), ctor_id); - let sym = exported_name(ccx, - id, - ty, - struct_item.attrs - .as_slice()); - let llfn = register_fn(ccx, struct_item.span, - sym, ctor_id, ty); - set_inline_hint(llfn); - llfn - } - } + ast_map::NodeMethod(m) => { + register_method(ccx, id, m) + } + + ast_map::NodeForeignItem(ni) => { + foreign = true; + + match ni.node { + ast::ForeignItemFn(..) => { + let abis = ccx.tcx.map.get_foreign_abis(id); + foreign::register_foreign_item_fn(ccx, abis, ni) + } + ast::ForeignItemStatic(..) => { + foreign::register_static(ccx, ni) } + } + } - ref variant => { - ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}", - variant)) + ast_map::NodeVariant(ref v) => { + let llfn; + let args = match v.node.kind { + ast::TupleVariantKind(ref args) => args, + ast::StructVariantKind(_) => { + fail!("struct variant kind unexpected in get_item_val") + } + }; + assert!(args.len() != 0u); + let ty = ty::node_id_to_type(ccx.tcx(), id); + let parent = ccx.tcx.map.get_parent(id); + let enm = ccx.tcx.map.expect_item(parent); + let sym = exported_name(ccx, + id, + ty, + enm.attrs.as_slice()); + + llfn = match enm.node { + ast::ItemEnum(_, _) => { + register_fn(ccx, (*v).span, sym, id, ty) } + _ => fail!("NodeVariant, shouldn't happen") }; + set_inline_hint(llfn); + llfn + } - // foreign items (extern fns and extern statics) don't have internal - // linkage b/c that doesn't quite make sense. Otherwise items can - // have internal linkage if they're not reachable. - if !foreign && !ccx.reachable.contains(&id) { - lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage); - } + ast_map::NodeStructCtor(struct_def) => { + // Only register the constructor if this is a tuple-like struct. + let ctor_id = match struct_def.ctor_id { + None => { + ccx.sess().bug("attempt to register a constructor of \ + a non-tuple-like struct") + } + Some(ctor_id) => ctor_id, + }; + let parent = ccx.tcx.map.get_parent(id); + let struct_item = ccx.tcx.map.expect_item(parent); + let ty = ty::node_id_to_type(ccx.tcx(), ctor_id); + let sym = exported_name(ccx, + id, + ty, + struct_item.attrs + .as_slice()); + let llfn = register_fn(ccx, struct_item.span, + sym, ctor_id, ty); + set_inline_hint(llfn); + llfn + } - let mut item_vals = ccx.item_vals.borrow_mut(); - item_vals.get().insert(id, val); - val + ref variant => { + ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}", + variant)) } + }; + + // foreign items (extern fns and extern statics) don't have internal + // linkage b/c that doesn't quite make sense. Otherwise items can + // have internal linkage if they're not reachable. + if !foreign && !ccx.reachable.contains(&id) { + lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage); } + + ccx.item_vals.borrow_mut().insert(id, val); + val } fn register_method(ccx: &CrateContext, id: ast::NodeId, @@ -2542,11 +2506,10 @@ pub fn trans_crate(krate: ast::Crate, println!("n_inlines: {}", ccx.stats.n_inlines.get()); println!("n_closures: {}", ccx.stats.n_closures.get()); println!("fn stats:"); - let mut fn_stats = ccx.stats.fn_stats.borrow_mut(); - fn_stats.get().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| { + ccx.stats.fn_stats.borrow_mut().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| { insns_b.cmp(&insns_a) }); - for tuple in fn_stats.get().iter() { + for tuple in ccx.stats.fn_stats.borrow().iter() { match *tuple { (ref name, ms, insns) => { println!("{} insns, {} ms, {}", insns, ms, *name); @@ -2555,8 +2518,7 @@ pub fn trans_crate(krate: ast::Crate, } } if ccx.sess().count_llvm_insns() { - let llvm_insns = ccx.stats.llvm_insns.borrow(); - for (k, v) in llvm_insns.get().iter() { + for (k, v) in ccx.stats.llvm_insns.borrow().iter() { println!("{:7u} {}", *v, *k); } } @@ -2566,7 +2528,7 @@ pub fn trans_crate(krate: ast::Crate, let llmod = ccx.llmod; let mut reachable: Vec<~str> = ccx.reachable.iter().filter_map(|id| { - ccx.item_symbols.borrow().get().find(id).map(|s| s.to_owned()) + ccx.item_symbols.borrow().find(id).map(|s| s.to_owned()) }).collect(); // Make sure that some other crucial symbols are not eliminated from the diff --git a/src/librustc/middle/trans/builder.rs b/src/librustc/middle/trans/builder.rs index 059582e95d4..4526f3505be 100644 --- a/src/librustc/middle/trans/builder.rs +++ b/src/librustc/middle/trans/builder.rs @@ -79,11 +79,11 @@ pub fn count_insn(&self, category: &str) { s.push_char('/'); s.push_str(category); - let n = match h.get().find(&s) { + let n = match h.find(&s) { Some(&n) => n, _ => 0u }; - h.get().insert(s, n+1u); + h.insert(s, n+1u); }) } } diff --git a/src/librustc/middle/trans/callee.rs b/src/librustc/middle/trans/callee.rs index 78ecc7cc2b3..92b97cdfc9f 100644 --- a/src/librustc/middle/trans/callee.rs +++ b/src/librustc/middle/trans/callee.rs @@ -170,16 +170,11 @@ pub fn trans_fn_ref(bcx: &Block, def_id: ast::DefId, node: ExprOrMethodCall) -> let _icx = push_ctxt("trans_fn_ref"); let type_params = node_id_type_params(bcx, node); - let vtables = match node { - ExprId(id) => node_vtables(bcx, id), - MethodCall(ref method_call) => { - if method_call.autoderef == 0 { - node_vtables(bcx, method_call.expr_id) - } else { - None - } - } + let vtable_key = match node { + ExprId(id) => MethodCall::expr(id), + MethodCall(method_call) => method_call }; + let vtables = node_vtables(bcx, vtable_key); debug!("trans_fn_ref(def_id={}, node={:?}, type_params={}, vtables={})", def_id.repr(bcx.tcx()), node, type_params.repr(bcx.tcx()), vtables.repr(bcx.tcx())); @@ -399,7 +394,7 @@ pub fn trans_fn_ref_with_vtables( let ref_ty = match node { ExprId(id) => node_id_type(bcx, id), MethodCall(method_call) => { - let t = bcx.ccx().maps.method_map.borrow().get().get(&method_call).ty; + let t = bcx.ccx().maps.method_map.borrow().get(&method_call).ty; monomorphize_type(bcx, t) } }; @@ -482,7 +477,7 @@ pub fn trans_method_call<'a>( let _icx = push_ctxt("trans_method_call"); debug!("trans_method_call(call_ex={})", call_ex.repr(bcx.tcx())); let method_call = MethodCall::expr(call_ex.id); - let method_ty = bcx.ccx().maps.method_map.borrow().get().get(&method_call).ty; + let method_ty = bcx.ccx().maps.method_map.borrow().get(&method_call).ty; trans_call_inner( bcx, Some(common::expr_info(call_ex)), diff --git a/src/librustc/middle/trans/cleanup.rs b/src/librustc/middle/trans/cleanup.rs index 75f236d5028..a977ea99ef1 100644 --- a/src/librustc/middle/trans/cleanup.rs +++ b/src/librustc/middle/trans/cleanup.rs @@ -194,8 +194,7 @@ fn top_loop_scope(&self) -> ast::NodeId { * Returns the id of the top-most loop scope */ - let scopes = self.scopes.borrow(); - for scope in scopes.get().iter().rev() { + for scope in self.scopes.borrow().iter().rev() { match scope.kind { LoopScopeKind(id, _) => { return id; @@ -316,8 +315,7 @@ fn schedule_clean_in_ast_scope(&self, debug!("schedule_clean_in_ast_scope(cleanup_scope={:?})", cleanup_scope); - let mut scopes = self.scopes.borrow_mut(); - for scope in scopes.get().mut_iter().rev() { + for scope in self.scopes.borrow_mut().mut_iter().rev() { if scope.kind.is_ast_with_id(cleanup_scope) { scope.cleanups.push(cleanup); scope.clear_cached_exits(); @@ -347,7 +345,7 @@ fn schedule_clean_in_custom_scope(&self, assert!(self.is_valid_custom_scope(custom_scope)); let mut scopes = self.scopes.borrow_mut(); - let scope = scopes.get().get_mut(custom_scope.index); + let scope = scopes.get_mut(custom_scope.index); scope.cleanups.push(cleanup); scope.clear_cached_exits(); } @@ -358,8 +356,7 @@ fn needs_invoke(&self) -> bool { * execute on failure. */ - let scopes = self.scopes.borrow(); - scopes.get().iter().rev().any(|s| s.needs_invoke()) + self.scopes.borrow().iter().rev().any(|s| s.needs_invoke()) } fn get_landing_pad(&'a self) -> BasicBlockRef { @@ -405,8 +402,7 @@ fn top_ast_scope(&self) -> Option { /*! * Returns the id of the current top-most AST scope, if any. */ - let scopes = self.scopes.borrow(); - for scope in scopes.get().iter().rev() { + for scope in self.scopes.borrow().iter().rev() { match scope.kind { CustomScopeKind | LoopScopeKind(..) => {} AstScopeKind(i) => { @@ -418,20 +414,18 @@ fn top_ast_scope(&self) -> Option { } fn top_nonempty_cleanup_scope(&self) -> Option { - let scopes = self.scopes.borrow(); - scopes.get().iter().rev().position(|s| !s.cleanups.is_empty()) + self.scopes.borrow().iter().rev().position(|s| !s.cleanups.is_empty()) } fn is_valid_to_pop_custom_scope(&self, custom_scope: CustomScopeIndex) -> bool { - let scopes = self.scopes.borrow(); self.is_valid_custom_scope(custom_scope) && - custom_scope.index == scopes.get().len() - 1 + custom_scope.index == self.scopes.borrow().len() - 1 } fn is_valid_custom_scope(&self, custom_scope: CustomScopeIndex) -> bool { let scopes = self.scopes.borrow(); - custom_scope.index < scopes.get().len() && - scopes.get().get(custom_scope.index).kind.is_temp() + custom_scope.index < scopes.len() && + scopes.get(custom_scope.index).kind.is_temp() } fn trans_scope_cleanups(&self, // cannot borrow self, will recurse @@ -449,13 +443,11 @@ fn trans_scope_cleanups(&self, // cannot borrow self, will recurse } fn scopes_len(&self) -> uint { - let scopes = self.scopes.borrow(); - scopes.get().len() + self.scopes.borrow().len() } fn push_scope(&self, scope: CleanupScope<'a>) { - let mut scopes = self.scopes.borrow_mut(); - scopes.get().push(scope); + self.scopes.borrow_mut().push(scope) } fn pop_scope(&self) -> CleanupScope<'a> { @@ -463,13 +455,11 @@ fn pop_scope(&self) -> CleanupScope<'a> { self.top_scope(|s| s.block_name("")), self.scopes_len() - 1); - let mut scopes = self.scopes.borrow_mut(); - scopes.get().pop().unwrap() + self.scopes.borrow_mut().pop().unwrap() } fn top_scope(&self, f: |&CleanupScope<'a>| -> R) -> R { - let scopes = self.scopes.borrow(); - f(scopes.get().last().unwrap()) + f(self.scopes.borrow().last().unwrap()) } fn trans_cleanups_to_exit_scope(&'a self, @@ -653,7 +643,7 @@ fn get_or_create_landing_pad(&'a self) -> BasicBlockRef { // Check if a landing pad block exists; if not, create one. { let mut scopes = self.scopes.borrow_mut(); - let last_scope = scopes.get().mut_last().unwrap(); + let last_scope = scopes.mut_last().unwrap(); match last_scope.cached_landing_pad { Some(llbb) => { return llbb; } None => { diff --git a/src/librustc/middle/trans/closure.rs b/src/librustc/middle/trans/closure.rs index 8b4348a8fcb..fb8f6d4df29 100644 --- a/src/librustc/middle/trans/closure.rs +++ b/src/librustc/middle/trans/closure.rs @@ -317,10 +317,7 @@ fn load_environment<'a>(bcx: &'a Block<'a>, cdata_ty: ty::t, } let def_id = ast_util::def_id_of_def(cap_var.def); - { - let mut llupvars = bcx.fcx.llupvars.borrow_mut(); - llupvars.get().insert(def_id.node, upvarptr); - } + bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvarptr); for &env_pointer_alloca in env_pointer_alloca.iter() { debuginfo::create_captured_var_metadata( @@ -395,13 +392,13 @@ pub fn trans_expr_fn<'a>( // set an inline hint for all closures set_inline_hint(llfn); - let cap_vars = ccx.maps.capture_map.borrow().get().get_copy(&id); + let cap_vars = ccx.maps.capture_map.borrow().get_copy(&id); let ClosureResult {llbox, cdata_ty, bcx} = - build_closure(bcx, cap_vars.deref().as_slice(), sigil); + build_closure(bcx, cap_vars.as_slice(), sigil); trans_closure(ccx, decl, body, llfn, bcx.fcx.param_substs, id, [], ty::ty_fn_ret(fty), - |bcx| load_environment(bcx, cdata_ty, cap_vars.deref().as_slice(), sigil)); + |bcx| load_environment(bcx, cdata_ty, cap_vars.as_slice(), sigil)); fill_fn_pair(bcx, dest_addr, llfn, llbox); bcx @@ -423,12 +420,9 @@ pub fn get_wrapper_for_bare_fn(ccx: &CrateContext, } }; - { - let cache = ccx.closure_bare_wrapper_cache.borrow(); - match cache.get().find(&fn_ptr) { - Some(&llval) => return llval, - None => {} - } + match ccx.closure_bare_wrapper_cache.borrow().find(&fn_ptr) { + Some(&llval) => return llval, + None => {} } let tcx = ccx.tcx(); @@ -457,10 +451,7 @@ pub fn get_wrapper_for_bare_fn(ccx: &CrateContext, decl_rust_fn(ccx, true, f.sig.inputs.as_slice(), f.sig.output, name) }; - { - let mut cache = ccx.closure_bare_wrapper_cache.borrow_mut(); - cache.get().insert(fn_ptr, llfn); - } + ccx.closure_bare_wrapper_cache.borrow_mut().insert(fn_ptr, llfn); // This is only used by statics inlined from a different crate. if !is_local { diff --git a/src/librustc/middle/trans/common.rs b/src/librustc/middle/trans/common.rs index 40ab85a91bf..78700bab3f2 100644 --- a/src/librustc/middle/trans/common.rs +++ b/src/librustc/middle/trans/common.rs @@ -465,8 +465,7 @@ pub fn expr_kind(&self, e: &ast::Expr) -> ty::ExprKind { } pub fn def(&self, nid: ast::NodeId) -> ast::Def { - let def_map = self.tcx().def_map.borrow(); - match def_map.get().find(&nid) { + match self.tcx().def_map.borrow().find(&nid) { Some(&v) => v, None => { self.tcx().sess.bug(format!( @@ -584,12 +583,9 @@ pub fn C_u8(ccx: &CrateContext, i: uint) -> ValueRef { // our boxed-and-length-annotated strings. pub fn C_cstr(cx: &CrateContext, s: InternedString) -> ValueRef { unsafe { - { - let const_cstr_cache = cx.const_cstr_cache.borrow(); - match const_cstr_cache.get().find(&s) { - Some(&llval) => return llval, - None => () - } + match cx.const_cstr_cache.borrow().find(&s) { + Some(&llval) => return llval, + None => () } let sc = llvm::LLVMConstStringInContext(cx.llcx, @@ -605,8 +601,7 @@ pub fn C_cstr(cx: &CrateContext, s: InternedString) -> ValueRef { llvm::LLVMSetGlobalConstant(g, True); lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage); - let mut const_cstr_cache = cx.const_cstr_cache.borrow_mut(); - const_cstr_cache.get().insert(s, g); + cx.const_cstr_cache.borrow_mut().insert(s, g); g } } @@ -715,7 +710,7 @@ pub fn is_null(val: ValueRef) -> bool { } // Used to identify cached monomorphized functions and vtables -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] pub enum mono_param_id { mono_precise(ty::t, Option<@Vec >), mono_any, @@ -725,7 +720,7 @@ pub enum mono_param_id { datum::RvalueMode), } -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] pub enum MonoDataClass { MonoBits, // Anything not treated differently from arbitrary integer data MonoNonNull, // Non-null pointers (used for optional-pointer optimization) @@ -747,7 +742,7 @@ pub fn mono_data_classify(t: ty::t) -> MonoDataClass { } } -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] pub struct mono_id_ { def: ast::DefId, params: Vec } @@ -795,7 +790,7 @@ pub fn expr_ty(bcx: &Block, ex: &ast::Expr) -> ty::t { pub fn expr_ty_adjusted(bcx: &Block, ex: &ast::Expr) -> ty::t { let tcx = bcx.tcx(); - let t = ty::expr_ty_adjusted(tcx, ex, bcx.ccx().maps.method_map.borrow().get()); + let t = ty::expr_ty_adjusted(tcx, ex, &*bcx.ccx().maps.method_map.borrow()); monomorphize_type(bcx, t) } @@ -814,7 +809,7 @@ pub fn node_id_type_params(bcx: &Block, node: ExprOrMethodCall) -> Vec { let params = match node { ExprId(id) => ty::node_id_to_type_params(tcx, id), MethodCall(method_call) => { - bcx.ccx().maps.method_map.borrow().get().get(&method_call).substs.tps.clone() + bcx.ccx().maps.method_map.borrow().get(&method_call).substs.tps.clone() } }; @@ -834,10 +829,10 @@ pub fn node_id_type_params(bcx: &Block, node: ExprOrMethodCall) -> Vec { } } -pub fn node_vtables(bcx: &Block, id: ast::NodeId) +pub fn node_vtables(bcx: &Block, id: typeck::MethodCall) -> Option { let vtable_map = bcx.ccx().maps.vtable_map.borrow(); - let raw_vtables = vtable_map.get().find(&id); + let raw_vtables = vtable_map.find(&id); raw_vtables.map(|vts| resolve_vtables_in_fn_ctxt(bcx.fcx, *vts)) } @@ -942,7 +937,7 @@ pub fn filename_and_line_num_from_span(bcx: &Block, span: Span) -> (ValueRef, ValueRef) { let loc = bcx.sess().codemap().lookup_char_pos(span.lo); let filename_cstr = C_cstr(bcx.ccx(), - token::intern_and_get_ident(loc.file.deref().name)); + token::intern_and_get_ident(loc.file.name)); let filename = build::PointerCast(bcx, filename_cstr, Type::i8p(bcx.ccx())); let line = C_int(bcx.ccx(), loc.line as int); (filename, line) diff --git a/src/librustc/middle/trans/consts.rs b/src/librustc/middle/trans/consts.rs index 49f07e140a3..dc154206e71 100644 --- a/src/librustc/middle/trans/consts.rs +++ b/src/librustc/middle/trans/consts.rs @@ -77,15 +77,14 @@ pub fn const_lit(cx: &CrateContext, e: &ast::Expr, lit: ast::Lit) ast::LitBool(b) => C_bool(cx, b), ast::LitNil => C_nil(cx), ast::LitStr(ref s, _) => C_str_slice(cx, (*s).clone()), - ast::LitBinary(ref data) => C_binary_slice(cx, data.deref().as_slice()), + ast::LitBinary(ref data) => C_binary_slice(cx, data.as_slice()), } } pub fn const_ptrcast(cx: &CrateContext, a: ValueRef, t: Type) -> ValueRef { unsafe { let b = llvm::LLVMConstPointerCast(a, t.ptr_to().to_ref()); - let mut const_globals = cx.const_globals.borrow_mut(); - assert!(const_globals.get().insert(b as int, a)); + assert!(cx.const_globals.borrow_mut().insert(b as int, a)); b } } @@ -118,8 +117,7 @@ fn const_addr_of(cx: &CrateContext, cv: ValueRef) -> ValueRef { } fn const_deref_ptr(cx: &CrateContext, v: ValueRef) -> ValueRef { - let const_globals = cx.const_globals.borrow(); - let v = match const_globals.get().find(&(v as int)) { + let v = match cx.const_globals.borrow().find(&(v as int)) { Some(&v) => v, None => v }; @@ -163,10 +161,7 @@ fn const_deref(cx: &CrateContext, v: ValueRef, t: ty::t, explicit: bool) pub fn get_const_val(cx: &CrateContext, mut def_id: ast::DefId) -> (ValueRef, bool) { - let contains_key = { - let const_values = cx.const_values.borrow(); - const_values.get().contains_key(&def_id.node) - }; + let contains_key = cx.const_values.borrow().contains_key(&def_id.node); if !ast_util::is_local(def_id) || !contains_key { if !ast_util::is_local(def_id) { def_id = inline::maybe_instantiate_inline(cx, def_id); @@ -180,10 +175,8 @@ pub fn get_const_val(cx: &CrateContext, } } - let const_values = cx.const_values.borrow(); - let non_inlineable_statics = cx.non_inlineable_statics.borrow(); - (const_values.get().get_copy(&def_id.node), - !non_inlineable_statics.get().contains(&def_id.node)) + (cx.const_values.borrow().get_copy(&def_id.node), + !cx.non_inlineable_statics.borrow().contains(&def_id.node)) } pub fn const_expr(cx: &CrateContext, e: &ast::Expr, is_local: bool) -> (ValueRef, bool) { @@ -192,12 +185,9 @@ pub fn const_expr(cx: &CrateContext, e: &ast::Expr, is_local: bool) -> (ValueRef let mut inlineable = inlineable; let ety = ty::expr_ty(cx.tcx(), e); let ety_adjusted = ty::expr_ty_adjusted(cx.tcx(), e, - cx.maps.method_map.borrow().get()); - let adjustment = { - let adjustments = cx.tcx.adjustments.borrow(); - adjustments.get().find_copy(&e.id) - }; - match adjustment { + &*cx.maps.method_map.borrow()); + let opt_adj = cx.tcx.adjustments.borrow().find_copy(&e.id); + match opt_adj { None => { } Some(adj) => { match *adj { @@ -424,7 +414,7 @@ fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr, } ast::ExprField(base, field, _) => { let bt = ty::expr_ty_adjusted(cx.tcx(), base, - cx.maps.method_map.borrow().get()); + &*cx.maps.method_map.borrow()); let brepr = adt::represent_type(cx, bt); let (bv, inlineable) = const_expr(cx, base, is_local); expr::with_field_tys(cx.tcx(), bt, None, |discr, field_tys| { @@ -435,7 +425,7 @@ fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr, ast::ExprIndex(base, index) => { let bt = ty::expr_ty_adjusted(cx.tcx(), base, - cx.maps.method_map.borrow().get()); + &*cx.maps.method_map.borrow()); let (bv, inlineable) = const_expr(cx, base, is_local); let iv = match const_eval::eval_const_expr(cx.tcx(), index) { const_eval::const_int(i) => i as u64, @@ -548,7 +538,7 @@ fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr, }; expr::with_field_tys(tcx, ety, Some(e.id), |discr, field_tys| { - let cs = field_tys.iter().enumerate() + let (cs, inlineable) = slice::unzip(field_tys.iter().enumerate() .map(|(ix, &field_ty)| { match fs.iter().find(|f| field_ty.ident.name == f.ident.node.name) { Some(f) => const_expr(cx, (*f).expr, is_local), @@ -562,8 +552,7 @@ fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr, } } } - }).to_owned_vec(); - let (cs, inlineable) = slice::unzip(cs.move_iter()); + })); (adt::trans_const(cx, repr, discr, cs), inlineable.iter().fold(true, |a, &b| a && b)) }) @@ -624,11 +613,7 @@ fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr, // Assert that there are no type parameters in this path. assert!(pth.segments.iter().all(|seg| seg.types.is_empty())); - let tcx = cx.tcx(); - let opt_def = { - let def_map = tcx.def_map.borrow(); - def_map.get().find_copy(&e.id) - }; + let opt_def = cx.tcx().def_map.borrow().find_copy(&e.id); match opt_def { Some(ast::DefFn(def_id, _purity)) => { if !ast_util::is_local(def_id) { @@ -661,11 +646,7 @@ fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr, } } ast::ExprCall(callee, ref args) => { - let tcx = cx.tcx(); - let opt_def = { - let def_map = tcx.def_map.borrow(); - def_map.get().find_copy(&callee.id) - }; + let opt_def = cx.tcx().def_map.borrow().find_copy(&callee.id); match opt_def { Some(ast::DefStruct(_)) => { let ety = ty::expr_ty(cx.tcx(), e); @@ -702,8 +683,7 @@ pub fn trans_const(ccx: &CrateContext, m: ast::Mutability, id: ast::NodeId) { let g = base::get_item_val(ccx, id); // At this point, get_item_val has already translated the // constant's initializer to determine its LLVM type. - let const_values = ccx.const_values.borrow(); - let v = const_values.get().get_copy(&id); + let v = ccx.const_values.borrow().get_copy(&id); llvm::LLVMSetInitializer(g, v); if m != ast::MutMutable { llvm::LLVMSetGlobalConstant(g, True); diff --git a/src/librustc/middle/trans/controlflow.rs b/src/librustc/middle/trans/controlflow.rs index 2796eaeb129..8e55319013b 100644 --- a/src/librustc/middle/trans/controlflow.rs +++ b/src/librustc/middle/trans/controlflow.rs @@ -273,8 +273,7 @@ pub fn trans_break_cont<'a>(bcx: &'a Block<'a>, let loop_id = match opt_label { None => fcx.top_loop_scope(), Some(_) => { - let def_map = bcx.tcx().def_map.borrow(); - match def_map.get().find(&expr_id) { + match bcx.tcx().def_map.borrow().find(&expr_id) { Some(&ast::DefLabel(loop_id)) => loop_id, ref r => { bcx.tcx().sess.bug(format!("{:?} in def-map for label", r)) @@ -335,7 +334,7 @@ pub fn trans_fail<'a>( let v_fail_str = C_cstr(ccx, fail_str); let _icx = push_ctxt("trans_fail_value"); let loc = bcx.sess().codemap().lookup_char_pos(sp.lo); - let v_filename = C_cstr(ccx, token::intern_and_get_ident(loc.file.deref().name)); + let v_filename = C_cstr(ccx, token::intern_and_get_ident(loc.file.name)); let v_line = loc.line as int; let v_str = PointerCast(bcx, v_fail_str, Type::i8p(ccx)); let v_filename = PointerCast(bcx, v_filename, Type::i8p(ccx)); diff --git a/src/librustc/middle/trans/datum.rs b/src/librustc/middle/trans/datum.rs index c334971db59..4ca2b5a47b0 100644 --- a/src/librustc/middle/trans/datum.rs +++ b/src/librustc/middle/trans/datum.rs @@ -82,7 +82,7 @@ impl Drop for Rvalue { fn drop(&mut self) { } } -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] pub enum RvalueMode { /// `val` is a pointer to the actual value (and thus has type *T) ByRef, diff --git a/src/librustc/middle/trans/debuginfo.rs b/src/librustc/middle/trans/debuginfo.rs index dce7e85742d..9f5959e05de 100644 --- a/src/librustc/middle/trans/debuginfo.rs +++ b/src/librustc/middle/trans/debuginfo.rs @@ -294,15 +294,12 @@ pub fn create_local_var_metadata(bcx: &Block, local: &ast::Local) { pat_util::pat_bindings(def_map, local.pat, |_, node_id, span, path_ref| { let var_ident = ast_util::path_to_ident(path_ref); - let datum = { - let lllocals = bcx.fcx.lllocals.borrow(); - match lllocals.get().find_copy(&node_id) { - Some(datum) => datum, - None => { - bcx.sess().span_bug(span, - format!("no entry in lllocals table for {:?}", - node_id)); - } + let datum = match bcx.fcx.lllocals.borrow().find_copy(&node_id) { + Some(datum) => datum, + None => { + bcx.sess().span_bug(span, + format!("no entry in lllocals table for {:?}", + node_id)); } }; @@ -436,15 +433,12 @@ pub fn create_argument_metadata(bcx: &Block, arg: &ast::Arg) { let scope_metadata = bcx.fcx.debug_context.get_ref(cx, arg.pat.span).fn_metadata; pat_util::pat_bindings(def_map, arg.pat, |_, node_id, span, path_ref| { - let llarg = { - let llargs = bcx.fcx.llargs.borrow(); - match llargs.get().find_copy(&node_id) { - Some(v) => v, - None => { - bcx.sess().span_bug(span, - format!("no entry in llargs table for {:?}", - node_id)); - } + let llarg = match bcx.fcx.llargs.borrow().find_copy(&node_id) { + Some(v) => v, + None => { + bcx.sess().span_bug(span, + format!("no entry in llargs table for {:?}", + node_id)); } }; @@ -616,7 +610,7 @@ pub fn create_function_debug_context(cx: &CrateContext, } let loc = span_start(cx, span); - let file_metadata = file_metadata(cx, loc.file.deref().name); + let file_metadata = file_metadata(cx, loc.file.name); let function_type_metadata = unsafe { let fn_signature = get_function_signature(cx, fn_ast_id, fn_decl, param_substs, span); @@ -686,14 +680,11 @@ pub fn create_function_debug_context(cx: &CrateContext, }; let arg_pats = fn_decl.inputs.map(|arg_ref| arg_ref.pat); - { - let mut scope_map = fn_debug_context.scope_map.borrow_mut(); - populate_scope_map(cx, - arg_pats.as_slice(), - top_level_block, - fn_metadata, - scope_map.get()); - } + populate_scope_map(cx, + arg_pats.as_slice(), + top_level_block, + 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); @@ -939,7 +930,7 @@ fn declare_local(bcx: &Block, span: Span) { let cx: &CrateContext = bcx.ccx(); - let filename = span_start(cx, span).file.deref().name.clone(); + let filename = span_start(cx, span).file.name.clone(); let file_metadata = file_metadata(cx, filename); let name = token::get_ident(variable_ident); @@ -1014,12 +1005,9 @@ fn declare_local(bcx: &Block, } fn file_metadata(cx: &CrateContext, full_path: &str) -> DIFile { - { - let created_files = debug_context(cx).created_files.borrow(); - match created_files.get().find_equiv(&full_path) { - Some(file_metadata) => return *file_metadata, - None => () - } + match debug_context(cx).created_files.borrow().find_equiv(&full_path) { + Some(file_metadata) => return *file_metadata, + None => () } debug!("file_metadata: {}", full_path); @@ -1043,7 +1031,7 @@ fn file_metadata(cx: &CrateContext, full_path: &str) -> DIFile { }); let mut created_files = debug_context(cx).created_files.borrow_mut(); - created_files.get().insert(full_path.to_owned(), file_metadata); + created_files.insert(full_path.to_owned(), file_metadata); return file_metadata; } @@ -1053,9 +1041,7 @@ fn scope_metadata(fcx: &FunctionContext, span: Span) -> DIScope { let scope_map = &fcx.debug_context.get_ref(fcx.ccx, span).scope_map; - let scope_map = scope_map.borrow(); - - match scope_map.get().find_copy(&node_id) { + match scope_map.borrow().find_copy(&node_id) { Some(scope_metadata) => scope_metadata, None => { let node = fcx.ccx.tcx.map.get(node_id); @@ -1195,7 +1181,7 @@ fn prepare_struct_metadata(cx: &CrateContext, let (containing_scope, definition_span) = get_namespace_and_span_for_item(cx, def_id); - let file_name = span_start(cx, definition_span).file.deref().name.clone(); + let file_name = span_start(cx, definition_span).file.name.clone(); let file_metadata = file_metadata(cx, file_name); let struct_metadata_stub = create_struct_stub(cx, @@ -1243,10 +1229,8 @@ fn finalize(&self, cx: &CrateContext) -> DICompositeType { ref member_description_factory } => { // Insert the stub into the cache in order to allow recursive references ... - { - let mut created_types = debug_context(cx).created_types.borrow_mut(); - created_types.get().insert(cache_id, metadata_stub); - } + debug_context(cx).created_types.borrow_mut() + .insert(cache_id, metadata_stub); // ... then create the member descriptions ... let member_descriptions = member_description_factory.create_member_descriptions(cx); @@ -1292,7 +1276,7 @@ fn prepare_tuple_metadata(cx: &CrateContext, let tuple_llvm_type = type_of::type_of(cx, tuple_type); let loc = span_start(cx, span); - let file_metadata = file_metadata(cx, loc.file.deref().name); + let file_metadata = file_metadata(cx, loc.file.name); UnfinishedMetadata { cache_id: cache_id_for_type(tuple_type), @@ -1452,7 +1436,7 @@ fn prepare_enum_metadata(cx: &CrateContext, let (containing_scope, definition_span) = get_namespace_and_span_for_item(cx, enum_def_id); let loc = span_start(cx, definition_span); - let file_metadata = file_metadata(cx, loc.file.deref().name); + let file_metadata = file_metadata(cx, loc.file.name); // For empty enums there is an early exit. Just describe it as an empty struct with the // appropriate type name @@ -1649,12 +1633,12 @@ fn set_members_of_composite_type(cx: &CrateContext, { let mut composite_types_completed = debug_context(cx).composite_types_completed.borrow_mut(); - if composite_types_completed.get().contains(&composite_type_metadata) { + if composite_types_completed.contains(&composite_type_metadata) { cx.sess().span_bug(definition_span, "debuginfo::set_members_of_composite_type() - \ Already completed forward declaration \ re-encountered."); } else { - composite_types_completed.get().insert(composite_type_metadata); + composite_types_completed.insert(composite_type_metadata); } } @@ -1791,7 +1775,7 @@ fn boxed_type_metadata(cx: &CrateContext, ]; let loc = span_start(cx, span); - let file_metadata = file_metadata(cx, loc.file.deref().name); + let file_metadata = file_metadata(cx, loc.file.name); return composite_type_metadata( cx, @@ -1892,7 +1876,7 @@ fn vec_metadata(cx: &CrateContext, assert!(member_descriptions.len() == member_llvm_types.len()); let loc = span_start(cx, span); - let file_metadata = file_metadata(cx, loc.file.deref().name); + let file_metadata = file_metadata(cx, loc.file.name); composite_type_metadata( cx, @@ -1943,7 +1927,7 @@ fn vec_slice_metadata(cx: &CrateContext, assert!(member_descriptions.len() == member_llvm_types.len()); let loc = span_start(cx, span); - let file_metadata = file_metadata(cx, loc.file.deref().name); + let file_metadata = file_metadata(cx, loc.file.name); return composite_type_metadata( cx, @@ -1969,7 +1953,7 @@ fn subroutine_type_metadata(cx: &CrateContext, span: Span) -> DICompositeType { let loc = span_start(cx, span); - let file_metadata = file_metadata(cx, loc.file.deref().name); + let file_metadata = file_metadata(cx, loc.file.name); let mut signature_metadata: Vec = Vec::with_capacity(signature.inputs.len() + 1); @@ -2015,7 +1999,7 @@ fn trait_metadata(cx: &CrateContext, let (containing_scope, definition_span) = get_namespace_and_span_for_item(cx, def_id); - let file_name = span_start(cx, definition_span).file.deref().name.clone(); + let file_name = span_start(cx, definition_span).file.name.clone(); let file_metadata = file_metadata(cx, file_name); let trait_llvm_type = type_of::type_of(cx, trait_type); @@ -2035,12 +2019,9 @@ fn type_metadata(cx: &CrateContext, -> DIType { let cache_id = cache_id_for_type(t); - { - let created_types = debug_context(cx).created_types.borrow(); - match created_types.get().find(&cache_id) { - Some(type_metadata) => return *type_metadata, - None => () - } + match debug_context(cx).created_types.borrow().find(&cache_id) { + Some(type_metadata) => return *type_metadata, + None => () } fn create_pointer_to_box_metadata(cx: &CrateContext, @@ -2149,8 +2130,7 @@ fn create_pointer_to_box_metadata(cx: &CrateContext, _ => cx.sess().bug(format!("debuginfo: unexpected type in type_metadata: {:?}", sty)) }; - let mut created_types = debug_context(cx).created_types.borrow_mut(); - created_types.get().insert(cache_id, type_metadata); + debug_context(cx).created_types.borrow_mut().insert(cache_id, type_metadata); type_metadata } @@ -2250,8 +2230,7 @@ fn fn_should_be_ignored(fcx: &FunctionContext) -> bool { } fn assert_type_for_node_id(cx: &CrateContext, node_id: ast::NodeId, error_span: Span) { - let node_types = cx.tcx.node_types.borrow(); - if !node_types.get().contains_key(&(node_id as uint)) { + if !cx.tcx.node_types.borrow().contains_key(&(node_id as uint)) { cx.sess().span_bug(error_span, "debuginfo: Could not find type for node id!"); } } @@ -2318,7 +2297,7 @@ fn with_new_scope(cx: &CrateContext, &mut HashMap|) { // Create a new lexical scope and push it onto the stack let loc = cx.sess().codemap().lookup_char_pos(scope_span.lo); - let file_metadata = file_metadata(cx, loc.file.deref().name); + let file_metadata = file_metadata(cx, loc.file.name); let parent_scope = scope_stack.last().unwrap().scope_metadata; let scope_metadata = unsafe { @@ -2435,7 +2414,7 @@ fn walk_pattern(cx: &CrateContext, if need_new_scope { // Create a new lexical scope and push it onto the stack let loc = cx.sess().codemap().lookup_char_pos(pat.span.lo); - let file_metadata = file_metadata(cx, loc.file.deref().name); + let file_metadata = file_metadata(cx, loc.file.name); let parent_scope = scope_stack.last().unwrap().scope_metadata; let scope_metadata = unsafe { @@ -2781,10 +2760,8 @@ fn namespace_for_item(cx: &CrateContext, def_id: ast::DefId) -> @NamespaceTreeNo let name = path_element.name(); current_key.push(name); - let existing_node = { - let namespace_map = debug_context(cx).namespace_map.borrow(); - namespace_map.get().find_copy(¤t_key) - }; + let existing_node = debug_context(cx).namespace_map.borrow() + .find_copy(¤t_key); let current_node = match existing_node { Some(existing_node) => existing_node, None => { @@ -2813,11 +2790,8 @@ fn namespace_for_item(cx: &CrateContext, def_id: ast::DefId) -> @NamespaceTreeNo parent: parent_node, }; - { - let mut namespace_map = debug_context(cx).namespace_map - .borrow_mut(); - namespace_map.get().insert(current_key.clone(), node); - } + debug_context(cx).namespace_map.borrow_mut() + .insert(current_key.clone(), node); node } diff --git a/src/librustc/middle/trans/expr.rs b/src/librustc/middle/trans/expr.rs index 543f2bcf968..5baf4056206 100644 --- a/src/librustc/middle/trans/expr.rs +++ b/src/librustc/middle/trans/expr.rs @@ -106,12 +106,7 @@ pub fn trans_into<'a>(bcx: &'a Block<'a>, let mut bcx = bcx; - let is_adjusted = { - let adjustments = bcx.tcx().adjustments.borrow(); - adjustments.get().contains_key(&expr.id) - }; - - if is_adjusted { + if bcx.tcx().adjustments.borrow().contains_key(&expr.id) { // use trans, which may be less efficient but // which will perform the adjustments: let datum = unpack_datum!(bcx, trans(bcx, expr)); @@ -172,14 +167,11 @@ fn apply_adjustments<'a>(bcx: &'a Block<'a>, let mut bcx = bcx; let mut datum = datum; - let adjustment = { - let adjustments = bcx.tcx().adjustments.borrow(); - match adjustments.get().find_copy(&expr.id) { - None => { - return DatumBlock(bcx, datum); - } - Some(adj) => { adj } + let adjustment = match bcx.tcx().adjustments.borrow().find_copy(&expr.id) { + None => { + return DatumBlock(bcx, datum); } + Some(adj) => { adj } }; debug!("unadjusted datum for expr {}: {}", expr.id, datum.to_str(bcx.ccx())); @@ -210,7 +202,7 @@ fn apply_adjustments<'a>(bcx: &'a Block<'a>, Some(AutoBorrowFn(..)) => { let adjusted_ty = ty::adjust_ty(bcx.tcx(), expr.span, expr.id, datum.ty, Some(adjustment), |method_call| { - bcx.ccx().maps.method_map.borrow().get() + bcx.ccx().maps.method_map.borrow() .find(&method_call).map(|method| method.ty) }); unpack_datum!(bcx, auto_borrow_fn(bcx, adjusted_ty, datum)) @@ -222,7 +214,7 @@ fn apply_adjustments<'a>(bcx: &'a Block<'a>, } AutoObject(..) => { let adjusted_ty = ty::expr_ty_adjusted(bcx.tcx(), expr, - bcx.ccx().maps.method_map.borrow().get()); + &*bcx.ccx().maps.method_map.borrow()); let scratch = rvalue_scratch_datum(bcx, adjusted_ty, "__adjust"); bcx = meth::trans_trait_cast( bcx, datum, expr.id, SaveIn(scratch.val)); @@ -567,13 +559,10 @@ fn get_val<'a>(bcx: &'a Block<'a>, did: ast::DefId, const_ty: ty::t) let pty = type_of::type_of(bcx.ccx(), const_ty).ptr_to(); PointerCast(bcx, val, pty) } else { - { - let extern_const_values = bcx.ccx().extern_const_values.borrow(); - match extern_const_values.get().find(&did) { - None => {} // Continue. - Some(llval) => { - return *llval; - } + match bcx.ccx().extern_const_values.borrow().find(&did) { + None => {} // Continue. + Some(llval) => { + return *llval; } } @@ -587,8 +576,8 @@ fn get_val<'a>(bcx: &'a Block<'a>, did: ast::DefId, const_ty: ty::t) llty.to_ref(), buf) }); - let mut extern_const_values = bcx.ccx().extern_const_values.borrow_mut(); - extern_const_values.get().insert(did, llval); + bcx.ccx().extern_const_values.borrow_mut() + .insert(did, llval); llval } } @@ -898,8 +887,7 @@ pub fn trans_local_var<'a>(bcx: &'a Block<'a>, ast::DefUpvar(nid, _, _, _) => { // Can't move upvars, so this is never a ZeroMemLastUse. let local_ty = node_id_type(bcx, nid); - let llupvars = bcx.fcx.llupvars.borrow(); - match llupvars.get().find(&nid) { + match bcx.fcx.llupvars.borrow().find(&nid) { Some(&val) => Datum(val, local_ty, Lvalue), None => { bcx.sess().bug(format!( @@ -908,12 +896,10 @@ pub fn trans_local_var<'a>(bcx: &'a Block<'a>, } } ast::DefArg(nid, _) => { - let llargs = bcx.fcx.llargs.borrow(); - take_local(bcx, llargs.get(), nid) + take_local(bcx, &*bcx.fcx.llargs.borrow(), nid) } ast::DefLocal(nid, _) | ast::DefBinding(nid, _) => { - let lllocals = bcx.fcx.lllocals.borrow(); - take_local(bcx, lllocals.get(), nid) + take_local(bcx, &*bcx.fcx.lllocals.borrow(), nid) } _ => { bcx.sess().unimpl(format!( @@ -965,11 +951,8 @@ pub fn with_field_tys(tcx: &ty::ctxt, ty.repr(tcx))); } Some(node_id) => { - let opt_def = { - let def_map = tcx.def_map.borrow(); - def_map.get().get_copy(&node_id) - }; - match opt_def { + let def = tcx.def_map.borrow().get_copy(&node_id); + match def { ast::DefVariant(enum_id, variant_id, _) => { let variant_info = ty::enum_variant_with_id( tcx, enum_id, variant_id); @@ -1159,7 +1142,7 @@ fn trans_unary<'a>(bcx: &'a Block<'a>, // Otherwise, we should be in the RvalueDpsExpr path. assert!( op == ast::UnDeref || - !ccx.maps.method_map.borrow().get().contains_key(&method_call)); + !ccx.maps.method_map.borrow().contains_key(&method_call)); let un_ty = expr_ty(bcx, expr); @@ -1436,7 +1419,7 @@ fn trans_binary<'a>(bcx: &'a Block<'a>, let ccx = bcx.ccx(); // if overloaded, would be RvalueDpsExpr - assert!(!ccx.maps.method_map.borrow().get().contains_key(&MethodCall::expr(expr.id))); + assert!(!ccx.maps.method_map.borrow().contains_key(&MethodCall::expr(expr.id))); match op { ast::BiAnd => { @@ -1476,7 +1459,7 @@ fn trans_overloaded_op<'a, 'b>( rhs: Option<(Datum, ast::NodeId)>, dest: Option) -> Result<'a> { - let method_ty = bcx.ccx().maps.method_map.borrow().get().get(&method_call).ty; + let method_ty = bcx.ccx().maps.method_map.borrow().get(&method_call).ty; callee::trans_call_inner(bcx, Some(expr_info(expr)), monomorphize_type(bcx, method_ty), @@ -1644,7 +1627,7 @@ fn trans_assign_op<'a>( debug!("trans_assign_op(expr={})", bcx.expr_to_str(expr)); // User-defined operator methods cannot be used with `+=` etc right now - assert!(!bcx.ccx().maps.method_map.borrow().get().contains_key(&MethodCall::expr(expr.id))); + assert!(!bcx.ccx().maps.method_map.borrow().contains_key(&MethodCall::expr(expr.id))); // Evaluate LHS (destination), which should be an lvalue let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, dst, "assign_op")); @@ -1722,7 +1705,7 @@ fn deref_once<'a>(bcx: &'a Block<'a>, expr_id: expr.id, autoderef: derefs as u32 }; - let method_ty = ccx.maps.method_map.borrow().get() + let method_ty = ccx.maps.method_map.borrow() .find(&method_call).map(|method| method.ty); let datum = match method_ty { Some(method_ty) => { diff --git a/src/librustc/middle/trans/foreign.rs b/src/librustc/middle/trans/foreign.rs index 3c808cf4232..3fd677b34d9 100644 --- a/src/librustc/middle/trans/foreign.rs +++ b/src/librustc/middle/trans/foreign.rs @@ -239,16 +239,12 @@ pub fn register_foreign_item_fn(ccx: &CrateContext, abis: AbiSet, // Create the LLVM value for the C extern fn let llfn_ty = lltype_for_fn_from_foreign_types(ccx, &tys); - let llfn; - { - let mut externs = ccx.externs.borrow_mut(); - llfn = base::get_extern_fn(externs.get(), + let llfn = base::get_extern_fn(&mut *ccx.externs.borrow_mut(), ccx.llmod, lname.get(), cc, llfn_ty, tys.fn_sig.output); - }; add_argument_attributes(&tys, llfn); llfn @@ -470,8 +466,8 @@ pub fn trans_foreign_mod(ccx: &CrateContext, foreign_mod: &ast::ForeignMod) { } let lname = link_name(foreign_item); - let mut item_symbols = ccx.item_symbols.borrow_mut(); - item_symbols.get().insert(foreign_item.id, lname.get().to_owned()); + ccx.item_symbols.borrow_mut().insert(foreign_item.id, + lname.get().to_owned()); } } diff --git a/src/librustc/middle/trans/glue.rs b/src/librustc/middle/trans/glue.rs index 836433e1dae..da9d06b9a75 100644 --- a/src/librustc/middle/trans/glue.rs +++ b/src/librustc/middle/trans/glue.rs @@ -128,7 +128,7 @@ pub fn drop_ty_immediate<'a>(bcx: &'a Block<'a>, v: ValueRef, t: ty::t) pub fn get_drop_glue(ccx: &CrateContext, t: ty::t) -> ValueRef { let t = get_drop_glue_type(ccx, t); - match ccx.drop_glues.borrow().get().find(&t) { + match ccx.drop_glues.borrow().find(&t) { Some(&glue) => return glue, _ => { } } @@ -136,7 +136,7 @@ pub fn get_drop_glue(ccx: &CrateContext, t: ty::t) -> ValueRef { let llfnty = Type::glue_fn(ccx, type_of(ccx, t).ptr_to()); let glue = declare_generic_glue(ccx, t, llfnty, "drop"); - ccx.drop_glues.borrow_mut().get().insert(t, glue); + ccx.drop_glues.borrow_mut().insert(t, glue); make_generic_glue(ccx, t, glue, make_drop_glue, "drop"); @@ -476,8 +476,7 @@ pub fn emit_tydescs(ccx: &CrateContext) { // As of this point, allow no more tydescs to be created. ccx.finished_tydescs.set(true); let glue_fn_ty = Type::generic_glue_fn(ccx).ptr_to(); - let mut tyds = ccx.tydescs.borrow_mut(); - for (_, &val) in tyds.get().iter() { + for (_, &val) in ccx.tydescs.borrow().iter() { let ti = val; // Each of the glue functions needs to be cast to a generic type diff --git a/src/librustc/middle/trans/inline.rs b/src/librustc/middle/trans/inline.rs index ee810a652dc..b96d71366e0 100644 --- a/src/librustc/middle/trans/inline.rs +++ b/src/librustc/middle/trans/inline.rs @@ -22,21 +22,18 @@ pub fn maybe_instantiate_inline(ccx: &CrateContext, fn_id: ast::DefId) -> ast::DefId { let _icx = push_ctxt("maybe_instantiate_inline"); - { - let external = ccx.external.borrow(); - match external.get().find(&fn_id) { - Some(&Some(node_id)) => { - // Already inline - debug!("maybe_instantiate_inline({}): already inline as node id {}", - ty::item_path_str(ccx.tcx(), fn_id), node_id); - return local_def(node_id); - } - Some(&None) => { - return fn_id; // Not inlinable - } - None => { - // Not seen yet - } + match ccx.external.borrow().find(&fn_id) { + Some(&Some(node_id)) => { + // Already inline + debug!("maybe_instantiate_inline({}): already inline as node id {}", + ty::item_path_str(ccx.tcx(), fn_id), node_id); + return local_def(node_id); + } + Some(&None) => { + return fn_id; // Not inlinable + } + None => { + // Not seen yet } } @@ -46,17 +43,12 @@ pub fn maybe_instantiate_inline(ccx: &CrateContext, fn_id: ast::DefId) |a,b,c,d| astencode::decode_inlined_item(a, b, &ccx.maps, c, d)); return match csearch_result { csearch::not_found => { - let mut external = ccx.external.borrow_mut(); - external.get().insert(fn_id, None); + ccx.external.borrow_mut().insert(fn_id, None); fn_id } csearch::found(ast::IIItem(item)) => { - { - let mut external = ccx.external.borrow_mut(); - let mut external_srcs = ccx.external_srcs.borrow_mut(); - external.get().insert(fn_id, Some(item.id)); - external_srcs.get().insert(item.id, fn_id); - } + ccx.external.borrow_mut().insert(fn_id, Some(item.id)); + ccx.external_srcs.borrow_mut().insert(item.id, fn_id); ccx.stats.n_inlines.set(ccx.stats.n_inlines.get() + 1); trans_item(ccx, item); @@ -85,21 +77,13 @@ pub fn maybe_instantiate_inline(ccx: &CrateContext, fn_id: ast::DefId) local_def(item.id) } csearch::found(ast::IIForeign(item)) => { - { - let mut external = ccx.external.borrow_mut(); - let mut external_srcs = ccx.external_srcs.borrow_mut(); - external.get().insert(fn_id, Some(item.id)); - external_srcs.get().insert(item.id, fn_id); - } + ccx.external.borrow_mut().insert(fn_id, Some(item.id)); + ccx.external_srcs.borrow_mut().insert(item.id, fn_id); local_def(item.id) } csearch::found_parent(parent_id, ast::IIItem(item)) => { - { - let mut external = ccx.external.borrow_mut(); - let mut external_srcs = ccx.external_srcs.borrow_mut(); - external.get().insert(parent_id, Some(item.id)); - external_srcs.get().insert(item.id, parent_id); - } + ccx.external.borrow_mut().insert(parent_id, Some(item.id)); + ccx.external_srcs.borrow_mut().insert(item.id, parent_id); let mut my_id = 0; match item.node { @@ -108,16 +92,14 @@ pub fn maybe_instantiate_inline(ccx: &CrateContext, fn_id: ast::DefId) let vs_there = ty::enum_variants(ccx.tcx(), parent_id); for (here, there) in vs_here.iter().zip(vs_there.iter()) { if there.id == fn_id { my_id = here.id.node; } - let mut external = ccx.external.borrow_mut(); - external.get().insert(there.id, Some(here.id.node)); + ccx.external.borrow_mut().insert(there.id, Some(here.id.node)); } } ast::ItemStruct(ref struct_def, _) => { match struct_def.ctor_id { None => {} Some(ctor_id) => { - let mut external = ccx.external.borrow_mut(); - let _ = external.get().insert(fn_id, Some(ctor_id)); + ccx.external.borrow_mut().insert(fn_id, Some(ctor_id)); my_id = ctor_id; } } @@ -133,12 +115,8 @@ pub fn maybe_instantiate_inline(ccx: &CrateContext, fn_id: ast::DefId) with a non-item parent"); } csearch::found(ast::IIMethod(impl_did, is_provided, mth)) => { - { - let mut external = ccx.external.borrow_mut(); - let mut external_srcs = ccx.external_srcs.borrow_mut(); - external.get().insert(fn_id, Some(mth.id)); - external_srcs.get().insert(mth.id, fn_id); - } + ccx.external.borrow_mut().insert(fn_id, Some(mth.id)); + ccx.external_srcs.borrow_mut().insert(mth.id, fn_id); ccx.stats.n_inlines.set(ccx.stats.n_inlines.get() + 1); diff --git a/src/librustc/middle/trans/meth.rs b/src/librustc/middle/trans/meth.rs index 918037e2181..4701f38c09a 100644 --- a/src/librustc/middle/trans/meth.rs +++ b/src/librustc/middle/trans/meth.rs @@ -100,7 +100,7 @@ pub fn trans_method_callee<'a>( let _icx = push_ctxt("meth::trans_method_callee"); let (origin, method_ty) = match bcx.ccx().maps.method_map - .borrow().get().find(&method_call) { + .borrow().find(&method_call) { Some(method) => { debug!("trans_method_callee({:?}, method={})", method_call, method.repr(bcx.tcx())); @@ -208,7 +208,8 @@ pub fn trans_static_method_callee(bcx: &Block, debug!("trans_static_method_callee: method_id={:?}, expr_id={:?}, \ name={}", method_id, expr_id, token::get_name(mname)); - let vtbls = ccx.maps.vtable_map.borrow().get().get_copy(&expr_id); + let vtable_key = MethodCall::expr(expr_id); + let vtbls = ccx.maps.vtable_map.borrow().get_copy(&vtable_key); let vtbls = resolve_vtables_in_fn_ctxt(bcx.fcx, vtbls); match vtbls.get(bound_index).get(0) { @@ -239,23 +240,18 @@ pub fn trans_static_method_callee(bcx: &Block, pub fn method_with_name(ccx: &CrateContext, impl_id: ast::DefId, name: ast::Name) -> ast::DefId { - { - let impl_method_cache = ccx.impl_method_cache.borrow(); - let meth_id_opt = impl_method_cache.get().find_copy(&(impl_id, name)); - match meth_id_opt { - Some(m) => return m, - None => {} - } + match ccx.impl_method_cache.borrow().find_copy(&(impl_id, name)) { + Some(m) => return m, + None => {} } - let impls = ccx.tcx.impls.borrow(); - let imp = impls.get().find(&impl_id) - .expect("could not find impl while translating"); + let imp = ccx.tcx.impls.borrow(); + let imp = imp.find(&impl_id) + .expect("could not find impl while translating"); let meth = imp.methods.iter().find(|m| m.ident.name == name) - .expect("could not find method while translating"); + .expect("could not find method while translating"); - let mut impl_method_cache = ccx.impl_method_cache.borrow_mut(); - impl_method_cache.get().insert((impl_id, name), meth.def_id); + ccx.impl_method_cache.borrow_mut().insert((impl_id, name), meth.def_id); meth.def_id } @@ -332,16 +328,11 @@ fn combine_impl_and_methods_tps(bcx: &Block, // Now, do the same work for the vtables. The vtables might not // exist, in which case we need to make them. - let vtables = match node { - ExprId(id) => node_vtables(bcx, id), - MethodCall(method_call) => { - if method_call.autoderef == 0 { - node_vtables(bcx, method_call.expr_id) - } else { - None - } - } + let vtable_key = match node { + ExprId(id) => MethodCall::expr(id), + MethodCall(method_call) => method_call }; + let vtables = node_vtables(bcx, vtable_key); let r_m_origins = match vtables { Some(vt) => vt, None => @Vec::from_elem(node_substs.len(), @Vec::new()) @@ -478,12 +469,9 @@ pub fn get_vtable(bcx: &Block, // Check the cache. let hash_id = (self_ty, vtable_id(ccx, origins.get(0))); - { - let vtables = ccx.vtables.borrow(); - match vtables.get().find(&hash_id) { - Some(&val) => { return val } - None => { } - } + match ccx.vtables.borrow().find(&hash_id) { + Some(&val) => { return val } + None => { } } // Not in the cache. Actually build it. @@ -507,8 +495,7 @@ pub fn get_vtable(bcx: &Block, let drop_glue = glue::get_drop_glue(ccx, self_ty); let vtable = make_vtable(ccx, drop_glue, methods.as_slice()); - let mut vtables = ccx.vtables.borrow_mut(); - vtables.get().insert(hash_id, vtable); + ccx.vtables.borrow_mut().insert(hash_id, vtable); return vtable; } @@ -606,15 +593,8 @@ pub fn trans_trait_cast<'a>(bcx: &'a Block<'a>, bcx = datum.store_to(bcx, llboxdest); // Store the vtable into the second half of pair. - // This is structured a bit funny because of dynamic borrow failures. - let origins = { - let res = { - let vtable_map = ccx.maps.vtable_map.borrow(); - *vtable_map.get().get(&id) - }; - let res = resolve_vtables_in_fn_ctxt(bcx.fcx, res); - *res.get(0) - }; + let res = *ccx.maps.vtable_map.borrow().get(&MethodCall::expr(id)); + let origins = *resolve_vtables_in_fn_ctxt(bcx.fcx, res).get(0); let vtable = get_vtable(bcx, v_ty, origins); let llvtabledest = GEPi(bcx, lldest, [0u, abi::trt_field_vtable]); let llvtabledest = PointerCast(bcx, llvtabledest, val_ty(vtable).ptr_to()); diff --git a/src/librustc/middle/trans/monomorphize.rs b/src/librustc/middle/trans/monomorphize.rs index 85c0e38e0f6..80a7fe2facf 100644 --- a/src/librustc/middle/trans/monomorphize.rs +++ b/src/librustc/middle/trans/monomorphize.rs @@ -74,16 +74,13 @@ pub fn monomorphic_fn(ccx: &CrateContext, psubsts.repr(ccx.tcx()), hash_id); - { - let monomorphized = ccx.monomorphized.borrow(); - match monomorphized.get().find(&hash_id) { - Some(&val) => { + match ccx.monomorphized.borrow().find(&hash_id) { + Some(&val) => { debug!("leaving monomorphic fn {}", - ty::item_path_str(ccx.tcx(), fn_id)); + ty::item_path_str(ccx.tcx(), fn_id)); return (val, must_cast); - } - None => () } + None => () } let tpt = ty::lookup_item_type(ccx.tcx(), fn_id); @@ -164,7 +161,7 @@ pub fn monomorphic_fn(ccx: &CrateContext, let depth; { let mut monomorphizing = ccx.monomorphizing.borrow_mut(); - depth = match monomorphizing.get().find(&fn_id) { + depth = match monomorphizing.find(&fn_id) { Some(&d) => d, None => 0 }; @@ -176,7 +173,7 @@ pub fn monomorphic_fn(ccx: &CrateContext, "reached the recursion limit during monomorphization"); } - monomorphizing.get().insert(fn_id, depth + 1); + monomorphizing.insert(fn_id, depth + 1); } let s = ccx.tcx.map.with_path(fn_id.node, |path| { @@ -188,8 +185,7 @@ pub fn monomorphic_fn(ccx: &CrateContext, let lldecl = decl_internal_rust_fn(ccx, false, f.sig.inputs.as_slice(), f.sig.output, s); - let mut monomorphized = ccx.monomorphized.borrow_mut(); - monomorphized.get().insert(hash_id, lldecl); + ccx.monomorphized.borrow_mut().insert(hash_id, lldecl); lldecl }; @@ -284,10 +280,7 @@ pub fn monomorphic_fn(ccx: &CrateContext, } }; - { - let mut monomorphizing = ccx.monomorphizing.borrow_mut(); - monomorphizing.get().insert(fn_id, depth); - } + ccx.monomorphizing.borrow_mut().insert(fn_id, depth); debug!("leaving monomorphic fn {}", ty::item_path_str(ccx.tcx(), fn_id)); (lldecl, must_cast) diff --git a/src/librustc/middle/trans/type_of.rs b/src/librustc/middle/trans/type_of.rs index dad254e2dc7..d7c58f146e1 100644 --- a/src/librustc/middle/trans/type_of.rs +++ b/src/librustc/middle/trans/type_of.rs @@ -102,12 +102,9 @@ pub fn type_of_fn_from_ty(cx: &CrateContext, fty: ty::t) -> Type { // recursive types. For example, enum types rely on this behavior. pub fn sizing_type_of(cx: &CrateContext, t: ty::t) -> Type { - { - let llsizingtypes = cx.llsizingtypes.borrow(); - match llsizingtypes.get().find_copy(&t) { - Some(t) => return t, - None => () - } + match cx.llsizingtypes.borrow().find_copy(&t) { + Some(t) => return t, + None => () } let llsizingty = match ty::get(t).sty { @@ -165,20 +162,16 @@ pub fn sizing_type_of(cx: &CrateContext, t: ty::t) -> Type { } }; - let mut llsizingtypes = cx.llsizingtypes.borrow_mut(); - llsizingtypes.get().insert(t, llsizingty); + cx.llsizingtypes.borrow_mut().insert(t, llsizingty); llsizingty } // NB: If you update this, be sure to update `sizing_type_of()` as well. pub fn type_of(cx: &CrateContext, t: ty::t) -> Type { // Check the cache. - { - let lltypes = cx.lltypes.borrow(); - match lltypes.get().find(&t) { - Some(&llty) => return llty, - None => () - } + match cx.lltypes.borrow().find(&t) { + Some(&llty) => return llty, + None => () } debug!("type_of {} {:?}", t.repr(cx.tcx()), t); @@ -198,8 +191,7 @@ pub fn type_of(cx: &CrateContext, t: ty::t) -> Type { t_norm.repr(cx.tcx()), t_norm, cx.tn.type_to_str(llty)); - let mut lltypes = cx.lltypes.borrow_mut(); - lltypes.get().insert(t, llty); + cx.lltypes.borrow_mut().insert(t, llty); return llty; } @@ -295,10 +287,8 @@ pub fn type_of(cx: &CrateContext, t: ty::t) -> Type { t.repr(cx.tcx()), t, cx.tn.type_to_str(llty)); - { - let mut lltypes = cx.lltypes.borrow_mut(); - lltypes.get().insert(t, llty); - } + + cx.lltypes.borrow_mut().insert(t, llty); // If this was an enum or struct, fill in the type now. match ty::get(t).sty { diff --git a/src/librustc/middle/trans/write_guard.rs b/src/librustc/middle/trans/write_guard.rs index 0f4b11bde70..565805446f7 100644 --- a/src/librustc/middle/trans/write_guard.rs +++ b/src/librustc/middle/trans/write_guard.rs @@ -34,8 +34,7 @@ pub fn root_and_write_guard<'a, K:KindOps>(datum: &Datum, // // (Note: root'd values are always boxes) let ccx = bcx.ccx(); - let root_map = ccx.maps.root_map.borrow(); - match root_map.get().find(&key) { + match ccx.maps.root_map.borrow().find(&key) { None => bcx, Some(&root_info) => root(datum, bcx, span, key, root_info) } diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 61cadfea253..425ac4f85e1 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -62,7 +62,7 @@ // Data types -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] pub struct field { ident: ast::Ident, mt: mt @@ -123,20 +123,20 @@ pub struct Impl { ident: Ident, methods: Vec<@Method> } -#[deriving(Clone, Eq, Hash)] +#[deriving(Clone, Eq, TotalEq, Hash)] pub struct mt { ty: t, mutbl: ast::Mutability, } -#[deriving(Clone, Eq, Encodable, Decodable, Hash, Show)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash, Show)] pub enum vstore { vstore_fixed(uint), vstore_uniq, vstore_slice(Region) } -#[deriving(Clone, Eq, Hash, Encodable, Decodable, Show)] +#[deriving(Clone, Eq, TotalEq, Hash, Encodable, Decodable, Show)] pub enum TraitStore { UniqTraitStore, // ~Trait RegionTraitStore(Region), // &Trait @@ -150,7 +150,7 @@ pub struct field_ty { // Contains information needed to resolve types and (in the future) look up // the types of AST nodes. -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] pub struct creader_cache_key { cnum: CrateNum, pos: uint, @@ -177,6 +177,8 @@ fn ne(&self, other: &intern_key) -> bool { } } +impl TotalEq for intern_key {} + impl Hash for intern_key { fn hash(&self, s: &mut W) { unsafe { (*self.sty).hash(s) } @@ -382,7 +384,7 @@ pub struct t_box_ { // alive, and using ty::get is unsafe when the ctxt is no longer alive. enum t_opaque {} -#[deriving(Clone, Eq, Hash)] +#[deriving(Clone, Eq, TotalEq, Hash)] pub struct t { priv inner: *t_opaque } impl fmt::Show for t { @@ -413,14 +415,14 @@ pub fn type_has_regions(t: t) -> bool { } pub fn type_id(t: t) -> uint { get(t).id } -#[deriving(Clone, Eq, Hash)] +#[deriving(Clone, Eq, TotalEq, Hash)] pub struct BareFnTy { purity: ast::Purity, abis: AbiSet, sig: FnSig } -#[deriving(Clone, Eq, Hash)] +#[deriving(Clone, Eq, TotalEq, Hash)] pub struct ClosureTy { purity: ast::Purity, sigil: ast::Sigil, @@ -442,7 +444,7 @@ pub struct ClosureTy { * - `output` is the return type. * - `variadic` indicates whether this is a varidic function. (only true for foreign fns) */ -#[deriving(Clone, Eq, Hash)] +#[deriving(Clone, Eq, TotalEq, Hash)] pub struct FnSig { binder_id: ast::NodeId, inputs: Vec, @@ -450,14 +452,14 @@ pub struct FnSig { variadic: bool } -#[deriving(Clone, Eq, Hash)] +#[deriving(Clone, Eq, TotalEq, Hash)] pub struct param_ty { idx: uint, def_id: DefId } /// Representation of regions: -#[deriving(Clone, Eq, Hash, Encodable, Decodable, Show)] +#[deriving(Clone, Eq, TotalEq, Hash, Encodable, Decodable, Show)] pub enum Region { // Region bound in a type or fn declaration which will be // substituted 'early' -- that is, at the same time when type @@ -498,13 +500,13 @@ pub enum Region { * the original var id (that is, the root variable that is referenced * by the upvar) and the id of the closure expression. */ -#[deriving(Clone, Eq, Hash)] +#[deriving(Clone, Eq, TotalEq, Hash)] pub struct UpvarId { var_id: ast::NodeId, closure_expr_id: ast::NodeId, } -#[deriving(Clone, Eq, Hash)] +#[deriving(Clone, Eq, TotalEq, Hash)] pub enum BorrowKind { /// Data must be immutable and is aliasable. ImmBorrow, @@ -642,7 +644,7 @@ pub enum BoundRegion { * Represents the values to use when substituting lifetime parameters. * If the value is `ErasedRegions`, then this subst is occurring during * trans, and all region parameters will be replaced with `ty::ReStatic`. */ -#[deriving(Clone, Eq, Hash)] +#[deriving(Clone, Eq, TotalEq, Hash)] pub enum RegionSubsts { ErasedRegions, NonerasedRegions(OwnedSlice) @@ -665,7 +667,7 @@ pub enum RegionSubsts { * - `self_ty` is the type to which `self` should be remapped, if any. The * `self` type is rather funny in that it can only appear on traits and is * always substituted away to the implementing type for a trait. */ -#[deriving(Clone, Eq, Hash)] +#[deriving(Clone, Eq, TotalEq, Hash)] pub struct substs { self_ty: Option, tps: Vec, @@ -720,7 +722,7 @@ macro_rules! def_prim_ty( // NB: If you change this, you'll probably want to change the corresponding // AST structure in libsyntax/ast.rs as well. -#[deriving(Clone, Eq, Hash)] +#[deriving(Clone, Eq, TotalEq, Hash)] pub enum sty { ty_nil, ty_bot, @@ -755,7 +757,7 @@ pub enum sty { ty_unboxed_vec(mt), } -#[deriving(Clone, Eq, Hash)] +#[deriving(Clone, Eq, TotalEq, Hash)] pub struct TyTrait { def_id: DefId, substs: substs, @@ -764,7 +766,7 @@ pub struct TyTrait { bounds: BuiltinBounds } -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] pub struct TraitRef { def_id: DefId, substs: substs @@ -826,19 +828,18 @@ pub enum type_err { terr_variadic_mismatch(expected_found) } -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] pub struct ParamBounds { builtin_bounds: BuiltinBounds, trait_bounds: Vec<@TraitRef> } pub type BuiltinBounds = EnumSet; -#[deriving(Clone, Encodable, Eq, Decodable, Hash, Show)] +#[deriving(Clone, Encodable, Eq, TotalEq, Decodable, Hash, Show)] #[repr(uint)] pub enum BuiltinBound { BoundStatic, BoundSend, - BoundFreeze, BoundSized, BoundPod, BoundShare, @@ -852,7 +853,6 @@ pub fn AllBuiltinBounds() -> BuiltinBounds { let mut set = EnumSet::empty(); set.add(BoundStatic); set.add(BoundSend); - set.add(BoundFreeze); set.add(BoundSized); set.add(BoundShare); set @@ -867,28 +867,28 @@ fn from_uint(v: uint) -> BuiltinBound { } } -#[deriving(Clone, Eq, Hash)] +#[deriving(Clone, Eq, TotalEq, Hash)] pub struct TyVid(uint); -#[deriving(Clone, Eq, Hash)] +#[deriving(Clone, Eq, TotalEq, Hash)] pub struct IntVid(uint); -#[deriving(Clone, Eq, Hash)] +#[deriving(Clone, Eq, TotalEq, Hash)] pub struct FloatVid(uint); -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct RegionVid { id: uint } -#[deriving(Clone, Eq, Hash)] +#[deriving(Clone, Eq, TotalEq, Hash)] pub enum InferTy { TyVar(TyVid), IntVar(IntVid), FloatVar(FloatVid) } -#[deriving(Clone, Encodable, Decodable, Hash, Show)] +#[deriving(Clone, Encodable, Decodable, TotalEq, Hash, Show)] pub enum InferRegion { ReVar(RegionVid), ReSkolemized(uint, BoundRegion) @@ -1009,13 +1009,13 @@ pub struct Generics { impl Generics { pub fn has_type_params(&self) -> bool { - !self.type_param_defs.deref().is_empty() + !self.type_param_defs.is_empty() } pub fn type_param_defs<'a>(&'a self) -> &'a [TypeParameterDef] { - self.type_param_defs.deref().as_slice() + self.type_param_defs.as_slice() } pub fn region_param_defs<'a>(&'a self) -> &'a [RegionParameterDef] { - self.region_param_defs.deref().as_slice() + self.region_param_defs.as_slice() } } @@ -1154,12 +1154,9 @@ pub fn mk_t(cx: &ctxt, st: sty) -> t { let key = intern_key { sty: &st }; - { - let mut interner = cx.interner.borrow_mut(); - match interner.get().find(&key) { - Some(t) => unsafe { return cast::transmute(&t.sty); }, - _ => () - } + match cx.interner.borrow().find(&key) { + Some(t) => unsafe { return cast::transmute(&t.sty); }, + _ => () } let mut flags = 0u; @@ -1255,8 +1252,7 @@ fn sflags(substs: &substs) -> uint { sty: sty_ptr, }; - let mut interner = cx.interner.borrow_mut(); - interner.get().insert(key, t); + cx.interner.borrow_mut().insert(key, t); cx.next_id.set(cx.next_id.get() + 1); @@ -1762,21 +1758,15 @@ pub fn type_needs_drop(cx: &ctxt, ty: t) -> bool { // that only contain scalars and shared boxes can avoid unwind // cleanups. pub fn type_needs_unwind_cleanup(cx: &ctxt, ty: t) -> bool { - { - let needs_unwind_cleanup_cache = cx.needs_unwind_cleanup_cache - .borrow(); - match needs_unwind_cleanup_cache.get().find(&ty) { - Some(&result) => return result, - None => () - } + match cx.needs_unwind_cleanup_cache.borrow().find(&ty) { + Some(&result) => return result, + None => () } let mut tycache = HashSet::new(); let needs_unwind_cleanup = type_needs_unwind_cleanup_(cx, ty, &mut tycache, false); - let mut needs_unwind_cleanup_cache = cx.needs_unwind_cleanup_cache - .borrow_mut(); - needs_unwind_cleanup_cache.get().insert(ty, needs_unwind_cleanup); + cx.needs_unwind_cleanup_cache.borrow_mut().insert(ty, needs_unwind_cleanup); return needs_unwind_cleanup; } @@ -1902,9 +1892,6 @@ mod TC { // that it neither reaches nor owns a managed pointer. Nonsendable = 0b0000_0111__0000_0100__0000, - // Things that prevent values from being considered freezable - Nonfreezable = 0b0000_1000__0000_0000__0000, - // Things that prevent values from being considered 'static Nonstatic = 0b0000_0010__0000_0000__0000, @@ -1939,7 +1926,6 @@ pub fn meets_bounds(&self, cx: &ctxt, bbs: BuiltinBounds) -> bool { pub fn meets_bound(&self, cx: &ctxt, bb: BuiltinBound) -> bool { match bb { BoundStatic => self.is_static(cx), - BoundFreeze => self.is_freezable(cx), BoundSend => self.is_sendable(cx), BoundSized => self.is_sized(cx), BoundPod => self.is_pod(cx), @@ -1975,10 +1961,6 @@ pub fn owns_owned(&self) -> bool { self.intersects(TC::OwnsOwned) } - pub fn is_freezable(&self, _: &ctxt) -> bool { - !self.intersects(TC::Nonfreezable) - } - pub fn is_sized(&self, _: &ctxt) -> bool { !self.intersects(TC::Nonsized) } @@ -2083,10 +2065,6 @@ pub fn type_is_sendable(cx: &ctxt, t: ty::t) -> bool { type_contents(cx, t).is_sendable(cx) } -pub fn type_is_freezable(cx: &ctxt, t: ty::t) -> bool { - type_contents(cx, t).is_freezable(cx) -} - pub fn type_interior_is_unsafe(cx: &ctxt, t: ty::t) -> bool { type_contents(cx, t).interior_unsafe() } @@ -2094,19 +2072,15 @@ pub fn type_interior_is_unsafe(cx: &ctxt, t: ty::t) -> bool { pub fn type_contents(cx: &ctxt, ty: t) -> TypeContents { let ty_id = type_id(ty); - { - let tc_cache = cx.tc_cache.borrow(); - match tc_cache.get().find(&ty_id) { - Some(tc) => { return *tc; } - None => {} - } + match cx.tc_cache.borrow().find(&ty_id) { + Some(tc) => { return *tc; } + None => {} } let mut cache = HashMap::new(); let result = tc_ty(cx, ty, &mut cache); - let mut tc_cache = cx.tc_cache.borrow_mut(); - tc_cache.get().insert(ty_id, result); + cx.tc_cache.borrow_mut().insert(ty_id, result); return result; fn tc_ty(cx: &ctxt, @@ -2139,17 +2113,14 @@ fn tc_ty(cx: &ctxt, Some(tc) => { return *tc; } None => {} } - { - let tc_cache = cx.tc_cache.borrow(); - match tc_cache.get().find(&ty_id) { // Must check both caches! - Some(tc) => { return *tc; } - None => {} - } + match cx.tc_cache.borrow().find(&ty_id) { // Must check both caches! + Some(tc) => { return *tc; } + None => {} } cache.insert(ty_id, TC::None); let result = match get(ty).sty { - // Scalar and unique types are sendable, freezable, and durable + // Scalar and unique types are sendable, and durable ty_nil | ty_bot | ty_bool | ty_int(_) | ty_uint(_) | ty_float(_) | ty_bare_fn(_) | ty::ty_char => { TC::None @@ -2243,7 +2214,7 @@ fn tc_ty(cx: &ctxt, assert_eq!(p.def_id.krate, ast::LOCAL_CRATE); let ty_param_defs = cx.ty_param_defs.borrow(); - let tp_def = ty_param_defs.get().get(&p.def_id.node); + let tp_def = ty_param_defs.get(&p.def_id.node); kind_bounds_to_contents(cx, tp_def.bounds.builtin_bounds, tp_def.bounds.trait_bounds.as_slice()) @@ -2287,9 +2258,7 @@ fn apply_lang_items(cx: &ctxt, did: ast::DefId, tc: TypeContents) -> TypeContents { - if Some(did) == cx.lang_items.no_freeze_bound() { - tc | TC::ReachesMutable - } else if Some(did) == cx.lang_items.no_send_bound() { + if Some(did) == cx.lang_items.no_send_bound() { tc | TC::ReachesNonsendAnnot } else if Some(did) == cx.lang_items.managed_bound() { tc | TC::Managed @@ -2374,7 +2343,6 @@ fn kind_bounds_to_contents(cx: &ctxt, tc = tc - match bound { BoundStatic => TC::Nonstatic, BoundSend => TC::Nonsendable, - BoundFreeze => TC::Nonfreezable, BoundSized => TC::Nonsized, BoundPod => TC::Nonpod, BoundShare => TC::Nonsharable, @@ -2686,7 +2654,7 @@ pub fn type_is_sized(cx: &ctxt, ty: ty::t) -> bool { // FIXME(#6308) add trait, vec, str, etc here. ty_param(p) => { let ty_param_defs = cx.ty_param_defs.borrow(); - let param_def = ty_param_defs.get().get(&p.def_id.node); + let param_def = ty_param_defs.get(&p.def_id.node); if param_def.bounds.builtin_bounds.contains_elem(BoundSized) { return true; } @@ -2746,8 +2714,7 @@ pub fn index(t: t) -> Option { } pub fn node_id_to_trait_ref(cx: &ctxt, id: ast::NodeId) -> @ty::TraitRef { - let trait_refs = cx.trait_refs.borrow(); - match trait_refs.get().find(&id) { + match cx.trait_refs.borrow().find(&id) { Some(&t) => t, None => cx.sess.bug( format!("node_id_to_trait_ref: no trait ref for node `{}`", @@ -2756,8 +2723,7 @@ pub fn node_id_to_trait_ref(cx: &ctxt, id: ast::NodeId) -> @ty::TraitRef { } pub fn try_node_id_to_type(cx: &ctxt, id: ast::NodeId) -> Option { - let node_types = cx.node_types.borrow(); - node_types.get().find_copy(&(id as uint)) + cx.node_types.borrow().find_copy(&(id as uint)) } pub fn node_id_to_type(cx: &ctxt, id: ast::NodeId) -> t { @@ -2770,9 +2736,7 @@ pub fn node_id_to_type(cx: &ctxt, id: ast::NodeId) -> t { } pub fn node_id_to_type_opt(cx: &ctxt, id: ast::NodeId) -> Option { - let node_types = cx.node_types.borrow(); - debug!("id: {:?}, node_types: {:?}", id, node_types); - match node_types.get().find(&(id as uint)) { + match cx.node_types.borrow().find(&(id as uint)) { Some(&t) => Some(t), None => None } @@ -2780,16 +2744,14 @@ pub fn node_id_to_type_opt(cx: &ctxt, id: ast::NodeId) -> Option { // FIXME(pcwalton): Makes a copy, bleh. Probably better to not do that. pub fn node_id_to_type_params(cx: &ctxt, id: ast::NodeId) -> Vec { - let node_type_substs = cx.node_type_substs.borrow(); - match node_type_substs.get().find(&id) { + match cx.node_type_substs.borrow().find(&id) { None => return Vec::new(), Some(ts) => return (*ts).clone(), } } fn node_id_has_type_params(cx: &ctxt, id: ast::NodeId) -> bool { - let node_type_substs = cx.node_type_substs.borrow(); - node_type_substs.get().contains_key(&id) + cx.node_type_substs.borrow().contains_key(&id) } pub fn fn_is_variadic(fty: t) -> bool { @@ -2970,7 +2932,7 @@ pub fn expr_ty_adjusted(cx: &ctxt, */ let unadjusted_ty = expr_ty(cx, expr); - let adjustment = cx.adjustments.borrow().get().find_copy(&expr.id); + let adjustment = cx.adjustments.borrow().find_copy(&expr.id); adjust_ty(cx, expr.span, expr.id, unadjusted_ty, adjustment, |method_call| { method_map.find(&method_call).map(|method| method.ty) }) @@ -3260,8 +3222,7 @@ pub fn method_call_type_param_defs(tcx: &ctxt, origin: typeck::MethodOrigin) } pub fn resolve_expr(tcx: &ctxt, expr: &ast::Expr) -> ast::Def { - let def_map = tcx.def_map.borrow(); - match def_map.get().find(&expr.id) { + match tcx.def_map.borrow().find(&expr.id) { Some(&def) => def, None => { tcx.sess.span_bug(expr.span, format!( @@ -3294,7 +3255,7 @@ pub enum ExprKind { pub fn expr_kind(tcx: &ctxt, method_map: MethodMap, expr: &ast::Expr) -> ExprKind { - if method_map.borrow().get().contains_key(&MethodCall::expr(expr.id)) { + if method_map.borrow().contains_key(&MethodCall::expr(expr.id)) { // Overloaded operations are generally calls, and hence they are // generated via DPS, but there are two exceptions: return match expr.node { @@ -3377,8 +3338,7 @@ pub fn expr_kind(tcx: &ctxt, } ast::ExprCast(..) => { - let node_types = tcx.node_types.borrow(); - match node_types.get().find(&(expr.id as uint)) { + match tcx.node_types.borrow().find(&(expr.id as uint)) { Some(&t) => { if type_is_trait(t) { RvalueDpsExpr @@ -3426,8 +3386,7 @@ pub fn expr_kind(tcx: &ctxt, ast::ExprBox(place, _) => { // Special case `~T` for now: - let def_map = tcx.def_map.borrow(); - let definition = match def_map.get().find(&place.id) { + let definition = match tcx.def_map.borrow().find(&place.id) { Some(&def) => def, None => fail!("no def for place"), }; @@ -3709,8 +3668,7 @@ pub fn def_has_ty_params(def: ast::Def) -> bool { } pub fn provided_source(cx: &ctxt, id: ast::DefId) -> Option { - let provided_method_sources = cx.provided_method_sources.borrow(); - provided_method_sources.get().find(&id).map(|x| *x) + cx.provided_method_sources.borrow().find(&id).map(|x| *x) } pub fn provided_trait_methods(cx: &ctxt, id: ast::DefId) -> Vec<@Method> { @@ -3747,12 +3705,9 @@ pub fn provided_trait_methods(cx: &ctxt, id: ast::DefId) -> Vec<@Method> { pub fn trait_supertraits(cx: &ctxt, id: ast::DefId) -> @Vec<@TraitRef> { // Check the cache. - { - let supertraits = cx.supertraits.borrow(); - match supertraits.get().find(&id) { - Some(&trait_refs) => { return trait_refs; } - None => {} // Continue. - } + match cx.supertraits.borrow().find(&id) { + Some(&trait_refs) => { return trait_refs; } + None => {} // Continue. } // Not in the cache. It had better be in the metadata, which means it @@ -3762,8 +3717,7 @@ pub fn trait_supertraits(cx: &ctxt, id: ast::DefId) -> @Vec<@TraitRef> { // Get the supertraits out of the metadata and create the // TraitRef for each. let result = @csearch::get_supertraits(cx, id); - let mut supertraits = cx.supertraits.borrow_mut(); - supertraits.get().insert(id, result); + cx.supertraits.borrow_mut().insert(id, result); return result; } @@ -3808,42 +3762,38 @@ pub fn trait_method(cx: &ctxt, trait_did: ast::DefId, idx: uint) -> @Method { pub fn trait_methods(cx: &ctxt, trait_did: ast::DefId) -> @Vec<@Method> { - let mut trait_methods_cache = cx.trait_methods_cache.borrow_mut(); - match trait_methods_cache.get().find(&trait_did) { + let mut trait_methods = cx.trait_methods_cache.borrow_mut(); + match trait_methods.find(&trait_did) { Some(&methods) => methods, None => { let def_ids = ty::trait_method_def_ids(cx, trait_did); let methods = @def_ids.map(|d| ty::method(cx, *d)); - trait_methods_cache.get().insert(trait_did, methods); + trait_methods.insert(trait_did, methods); methods } } } pub fn method(cx: &ctxt, id: ast::DefId) -> @Method { - let mut methods = cx.methods.borrow_mut(); - lookup_locally_or_in_crate_store("methods", id, methods.get(), || { + lookup_locally_or_in_crate_store("methods", id, + &mut *cx.methods.borrow_mut(), || { @csearch::get_method(cx, id) }) } pub fn trait_method_def_ids(cx: &ctxt, id: ast::DefId) -> @Vec { - let mut trait_method_def_ids = cx.trait_method_def_ids.borrow_mut(); lookup_locally_or_in_crate_store("trait_method_def_ids", id, - trait_method_def_ids.get(), + &mut *cx.trait_method_def_ids.borrow_mut(), || { @csearch::get_trait_method_def_ids(&cx.sess.cstore, id) }) } pub fn impl_trait_ref(cx: &ctxt, id: ast::DefId) -> Option<@TraitRef> { - { - let mut impl_trait_cache = cx.impl_trait_cache.borrow_mut(); - match impl_trait_cache.get().find(&id) { - Some(&ret) => { return ret; } - None => {} - } + match cx.impl_trait_cache.borrow().find(&id) { + Some(&ret) => { return ret; } + None => {} } let ret = if id.krate == ast::LOCAL_CRATE { @@ -3868,17 +3818,15 @@ pub fn impl_trait_ref(cx: &ctxt, id: ast::DefId) -> Option<@TraitRef> { csearch::get_impl_trait(cx, id) }; - let mut impl_trait_cache = cx.impl_trait_cache.borrow_mut(); - impl_trait_cache.get().insert(id, ret); + cx.impl_trait_cache.borrow_mut().insert(id, ret); return ret; } pub fn trait_ref_to_def_id(tcx: &ctxt, tr: &ast::TraitRef) -> ast::DefId { - let def_map = tcx.def_map.borrow(); - let def = def_map.get() + let def = *tcx.def_map.borrow() .find(&tr.ref_id) .expect("no def-map entry for trait"); - ast_util::def_id_of_def(*def) + ast_util::def_id_of_def(def) } pub fn try_add_builtin_trait(tcx: &ctxt, @@ -4021,8 +3969,7 @@ pub fn has_drop_flag(&self) -> bool { /* If struct_id names a struct with a dtor, return Some(the dtor's id). Otherwise return none. */ pub fn ty_dtor(cx: &ctxt, struct_id: DefId) -> DtorKind { - let destructor_for_type = cx.destructor_for_type.borrow(); - match destructor_for_type.get().find(&struct_id) { + match cx.destructor_for_type.borrow().find(&struct_id) { Some(&method_def_id) => { let flag = !has_attr(cx, struct_id, "unsafe_no_drop_flag"); @@ -4056,12 +4003,9 @@ pub fn type_is_empty(cx: &ctxt, t: t) -> bool { } pub fn enum_variants(cx: &ctxt, id: ast::DefId) -> @Vec<@VariantInfo> { - { - let enum_var_cache = cx.enum_var_cache.borrow(); - match enum_var_cache.get().find(&id) { - Some(&variants) => return variants, - _ => { /* fallthrough */ } - } + match cx.enum_var_cache.borrow().find(&id) { + Some(&variants) => return variants, + _ => { /* fallthrough */ } } let result = if ast::LOCAL_CRATE != id.krate { @@ -4129,11 +4073,8 @@ pub fn enum_variants(cx: &ctxt, id: ast::DefId) -> @Vec<@VariantInfo> { } }; - { - let mut enum_var_cache = cx.enum_var_cache.borrow_mut(); - enum_var_cache.get().insert(id, result); - result - } + cx.enum_var_cache.borrow_mut().insert(id, result); + result } @@ -4160,25 +4101,23 @@ pub fn enum_variant_with_id(cx: &ctxt, pub fn lookup_item_type(cx: &ctxt, did: ast::DefId) -> ty_param_bounds_and_ty { - let mut tcache = cx.tcache.borrow_mut(); lookup_locally_or_in_crate_store( - "tcache", did, tcache.get(), + "tcache", did, &mut *cx.tcache.borrow_mut(), || csearch::get_type(cx, did)) } pub fn lookup_impl_vtables(cx: &ctxt, did: ast::DefId) -> typeck::impl_res { - let mut impl_vtables = cx.impl_vtables.borrow_mut(); lookup_locally_or_in_crate_store( - "impl_vtables", did, impl_vtables.get(), + "impl_vtables", did, &mut *cx.impl_vtables.borrow_mut(), || csearch::get_impl_vtables(cx, did) ) } /// Given the did of a trait, returns its canonical trait ref. pub fn lookup_trait_def(cx: &ctxt, did: ast::DefId) -> @ty::TraitDef { let mut trait_defs = cx.trait_defs.borrow_mut(); - match trait_defs.get().find(&did) { + match trait_defs.find(&did) { Some(&trait_def) => { // The item is in this crate. The caller should have added it to the // type cache already @@ -4187,7 +4126,7 @@ pub fn lookup_trait_def(cx: &ctxt, did: ast::DefId) -> @ty::TraitDef { None => { assert!(did.krate != ast::LOCAL_CRATE); let trait_def = @csearch::get_trait_def(cx, did); - trait_defs.get().insert(did, trait_def); + trait_defs.insert(did, trait_def); return trait_def; } } @@ -4255,16 +4194,14 @@ pub fn lookup_field_type(tcx: &ctxt, let t = if id.krate == ast::LOCAL_CRATE { node_id_to_type(tcx, id.node) } else { - { - let mut tcache = tcx.tcache.borrow_mut(); - match tcache.get().find(&id) { - Some(&ty_param_bounds_and_ty {ty, ..}) => ty, - None => { - let tpt = csearch::get_field_type(tcx, struct_id, id); - tcache.get().insert(id, tpt.clone()); - tpt.ty - } - } + let mut tcache = tcx.tcache.borrow_mut(); + match tcache.find(&id) { + Some(&ty_param_bounds_and_ty {ty, ..}) => ty, + None => { + let tpt = csearch::get_field_type(tcx, struct_id, id); + tcache.insert(id, tpt.clone()); + tpt.ty + } } }; subst(tcx, substs, t) @@ -4444,23 +4381,14 @@ impl<'a> TypeFolder for TypeNormalizer<'a> { fn tcx<'a>(&'a self) -> &'a ctxt { let TypeNormalizer(c) = *self; c } fn fold_ty(&mut self, t: ty::t) -> ty::t { - let normalized_opt = { - let normalized_cache = self.tcx().normalized_cache.borrow(); - normalized_cache.get().find_copy(&t) - }; - match normalized_opt { - Some(u) => { - return u; - } - None => { - let t_norm = ty_fold::super_fold_ty(self, t); - let mut normalized_cache = self.tcx() - .normalized_cache - .borrow_mut(); - normalized_cache.get().insert(t, t_norm); - return t_norm; - } + match self.tcx().normalized_cache.borrow().find_copy(&t) { + None => {} + Some(u) => return u } + + let t_norm = ty_fold::super_fold_ty(self, t); + self.tcx().normalized_cache.borrow_mut().insert(t, t_norm); + return t_norm; } fn fold_vstore(&mut self, vstore: vstore) -> vstore { @@ -4636,16 +4564,14 @@ pub fn count_traits_and_supertraits(tcx: &ctxt, pub fn get_tydesc_ty(tcx: &ctxt) -> Result { tcx.lang_items.require(TyDescStructLangItem).map(|tydesc_lang_item| { - let intrinsic_defs = tcx.intrinsic_defs.borrow(); - intrinsic_defs.get().find_copy(&tydesc_lang_item) + tcx.intrinsic_defs.borrow().find_copy(&tydesc_lang_item) .expect("Failed to resolve TyDesc") }) } pub fn get_opaque_ty(tcx: &ctxt) -> Result { tcx.lang_items.require(OpaqueStructLangItem).map(|opaque_lang_item| { - let intrinsic_defs = tcx.intrinsic_defs.borrow(); - intrinsic_defs.get().find_copy(&opaque_lang_item) + tcx.intrinsic_defs.borrow().find_copy(&opaque_lang_item) .expect("Failed to resolve Opaque") }) } @@ -4672,9 +4598,8 @@ pub fn visitor_object_ty(tcx: &ctxt, } pub fn item_variances(tcx: &ctxt, item_id: ast::DefId) -> @ItemVariances { - let mut item_variance_map = tcx.item_variance_map.borrow_mut(); lookup_locally_or_in_crate_store( - "item_variance_map", item_id, item_variance_map.get(), + "item_variance_map", item_id, &mut *tcx.item_variance_map.borrow_mut(), || @csearch::get_item_variances(&tcx.sess.cstore, item_id)) } @@ -4684,18 +4609,17 @@ fn record_trait_implementation(tcx: &ctxt, implementation: @Impl) { let implementation_list; let mut trait_impls = tcx.trait_impls.borrow_mut(); - match trait_impls.get().find(&trait_def_id) { + match trait_impls.find(&trait_def_id) { None => { implementation_list = @RefCell::new(Vec::new()); - trait_impls.get().insert(trait_def_id, implementation_list); + trait_impls.insert(trait_def_id, implementation_list); } Some(&existing_implementation_list) => { implementation_list = existing_implementation_list } } - let mut implementation_list = implementation_list.borrow_mut(); - implementation_list.get().push(implementation); + implementation_list.borrow_mut().push(implementation); } /// Populates the type context with all the implementations for the given type @@ -4705,11 +4629,8 @@ pub fn populate_implementations_for_type_if_necessary(tcx: &ctxt, if type_id.krate == LOCAL_CRATE { return } - { - let populated_external_types = tcx.populated_external_types.borrow(); - if populated_external_types.get().contains(&type_id) { - return - } + if tcx.populated_external_types.borrow().contains(&type_id) { + return } csearch::each_implementation_for_type(&tcx.sess.cstore, type_id, @@ -4729,9 +4650,8 @@ pub fn populate_implementations_for_type_if_necessary(tcx: &ctxt, // the map. This is a bit unfortunate. for method in implementation.methods.iter() { for source in method.provided_source.iter() { - let mut provided_method_sources = - tcx.provided_method_sources.borrow_mut(); - provided_method_sources.get().insert(method.def_id, *source); + tcx.provided_method_sources.borrow_mut() + .insert(method.def_id, *source); } } @@ -4739,30 +4659,23 @@ pub fn populate_implementations_for_type_if_necessary(tcx: &ctxt, if associated_traits.is_none() { let implementation_list; let mut inherent_impls = tcx.inherent_impls.borrow_mut(); - match inherent_impls.get().find(&type_id) { + match inherent_impls.find(&type_id) { None => { implementation_list = @RefCell::new(Vec::new()); - inherent_impls.get().insert(type_id, implementation_list); + inherent_impls.insert(type_id, implementation_list); } Some(&existing_implementation_list) => { implementation_list = existing_implementation_list; } } - { - let mut implementation_list = - implementation_list.borrow_mut(); - implementation_list.get().push(implementation); - } + implementation_list.borrow_mut().push(implementation); } // Store the implementation info. - let mut impls = tcx.impls.borrow_mut(); - impls.get().insert(implementation_def_id, implementation); + tcx.impls.borrow_mut().insert(implementation_def_id, implementation); }); - let mut populated_external_types = tcx.populated_external_types - .borrow_mut(); - populated_external_types.get().insert(type_id); + tcx.populated_external_types.borrow_mut().insert(type_id); } /// Populates the type context with all the implementations for the given @@ -4773,12 +4686,8 @@ pub fn populate_implementations_for_trait_if_necessary( if trait_id.krate == LOCAL_CRATE { return } - { - let populated_external_traits = tcx.populated_external_traits - .borrow(); - if populated_external_traits.get().contains(&trait_id) { - return - } + if tcx.populated_external_traits.borrow().contains(&trait_id) { + return } csearch::each_implementation_for_trait(&tcx.sess.cstore, trait_id, @@ -4792,20 +4701,16 @@ pub fn populate_implementations_for_trait_if_necessary( // the map. This is a bit unfortunate. for method in implementation.methods.iter() { for source in method.provided_source.iter() { - let mut provided_method_sources = - tcx.provided_method_sources.borrow_mut(); - provided_method_sources.get().insert(method.def_id, *source); + tcx.provided_method_sources.borrow_mut() + .insert(method.def_id, *source); } } // Store the implementation info. - let mut impls = tcx.impls.borrow_mut(); - impls.get().insert(implementation_def_id, implementation); + tcx.impls.borrow_mut().insert(implementation_def_id, implementation); }); - let mut populated_external_traits = tcx.populated_external_traits - .borrow_mut(); - populated_external_traits.get().insert(trait_id); + tcx.populated_external_traits.borrow_mut().insert(trait_id); } /// Given the def_id of an impl, return the def_id of the trait it implements. @@ -4837,12 +4742,7 @@ pub fn trait_of_method(tcx: &ctxt, def_id: ast::DefId) if def_id.krate != LOCAL_CRATE { return csearch::get_trait_of_method(&tcx.sess.cstore, def_id, tcx); } - let method; - { - let methods = tcx.methods.borrow(); - method = methods.get().find(&def_id).map(|method| *method); - } - match method { + match tcx.methods.borrow().find(&def_id).map(|m| *m) { Some(method) => { match method.container { TraitContainer(def_id) => Some(def_id), @@ -4861,14 +4761,10 @@ pub fn trait_of_method(tcx: &ctxt, def_id: ast::DefId) /// Otherwise, return `None`. pub fn trait_method_of_method(tcx: &ctxt, def_id: ast::DefId) -> Option { - let method; - { - let methods = tcx.methods.borrow(); - match methods.get().find(&def_id) { - Some(m) => method = *m, - None => return None, - } - } + let method = match tcx.methods.borrow().find(&def_id) { + Some(&m) => m, + None => return None, + }; let name = method.ident.name; match trait_of_method(tcx, def_id) { Some(trait_did) => { diff --git a/src/librustc/middle/typeck/astconv.rs b/src/librustc/middle/typeck/astconv.rs index d28ad74e49b..93962b3e410 100644 --- a/src/librustc/middle/typeck/astconv.rs +++ b/src/librustc/middle/typeck/astconv.rs @@ -324,8 +324,7 @@ fn check_path_args(tcx: &ty::ctxt, pub fn ast_ty_to_prim_ty(tcx: &ty::ctxt, ast_ty: &ast::Ty) -> Option { match ast_ty.node { ast::TyPath(ref path, _, id) => { - let def_map = tcx.def_map.borrow(); - let a_def = match def_map.get().find(&id) { + let a_def = match tcx.def_map.borrow().find(&id) { None => tcx.sess.span_fatal( ast_ty.span, format!("unbound path {}", path_to_str(path))), Some(&d) => d @@ -430,8 +429,7 @@ fn mk_pointer { check_path_args(tcx, path, NO_TPS | NO_REGIONS); @@ -474,20 +472,19 @@ fn mk_pointer return ty, - Some(&ty::atttce_unresolved) => { - tcx.sess.span_fatal(ast_ty.span, - "illegal recursive type; insert an enum \ - or struct in the cycle, if this is \ - desired"); - } - None => { /* go on */ } + let mut ast_ty_to_ty_cache = tcx.ast_ty_to_ty_cache.borrow_mut(); + match ast_ty_to_ty_cache.find(&ast_ty.id) { + Some(&ty::atttce_resolved(ty)) => return ty, + Some(&ty::atttce_unresolved) => { + tcx.sess.span_fatal(ast_ty.span, + "illegal recursive type; insert an enum \ + or struct in the cycle, if this is \ + desired"); } - ast_ty_to_ty_cache.get().insert(ast_ty.id, ty::atttce_unresolved); + None => { /* go on */ } } + ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_unresolved); + drop(ast_ty_to_ty_cache); let typ = ast_ty_to_prim_ty(tcx, ast_ty).unwrap_or_else(|| match ast_ty.node { ast::TyNil => ty::mk_nil(), @@ -556,8 +553,7 @@ fn mk_pointer { - let def_map = tcx.def_map.borrow(); - let a_def = match def_map.get().find(&id) { + let a_def = match tcx.def_map.borrow().find(&id) { None => tcx.sess.span_fatal( ast_ty.span, format!("unbound path {}", path_to_str(path))), Some(&d) => d @@ -645,8 +641,7 @@ fn mk_pointer { // OK. @@ -399,8 +398,7 @@ pub fn check_struct_like_enum_variant_pat(pcx: &pat_ctxt, let tcx = pcx.fcx.ccx.tcx; // Find the variant that was specified. - let def_map = tcx.def_map.borrow(); - match def_map.get().find(&pat_id) { + match tcx.def_map.borrow().find(&pat_id) { Some(&ast::DefVariant(found_enum_id, variant_id, _)) if found_enum_id == enum_id => { // Get the struct fields from this struct-like enum variant. @@ -470,9 +468,8 @@ pub fn check_pat(pcx: &pat_ctxt, pat: &ast::Pat, expected: ty::t) { } ast::PatEnum(..) | ast::PatIdent(..) if pat_is_const(tcx.def_map, pat) => { - let def_map = tcx.def_map.borrow(); - let const_did = ast_util::def_id_of_def(def_map.get() - .get_copy(&pat.id)); + let const_did = ast_util::def_id_of_def(tcx.def_map.borrow() + .get_copy(&pat.id)); let const_tpt = ty::lookup_item_type(tcx, const_did); demand::suptype(fcx, pat.span, expected, const_tpt.ty); fcx.write_ty(pat.id, const_tpt.ty); @@ -548,8 +545,7 @@ pub fn check_pat(pcx: &pat_ctxt, pat: &ast::Pat, expected: ty::t) { e, actual)})}, Some(expected), ~"a structure pattern", None); - let def_map = tcx.def_map.borrow(); - match def_map.get().find(&pat.id) { + match tcx.def_map.borrow().find(&pat.id) { Some(&ast::DefStruct(supplied_def_id)) => { check_struct_pat(pcx, pat.id, diff --git a/src/librustc/middle/typeck/check/method.rs b/src/librustc/middle/typeck/check/method.rs index fc577f12f6a..9b623f1e78e 100644 --- a/src/librustc/middle/typeck/check/method.rs +++ b/src/librustc/middle/typeck/check/method.rs @@ -466,8 +466,8 @@ fn push_extension_candidate(&mut self, trait_did: DefId) { ty::populate_implementations_for_trait_if_necessary(self.tcx(), trait_did); // Look for explicit implementations. - for impl_infos in self.tcx().trait_impls.borrow().get().find(&trait_did).iter() { - for impl_info in impl_infos.borrow().get().iter() { + for impl_infos in self.tcx().trait_impls.borrow().find(&trait_did).iter() { + for impl_info in impl_infos.borrow().iter() { self.push_candidates_from_impl(*impl_info, true); } } @@ -641,8 +641,8 @@ fn push_inherent_impl_candidates_for_type(&mut self, did: DefId) { // metadata if necessary. ty::populate_implementations_for_type_if_necessary(self.tcx(), did); - for impl_infos in self.tcx().inherent_impls.borrow().get().find(&did).iter() { - for impl_info in impl_infos.borrow().get().iter() { + for impl_infos in self.tcx().inherent_impls.borrow().find(&did).iter() { + for impl_info in impl_infos.borrow().iter() { self.push_candidates_from_impl(*impl_info, false); } } @@ -1110,7 +1110,7 @@ fn confirm_candidate(&self, rcvr_ty: ty::t, candidate: &Candidate) let m_regions = self.fcx.infcx().region_vars_for_defs( self.span, - candidate.method_ty.generics.region_param_defs.deref().as_slice()); + candidate.method_ty.generics.region_param_defs.as_slice()); for &r in m_regions.iter() { all_regions.push(r); } @@ -1259,17 +1259,14 @@ fn enforce_drop_trait_limitations(&self, candidate: &Candidate) { let bad; match candidate.origin { MethodStatic(method_id) => { - let destructors = self.tcx().destructors.borrow(); - bad = destructors.get().contains(&method_id); + bad = self.tcx().destructors.borrow().contains(&method_id); } // FIXME: does this properly enforce this on everything now // that self has been merged in? -sully MethodParam(MethodParam { trait_id: trait_id, .. }) | MethodObject(MethodObject { trait_id: trait_id, .. }) => { - let destructor_for_type = self.tcx() - .destructor_for_type - .borrow(); - bad = destructor_for_type.get().contains_key(&trait_id); + bad = self.tcx().destructor_for_type.borrow() + .contains_key(&trait_id); } } diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc/middle/typeck/check/mod.rs index b4b19d88fda..2410390b5e7 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc/middle/typeck/check/mod.rs @@ -267,7 +267,7 @@ fn new(tcx: &'a ty::ctxt, node_type_substs: RefCell::new(NodeMap::new()), adjustments: RefCell::new(NodeMap::new()), method_map: @RefCell::new(FnvHashMap::new()), - vtable_map: @RefCell::new(NodeMap::new()), + vtable_map: @RefCell::new(FnvHashMap::new()), upvar_borrow_map: RefCell::new(HashMap::new()), } } @@ -355,13 +355,11 @@ fn assign(&mut self, nid: ast::NodeId, ty_opt: Option) { // infer the variable's type let var_id = self.fcx.infcx().next_ty_var_id(); let var_ty = ty::mk_var(self.fcx.tcx(), var_id); - let mut locals = self.fcx.inh.locals.borrow_mut(); - locals.get().insert(nid, var_ty); + self.fcx.inh.locals.borrow_mut().insert(nid, var_ty); } Some(typ) => { // take type that the user specified - let mut locals = self.fcx.inh.locals.borrow_mut(); - locals.get().insert(nid, typ); + self.fcx.inh.locals.borrow_mut().insert(nid, typ); } } } @@ -375,13 +373,10 @@ fn visit_local(&mut self, local: &ast::Local, _: ()) { _ => Some(self.fcx.to_ty(local.ty)) }; self.assign(local.id, o_ty); - { - let locals = self.fcx.inh.locals.borrow(); - debug!("Local variable {} is assigned type {}", - self.fcx.pat_to_str(local.pat), - self.fcx.infcx().ty_to_str( - locals.get().get_copy(&local.id))); - } + debug!("Local variable {} is assigned type {}", + self.fcx.pat_to_str(local.pat), + self.fcx.infcx().ty_to_str( + self.fcx.inh.locals.borrow().get_copy(&local.id))); visit::walk_local(self, local, ()); } @@ -391,13 +386,10 @@ fn visit_pat(&mut self, p: &ast::Pat, _: ()) { ast::PatIdent(_, ref path, _) if pat_util::pat_is_binding(self.fcx.ccx.tcx.def_map, p) => { self.assign(p.id, None); - { - let locals = self.fcx.inh.locals.borrow(); - debug!("Pattern binding {} is assigned to {}", - token::get_ident(path.segments.get(0).identifier), - self.fcx.infcx().ty_to_str( - locals.get().get_copy(&p.id))); - } + debug!("Pattern binding {} is assigned to {}", + token::get_ident(path.segments.get(0).identifier), + self.fcx.infcx().ty_to_str( + self.fcx.inh.locals.borrow().get_copy(&p.id))); } _ => {} } @@ -573,7 +565,7 @@ pub fn check_item(ccx: &CrateCtxt, it: &ast::Item) { fn_tpt.generics.type_param_defs(), [], [], - fn_tpt.generics.region_param_defs.deref().as_slice(), + fn_tpt.generics.region_param_defs.as_slice(), body.id); check_bare_fn(ccx, decl, body, it.id, fn_tpt.ty, param_env); @@ -1007,8 +999,7 @@ pub fn tag(&self) -> ~str { } pub fn local_ty(&self, span: Span, nid: ast::NodeId) -> ty::t { - let locals = self.inh.locals.borrow(); - match locals.get().find(&nid) { + match self.inh.locals.borrow().find(&nid) { Some(&t) => t, None => { self.tcx().sess.span_bug( @@ -1026,8 +1017,7 @@ pub fn block_region(&self) -> ty::Region { pub fn write_ty(&self, node_id: ast::NodeId, ty: ty::t) { debug!("write_ty({}, {}) in fcx {}", node_id, ppaux::ty_to_str(self.tcx(), ty), self.tag()); - let mut node_types = self.inh.node_types.borrow_mut(); - node_types.get().insert(node_id, ty); + self.inh.node_types.borrow_mut().insert(node_id, ty); } pub fn write_substs(&self, node_id: ast::NodeId, substs: ty::substs) { @@ -1037,8 +1027,7 @@ pub fn write_substs(&self, node_id: ast::NodeId, substs: ty::substs) { ty::substs_to_str(self.tcx(), &substs), self.tag()); - let mut node_type_substs = self.inh.node_type_substs.borrow_mut(); - node_type_substs.get().insert(node_id, substs); + self.inh.node_type_substs.borrow_mut().insert(node_id, substs); } } @@ -1067,8 +1056,7 @@ pub fn write_adjustment(&self, node_id: ast::NodeId, adj: @ty::AutoAdjustment) { debug!("write_adjustment(node_id={:?}, adj={:?})", node_id, adj); - let mut adjustments = self.inh.adjustments.borrow_mut(); - adjustments.get().insert(node_id, adj); + self.inh.adjustments.borrow_mut().insert(node_id, adj); } pub fn write_nil(&self, node_id: ast::NodeId) { @@ -1090,8 +1078,7 @@ pub fn pat_to_str(&self, pat: &ast::Pat) -> ~str { } pub fn expr_ty(&self, ex: &ast::Expr) -> ty::t { - let node_types = self.inh.node_types.borrow(); - match node_types.get().find(&ex.id) { + match self.inh.node_types.borrow().find(&ex.id) { Some(&t) => t, None => { self.tcx().sess.bug(format!("no type for expr in fcx {}", @@ -1101,7 +1088,7 @@ pub fn expr_ty(&self, ex: &ast::Expr) -> ty::t { } pub fn node_ty(&self, id: ast::NodeId) -> ty::t { - match self.inh.node_types.borrow().get().find(&id) { + match self.inh.node_types.borrow().find(&id) { Some(&t) => t, None => { self.tcx().sess.bug( @@ -1113,7 +1100,7 @@ pub fn node_ty(&self, id: ast::NodeId) -> ty::t { } pub fn node_ty_substs(&self, id: ast::NodeId) -> ty::substs { - match self.inh.node_type_substs.borrow().get().find(&id) { + match self.inh.node_type_substs.borrow().find(&id) { Some(ts) => (*ts).clone(), None => { self.tcx().sess.bug( @@ -1125,7 +1112,7 @@ pub fn node_ty_substs(&self, id: ast::NodeId) -> ty::substs { } pub fn method_ty_substs(&self, id: ast::NodeId) -> ty::substs { - match self.inh.method_map.borrow().get().find(&MethodCall::expr(id)) { + match self.inh.method_map.borrow().find(&MethodCall::expr(id)) { Some(method) => method.substs.clone(), None => { self.tcx().sess.bug( @@ -1140,8 +1127,7 @@ pub fn opt_node_ty_substs(&self, id: ast::NodeId, f: |&ty::substs| -> bool) -> bool { - let node_type_substs = self.inh.node_type_substs.borrow(); - match node_type_substs.get().find(&id) { + match self.inh.node_type_substs.borrow().find(&id) { Some(s) => f(s), None => true } @@ -1327,7 +1313,7 @@ fn try_overloaded_deref(fcx: &FnCtxt, let ref_ty = ty::ty_fn_ret(method.ty); match method_call { Some(method_call) => { - fcx.inh.method_map.borrow_mut().get().insert(method_call, method); + fcx.inh.method_map.borrow_mut().insert(method_call, method); } None => {} } @@ -1908,7 +1894,7 @@ fn check_method_call(fcx: &FnCtxt, Some(method) => { let method_ty = method.ty; let method_call = MethodCall::expr(expr.id); - fcx.inh.method_map.borrow_mut().get().insert(method_call, method); + fcx.inh.method_map.borrow_mut().insert(method_call, method); method_ty } None => { @@ -1998,7 +1984,7 @@ fn lookup_op_method(fcx: &FnCtxt, let method_ty = method.ty; // HACK(eddyb) Fully qualified path to work around a resolve bug. let method_call = ::middle::typeck::MethodCall::expr(op_ex.id); - fcx.inh.method_map.borrow_mut().get().insert(method_call, method); + fcx.inh.method_map.borrow_mut().insert(method_call, method); check_method_argument_types(fcx, op_ex.span, method_ty, op_ex, args, DoDerefArgs) @@ -3131,8 +3117,7 @@ fn types_compatible(fcx: &FnCtxt, sp: Span, } ast::ExprStruct(ref path, ref fields, base_expr) => { // Resolve the path. - let def_map = tcx.def_map.borrow(); - match def_map.get().find(&id) { + match tcx.def_map.borrow().find(&id) { Some(&ast::DefStruct(type_def_id)) => { check_struct_constructor(fcx, id, expr.span, type_def_id, fields.as_slice(), base_expr); @@ -3323,8 +3308,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.get().recurse(blk); - replace(fcx_ps.get(), purity_state) + let purity_state = fcx_ps.recurse(blk); + replace(&mut *fcx_ps, purity_state) }; fcx.with_region_lb(blk.id, || { @@ -3394,10 +3379,7 @@ pub fn check_const(ccx: &CrateCtxt, let inh = blank_inherited_fields(ccx); let rty = ty::node_id_to_type(ccx.tcx, id); let fcx = blank_fn_ctxt(ccx, &inh, rty, e.id); - let declty = { - let tcache = fcx.ccx.tcx.tcache.borrow(); - tcache.get().get(&local_def(id)).ty - }; + let declty = fcx.ccx.tcx.tcache.borrow().get(&local_def(id)).ty; check_const_with_ty(&fcx, sp, e, declty); } @@ -3608,10 +3590,7 @@ fn do_check(ccx: &CrateCtxt, let variants = do_check(ccx, vs, id, hint); // cache so that ty::enum_variants won't repeat this work - { - let mut enum_var_cache = ccx.tcx.enum_var_cache.borrow_mut(); - enum_var_cache.get().insert(local_def(id), @variants); - } + ccx.tcx.enum_var_cache.borrow_mut().insert(local_def(id), @variants); // Check that it is possible to represent this enum. check_representable(ccx.tcx, sp, id, "enum"); @@ -3719,7 +3698,7 @@ pub fn instantiate_path(fcx: &FnCtxt, nsupplied = num_supplied_regions)); } - fcx.infcx().region_vars_for_defs(span, tpt.generics.region_param_defs.deref().as_slice()) + fcx.infcx().region_vars_for_defs(span, tpt.generics.region_param_defs.as_slice()) }; let regions = ty::NonerasedRegions(regions); @@ -3958,8 +3937,7 @@ pub fn may_break(cx: &ty::ctxt, id: ast::NodeId, b: ast::P) -> bool (block_query(b, |e| { match e.node { ast::ExprBreak(Some(_)) => { - let def_map = cx.def_map.borrow(); - match def_map.get().find(&e.id) { + match cx.def_map.borrow().find(&e.id) { Some(&ast::DefLabel(loop_id)) if id == loop_id => true, _ => false, } diff --git a/src/librustc/middle/typeck/check/regionck.rs b/src/librustc/middle/typeck/check/regionck.rs index 1533943a55c..e67a83cd926 100644 --- a/src/librustc/middle/typeck/check/regionck.rs +++ b/src/librustc/middle/typeck/check/regionck.rs @@ -241,7 +241,7 @@ fn resolve_node_type(&mut self, id: ast::NodeId) -> ty::t { } fn resolve_method_type(&self, method_call: MethodCall) -> Option { - let method_ty = self.fcx.inh.method_map.borrow().get() + let method_ty = self.fcx.inh.method_map.borrow() .find(&method_call).map(|method| method.ty); method_ty.map(|method_ty| self.resolve_type(method_ty)) } @@ -253,7 +253,7 @@ pub fn resolve_expr_type_adjusted(&mut self, expr: &ast::Expr) -> ty::t { ty_unadjusted } else { let tcx = self.fcx.tcx(); - let adjustment = self.fcx.inh.adjustments.borrow().get().find_copy(&expr.id); + let adjustment = self.fcx.inh.adjustments.borrow().find_copy(&expr.id); ty::adjust_ty(tcx, expr.span, expr.id, ty_unadjusted, adjustment, |method_call| self.resolve_method_type(method_call)) } @@ -275,12 +275,11 @@ fn node_method_ty(&self, method_call: MethodCall) -> Option { } fn adjustment(&mut self, id: ast::NodeId) -> Option<@ty::AutoAdjustment> { - let adjustments = self.fcx.inh.adjustments.borrow(); - adjustments.get().find_copy(&id) + self.fcx.inh.adjustments.borrow().find_copy(&id) } fn is_method_call(&mut self, id: ast::NodeId) -> bool { - self.fcx.inh.method_map.borrow().get().contains_key(&MethodCall::expr(id)) + self.fcx.inh.method_map.borrow().contains_key(&MethodCall::expr(id)) } fn temporary_scope(&mut self, id: ast::NodeId) -> Option { @@ -288,8 +287,7 @@ fn temporary_scope(&mut self, id: ast::NodeId) -> Option { } fn upvar_borrow(&mut self, id: ty::UpvarId) -> ty::UpvarBorrow { - let upvar_borrow_map = self.fcx.inh.upvar_borrow_map.borrow(); - upvar_borrow_map.get().get_copy(&id) + self.fcx.inh.upvar_borrow_map.borrow().get_copy(&id) } } @@ -403,7 +401,7 @@ fn visit_expr(rcx: &mut Rcx, expr: &ast::Expr) { let has_method_map = rcx.fcx.inh.method_map.get().contains_key(&method_call); // Check any autoderefs or autorefs that appear. - for &adjustment in rcx.fcx.inh.adjustments.borrow().get().find(&expr.id).iter() { + for &adjustment in rcx.fcx.inh.adjustments.borrow().find(&expr.id).iter() { debug!("adjustment={:?}", adjustment); match **adjustment { ty::AutoDerefRef(ty::AutoDerefRef {autoderefs, autoref: opt_autoref}) => { @@ -678,8 +676,8 @@ fn constrain_free_variables(rcx: &mut Rcx, // immutable as dictated by the uses. let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow, region: freevar_region }; - let mut upvar_borrow_map = rcx.fcx.inh.upvar_borrow_map.borrow_mut(); - upvar_borrow_map.get().insert(upvar_id, upvar_borrow); + rcx.fcx.inh.upvar_borrow_map.borrow_mut().insert(upvar_id, + upvar_borrow); // Guarantee that the closure does not outlive the variable itself. let en_region = region_of_def(rcx.fcx, def); @@ -951,7 +949,7 @@ fn constrain_regions_in_type_of_node( // is going to fail anyway, so just stop here and let typeck // report errors later on in the writeback phase. let ty0 = rcx.resolve_node_type(id); - let adjustment = rcx.fcx.inh.adjustments.borrow().get().find_copy(&id); + let adjustment = rcx.fcx.inh.adjustments.borrow().find_copy(&id); let ty = ty::adjust_ty(tcx, origin.span(), id, ty0, adjustment, |method_call| rcx.resolve_method_type(method_call)); debug!("constrain_regions_in_type_of_node(\ @@ -1204,9 +1202,8 @@ fn link_region(rcx: &mut Rcx, // to use for each upvar. let cause = match base.cat { mc::cat_upvar(ref upvar_id, _) => { - let mut upvar_borrow_map = - rcx.fcx.inh.upvar_borrow_map.borrow_mut(); - match upvar_borrow_map.get().find_mut(upvar_id) { + match rcx.fcx.inh.upvar_borrow_map.borrow_mut() + .find_mut(upvar_id) { Some(upvar_borrow) => { debug!("link_region: {} <= {}", region_min.repr(rcx.tcx()), @@ -1324,7 +1321,7 @@ fn adjust_upvar_borrow_kind_for_mut(rcx: &mut Rcx, // is inferred to mutable if necessary let mut upvar_borrow_map = rcx.fcx.inh.upvar_borrow_map.borrow_mut(); - let ub = upvar_borrow_map.get().get_mut(upvar_id); + let ub = upvar_borrow_map.get_mut(upvar_id); return adjust_upvar_borrow_kind(*upvar_id, ub, ty::MutBorrow); } @@ -1377,9 +1374,8 @@ fn adjust_upvar_borrow_kind_for_unique(rcx: &mut Rcx, // upvar, then we need to modify the // borrow_kind of the upvar to make sure it // is inferred to unique if necessary - let mut upvar_borrow_map = - rcx.fcx.inh.upvar_borrow_map.borrow_mut(); - let ub = upvar_borrow_map.get().get_mut(upvar_id); + let mut ub = rcx.fcx.inh.upvar_borrow_map.borrow_mut(); + let ub = ub.get_mut(upvar_id); return adjust_upvar_borrow_kind(*upvar_id, ub, ty::UniqueImmBorrow); } @@ -1419,8 +1415,8 @@ fn link_upvar_borrow_kind_for_nested_closures(rcx: &mut Rcx, inner_upvar_id, outer_upvar_id); let mut upvar_borrow_map = rcx.fcx.inh.upvar_borrow_map.borrow_mut(); - let inner_borrow = upvar_borrow_map.get().get_copy(&inner_upvar_id); - match upvar_borrow_map.get().find_mut(&outer_upvar_id) { + let inner_borrow = upvar_borrow_map.get_copy(&inner_upvar_id); + match upvar_borrow_map.find_mut(&outer_upvar_id) { Some(outer_borrow) => { adjust_upvar_borrow_kind(outer_upvar_id, outer_borrow, inner_borrow.kind); } diff --git a/src/librustc/middle/typeck/check/vtable.rs b/src/librustc/middle/typeck/check/vtable.rs index e3c6db17081..15de3bf2b5f 100644 --- a/src/librustc/middle/typeck/check/vtable.rs +++ b/src/librustc/middle/typeck/check/vtable.rs @@ -321,15 +321,10 @@ fn search_for_vtable(vcx: &VtableContext, // FIXME: this is a bad way to do this, since we do // pointless allocations. - let impls = { - let trait_impls = tcx.trait_impls.borrow(); - trait_impls.get() - .find(&trait_ref.def_id) - .map_or(@RefCell::new(Vec::new()), |x| *x) - }; + let impls = tcx.trait_impls.borrow().find(&trait_ref.def_id) + .map_or(@RefCell::new(Vec::new()), |x| *x); // impls is the list of all impls in scope for trait_ref. - let impls = impls.borrow(); - for im in impls.get().iter() { + for im in impls.borrow().iter() { // im is one specific impl of trait_ref. // First, ensure we haven't processed this impl yet. @@ -521,10 +516,10 @@ fn connect_trait_tps(vcx: &VtableContext, relate_trait_refs(vcx, span, impl_trait_ref, trait_ref); } -fn insert_vtables(fcx: &FnCtxt, expr_id: ast::NodeId, vtables: vtable_res) { - debug!("insert_vtables(expr_id={}, vtables={:?})", - expr_id, vtables.repr(fcx.tcx())); - fcx.inh.vtable_map.borrow_mut().get().insert(expr_id, vtables); +fn insert_vtables(fcx: &FnCtxt, vtable_key: MethodCall, vtables: vtable_res) { + debug!("insert_vtables(vtable_key={}, vtables={:?})", + vtable_key, vtables.repr(fcx.tcx())); + fcx.inh.vtable_map.borrow_mut().insert(vtable_key, vtables); } pub fn early_resolve_expr(ex: &ast::Expr, fcx: &FnCtxt, is_early: bool) { @@ -596,7 +591,7 @@ fn mutability_allowed(a_mutbl: ast::Mutability, is_early); if !is_early { - insert_vtables(fcx, ex.id, @vec!(vtables)); + insert_vtables(fcx, MethodCall::expr(ex.id), @vec!(vtables)); } // Now, if this is &trait, we need to link the @@ -640,8 +635,7 @@ fn mutability_allowed(a_mutbl: ast::Mutability, fcx.opt_node_ty_substs(ex.id, |substs| { debug!("vtable resolution on parameter bounds for expr {}", ex.repr(fcx.tcx())); - let def_map = cx.tcx.def_map.borrow(); - let def = def_map.get().get_copy(&ex.id); + let def = cx.tcx.def_map.borrow().get_copy(&ex.id); let did = ast_util::def_id_of_def(def); let item_ty = ty::lookup_item_type(cx.tcx, did); debug!("early resolve expr: def {:?} {:?}, {:?}, {}", ex.id, did, def, @@ -654,7 +648,7 @@ fn mutability_allowed(a_mutbl: ast::Mutability, item_ty.generics.type_param_defs(), substs, is_early); if !is_early { - insert_vtables(fcx, ex.id, vtbls); + insert_vtables(fcx, MethodCall::expr(ex.id), vtbls); } } true @@ -667,20 +661,19 @@ fn mutability_allowed(a_mutbl: ast::Mutability, ast::ExprAssignOp(_, _, _) | ast::ExprIndex(_, _) | ast::ExprMethodCall(_, _, _) => { - match fcx.inh.method_map.borrow().get().find(&MethodCall::expr(ex.id)) { + match fcx.inh.method_map.borrow().find(&MethodCall::expr(ex.id)) { Some(method) => { debug!("vtable resolution on parameter bounds for method call {}", ex.repr(fcx.tcx())); let type_param_defs = ty::method_call_type_param_defs(cx.tcx, method.origin); - if has_trait_bounds(type_param_defs.deref().as_slice()) { + if has_trait_bounds(type_param_defs.as_slice()) { let substs = fcx.method_ty_substs(ex.id); let vcx = fcx.vtable_context(); let vtbls = lookup_vtables(&vcx, ex.span, - type_param_defs.deref() - .as_slice(), + type_param_defs.as_slice(), &substs, is_early); if !is_early { - insert_vtables(fcx, ex.id, vtbls); + insert_vtables(fcx, MethodCall::expr(ex.id), vtbls); } } } @@ -696,10 +689,33 @@ fn mutability_allowed(a_mutbl: ast::Mutability, } // Search for auto-adjustments to find trait coercions - let adjustments = fcx.inh.adjustments.borrow(); - match adjustments.get().find(&ex.id) { + match fcx.inh.adjustments.borrow().find(&ex.id) { Some(adjustment) => { match **adjustment { + AutoDerefRef(adj) => { + for autoderef in range(0, adj.autoderefs) { + let method_call = MethodCall::autoderef(ex.id, autoderef as u32); + match fcx.inh.method_map.borrow().find(&method_call) { + Some(method) => { + debug!("vtable resolution on parameter bounds for autoderef {}", + ex.repr(fcx.tcx())); + let type_param_defs = + ty::method_call_type_param_defs(cx.tcx, method.origin); + if has_trait_bounds(type_param_defs.deref().as_slice()) { + let vcx = fcx.vtable_context(); + let vtbls = lookup_vtables(&vcx, ex.span, + type_param_defs.deref() + .as_slice(), + &method.substs, is_early); + if !is_early { + insert_vtables(fcx, method_call, vtbls); + } + } + } + None => {} + } + } + } AutoObject(ref sigil, ref region, m, @@ -721,7 +737,7 @@ fn mutability_allowed(a_mutbl: ast::Mutability, b); resolve_object_cast(ex, object_ty); } - AutoAddEnv(..) | AutoDerefRef(..) => {} + AutoAddEnv(..) => {} } } None => {} @@ -779,8 +795,7 @@ pub fn resolve_impl(tcx: &ty::ctxt, }; let impl_def_id = ast_util::local_def(impl_item.id); - let mut impl_vtables = tcx.impl_vtables.borrow_mut(); - impl_vtables.get().insert(impl_def_id, res); + tcx.impl_vtables.borrow_mut().insert(impl_def_id, res); } /// Resolve vtables for a method call after typeck has finished. @@ -788,7 +803,7 @@ pub fn resolve_impl(tcx: &ty::ctxt, pub fn trans_resolve_method(tcx: &ty::ctxt, id: ast::NodeId, substs: &ty::substs) -> Option { let generics = ty::lookup_item_type(tcx, ast_util::local_def(id)).generics; - let type_param_defs = generics.type_param_defs.deref(); + let type_param_defs = &*generics.type_param_defs; if has_trait_bounds(type_param_defs.as_slice()) { let vcx = VtableContext { infcx: &infer::new_infer_ctxt(tcx), diff --git a/src/librustc/middle/typeck/check/writeback.rs b/src/librustc/middle/typeck/check/writeback.rs index 669f14ccb8c..31d74a1e938 100644 --- a/src/librustc/middle/typeck/check/writeback.rs +++ b/src/librustc/middle/typeck/check/writeback.rs @@ -21,8 +21,7 @@ use middle::typeck::infer::resolve_type; use middle::typeck::infer; use middle::typeck::{MethodCall, MethodCallee}; -use middle::typeck::{vtable_res, vtable_origin}; -use middle::typeck::{vtable_static, vtable_param}; +use middle::typeck::{vtable_res, vtable_static, vtable_param}; use middle::typeck::write_substs_to_tcx; use middle::typeck::write_ty_to_tcx; use util::ppaux; @@ -67,7 +66,7 @@ fn resolve_method_map_entry(wbcx: &mut WbCtxt, sp: Span, method_call: MethodCall let tcx = fcx.ccx.tcx; // Resolve any method map entry - match fcx.inh.method_map.borrow().get().find(&method_call) { + match fcx.inh.method_map.borrow().find(&method_call) { Some(method) => { debug!("writeback::resolve_method_map_entry(call={:?}, entry={:?})", method_call, method.repr(tcx)); @@ -94,44 +93,40 @@ fn resolve_method_map_entry(wbcx: &mut WbCtxt, sp: Span, method_call: MethodCall self_ty: None } }; - fcx.ccx.method_map.borrow_mut().get().insert(method_call, new_method); + fcx.ccx.method_map.borrow_mut().insert(method_call, new_method); } None => {} } } -fn resolve_vtable_map_entry(fcx: &FnCtxt, sp: Span, id: ast::NodeId) { +fn resolve_vtable_map_entry(fcx: &FnCtxt, sp: Span, vtable_key: MethodCall) { // Resolve any vtable map entry - match fcx.inh.vtable_map.borrow().get().find_copy(&id) { + match fcx.inh.vtable_map.borrow().find_copy(&vtable_key) { Some(origins) => { let r_origins = resolve_origins(fcx, sp, origins); - fcx.ccx.vtable_map.borrow_mut().get().insert(id, r_origins); - debug!("writeback::resolve_vtable_map_entry(id={}, vtables={:?})", - id, r_origins.repr(fcx.tcx())); + fcx.ccx.vtable_map.borrow_mut().insert(vtable_key, r_origins); + debug!("writeback::resolve_vtable_map_entry(vtable_key={}, vtables={:?})", + vtable_key, r_origins.repr(fcx.tcx())); } None => {} } fn resolve_origins(fcx: &FnCtxt, sp: Span, vtbls: vtable_res) -> vtable_res { - @vtbls.map(|os| @os.map(|o| resolve_origin(fcx, sp, o))) - } - - fn resolve_origin(fcx: &FnCtxt, - sp: Span, - origin: &vtable_origin) -> vtable_origin { - match origin { - &vtable_static(def_id, ref tys, origins) => { - let r_tys = resolve_type_vars_in_types(fcx, - sp, - tys.as_slice()); - let r_origins = resolve_origins(fcx, sp, origins); - vtable_static(def_id, r_tys, r_origins) - } - &vtable_param(n, b) => { - vtable_param(n, b) + @vtbls.map(|os| @os.map(|origin| { + match origin { + &vtable_static(def_id, ref tys, origins) => { + let r_tys = resolve_type_vars_in_types(fcx, + sp, + tys.as_slice()); + let r_origins = resolve_origins(fcx, sp, origins); + vtable_static(def_id, r_tys, r_origins) + } + &vtable_param(n, b) => { + vtable_param(n, b) + } } - } + })) } } @@ -141,8 +136,7 @@ fn resolve_type_vars_for_node(wbcx: &mut WbCtxt, sp: Span, id: ast::NodeId) let tcx = fcx.ccx.tcx; // Resolve any borrowings for the node with id `id` - let adjustment = fcx.inh.adjustments.borrow().get().find_copy(&id); - match adjustment { + match fcx.inh.adjustments.borrow().find_copy(&id) { None => (), Some(adjustment) => { @@ -163,7 +157,7 @@ fn resolve_type_vars_for_node(wbcx: &mut WbCtxt, sp: Span, id: ast::NodeId) // FIXME(eddyb) #2190 Allow only statically resolved // bare functions to coerce to a closure to avoid // constructing (slower) indirect call wrappers. - match tcx.def_map.borrow().get().find(&id) { + match tcx.def_map.borrow().find(&id) { Some(&ast::DefFn(..)) | Some(&ast::DefStaticMethod(..)) | Some(&ast::DefVariant(..)) | @@ -175,7 +169,7 @@ fn resolve_type_vars_for_node(wbcx: &mut WbCtxt, sp: Span, id: ast::NodeId) let resolved_adj = @ty::AutoAddEnv(r1, s); debug!("Adjustments for node {}: {:?}", id, resolved_adj); - tcx.adjustments.borrow_mut().get().insert(id, resolved_adj); + tcx.adjustments.borrow_mut().insert(id, resolved_adj); } } } @@ -184,6 +178,7 @@ fn resolve_type_vars_for_node(wbcx: &mut WbCtxt, sp: Span, id: ast::NodeId) for autoderef in range(0, adj.autoderefs) { let method_call = MethodCall::autoderef(id, autoderef as u32); resolve_method_map_entry(wbcx, sp, method_call); + resolve_vtable_map_entry(wbcx.fcx, sp, method_call); } let fixup_region = |r| { @@ -213,12 +208,12 @@ fn resolve_type_vars_for_node(wbcx: &mut WbCtxt, sp: Span, id: ast::NodeId) autoref: resolved_autoref, }); debug!("Adjustments for node {}: {:?}", id, resolved_adj); - tcx.adjustments.borrow_mut().get().insert(id, resolved_adj); + tcx.adjustments.borrow_mut().insert(id, resolved_adj); } ty::AutoObject(..) => { debug!("Adjustments for node {}: {:?}", id, adjustment); - tcx.adjustments.borrow_mut().get().insert(id, adjustment); + tcx.adjustments.borrow_mut().insert(id, adjustment); } } } @@ -274,7 +269,7 @@ fn visit_expr(e: &ast::Expr, wbcx: &mut WbCtxt) { resolve_type_vars_for_node(wbcx, e.span, e.id); resolve_method_map_entry(wbcx, e.span, MethodCall::expr(e.id)); - resolve_vtable_map_entry(wbcx.fcx, e.span, e.id); + resolve_vtable_map_entry(wbcx.fcx, e.span, MethodCall::expr(e.id)); match e.node { ast::ExprFnBlock(ref decl, _) | ast::ExprProc(ref decl, _) => { @@ -355,8 +350,7 @@ fn resolve_upvar_borrow_map(wbcx: &mut WbCtxt) { let fcx = wbcx.fcx; let tcx = fcx.tcx(); - let upvar_borrow_map = fcx.inh.upvar_borrow_map.borrow(); - for (upvar_id, upvar_borrow) in upvar_borrow_map.get().iter() { + for (upvar_id, upvar_borrow) in fcx.inh.upvar_borrow_map.borrow().iter() { let r = upvar_borrow.region; match resolve_region(fcx.infcx(), r, resolve_all | force_all) { Ok(r) => { @@ -366,8 +360,8 @@ fn resolve_upvar_borrow_map(wbcx: &mut WbCtxt) { }; debug!("Upvar borrow for {} resolved to {}", upvar_id.repr(tcx), new_upvar_borrow.repr(tcx)); - let mut tcx_upvar_borrow_map = tcx.upvar_borrow_map.borrow_mut(); - tcx_upvar_borrow_map.get().insert(*upvar_id, new_upvar_borrow); + tcx.upvar_borrow_map.borrow_mut().insert(*upvar_id, + new_upvar_borrow); } Err(e) => { let span = ty::expr_span(tcx, upvar_id.closure_expr_id); diff --git a/src/librustc/middle/typeck/coherence.rs b/src/librustc/middle/typeck/coherence.rs index c75e56914b2..321de8925ac 100644 --- a/src/librustc/middle/typeck/coherence.rs +++ b/src/librustc/middle/typeck/coherence.rs @@ -306,8 +306,7 @@ fn check_implementation(&self, item: &Item, } } - let mut impls = tcx.impls.borrow_mut(); - impls.get().insert(implementation.did, implementation); + tcx.impls.borrow_mut().insert(implementation.did, implementation); } // Creates default method IDs and performs type substitutions for an impl @@ -359,20 +358,13 @@ fn instantiate_default_methods(&self, impl_id: ast::DefId, }; debug!("new_polytype={}", new_polytype.repr(tcx)); - { - let mut tcache = tcx.tcache.borrow_mut(); - tcache.get().insert(new_did, new_polytype); - } - - let mut methods = tcx.methods.borrow_mut(); - methods.get().insert(new_did, new_method_ty); + tcx.tcache.borrow_mut().insert(new_did, new_polytype); + tcx.methods.borrow_mut().insert(new_did, new_method_ty); // Pair the new synthesized ID up with the // ID of the method. - let mut provided_method_sources = - self.crate_context.tcx.provided_method_sources.borrow_mut(); - provided_method_sources.get().insert(new_did, - trait_method.def_id); + self.crate_context.tcx.provided_method_sources.borrow_mut() + .insert(new_did, trait_method.def_id); } } @@ -381,18 +373,17 @@ fn add_inherent_impl(&self, base_def_id: DefId, let tcx = self.crate_context.tcx; let implementation_list; let mut inherent_impls = tcx.inherent_impls.borrow_mut(); - match inherent_impls.get().find(&base_def_id) { + match inherent_impls.find(&base_def_id) { None => { implementation_list = @RefCell::new(Vec::new()); - inherent_impls.get().insert(base_def_id, implementation_list); + inherent_impls.insert(base_def_id, implementation_list); } Some(&existing_implementation_list) => { implementation_list = existing_implementation_list; } } - let mut implementation_list = implementation_list.borrow_mut(); - implementation_list.get().push(implementation); + implementation_list.borrow_mut().push(implementation); } fn add_trait_impl(&self, base_def_id: DefId, @@ -400,23 +391,21 @@ fn add_trait_impl(&self, base_def_id: DefId, let tcx = self.crate_context.tcx; let implementation_list; let mut trait_impls = tcx.trait_impls.borrow_mut(); - match trait_impls.get().find(&base_def_id) { + match trait_impls.find(&base_def_id) { None => { implementation_list = @RefCell::new(Vec::new()); - trait_impls.get().insert(base_def_id, implementation_list); + trait_impls.insert(base_def_id, implementation_list); } Some(&existing_implementation_list) => { implementation_list = existing_implementation_list; } } - let mut implementation_list = implementation_list.borrow_mut(); - implementation_list.get().push(implementation); + implementation_list.borrow_mut().push(implementation); } fn check_implementation_coherence(&self) { - let trait_impls = self.crate_context.tcx.trait_impls.borrow(); - for &trait_id in trait_impls.get().keys() { + for &trait_id in self.crate_context.tcx.trait_impls.borrow().keys() { self.check_implementation_coherence_of(trait_id); } } @@ -476,11 +465,9 @@ fn iter_impls_of_trait(&self, trait_def_id: DefId, f: |@Impl|) { } fn iter_impls_of_trait_local(&self, trait_def_id: DefId, f: |@Impl|) { - let trait_impls = self.crate_context.tcx.trait_impls.borrow(); - match trait_impls.get().find(&trait_def_id) { + match self.crate_context.tcx.trait_impls.borrow().find(&trait_def_id) { Some(impls) => { - let impls = impls.borrow(); - for &im in impls.get().iter() { + for &im in impls.borrow().iter() { f(im); } } @@ -543,8 +530,7 @@ fn can_unify_universally_quantified<'a>(&self, fn get_self_type_for_implementation(&self, implementation: @Impl) -> ty_param_bounds_and_ty { - let tcache = self.crate_context.tcx.tcache.borrow(); - return tcache.get().get_copy(&implementation.did); + self.crate_context.tcx.tcache.borrow().get_copy(&implementation.did) } // Privileged scope checking @@ -555,8 +541,7 @@ fn check_privileged_scopes(&self, krate: &Crate) { fn trait_ref_to_trait_def_id(&self, trait_ref: &TraitRef) -> DefId { let def_map = self.crate_context.tcx.def_map; - let def_map = def_map.borrow(); - let trait_def = def_map.get().get_copy(&trait_ref.ref_id); + let trait_def = def_map.borrow().get_copy(&trait_ref.ref_id); let trait_id = def_id_of_def(trait_def); return trait_id; } @@ -567,8 +552,7 @@ fn trait_ref_to_trait_def_id(&self, trait_ref: &TraitRef) -> DefId { fn ast_type_is_defined_in_local_crate(&self, original_type: &ast::Ty) -> bool { match original_type.node { TyPath(_, _, path_id) => { - let def_map = self.crate_context.tcx.def_map.borrow(); - match def_map.get().get_copy(&path_id) { + match self.crate_context.tcx.def_map.borrow().get_copy(&path_id) { DefTy(def_id) | DefStruct(def_id) => { if def_id.krate != LOCAL_CRATE { return false; @@ -666,14 +650,12 @@ fn add_external_impl(&self, // the map. This is a bit unfortunate. for method in implementation.methods.iter() { for source in method.provided_source.iter() { - let mut provided_method_sources = tcx.provided_method_sources - .borrow_mut(); - provided_method_sources.get().insert(method.def_id, *source); + tcx.provided_method_sources.borrow_mut() + .insert(method.def_id, *source); } } - let mut impls = tcx.impls.borrow_mut(); - impls.get().insert(implementation.did, implementation); + tcx.impls.borrow_mut().insert(implementation.did, implementation); } // Adds implementations and traits from external crates to the coherence @@ -701,15 +683,14 @@ fn populate_destructor_table(&self) { }; let trait_impls = tcx.trait_impls.borrow(); - let impls_opt = trait_impls.get().find(&drop_trait); + let impls_opt = trait_impls.find(&drop_trait); let impls; match impls_opt { None => return, // No types with (new-style) dtors present. Some(found_impls) => impls = found_impls } - let impls = impls.borrow(); - for impl_info in impls.get().iter() { + for impl_info in impls.borrow().iter() { if impl_info.methods.len() < 1 { // We'll error out later. For now, just don't ICE. continue; @@ -720,12 +701,9 @@ fn populate_destructor_table(&self) { match ty::get(self_type.ty).sty { ty::ty_enum(type_def_id, _) | ty::ty_struct(type_def_id, _) => { - let mut destructor_for_type = tcx.destructor_for_type - .borrow_mut(); - destructor_for_type.get().insert(type_def_id, - method_def_id); - let mut destructors = tcx.destructors.borrow_mut(); - destructors.get().insert(method_def_id); + tcx.destructor_for_type.borrow_mut().insert(type_def_id, + method_def_id); + tcx.destructors.borrow_mut().insert(method_def_id); } _ => { // Destructors only work on nominal types. diff --git a/src/librustc/middle/typeck/collect.rs b/src/librustc/middle/typeck/collect.rs index 4eeae31d0a4..9ed59bd19b9 100644 --- a/src/librustc/middle/typeck/collect.rs +++ b/src/librustc/middle/typeck/collect.rs @@ -82,8 +82,7 @@ fn collect_intrinsic_type(ccx: &CrateCtxt, lang_item: ast::DefId) { let ty::ty_param_bounds_and_ty { ty: ty, .. } = ccx.get_item_ty(lang_item); - let mut intrinsic_defs = ccx.tcx.intrinsic_defs.borrow_mut(); - intrinsic_defs.get().insert(lang_item, ty); + ccx.tcx.intrinsic_defs.borrow_mut().insert(lang_item, ty); } match ccx.tcx.lang_items.ty_desc() { @@ -180,10 +179,7 @@ pub fn get_enum_variant_types(ccx: &CrateCtxt, ty: result_ty }; - { - let mut tcache = tcx.tcache.borrow_mut(); - tcache.get().insert(local_def(variant.node.id), tpt); - } + tcx.tcache.borrow_mut().insert(local_def(variant.node.id), tpt); write_ty_to_tcx(tcx, variant.node.id, result_ty); } @@ -221,8 +217,8 @@ pub fn ensure_trait_methods(ccx: &CrateCtxt, trait_id: ast::NodeId) { &trait_ty_generics); } - let mut methods = tcx.methods.borrow_mut(); - methods.get().insert(ty_method.def_id, ty_method); + tcx.methods.borrow_mut().insert(ty_method.def_id, + ty_method); } // Add an entry mapping @@ -238,13 +234,10 @@ pub fn ensure_trait_methods(ccx: &CrateCtxt, trait_id: ast::NodeId) { }); let trait_def_id = local_def(trait_id); - let mut trait_method_def_ids = tcx.trait_method_def_ids - .borrow_mut(); - trait_method_def_ids.get() - .insert(trait_def_id, - @method_def_ids.iter() - .map(|x| *x) - .collect()); + tcx.trait_method_def_ids.borrow_mut() + .insert(trait_def_id, @method_def_ids.iter() + .map(|x| *x) + .collect()); } _ => {} // Ignore things that aren't traits. } @@ -345,8 +338,7 @@ fn make_static_method_ty(ccx: &CrateCtxt, let mut new_type_param_defs = Vec::new(); let substd_type_param_defs = trait_ty_generics.type_param_defs.subst(tcx, &substs); - new_type_param_defs.push_all(substd_type_param_defs.deref() - .as_slice()); + new_type_param_defs.push_all(substd_type_param_defs.as_slice()); // add in the "self" type parameter let self_trait_def = get_trait_def(ccx, local_def(trait_id)); @@ -363,8 +355,7 @@ fn make_static_method_ty(ccx: &CrateCtxt, // add in the type parameters from the method let substd_type_param_defs = m.generics.type_param_defs.subst(tcx, &substs); - new_type_param_defs.push_all(substd_type_param_defs.deref() - .as_slice()); + new_type_param_defs.push_all(substd_type_param_defs.as_slice()); debug!("static method {} type_param_defs={} ty={}, substs={}", m.def_id.repr(tcx), @@ -372,8 +363,7 @@ fn make_static_method_ty(ccx: &CrateCtxt, ty.repr(tcx), substs.repr(tcx)); - let mut tcache = tcx.tcache.borrow_mut(); - tcache.get().insert(m.def_id, + tcx.tcache.borrow_mut().insert(m.def_id, ty_param_bounds_and_ty { generics: ty::Generics { type_param_defs: Rc::new(new_type_param_defs), @@ -423,10 +413,7 @@ pub fn ensure_supertraits(ccx: &CrateCtxt, // Called only the first time trait_def_of_item is called. // Supertraits are ensured at the same time. - { - let supertraits = tcx.supertraits.borrow(); - assert!(!supertraits.get().contains_key(&local_def(id))); - } + assert!(!tcx.supertraits.borrow().contains_key(&local_def(id))); let self_ty = ty::mk_self(ccx.tcx, local_def(id)); let mut ty_trait_refs: Vec<@ty::TraitRef> = Vec::new(); @@ -451,8 +438,7 @@ pub fn ensure_supertraits(ccx: &CrateCtxt, } } - let mut supertraits = tcx.supertraits.borrow_mut(); - supertraits.get().insert(local_def(id), @ty_trait_refs); + tcx.supertraits.borrow_mut().insert(local_def(id), @ty_trait_refs); bounds } @@ -462,8 +448,7 @@ pub fn convert_field(ccx: &CrateCtxt, let tt = ccx.to_ty(&ExplicitRscope, v.node.ty); write_ty_to_tcx(ccx.tcx, v.node.id, tt); /* add the field to the tcache */ - let mut tcache = ccx.tcx.tcache.borrow_mut(); - tcache.get().insert(local_def(v.node.id), + ccx.tcx.tcache.borrow_mut().insert(local_def(v.node.id), ty::ty_param_bounds_and_ty { generics: struct_generics.clone(), ty: tt @@ -499,32 +484,28 @@ fn convert_methods(ccx: &CrateCtxt, m.ident.repr(ccx.tcx), m.id, fty.repr(ccx.tcx)); - { - let mut tcache = tcx.tcache.borrow_mut(); - tcache.get().insert( - local_def(m.id), - - // n.b.: the type of a method is parameterized by both - // the parameters on the receiver and those on the method - // itself - ty_param_bounds_and_ty { - generics: ty::Generics { - type_param_defs: Rc::new(vec::append( - Vec::from_slice( - rcvr_ty_generics.type_param_defs()), - m_ty_generics.type_param_defs())), - region_param_defs: Rc::new(vec::append( - Vec::from_slice(rcvr_ty_generics.region_param_defs()), - m_ty_generics.region_param_defs())), - }, - ty: fty - }); - } + tcx.tcache.borrow_mut().insert( + local_def(m.id), + + // n.b.: the type of a method is parameterized by both + // the parameters on the receiver and those on the method + // itself + ty_param_bounds_and_ty { + generics: ty::Generics { + type_param_defs: Rc::new(vec::append( + Vec::from_slice( + rcvr_ty_generics.type_param_defs()), + m_ty_generics.type_param_defs())), + region_param_defs: Rc::new(vec::append( + Vec::from_slice(rcvr_ty_generics.region_param_defs()), + m_ty_generics.region_param_defs())), + }, + ty: fty + }); write_ty_to_tcx(tcx, m.id, fty); - let mut methods = tcx.methods.borrow_mut(); - methods.get().insert(mty.def_id, mty); + tcx.methods.borrow_mut().insert(mty.def_id, mty); } fn ty_of_method(ccx: &CrateCtxt, @@ -605,13 +586,10 @@ pub fn convert(ccx: &CrateCtxt, it: &ast::Item) { let selfty = ccx.to_ty(&ExplicitRscope, selfty); write_ty_to_tcx(tcx, it.id, selfty); - { - let mut tcache = tcx.tcache.borrow_mut(); - tcache.get().insert(local_def(it.id), - ty_param_bounds_and_ty { - generics: ty_generics.clone(), - ty: selfty}); - } + tcx.tcache.borrow_mut().insert(local_def(it.id), + ty_param_bounds_and_ty { + generics: ty_generics.clone(), + ty: selfty}); // If there is a trait reference, treat the methods as always public. // This is to work around some incorrect behavior in privacy checking: @@ -670,10 +648,7 @@ pub fn convert(ccx: &CrateCtxt, it: &ast::Item) { let tpt = ty_of_item(ccx, it); write_ty_to_tcx(tcx, it.id, tpt.ty); - { - let mut tcache = tcx.tcache.borrow_mut(); - tcache.get().insert(local_def(it.id), tpt.clone()); - } + tcx.tcache.borrow_mut().insert(local_def(it.id), tpt.clone()); convert_struct(ccx, struct_def, tpt, it.id); }, @@ -719,32 +694,23 @@ pub fn convert_struct(ccx: &CrateCtxt, // Enum-like. write_ty_to_tcx(tcx, ctor_id, selfty); - { - let mut tcache = tcx.tcache.borrow_mut(); - tcache.get().insert(local_def(ctor_id), tpt); - } + tcx.tcache.borrow_mut().insert(local_def(ctor_id), tpt); } else if struct_def.fields.get(0).node.kind == ast::UnnamedField { // Tuple-like. - let inputs = { - let tcache = tcx.tcache.borrow(); - struct_def.fields.map( - |field| tcache.get().get( - &local_def(field.node.id)).ty) - }; + let inputs = struct_def.fields.map( + |field| tcx.tcache.borrow().get( + &local_def(field.node.id)).ty); let ctor_fn_ty = ty::mk_ctor_fn(tcx, ctor_id, inputs.as_slice(), selfty); write_ty_to_tcx(tcx, ctor_id, ctor_fn_ty); - { - let mut tcache = tcx.tcache.borrow_mut(); - tcache.get().insert(local_def(ctor_id), - ty_param_bounds_and_ty { - generics: tpt.generics, - ty: ctor_fn_ty - }); - } + tcx.tcache.borrow_mut().insert(local_def(ctor_id), + ty_param_bounds_and_ty { + generics: tpt.generics, + ty: ctor_fn_ty + }); } } } @@ -764,8 +730,7 @@ pub fn convert_foreign(ccx: &CrateCtxt, i: &ast::ForeignItem) { let tpt = ty_of_foreign_item(ccx, i, abis); write_ty_to_tcx(ccx.tcx, i.id, tpt.ty); - let mut tcache = ccx.tcx.tcache.borrow_mut(); - tcache.get().insert(local_def(i.id), tpt); + ccx.tcx.tcache.borrow_mut().insert(local_def(i.id), tpt); } pub fn instantiate_trait_ref(ccx: &CrateCtxt, @@ -787,8 +752,8 @@ pub fn instantiate_trait_ref(ccx: &CrateCtxt, astconv::ast_path_to_trait_ref( ccx, &rscope, trait_did, Some(self_ty), &ast_trait_ref.path); - let mut trait_refs = ccx.tcx.trait_refs.borrow_mut(); - trait_refs.get().insert(ast_trait_ref.ref_id, trait_ref); + ccx.tcx.trait_refs.borrow_mut().insert(ast_trait_ref.ref_id, + trait_ref); return trait_ref; } _ => { @@ -815,12 +780,9 @@ fn get_trait_def(ccx: &CrateCtxt, trait_id: ast::DefId) -> @ty::TraitDef { pub fn trait_def_of_item(ccx: &CrateCtxt, it: &ast::Item) -> @ty::TraitDef { let def_id = local_def(it.id); let tcx = ccx.tcx; - { - let trait_defs = tcx.trait_defs.borrow(); - match trait_defs.get().find(&def_id) { - Some(&def) => return def, - _ => {} - } + match tcx.trait_defs.borrow().find(&def_id) { + Some(&def) => return def, + _ => {} } match it.node { @@ -837,8 +799,7 @@ pub fn trait_def_of_item(ccx: &CrateCtxt, it: &ast::Item) -> @ty::TraitDef { let trait_def = @ty::TraitDef {generics: ty_generics, bounds: bounds, trait_ref: trait_ref}; - let mut trait_defs = tcx.trait_defs.borrow_mut(); - trait_defs.get().insert(def_id, trait_def); + tcx.trait_defs.borrow_mut().insert(def_id, trait_def); return trait_def; } ref s => { @@ -853,20 +814,16 @@ pub fn ty_of_item(ccx: &CrateCtxt, it: &ast::Item) -> ty::ty_param_bounds_and_ty { let def_id = local_def(it.id); let tcx = ccx.tcx; - { - let tcache = tcx.tcache.borrow(); - match tcache.get().find(&def_id) { - Some(tpt) => return tpt.clone(), - _ => {} - } + match tcx.tcache.borrow().find(&def_id) { + Some(tpt) => return tpt.clone(), + _ => {} } match it.node { ast::ItemStatic(t, _, _) => { let typ = ccx.to_ty(&ExplicitRscope, t); let tpt = no_params(typ); - let mut tcache = tcx.tcache.borrow_mut(); - tcache.get().insert(local_def(it.id), tpt.clone()); + tcx.tcache.borrow_mut().insert(local_def(it.id), tpt.clone()); return tpt; } ast::ItemFn(decl, purity, abi, ref generics, _) => { @@ -885,17 +842,13 @@ pub fn ty_of_item(ccx: &CrateCtxt, it: &ast::Item) it.id, ppaux::ty_to_str(tcx, tpt.ty)); - let mut tcache = ccx.tcx.tcache.borrow_mut(); - tcache.get().insert(local_def(it.id), tpt.clone()); + ccx.tcx.tcache.borrow_mut().insert(local_def(it.id), tpt.clone()); return tpt; } ast::ItemTy(t, ref generics) => { - { - let mut tcache = tcx.tcache.borrow_mut(); - match tcache.get().find(&local_def(it.id)) { - Some(tpt) => return tpt.clone(), - None => { } - } + match tcx.tcache.borrow_mut().find(&local_def(it.id)) { + Some(tpt) => return tpt.clone(), + None => { } } let tpt = { @@ -906,8 +859,7 @@ pub fn ty_of_item(ccx: &CrateCtxt, it: &ast::Item) } }; - let mut tcache = tcx.tcache.borrow_mut(); - tcache.get().insert(local_def(it.id), tpt.clone()); + tcx.tcache.borrow_mut().insert(local_def(it.id), tpt.clone()); return tpt; } ast::ItemEnum(_, ref generics) => { @@ -920,8 +872,7 @@ pub fn ty_of_item(ccx: &CrateCtxt, it: &ast::Item) ty: t }; - let mut tcache = tcx.tcache.borrow_mut(); - tcache.get().insert(local_def(it.id), tpt.clone()); + tcx.tcache.borrow_mut().insert(local_def(it.id), tpt.clone()); return tpt; } ast::ItemTrait(..) => { @@ -938,8 +889,7 @@ pub fn ty_of_item(ccx: &CrateCtxt, it: &ast::Item) ty: t }; - let mut tcache = tcx.tcache.borrow_mut(); - tcache.get().insert(local_def(it.id), tpt.clone()); + tcx.tcache.borrow_mut().insert(local_def(it.id), tpt.clone()); return tpt; } ast::ItemImpl(..) | ast::ItemMod(_) | @@ -997,7 +947,7 @@ pub fn ty_generics(ccx: &CrateCtxt, type_param_defs: Rc::new(ty_params.iter().enumerate().map(|(offset, param)| { let existing_def_opt = { let ty_param_defs = ccx.tcx.ty_param_defs.borrow(); - ty_param_defs.get().find(¶m.id).map(|&def| def) + ty_param_defs.find(¶m.id).map(|&def| def) }; existing_def_opt.unwrap_or_else(|| { let param_ty = ty::param_ty {idx: base_index + offset, @@ -1011,8 +961,7 @@ pub fn ty_generics(ccx: &CrateCtxt, default: default }; debug!("def for param: {}", def.repr(ccx.tcx)); - let mut ty_param_defs = ccx.tcx.ty_param_defs.borrow_mut(); - ty_param_defs.get().insert(param.id, def); + ccx.tcx.ty_param_defs.borrow_mut().insert(param.id, def); def }) }).collect()), @@ -1027,8 +976,7 @@ fn compute_bounds( * Translate the AST's notion of ty param bounds (which are an * enum consisting of a newtyped Ty or a region) to ty's * notion of ty param bounds, which can either be user-defined - * traits, or one of the two built-in traits (formerly known - * as kinds): Freeze and Send. + * traits, or the built-in trait (formerly known as kind): Send. */ let mut param_bounds = ty::ParamBounds { @@ -1100,8 +1048,7 @@ pub fn ty_of_foreign_fn_decl(ccx: &CrateCtxt, ty: t_fn }; - let mut tcache = ccx.tcx.tcache.borrow_mut(); - tcache.get().insert(def_id, tpt.clone()); + ccx.tcx.tcache.borrow_mut().insert(def_id, tpt.clone()); return tpt; } diff --git a/src/librustc/middle/typeck/infer/error_reporting.rs b/src/librustc/middle/typeck/infer/error_reporting.rs index 4cd9d46ff7a..b0fd7d7c55b 100644 --- a/src/librustc/middle/typeck/infer/error_reporting.rs +++ b/src/librustc/middle/typeck/infer/error_reporting.rs @@ -757,8 +757,7 @@ fn inc_cur_anon(&self, n: uint) { fn offset_cur_anon(&self) { let mut anon = self.cur_anon.get(); - let inserted_anons = self.inserted_anons.borrow(); - while inserted_anons.get().contains(&anon) { + while self.inserted_anons.borrow().contains(&anon) { anon += 1; } self.cur_anon.set(anon); @@ -770,8 +769,7 @@ fn inc_and_offset_cur_anon(&self, n: uint) { } fn track_anon(&self, anon: uint) { - let mut inserted_anons = self.inserted_anons.borrow_mut(); - inserted_anons.get().insert(anon); + self.inserted_anons.borrow_mut().insert(anon); } fn rebuild_generics(&self, @@ -845,8 +843,7 @@ fn rebuild_arg_ty_or_output(&self, ty_queue.push(mut_ty.ty); } ast::TyPath(ref path, _, id) => { - let def_map = self.tcx.def_map.borrow(); - let a_def = match def_map.get().find(&id) { + let a_def = match self.tcx.def_map.borrow().find(&id) { None => self.tcx.sess.fatal(format!("unbound path {}", pprust::path_to_str(path))), Some(&d) => d @@ -1258,8 +1255,7 @@ fn give_lifetime(&self) -> ast::Lifetime { if !self.taken.contains(&s) { lifetime = name_to_dummy_lifetime( token::str_to_ident(s.as_slice()).name); - let mut generated = self.generated.borrow_mut(); - generated.get().push(lifetime); + self.generated.borrow_mut().push(lifetime); break; } self.inc_counter(); diff --git a/src/librustc/middle/typeck/infer/mod.rs b/src/librustc/middle/typeck/infer/mod.rs index b1a1a6e3bd1..a6baf9ef7bf 100644 --- a/src/librustc/middle/typeck/infer/mod.rs +++ b/src/librustc/middle/typeck/infer/mod.rs @@ -530,25 +530,21 @@ pub fn in_snapshot(&self) -> bool { } pub fn start_snapshot(&self) -> Snapshot { - let ty_var_bindings = self.ty_var_bindings.borrow(); - let int_var_bindings = self.int_var_bindings.borrow(); - let float_var_bindings = self.float_var_bindings.borrow(); Snapshot { - ty_var_bindings_len: ty_var_bindings.get().bindings.len(), - int_var_bindings_len: int_var_bindings.get().bindings.len(), - float_var_bindings_len: float_var_bindings.get().bindings.len(), + ty_var_bindings_len: self.ty_var_bindings.borrow().bindings.len(), + int_var_bindings_len: self.int_var_bindings.borrow().bindings.len(), + float_var_bindings_len: self.float_var_bindings.borrow().bindings.len(), region_vars_snapshot: self.region_vars.start_snapshot(), } } pub fn rollback_to(&self, snapshot: &Snapshot) { debug!("rollback!"); - let mut ty_var_bindings = self.ty_var_bindings.borrow_mut(); - let mut int_var_bindings = self.int_var_bindings.borrow_mut(); - let mut float_var_bindings = self.float_var_bindings.borrow_mut(); - rollback_to(ty_var_bindings.get(), snapshot.ty_var_bindings_len); - rollback_to(int_var_bindings.get(), snapshot.int_var_bindings_len); - rollback_to(float_var_bindings.get(), + rollback_to(&mut *self.ty_var_bindings.borrow_mut(), + snapshot.ty_var_bindings_len); + rollback_to(&mut *self.int_var_bindings.borrow_mut(), + snapshot.int_var_bindings_len); + rollback_to(&mut *self.float_var_bindings.borrow_mut(), snapshot.float_var_bindings_len); self.region_vars.rollback_to(snapshot.region_vars_snapshot); @@ -562,10 +558,8 @@ pub fn commit(&self, f: || -> Result) -> Result { indent(|| { let r = self.try(|| f()); - let mut ty_var_bindings = self.ty_var_bindings.borrow_mut(); - let mut int_var_bindings = self.int_var_bindings.borrow_mut(); - ty_var_bindings.get().bindings.truncate(0); - int_var_bindings.get().bindings.truncate(0); + self.ty_var_bindings.borrow_mut().bindings.truncate(0); + self.int_var_bindings.borrow_mut().bindings.truncate(0); self.region_vars.commit(); r }) @@ -614,7 +608,7 @@ pub fn next_ty_var_id(&self) -> TyVid { self.ty_var_counter.set(id + 1); { let mut ty_var_bindings = self.ty_var_bindings.borrow_mut(); - let vals = &mut ty_var_bindings.get().vals; + let vals = &mut ty_var_bindings.vals; vals.insert(id, Root(Bounds { lb: None, ub: None }, 0u)); } return TyVid(id); @@ -632,7 +626,7 @@ pub fn next_int_var_id(&self) -> IntVid { let mut int_var_counter = self.int_var_counter.get(); let mut int_var_bindings = self.int_var_bindings.borrow_mut(); let result = IntVid(next_simple_var(&mut int_var_counter, - int_var_bindings.get())); + &mut *int_var_bindings)); self.int_var_counter.set(int_var_counter); result } @@ -645,7 +639,7 @@ pub fn next_float_var_id(&self) -> FloatVid { let mut float_var_counter = self.float_var_counter.get(); let mut float_var_bindings = self.float_var_bindings.borrow_mut(); let result = FloatVid(next_simple_var(&mut float_var_counter, - float_var_bindings.get())); + &mut *float_var_bindings)); self.float_var_counter.set(float_var_counter); result } diff --git a/src/librustc/middle/typeck/infer/region_inference/mod.rs b/src/librustc/middle/typeck/infer/region_inference/mod.rs index 7c13c15ffec..567916a59f8 100644 --- a/src/librustc/middle/typeck/infer/region_inference/mod.rs +++ b/src/librustc/middle/typeck/infer/region_inference/mod.rs @@ -32,7 +32,7 @@ mod doc; -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] pub enum Constraint { ConstrainVarSubVar(RegionVid, RegionVid), ConstrainRegSubVar(Region, RegionVid), @@ -40,7 +40,7 @@ pub enum Constraint { ConstrainRegSubReg(Region, Region), } -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] pub struct TwoRegions { a: Region, b: Region, @@ -160,78 +160,63 @@ pub fn RegionVarBindings<'a>(tcx: &'a ty::ctxt) -> RegionVarBindings<'a> { impl<'a> RegionVarBindings<'a> { pub fn in_snapshot(&self) -> bool { - let undo_log = self.undo_log.borrow(); - undo_log.get().len() > 0 + self.undo_log.borrow().len() > 0 } pub fn start_snapshot(&self) -> uint { debug!("RegionVarBindings: start_snapshot()"); if self.in_snapshot() { - { - let undo_log = self.undo_log.borrow(); - undo_log.get().len() - } + self.undo_log.borrow().len() } else { - { - let mut undo_log = self.undo_log.borrow_mut(); - undo_log.get().push(Snapshot); - 0 - } + self.undo_log.borrow_mut().push(Snapshot); + 0 } } pub fn commit(&self) { debug!("RegionVarBindings: commit()"); let mut undo_log = self.undo_log.borrow_mut(); - while undo_log.get().len() > 0 { - undo_log.get().pop().unwrap(); + while undo_log.len() > 0 { + undo_log.pop().unwrap(); } } pub fn rollback_to(&self, snapshot: uint) { debug!("RegionVarBindings: rollback_to({})", snapshot); let mut undo_log = self.undo_log.borrow_mut(); - while undo_log.get().len() > snapshot { - let undo_item = undo_log.get().pop().unwrap(); + while undo_log.len() > snapshot { + let undo_item = undo_log.pop().unwrap(); debug!("undo_item={:?}", undo_item); match undo_item { Snapshot => {} AddVar(vid) => { let mut var_origins = self.var_origins.borrow_mut(); - assert_eq!(var_origins.get().len(), vid.to_uint() + 1); - var_origins.get().pop().unwrap(); + assert_eq!(var_origins.len(), vid.to_uint() + 1); + var_origins.pop().unwrap(); } AddConstraint(ref constraint) => { - let mut constraints = self.constraints.borrow_mut(); - constraints.get().remove(constraint); + self.constraints.borrow_mut().remove(constraint); } AddCombination(Glb, ref regions) => { - let mut glbs = self.glbs.borrow_mut(); - glbs.get().remove(regions); + self.glbs.borrow_mut().remove(regions); } AddCombination(Lub, ref regions) => { - let mut lubs = self.lubs.borrow_mut(); - lubs.get().remove(regions); + self.lubs.borrow_mut().remove(regions); } } } } pub fn num_vars(&self) -> uint { - let var_origins = self.var_origins.borrow(); - var_origins.get().len() + self.var_origins.borrow().len() } pub fn new_region_var(&self, origin: RegionVariableOrigin) -> RegionVid { let id = self.num_vars(); - let mut var_origins = self.var_origins.borrow_mut(); - var_origins.get().push(origin); + self.var_origins.borrow_mut().push(origin); let vid = RegionVid { id: id }; if self.in_snapshot() { - { - let mut undo_log = self.undo_log.borrow_mut(); - undo_log.get().push(AddVar(vid)); - } + self.undo_log.borrow_mut().push(AddVar(vid)); } debug!("created new region variable {:?} with origin {:?}", vid, origin.repr(self.tcx)); @@ -274,8 +259,7 @@ pub fn new_bound(&self, binder_id: ast::NodeId) -> Region { } fn values_are_none(&self) -> bool { - let values = self.values.borrow(); - values.get().is_none() + self.values.borrow().is_none() } pub fn add_constraint(&self, @@ -286,13 +270,9 @@ pub fn add_constraint(&self, debug!("RegionVarBindings: add_constraint({:?})", constraint); - let mut constraints = self.constraints.borrow_mut(); - if constraints.get().insert(constraint, origin) { + if self.constraints.borrow_mut().insert(constraint, origin) { if self.in_snapshot() { - { - let mut undo_log = self.undo_log.borrow_mut(); - undo_log.get().push(AddConstraint(constraint)); - } + self.undo_log.borrow_mut().push(AddConstraint(constraint)); } } } @@ -383,12 +363,10 @@ pub fn glb_regions(&self, } pub fn resolve_var(&self, rid: RegionVid) -> ty::Region { - let values = self.values.borrow(); - let v = match *values.get() { + let v = match *self.values.borrow() { None => { - let var_origins = self.var_origins.borrow(); self.tcx.sess.span_bug( - var_origins.get().get(rid.to_uint()).span(), + self.var_origins.borrow().get(rid.to_uint()).span(), format!("attempt to resolve region variable before \ values have been computed!")) } @@ -430,25 +408,16 @@ pub fn combine_vars(&self, new_r: Region|) -> Region { let vars = TwoRegions { a: a, b: b }; - { - let map = self.combine_map(t).borrow(); - match map.get().find(&vars) { - Some(&c) => { - return ReInfer(ReVar(c)); - } - None => {} + match self.combine_map(t).borrow().find(&vars) { + Some(&c) => { + return ReInfer(ReVar(c)); } + None => {} } let c = self.new_region_var(infer::MiscVariable(origin.span())); - { - let mut map = self.combine_map(t).borrow_mut(); - map.get().insert(vars, c); - } + self.combine_map(t).borrow_mut().insert(vars, c); if self.in_snapshot() { - { - let mut undo_log = self.undo_log.borrow_mut(); - undo_log.get().push(AddCombination(t, vars)); - } + self.undo_log.borrow_mut().push(AddCombination(t, vars)); } relate(self, a, ReInfer(ReVar(c))); relate(self, b, ReInfer(ReVar(c))); @@ -458,8 +427,7 @@ pub fn combine_vars(&self, pub fn vars_created_since_snapshot(&self, snapshot: uint) -> Vec { - let undo_log = self.undo_log.borrow(); - undo_log.get().slice_from(snapshot).iter() + self.undo_log.borrow().slice_from(snapshot).iter() .filter_map(|&elt| match elt { AddVar(vid) => Some(vid), _ => None @@ -479,10 +447,7 @@ pub fn tainted(&self, snapshot: uint, r0: Region) -> Vec { debug!("tainted(snapshot={}, r0={:?})", snapshot, r0); let _indenter = indenter(); - let undo_len = { - let undo_log = self.undo_log.borrow(); - undo_log.get().len() - }; + let undo_len = self.undo_log.borrow().len(); // `result_set` acts as a worklist: we explore all outgoing // edges and add any new regions we find to result_set. This @@ -498,25 +463,22 @@ pub fn tainted(&self, snapshot: uint, r0: Region) -> Vec { let mut undo_index = snapshot; while undo_index < undo_len { // nb: can't use uint::range() here as we move result_set - let regs = { - let undo_log = self.undo_log.borrow(); - match undo_log.get().get(undo_index) { - &AddConstraint(ConstrainVarSubVar(ref a, ref b)) => { - Some((ReInfer(ReVar(*a)), - ReInfer(ReVar(*b)))) - } - &AddConstraint(ConstrainRegSubVar(ref a, ref b)) => { - Some((*a, ReInfer(ReVar(*b)))) - } - &AddConstraint(ConstrainVarSubReg(ref a, ref b)) => { - Some((ReInfer(ReVar(*a)), *b)) - } - &AddConstraint(ConstrainRegSubReg(a, b)) => { - Some((a, b)) - } - _ => { - None - } + let regs = match self.undo_log.borrow().get(undo_index) { + &AddConstraint(ConstrainVarSubVar(ref a, ref b)) => { + Some((ReInfer(ReVar(*a)), + ReInfer(ReVar(*b)))) + } + &AddConstraint(ConstrainRegSubVar(ref a, ref b)) => { + Some((*a, ReInfer(ReVar(*b)))) + } + &AddConstraint(ConstrainVarSubReg(ref a, ref b)) => { + Some((ReInfer(ReVar(*a)), *b)) + } + &AddConstraint(ConstrainRegSubReg(a, b)) => { + Some((a, b)) + } + _ => { + None } }; @@ -563,8 +525,7 @@ pub fn resolve_regions(&self) -> Vec { debug!("RegionVarBindings: resolve_regions()"); let mut errors = vec!(); let v = self.infer_variable_values(&mut errors); - let mut values = self.values.borrow_mut(); - *values.get() = Some(v); + *self.values.borrow_mut() = Some(v); errors } } @@ -595,9 +556,8 @@ fn lub_concrete_regions(&self, a: Region, b: Region) -> Region { } (ReInfer(ReVar(v_id)), _) | (_, ReInfer(ReVar(v_id))) => { - let var_origins = self.var_origins.borrow(); self.tcx.sess.span_bug( - var_origins.get().get(v_id.to_uint()).span(), + self.var_origins.borrow().get(v_id.to_uint()).span(), format!("lub_concrete_regions invoked with \ non-concrete regions: {:?}, {:?}", a, b)); } @@ -700,9 +660,8 @@ fn glb_concrete_regions(&self, (ReInfer(ReVar(v_id)), _) | (_, ReInfer(ReVar(v_id))) => { - let var_origins = self.var_origins.borrow(); self.tcx.sess.span_bug( - var_origins.get().get(v_id.to_uint()).span(), + self.var_origins.borrow().get(v_id.to_uint()).span(), format!("glb_concrete_regions invoked with \ non-concrete regions: {:?}, {:?}", a, b)); } @@ -1004,8 +963,7 @@ fn collect_concrete_region_errors( &self, errors: &mut Vec) { - let constraints = self.constraints.borrow(); - for (constraint, _) in constraints.get().iter() { + for (constraint, _) in self.constraints.borrow().iter() { let (sub, sup) = match *constraint { ConstrainVarSubVar(..) | ConstrainRegSubVar(..) | @@ -1023,7 +981,7 @@ fn collect_concrete_region_errors( debug!("ConcreteFailure: !(sub <= sup): sub={:?}, sup={:?}", sub, sup); - let origin = constraints.get().get_copy(constraint); + let origin = self.constraints.borrow().get_copy(constraint); errors.push(ConcreteFailure(origin, sub, sup)); } } @@ -1112,7 +1070,7 @@ fn construct_graph(&self) -> RegionGraph { let num_vars = self.num_vars(); let constraints = self.constraints.borrow(); - let num_edges = constraints.get().len(); + let num_edges = constraints.len(); let mut graph = graph::Graph::with_capacity(num_vars + 1, num_edges); @@ -1122,7 +1080,7 @@ fn construct_graph(&self) -> RegionGraph { } let dummy_idx = graph.add_node(()); - for (constraint, _) in constraints.get().iter() { + for (constraint, _) in constraints.iter() { match *constraint { ConstrainVarSubVar(a_id, b_id) => { graph.add_edge(NodeIndex(a_id.to_uint()), @@ -1174,23 +1132,19 @@ fn collect_error_for_expanding_node( for upper_bound in upper_bounds.iter() { if !self.is_subregion_of(lower_bound.region, upper_bound.region) { - { - let var_origins = self.var_origins.borrow(); - errors.push(SubSupConflict( - *var_origins.get().get(node_idx.to_uint()), - lower_bound.origin, - lower_bound.region, - upper_bound.origin, - upper_bound.region)); - return; - } + errors.push(SubSupConflict( + *self.var_origins.borrow().get(node_idx.to_uint()), + lower_bound.origin, + lower_bound.region, + upper_bound.origin, + upper_bound.region)); + return; } } } - let var_origins = self.var_origins.borrow(); self.tcx.sess.span_bug( - var_origins.get().get(node_idx.to_uint()).span(), + self.var_origins.borrow().get(node_idx.to_uint()).span(), format!("collect_error_for_expanding_node() could not find error \ for var {:?}, lower_bounds={}, upper_bounds={}", node_idx, @@ -1222,9 +1176,8 @@ fn collect_error_for_contracting_node( upper_bound_2.region) { Ok(_) => {} Err(_) => { - let var_origins = self.var_origins.borrow(); errors.push(SupSupConflict( - *var_origins.get().get(node_idx.to_uint()), + *self.var_origins.borrow().get(node_idx.to_uint()), upper_bound_1.origin, upper_bound_1.region, upper_bound_2.origin, @@ -1235,9 +1188,8 @@ fn collect_error_for_contracting_node( } } - let var_origins = self.var_origins.borrow(); self.tcx.sess.span_bug( - var_origins.get().get(node_idx.to_uint()).span(), + self.var_origins.borrow().get(node_idx.to_uint()).span(), format!("collect_error_for_contracting_node() could not find error \ for var {:?}, upper_bounds={}", node_idx, @@ -1317,10 +1269,9 @@ fn process_edges(this: &RegionVarBindings, ConstrainRegSubVar(region, _) | ConstrainVarSubReg(_, region) => { - let constraints = this.constraints.borrow(); state.result.push(RegionAndOrigin { region: region, - origin: constraints.get().get_copy(&edge.data) + origin: this.constraints.borrow().get_copy(&edge.data) }); } @@ -1340,8 +1291,7 @@ fn iterate_until_fixed_point(&self, changed = false; iteration += 1; debug!("---- {} Iteration \\#{}", tag, iteration); - let constraints = self.constraints.borrow(); - for (constraint, _) in constraints.get().iter() { + for (constraint, _) in self.constraints.borrow().iter() { let edge_changed = body(constraint); if edge_changed { debug!("Updated due to constraint {}", diff --git a/src/librustc/middle/typeck/infer/unify.rs b/src/librustc/middle/typeck/infer/unify.rs index 1c2ca2799ac..20d268bca6c 100644 --- a/src/librustc/middle/typeck/infer/unify.rs +++ b/src/librustc/middle/typeck/infer/unify.rs @@ -75,8 +75,7 @@ fn get( tcx: &ty::ctxt, @@ -123,9 +122,9 @@ fn set ~str { } } -pub type vtable_map = @RefCell>; +pub type vtable_map = @RefCell>; // Information about the vtable resolutions for a trait impl. @@ -252,8 +252,7 @@ pub struct CrateCtxt<'a> { pub fn write_ty_to_tcx(tcx: &ty::ctxt, node_id: ast::NodeId, ty: ty::t) { debug!("write_ty_to_tcx({}, {})", node_id, ppaux::ty_to_str(tcx, ty)); assert!(!ty::type_needs_infer(ty)); - let mut node_types = tcx.node_types.borrow_mut(); - node_types.get().insert(node_id as uint, ty); + tcx.node_types.borrow_mut().insert(node_id as uint, ty); } pub fn write_substs_to_tcx(tcx: &ty::ctxt, node_id: ast::NodeId, @@ -263,8 +262,7 @@ pub fn write_substs_to_tcx(tcx: &ty::ctxt, substs.map(|t| ppaux::ty_to_str(tcx, *t))); assert!(substs.iter().all(|t| !ty::type_needs_infer(*t))); - let mut node_type_substs = tcx.node_type_substs.borrow_mut(); - node_type_substs.get().insert(node_id, substs); + tcx.node_type_substs.borrow_mut().insert(node_id, substs); } } pub fn write_tpt_to_tcx(tcx: &ty::ctxt, @@ -277,8 +275,7 @@ pub fn write_tpt_to_tcx(tcx: &ty::ctxt, } pub fn lookup_def_tcx(tcx:&ty::ctxt, sp: Span, id: ast::NodeId) -> ast::Def { - let def_map = tcx.def_map.borrow(); - match def_map.get().find(&id) { + match tcx.def_map.borrow().find(&id) { Some(&x) => x, _ => { tcx.sess.span_fatal(sp, "internal error looking up a definition") @@ -464,7 +461,7 @@ pub fn check_crate(tcx: &ty::ctxt, let ccx = CrateCtxt { trait_map: trait_map, method_map: @RefCell::new(FnvHashMap::new()), - vtable_map: @RefCell::new(NodeMap::new()), + vtable_map: @RefCell::new(FnvHashMap::new()), tcx: tcx }; diff --git a/src/librustc/middle/typeck/variance.rs b/src/librustc/middle/typeck/variance.rs index 8748c332170..baa4e1c1db1 100644 --- a/src/librustc/middle/typeck/variance.rs +++ b/src/librustc/middle/typeck/variance.rs @@ -359,10 +359,7 @@ fn visit_item(&mut self, item: &ast::Item, _: ()) { // "invalid item id" from "item id with no // parameters". if self.num_inferred() == inferreds_on_entry { - let mut item_variance_map = self.tcx - .item_variance_map - .borrow_mut(); - let newly_added = item_variance_map.get().insert( + let newly_added = self.tcx.item_variance_map.borrow_mut().insert( ast_util::local_def(item.id), self.empty_variances); assert!(newly_added); @@ -944,9 +941,8 @@ fn write(&self) { tcx.sess.span_err(tcx.map.span(item_id), found); } - let mut item_variance_map = tcx.item_variance_map.borrow_mut(); - let newly_added = item_variance_map.get().insert(item_def_id, - @item_variances); + let newly_added = tcx.item_variance_map.borrow_mut() + .insert(item_def_id, @item_variances); assert!(newly_added); } } diff --git a/src/librustc/util/nodemap.rs b/src/librustc/util/nodemap.rs index bbe3192999a..ac4db178a00 100644 --- a/src/librustc/util/nodemap.rs +++ b/src/librustc/util/nodemap.rs @@ -27,7 +27,7 @@ pub mod FnvHashMap { use std::hash::Hash; use collections::HashMap; - pub fn new + Eq, V>() -> super::FnvHashMap { + pub fn new + TotalEq, V>() -> super::FnvHashMap { HashMap::with_hasher(super::FnvHasher) } } diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index b2568c60dc0..1a017340c95 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -459,9 +459,7 @@ fn push_sig_to_str(cx: &ctxt, ty_infer(infer_ty) => infer_ty.to_str(), ty_err => ~"[type error]", ty_param(param_ty {idx: id, def_id: did}) => { - let ty_param_defs = cx.ty_param_defs.borrow(); - let param_def = ty_param_defs.get().find(&did.node); - let ident = match param_def { + let ident = match cx.ty_param_defs.borrow().find(&did.node) { Some(def) => token::get_ident(def.ident).get().to_str(), // This should not happen... None => format!("BUG[{:?}]", id) @@ -666,7 +664,6 @@ fn repr(&self, tcx: &ctxt) -> ~str { res.push(match b { ty::BoundStatic => ~"'static", ty::BoundSend => ~"Send", - ty::BoundFreeze => ~"Freeze", ty::BoundSized => ~"Sized", ty::BoundPod => ~"Pod", ty::BoundShare => ~"Share", @@ -954,7 +951,6 @@ fn user_string(&self, _tcx: &ctxt) -> ~str { match *self { ty::BoundStatic => ~"'static", ty::BoundSend => ~"Send", - ty::BoundFreeze => ~"Freeze", ty::BoundSized => ~"Sized", ty::BoundPod => ~"Pod", ty::BoundShare => ~"Share", diff --git a/src/librustdoc/clean.rs b/src/librustdoc/clean.rs index e8854215c00..b0554c21bf9 100644 --- a/src/librustdoc/clean.rs +++ b/src/librustdoc/clean.rs @@ -1181,7 +1181,7 @@ fn to_src(&self) -> ~str { fn lit_to_str(lit: &ast::Lit) -> ~str { match lit.node { ast::LitStr(ref st, _) => st.get().to_owned(), - ast::LitBinary(ref data) => format!("{:?}", data.deref().as_slice()), + ast::LitBinary(ref data) => format!("{:?}", data.as_slice()), ast::LitChar(c) => ~"'" + std::char::from_u32(c).unwrap().to_str() + "'", ast::LitInt(i, _t) => i.to_str(), ast::LitUint(u, _t) => u.to_str(), @@ -1229,16 +1229,15 @@ fn resolve_type(path: Path, tpbs: Option >, core::NotTyped(_) => return Bool }; debug!("searching for {:?} in defmap", id); - let def_map = tycx.def_map.borrow(); - let d = match def_map.get().find(&id) { - Some(k) => k, + let d = match tycx.def_map.borrow().find(&id) { + Some(&k) => k, None => { debug!("could not find {:?} in defmap (`{}`)", id, tycx.map.node_to_str(id)); fail!("Unexpected failure: unresolved id not in defmap (this is a bug!)") } }; - let (def_id, kind) = match *d { + let (def_id, kind) = match d { ast::DefFn(i, _) => (i, TypeFunction), ast::DefSelfTy(i) => return Self(i), ast::DefTy(i) => (i, TypeEnum), @@ -1285,8 +1284,7 @@ fn resolve_def(id: ast::NodeId) -> Option { let cx = local_data::get(super::ctxtkey, |x| *x.unwrap()); match cx.maybe_typed { core::Typed(ref tcx) => { - let def_map = tcx.def_map.borrow(); - def_map.get().find(&id).map(|&d| ast_util::def_id_of_def(d)) + tcx.def_map.borrow().find(&id).map(|&d| ast_util::def_id_of_def(d)) } core::NotTyped(_) => None } diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index a045d042dcd..b162d9d4b78 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.to_owned_vec().connect("\n"); + let text = lines.collect::<~[&str]>().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() } - }).to_owned_vec().connect("-"); + }).collect::<~[~str]>().connect("-"); let opaque = unsafe {&mut *(opaque as *mut my_opaque)}; @@ -284,7 +284,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.to_owned_vec().connect("\n"); + let text = lines.collect::<~[&str]>().connect("\n"); tests.add_test(text, should_fail, no_run); }) } diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 4079fafb368..66b965633a0 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -116,8 +116,8 @@ pub enum Implementor { /// /// This structure purposefully does not implement `Clone` because it's intended /// to be a fairly large and expensive structure to clone. Instead this adheres -/// to both `Send` and `Freeze` so it may be stored in a `Arc` instance and -/// shared among the various rendering tasks. +/// to `Send` so it may be stored in a `Arc` instance and shared among the various +/// rendering tasks. pub struct Cache { /// Mapping of typaram ids to the name of the type parameter. This is used /// when pretty-printing a type (so pretty printing doesn't have to @@ -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()).to_owned_vec(); - let provided = t.methods.iter().filter(|m| !m.is_req()).to_owned_vec(); + 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]>(); 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.to_owned_vec(); + let non_trait = non_trait.collect::<~[&(clean::Impl, Option<~str>)]>(); let mut traits = v.iter().filter(|p| { p.ref0().trait_.is_some() }); - let traits = traits.to_owned_vec(); + let traits = traits.collect::<~[&(clean::Impl, Option<~str>)]>(); if non_trait.len() > 0 { try!(write!(w, "

Methods

")); diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index df533d882f7..8be3535b3ec 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -186,7 +186,7 @@ fn resolve_id(&mut self, id: ast::NodeId, glob: bool, core::Typed(ref tcx) => tcx, core::NotTyped(_) => return false }; - let def = ast_util::def_id_of_def(*tcx.def_map.borrow().get().get(&id)); + let def = ast_util::def_id_of_def(*tcx.def_map.borrow().get(&id)); if !ast_util::is_local(def) { return false } let analysis = match self.analysis { Some(analysis) => analysis, None => return false diff --git a/src/librustuv/idle.rs b/src/librustuv/idle.rs index a6c0a7b829a..1f059ca9fb9 100644 --- a/src/librustuv/idle.rs +++ b/src/librustuv/idle.rs @@ -113,8 +113,7 @@ impl Callback for MyCallback { fn call(&mut self) { let task = match *self { MyCallback(ref rc, n) => { - let mut slot = rc.deref().borrow_mut(); - match *slot.get() { + match *rc.borrow_mut().deref_mut() { (ref mut task, ref mut val) => { *val = n; match task.take() { @@ -140,8 +139,7 @@ fn mk(v: uint) -> (~IdleWatcher, Chan) { fn sleep(chan: &Chan) -> uint { let task: ~Task = Local::take(); task.deschedule(1, |task| { - let mut slot = chan.deref().borrow_mut(); - match *slot.get() { + match *chan.borrow_mut().deref_mut() { (ref mut slot, _) => { assert!(slot.is_none()); *slot = Some(task); @@ -150,8 +148,7 @@ fn sleep(chan: &Chan) -> uint { Ok(()) }); - let slot = chan.deref().borrow(); - match *slot.get() { (_, n) => n } + match *chan.borrow() { (_, n) => n } } #[test] diff --git a/src/librustuv/lib.rs b/src/librustuv/lib.rs index 42ccdaf9562..82ca84190f7 100644 --- a/src/librustuv/lib.rs +++ b/src/librustuv/lib.rs @@ -42,7 +42,6 @@ #[feature(macro_rules)]; #[deny(unused_result, unused_must_use)]; #[allow(visible_private_types)]; -#[allow(deprecated_owned_vector)]; // NOTE: remove after stage0 #[cfg(test)] extern crate green; #[cfg(test)] extern crate realrustuv = "rustuv"; diff --git a/src/libserialize/collection_impls.rs b/src/libserialize/collection_impls.rs index 2d86734e569..bb823c2d8ca 100644 --- a/src/libserialize/collection_impls.rs +++ b/src/libserialize/collection_impls.rs @@ -165,7 +165,7 @@ fn decode(d: &mut D) -> EnumSet { impl< E: Encoder, - K: Encodable + Hash + Eq, + K: Encodable + Hash + TotalEq, V: Encodable, S, H: Hasher @@ -184,7 +184,7 @@ fn encode(&self, e: &mut E) { impl< D: Decoder, - K: Decodable + Hash + Eq, + K: Decodable + Hash + TotalEq, V: Decodable, S, H: Hasher + Default @@ -205,7 +205,7 @@ fn decode(d: &mut D) -> HashMap { impl< E: Encoder, - T: Encodable + Hash + Eq, + T: Encodable + Hash + TotalEq, S, H: Hasher > Encodable for HashSet { @@ -222,7 +222,7 @@ fn encode(&self, s: &mut E) { impl< D: Decoder, - T: Decodable + Hash + Eq, + T: Decodable + Hash + TotalEq, S, H: Hasher + Default > Decodable for HashSet { diff --git a/src/libserialize/lib.rs b/src/libserialize/lib.rs index ad2e741f782..8a5829da9d6 100644 --- a/src/libserialize/lib.rs +++ b/src/libserialize/lib.rs @@ -22,7 +22,6 @@ html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://static.rust-lang.org/doc/master")]; #[feature(macro_rules, managed_boxes, default_type_params, phase)]; -#[allow(deprecated_owned_vector)]; // NOTE: remove after stage0 // test harness access #[cfg(test)] diff --git a/src/libserialize/serialize.rs b/src/libserialize/serialize.rs index 60de03a7b43..a65443653cc 100644 --- a/src/libserialize/serialize.rs +++ b/src/libserialize/serialize.rs @@ -387,7 +387,7 @@ fn encode(&self, s: &mut S) { impl> Encodable for Rc { #[inline] fn encode(&self, s: &mut S) { - self.deref().encode(s) + (**self).encode(s) } } @@ -477,153 +477,43 @@ fn decode(d: &mut D) -> Option { } } -impl,T1:Encodable> Encodable for (T0, T1) { - fn encode(&self, s: &mut S) { - match *self { - (ref t0, ref t1) => { - s.emit_seq(2, |s| { - s.emit_seq_elt(0, |s| t0.encode(s)); - s.emit_seq_elt(1, |s| t1.encode(s)); +macro_rules! peel(($name:ident, $($other:ident,)*) => (tuple!($($other,)*))) + +macro_rules! tuple ( + () => (); + ( $($name:ident,)+ ) => ( + impl),*> Decodable for ($($name,)*) { + #[allow(uppercase_variables)] + fn decode(d: &mut D) -> ($($name,)*) { + d.read_tuple(|d, amt| { + let mut i = 0; + let ret = ($(d.read_tuple_arg({ i+=1; i-1 }, |d| -> $name { + Decodable::decode(d) + }),)*); + assert!(amt == i, + "expected tuple of length `{}`, found tuple \ + of length `{}`", i, amt); + return ret; }) } } - } -} - -impl,T1:Decodable> Decodable for (T0, T1) { - fn decode(d: &mut D) -> (T0, T1) { - d.read_seq(|d, len| { - assert_eq!(len, 2); - ( - d.read_seq_elt(0, |d| Decodable::decode(d)), - d.read_seq_elt(1, |d| Decodable::decode(d)) - ) - }) - } -} - -impl< - S: Encoder, - T0: Encodable, - T1: Encodable, - T2: Encodable -> Encodable for (T0, T1, T2) { - fn encode(&self, s: &mut S) { - match *self { - (ref t0, ref t1, ref t2) => { - s.emit_seq(3, |s| { - s.emit_seq_elt(0, |s| t0.encode(s)); - s.emit_seq_elt(1, |s| t1.encode(s)); - s.emit_seq_elt(2, |s| t2.encode(s)); + impl),*> Encodable for ($($name,)*) { + #[allow(uppercase_variables)] + fn encode(&self, s: &mut S) { + let ($(ref $name,)*) = *self; + let mut n = 0; + $(let $name = $name; n += 1;)* + s.emit_tuple(n, |s| { + let mut i = 0; + $(s.emit_seq_elt({ i+=1; i-1 }, |s| $name.encode(s));)* }) } } - } -} - -impl< - D: Decoder, - T0: Decodable, - T1: Decodable, - T2: Decodable -> Decodable for (T0, T1, T2) { - fn decode(d: &mut D) -> (T0, T1, T2) { - d.read_seq(|d, len| { - assert_eq!(len, 3); - ( - d.read_seq_elt(0, |d| Decodable::decode(d)), - d.read_seq_elt(1, |d| Decodable::decode(d)), - d.read_seq_elt(2, |d| Decodable::decode(d)) - ) - }) - } -} + peel!($($name,)*) + ) +) -impl< - S: Encoder, - T0: Encodable, - T1: Encodable, - T2: Encodable, - T3: Encodable -> Encodable for (T0, T1, T2, T3) { - fn encode(&self, s: &mut S) { - match *self { - (ref t0, ref t1, ref t2, ref t3) => { - s.emit_seq(4, |s| { - s.emit_seq_elt(0, |s| t0.encode(s)); - s.emit_seq_elt(1, |s| t1.encode(s)); - s.emit_seq_elt(2, |s| t2.encode(s)); - s.emit_seq_elt(3, |s| t3.encode(s)); - }) - } - } - } -} - -impl< - D: Decoder, - T0: Decodable, - T1: Decodable, - T2: Decodable, - T3: Decodable -> Decodable for (T0, T1, T2, T3) { - fn decode(d: &mut D) -> (T0, T1, T2, T3) { - d.read_seq(|d, len| { - assert_eq!(len, 4); - ( - d.read_seq_elt(0, |d| Decodable::decode(d)), - d.read_seq_elt(1, |d| Decodable::decode(d)), - d.read_seq_elt(2, |d| Decodable::decode(d)), - d.read_seq_elt(3, |d| Decodable::decode(d)) - ) - }) - } -} - -impl< - S: Encoder, - T0: Encodable, - T1: Encodable, - T2: Encodable, - T3: Encodable, - T4: Encodable -> Encodable for (T0, T1, T2, T3, T4) { - fn encode(&self, s: &mut S) { - match *self { - (ref t0, ref t1, ref t2, ref t3, ref t4) => { - s.emit_seq(5, |s| { - s.emit_seq_elt(0, |s| t0.encode(s)); - s.emit_seq_elt(1, |s| t1.encode(s)); - s.emit_seq_elt(2, |s| t2.encode(s)); - s.emit_seq_elt(3, |s| t3.encode(s)); - s.emit_seq_elt(4, |s| t4.encode(s)); - }) - } - } - } -} - -impl< - D: Decoder, - T0: Decodable, - T1: Decodable, - T2: Decodable, - T3: Decodable, - T4: Decodable -> Decodable for (T0, T1, T2, T3, T4) { - fn decode(d: &mut D) -> (T0, T1, T2, T3, T4) { - d.read_seq(|d, len| { - assert_eq!(len, 5); - ( - d.read_seq_elt(0, |d| Decodable::decode(d)), - d.read_seq_elt(1, |d| Decodable::decode(d)), - d.read_seq_elt(2, |d| Decodable::decode(d)), - d.read_seq_elt(3, |d| Decodable::decode(d)), - d.read_seq_elt(4, |d| Decodable::decode(d)) - ) - }) - } -} +tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, } impl Encodable for path::posix::Path { fn encode(&self, e: &mut E) { diff --git a/src/libstd/ascii.rs b/src/libstd/ascii.rs index 63632770230..85df875dc1d 100644 --- a/src/libstd/ascii.rs +++ b/src/libstd/ascii.rs @@ -400,7 +400,7 @@ unsafe fn str_map_bytes(string: ~str, map: &'static [u8]) -> ~str { #[inline] unsafe fn str_copy_map_bytes(string: &str, map: &'static [u8]) -> ~str { - let bytes = string.bytes().map(|b| map[b]).to_owned_vec(); + let bytes = string.bytes().map(|b| map[b]).collect::<~[_]>(); str::raw::from_utf8_owned(bytes) } diff --git a/src/libstd/cell.rs b/src/libstd/cell.rs index b54396efec5..e0912b826cd 100644 --- a/src/libstd/cell.rs +++ b/src/libstd/cell.rs @@ -22,8 +22,7 @@ /// A mutable memory location that admits only `Pod` data. pub struct Cell { priv value: Unsafe, - priv marker1: marker::NoFreeze, - priv marker2: marker::NoShare, + priv noshare: marker::NoShare, } impl Cell { @@ -31,8 +30,7 @@ impl Cell { pub fn new(value: T) -> Cell { Cell { value: Unsafe::new(value), - marker1: marker::NoFreeze, - marker2: marker::NoShare, + noshare: marker::NoShare, } } @@ -73,9 +71,8 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { pub struct RefCell { priv value: Unsafe, priv borrow: BorrowFlag, - priv marker1: marker::NoFreeze, - priv marker2: marker::NoPod, - priv marker3: marker::NoShare, + priv nopod: marker::NoPod, + priv noshare: marker::NoShare, } // Values [1, MAX-1] represent the number of `Ref` active @@ -88,10 +85,9 @@ impl RefCell { /// Create a new `RefCell` containing `value` pub fn new(value: T) -> RefCell { RefCell { - marker1: marker::NoFreeze, - marker2: marker::NoPod, - marker3: marker::NoShare, value: Unsafe::new(value), + nopod: marker::NoPod, + noshare: marker::NoShare, borrow: UNUSED, } } @@ -176,8 +172,7 @@ pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> { /// Fails if the value is currently borrowed. #[inline] pub fn set(&self, value: T) { - let mut reference = self.borrow_mut(); - *reference.get() = value; + *self.borrow_mut() = value; } } @@ -189,23 +184,19 @@ impl RefCell { /// Fails if the value is currently mutably borrowed. #[inline] pub fn get(&self) -> T { - let reference = self.borrow(); - (*reference.get()).clone() + (*self.borrow()).clone() } } impl Clone for RefCell { fn clone(&self) -> RefCell { - let x = self.borrow(); - RefCell::new(x.get().clone()) + RefCell::new(self.get()) } } impl Eq for RefCell { fn eq(&self, other: &RefCell) -> bool { - let a = self.borrow(); - let b = other.borrow(); - a.get() == b.get() + *self.borrow() == *other.borrow() } } @@ -222,14 +213,6 @@ fn drop(&mut self) { } } -impl<'b, T> Ref<'b, T> { - /// Retrieve an immutable reference to the stored value. - #[inline] - pub fn get<'a>(&'a self) -> &'a T { - unsafe{ &*self.parent.value.get() } - } -} - impl<'b, T> Deref for Ref<'b, T> { #[inline] fn deref<'a>(&'a self) -> &'a T { @@ -250,14 +233,6 @@ fn drop(&mut self) { } } -impl<'b, T> RefMut<'b, T> { - /// Retrieve a mutable reference to the stored value. - #[inline] - pub fn get<'a>(&'a mut self) -> &'a mut T { - unsafe{ &mut *self.parent.value.get() } - } -} - impl<'b, T> Deref for RefMut<'b, T> { #[inline] fn deref<'a>(&'a self) -> &'a T { diff --git a/src/libstd/cmp.rs b/src/libstd/cmp.rs index 5130da44ed5..e956a1cdf1d 100644 --- a/src/libstd/cmp.rs +++ b/src/libstd/cmp.rs @@ -42,6 +42,21 @@ fn ne(&self, other: &Self) -> bool { !self.eq(other) } } /// Trait for equality comparisons where `a == b` and `a != b` are strict inverses. +#[cfg(not(stage0))] +pub trait TotalEq: Eq { + // FIXME #13101: this method is used solely by #[deriving] to + // assert that every component of a type implements #[deriving] + // itself, the current deriving infrastructure means doing this + // assertion without using a method on this trait is nearly + // impossible. + // + // This should never be implemented by hand. + #[doc(hidden)] + #[inline(always)] + fn assert_receiver_is_total_eq(&self) {} +} + +#[cfg(stage0)] pub trait TotalEq: Eq { /// This method must return the same value as `eq`. It exists to prevent /// deriving `TotalEq` from fields not implementing the `TotalEq` trait. @@ -52,10 +67,7 @@ fn equals(&self, other: &Self) -> bool { macro_rules! totaleq_impl( ($t:ty) => { - impl TotalEq for $t { - #[inline] - fn equals(&self, other: &$t) -> bool { *self == *other } - } + impl TotalEq for $t {} } ) @@ -84,12 +96,7 @@ pub trait TotalOrd: TotalEq + Ord { fn cmp(&self, other: &Self) -> Ordering; } -impl TotalEq for Ordering { - #[inline] - fn equals(&self, other: &Ordering) -> bool { - *self == *other - } -} +impl TotalEq for Ordering {} impl TotalOrd for Ordering { #[inline] fn cmp(&self, other: &Ordering) -> Ordering { @@ -194,12 +201,6 @@ fn test_int_totalord() { assert_eq!(12.cmp(-5), Greater); } - #[test] - fn test_int_totaleq() { - assert!(5.equals(&5)); - assert!(!2.equals(&17)); - } - #[test] fn test_ordering_order() { assert!(Less < Equal); diff --git a/src/libstd/comm/mod.rs b/src/libstd/comm/mod.rs index e25571dd246..267140a0089 100644 --- a/src/libstd/comm/mod.rs +++ b/src/libstd/comm/mod.rs @@ -291,7 +291,7 @@ pub struct Receiver { priv inner: Flavor, priv receives: Cell, // can't share in an arc - priv marker: marker::NoFreeze, + priv marker: marker::NoShare, } /// An iterator over messages on a receiver, this iterator will block @@ -307,7 +307,7 @@ pub struct Sender { priv inner: Flavor, priv sends: Cell, // can't share in an arc - priv marker: marker::NoFreeze, + priv marker: marker::NoShare, } /// This enumeration is the list of the possible reasons that try_recv could not @@ -340,7 +340,7 @@ pub fn channel() -> (Sender, Receiver) { impl Sender { fn my_new(inner: Flavor) -> Sender { - Sender { inner: inner, sends: Cell::new(0), marker: marker::NoFreeze } + Sender { inner: inner, sends: Cell::new(0), marker: marker::NoShare } } /// Sends a value along this channel to be received by the corresponding @@ -478,7 +478,7 @@ fn drop(&mut self) { impl Receiver { fn my_new(inner: Flavor) -> Receiver { - Receiver { inner: inner, receives: Cell::new(0), marker: marker::NoFreeze } + Receiver { inner: inner, receives: Cell::new(0), marker: marker::NoShare } } /// Blocks waiting for a value on this receiver diff --git a/src/libstd/comm/select.rs b/src/libstd/comm/select.rs index 3e134b92493..5872c308f93 100644 --- a/src/libstd/comm/select.rs +++ b/src/libstd/comm/select.rs @@ -66,7 +66,6 @@ pub struct Select { priv tail: *mut Handle<'static, ()>, priv next_id: Cell, priv marker1: marker::NoSend, - priv marker2: marker::NoFreeze, } /// A handle to a receiver which is currently a member of a `Select` set of @@ -105,7 +104,6 @@ impl Select { pub fn new() -> Select { Select { marker1: marker::NoSend, - marker2: marker::NoFreeze, head: 0 as *mut Handle<'static, ()>, tail: 0 as *mut Handle<'static, ()>, next_id: Cell::new(1), diff --git a/src/libstd/fmt/parse.rs b/src/libstd/fmt/parse.rs index 948f85ca1c2..67088e6f4f8 100644 --- a/src/libstd/fmt/parse.rs +++ b/src/libstd/fmt/parse.rs @@ -121,7 +121,7 @@ pub enum Method<'a> { } /// A selector for what pluralization a plural method should take -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] pub enum PluralSelector { /// One of the plural keywords should be used Keyword(PluralKeyword), @@ -143,7 +143,7 @@ pub struct PluralArm<'a> { /// specially placed in the `Plural` variant of `Method` /// /// http://www.icu-project.org/apiref/icu4c/classicu_1_1PluralRules.html -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] #[allow(missing_doc)] pub enum PluralKeyword { Zero, One, Two, Few, Many diff --git a/src/libstd/hash/mod.rs b/src/libstd/hash/mod.rs index 3791aa38b82..dc7d5c5b9c7 100644 --- a/src/libstd/hash/mod.rs +++ b/src/libstd/hash/mod.rs @@ -66,7 +66,6 @@ use container::Container; use io::Writer; use iter::Iterator; -use ops::Deref; use option::{Option, Some, None}; use rc::Rc; use str::{Str, StrSlice}; @@ -247,7 +246,7 @@ fn hash(&self, state: &mut S) { impl> Hash for Rc { #[inline] fn hash(&self, state: &mut S) { - self.deref().hash(state); + (**self).hash(state); } } diff --git a/src/libstd/intrinsics.rs b/src/libstd/intrinsics.rs index 95607bd8f79..78e3df4b6f8 100644 --- a/src/libstd/intrinsics.rs +++ b/src/libstd/intrinsics.rs @@ -164,90 +164,7 @@ fn visit_leave_fn(&mut self, purity: uint, proto: uint, fn visit_self(&mut self) -> bool; } -#[cfg(stage0)] -extern "rust-intrinsic" { - pub fn atomic_cxchg(dst: &mut T, old: T, src: T) -> T; - pub fn atomic_cxchg_acq(dst: &mut T, old: T, src: T) -> T; - pub fn atomic_cxchg_rel(dst: &mut T, old: T, src: T) -> T; - pub fn atomic_cxchg_acqrel(dst: &mut T, old: T, src: T) -> T; - pub fn atomic_cxchg_relaxed(dst: &mut T, old: T, src: T) -> T; - - pub fn atomic_load(src: &T) -> T; - pub fn atomic_load_acq(src: &T) -> T; - pub fn atomic_load_relaxed(src: &T) -> T; - - pub fn atomic_store(dst: &mut T, val: T); - pub fn atomic_store_rel(dst: &mut T, val: T); - pub fn atomic_store_relaxed(dst: &mut T, val: T); - - pub fn atomic_xchg(dst: &mut T, src: T) -> T; - pub fn atomic_xchg_acq(dst: &mut T, src: T) -> T; - pub fn atomic_xchg_rel(dst: &mut T, src: T) -> T; - pub fn atomic_xchg_acqrel(dst: &mut T, src: T) -> T; - pub fn atomic_xchg_relaxed(dst: &mut T, src: T) -> T; - - pub fn atomic_xadd(dst: &mut T, src: T) -> T; - pub fn atomic_xadd_acq(dst: &mut T, src: T) -> T; - pub fn atomic_xadd_rel(dst: &mut T, src: T) -> T; - pub fn atomic_xadd_acqrel(dst: &mut T, src: T) -> T; - pub fn atomic_xadd_relaxed(dst: &mut T, src: T) -> T; - - pub fn atomic_xsub(dst: &mut T, src: T) -> T; - pub fn atomic_xsub_acq(dst: &mut T, src: T) -> T; - pub fn atomic_xsub_rel(dst: &mut T, src: T) -> T; - pub fn atomic_xsub_acqrel(dst: &mut T, src: T) -> T; - pub fn atomic_xsub_relaxed(dst: &mut T, src: T) -> T; - - pub fn atomic_and(dst: &mut T, src: T) -> T; - pub fn atomic_and_acq(dst: &mut T, src: T) -> T; - pub fn atomic_and_rel(dst: &mut T, src: T) -> T; - pub fn atomic_and_acqrel(dst: &mut T, src: T) -> T; - pub fn atomic_and_relaxed(dst: &mut T, src: T) -> T; - - pub fn atomic_nand(dst: &mut T, src: T) -> T; - pub fn atomic_nand_acq(dst: &mut T, src: T) -> T; - pub fn atomic_nand_rel(dst: &mut T, src: T) -> T; - pub fn atomic_nand_acqrel(dst: &mut T, src: T) -> T; - pub fn atomic_nand_relaxed(dst: &mut T, src: T) -> T; - - pub fn atomic_or(dst: &mut T, src: T) -> T; - pub fn atomic_or_acq(dst: &mut T, src: T) -> T; - pub fn atomic_or_rel(dst: &mut T, src: T) -> T; - pub fn atomic_or_acqrel(dst: &mut T, src: T) -> T; - pub fn atomic_or_relaxed(dst: &mut T, src: T) -> T; - - pub fn atomic_xor(dst: &mut T, src: T) -> T; - pub fn atomic_xor_acq(dst: &mut T, src: T) -> T; - pub fn atomic_xor_rel(dst: &mut T, src: T) -> T; - pub fn atomic_xor_acqrel(dst: &mut T, src: T) -> T; - pub fn atomic_xor_relaxed(dst: &mut T, src: T) -> T; - - pub fn atomic_max(dst: &mut T, src: T) -> T; - pub fn atomic_max_acq(dst: &mut T, src: T) -> T; - pub fn atomic_max_rel(dst: &mut T, src: T) -> T; - pub fn atomic_max_acqrel(dst: &mut T, src: T) -> T; - pub fn atomic_max_relaxed(dst: &mut T, src: T) -> T; - - pub fn atomic_min(dst: &mut T, src: T) -> T; - pub fn atomic_min_acq(dst: &mut T, src: T) -> T; - pub fn atomic_min_rel(dst: &mut T, src: T) -> T; - pub fn atomic_min_acqrel(dst: &mut T, src: T) -> T; - pub fn atomic_min_relaxed(dst: &mut T, src: T) -> T; - - pub fn atomic_umin(dst: &mut T, src: T) -> T; - pub fn atomic_umin_acq(dst: &mut T, src: T) -> T; - pub fn atomic_umin_rel(dst: &mut T, src: T) -> T; - pub fn atomic_umin_acqrel(dst: &mut T, src: T) -> T; - pub fn atomic_umin_relaxed(dst: &mut T, src: T) -> T; - - pub fn atomic_umax(dst: &mut T, src: T) -> T; - pub fn atomic_umax_acq(dst: &mut T, src: T) -> T; - pub fn atomic_umax_rel(dst: &mut T, src: T) -> T; - pub fn atomic_umax_acqrel(dst: &mut T, src: T) -> T; - pub fn atomic_umax_relaxed(dst: &mut T, src: T) -> T; -} -#[cfg(not(stage0))] extern "rust-intrinsic" { // NB: These intrinsics take unsafe pointers because they mutate aliased diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index 5f3b88d5205..fed47dfcff3 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -19,13 +19,14 @@ use result::{Ok, Err}; use slice::{OwnedVector, ImmutableVector, MutableVector}; use slice; +use vec::Vec; /// Wraps a Reader and buffers input from it /// -/// It can be excessively inefficient to work directly with a `Reader` or -/// `Writer`. Every call to `read` or `write` on `TcpStream` results in a -/// system call, for example. This module provides structures that wrap -/// `Readers`, `Writers`, and `Streams` and buffer input and output to them. +/// It can be excessively inefficient to work directly with a `Reader`. For +/// example, every call to `read` on `TcpStream` results in a system call. A +/// `BufferedReader` performs large, infrequent reads on the underlying +/// `Reader` and maintains an in-memory buffer of the results. /// /// # Example /// @@ -43,10 +44,9 @@ /// ``` pub struct BufferedReader { priv inner: R, - priv buf: ~[u8], + priv buf: Vec, priv pos: uint, priv cap: uint, - priv eof: bool, } impl BufferedReader { @@ -58,14 +58,13 @@ pub fn with_capacity(cap: uint, inner: R) -> BufferedReader { // everything up-front. This allows creation of BufferedReader instances // to be very cheap (large mallocs are not nearly as expensive as large // callocs). - let mut buf = slice::with_capacity(cap); + let mut buf = Vec::with_capacity(cap); unsafe { buf.set_len(cap); } BufferedReader { inner: inner, buf: buf, pos: 0, cap: 0, - eof: false, } } @@ -80,7 +79,7 @@ pub fn new(inner: R) -> BufferedReader { /// underlying reader because that could possibly corrupt the buffer. pub fn get_ref<'a>(&'a self) -> &'a R { &self.inner } - /// Unwraps this buffer, returning the underlying reader. + /// Unwraps this `BufferedReader`, returning the underlying reader. /// /// Note that any leftover data in the internal buffer is lost. pub fn unwrap(self) -> R { self.inner } @@ -89,7 +88,7 @@ pub fn unwrap(self) -> R { self.inner } impl Buffer for BufferedReader { fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]> { if self.pos == self.cap { - self.cap = try!(self.inner.read(self.buf)); + self.cap = try!(self.inner.read(self.buf.as_mut_slice())); self.pos = 0; } Ok(self.buf.slice(self.pos, self.cap)) @@ -116,6 +115,11 @@ fn read(&mut self, buf: &mut [u8]) -> IoResult { /// Wraps a Writer and buffers output to it /// +/// It can be excessively inefficient to work directly with a `Writer`. For +/// example, every call to `write` on `TcpStream` results in a system call. A +/// `BufferedWriter` keeps an in memory buffer of data and writes it to the +/// underlying `Writer` in large, infrequent batches. +/// /// This writer will be flushed when it is dropped. /// /// # Example @@ -132,7 +136,7 @@ fn read(&mut self, buf: &mut [u8]) -> IoResult { /// ``` pub struct BufferedWriter { priv inner: Option, - priv buf: ~[u8], + priv buf: Vec, priv pos: uint } @@ -140,7 +144,7 @@ impl BufferedWriter { /// Creates a new `BufferedWriter` with the specified buffer capacity pub fn with_capacity(cap: uint, inner: W) -> BufferedWriter { // See comments in BufferedReader for why this uses unsafe code. - let mut buf = slice::with_capacity(cap); + let mut buf = Vec::with_capacity(cap); unsafe { buf.set_len(cap); } BufferedWriter { inner: Some(inner), @@ -170,7 +174,7 @@ fn flush_buf(&mut self) -> IoResult<()> { /// underlying reader because that could possibly corrupt the buffer. pub fn get_ref<'a>(&'a self) -> &'a W { self.inner.get_ref() } - /// Unwraps this buffer, returning the underlying writer. + /// Unwraps this `BufferedWriter`, returning the underlying writer. /// /// The buffer is flushed before returning the writer. pub fn unwrap(mut self) -> W { @@ -234,7 +238,7 @@ pub fn new(inner: W) -> LineBufferedWriter { /// underlying reader because that could possibly corrupt the buffer. pub fn get_ref<'a>(&'a self) -> &'a W { self.inner.get_ref() } - /// Unwraps this buffer, returning the underlying writer. + /// Unwraps this `LineBufferedWriter`, returning the underlying writer. /// /// The internal buffer is flushed before returning the writer. pub fn unwrap(self) -> W { self.inner.unwrap() } @@ -273,6 +277,11 @@ fn read(&mut self, buf: &mut [u8]) -> IoResult { /// Wraps a Stream and buffers input and output to and from it. /// +/// It can be excessively inefficient to work directly with a `Stream`. For +/// example, every call to `read` or `write` on `TcpStream` results in a system +/// call. A `BufferedStream` keeps in memory buffers of data, making large, +/// infrequent calls to `read` and `write` on the underlying `Stream`. +/// /// The output half will be flushed when this stream is dropped. /// /// # Example @@ -325,7 +334,7 @@ pub fn get_ref<'a>(&'a self) -> &'a S { w.get_ref() } - /// Unwraps this buffer, returning the underlying stream. + /// Unwraps this `BufferedStream`, returning the underlying stream. /// /// The internal buffer is flushed before returning the stream. Any leftover /// data in the read buffer is lost. diff --git a/src/libstd/io/fs.rs b/src/libstd/io/fs.rs index 870f33733f4..8681ab21f10 100644 --- a/src/libstd/io/fs.rs +++ b/src/libstd/io/fs.rs @@ -1282,10 +1282,10 @@ fn utime_noexist() { } iotest!(fn binary_file() { - use rand::{rng, Rng}; + use rand::{Rng, task_rng}; let mut bytes = [0, ..1024]; - rng().fill_bytes(bytes); + task_rng().fill_bytes(bytes); let tmpdir = tmpdir(); diff --git a/src/libstd/iter.rs b/src/libstd/iter.rs index 320383d4f81..8762f23c3ce 100644 --- a/src/libstd/iter.rs +++ b/src/libstd/iter.rs @@ -463,21 +463,6 @@ fn collect>(&mut self) -> B { FromIterator::from_iterator(self) } - /// Loops through the entire iterator, collecting all of the elements into - /// a unique vector. This is simply collect() specialized for vectors. - /// - /// # Example - /// - /// ```rust - /// let a = [1, 2, 3, 4, 5]; - /// let b: ~[int] = a.iter().map(|&x| x).to_owned_vec(); - /// assert!(a == b); - /// ``` - #[inline] - fn to_owned_vec(&mut self) -> ~[A] { - self.collect() - } - /// Loops through `n` iterations, returning the `n`th element of the /// iterator. /// @@ -2195,13 +2180,13 @@ pub mod order { use option::{Some, None}; use super::Iterator; - /// Compare `a` and `b` for equality using `TotalOrd` + /// Compare `a` and `b` for equality using `TotalEq` pub fn equals>(mut a: T, mut b: T) -> bool { loop { match (a.next(), b.next()) { (None, None) => return true, (None, _) | (_, None) => return false, - (Some(x), Some(y)) => if !x.equals(&y) { return false }, + (Some(x), Some(y)) => if x != y { return false }, } } } diff --git a/src/libstd/kinds.rs b/src/libstd/kinds.rs index b44616421d1..2ce41a33c29 100644 --- a/src/libstd/kinds.rs +++ b/src/libstd/kinds.rs @@ -26,12 +26,6 @@ pub trait Send { // empty. } -/// Types that are either immutable or have inherited mutability. -#[lang="freeze"] -pub trait Freeze { - // empty. -} - /// Types with a constant size known at compile-time. #[lang="sized"] pub trait Sized { @@ -47,16 +41,6 @@ pub trait Pod { } /// Types that can be safely shared between threads, hence thread-safe. -#[cfg(stage0)] -pub trait Share { - // Empty -} - -#[cfg(stage0)] -impl Share for T {} - -/// Types that can be safely shared between threads, hence thread-safe. -#[cfg(not(stage0))] #[lang="share"] pub trait Share { // Empty @@ -225,14 +209,6 @@ pub mod marker { #[deriving(Eq,Clone)] pub struct InvariantLifetime<'a>; - /// A type which is considered "not freezable", meaning that - /// its contents could change even if stored in an immutable - /// context or it is the referent of an `&T` pointer. This is - /// typically embedded in other types, such as `Cell`. - #[lang="no_freeze_bound"] - #[deriving(Eq,Clone)] - pub struct NoFreeze; - /// A type which is considered "not sendable", meaning that it cannot /// be safely sent between tasks, even if it is owned. This is /// typically embedded in other types, such as `Gc`, to ensure that diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index 7d734469b12..021a932fc8b 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -58,7 +58,6 @@ #[no_std]; #[deny(missing_doc)]; -#[allow(deprecated_owned_vector)]; // NOTE: remove after stage0 // When testing libstd, bring in libuv as the I/O backend so tests can print // things and all of the std::io tests have an I/O interface to run on top @@ -78,9 +77,6 @@ #[cfg(test)] pub use cmp = realstd::cmp; #[cfg(test)] pub use ty = realstd::ty; -#[cfg(stage0)] -pub use vec_ng = vec; - // Run tests with libgreen instead of libnative. // // FIXME: This egregiously hacks around starting the test runner in a different @@ -134,7 +130,7 @@ fn start(argc: int, argv: **u8) -> int { pub mod ptr; pub mod owned; -pub mod managed; +mod managed; mod reference; pub mod rc; pub mod gc; diff --git a/src/libstd/managed.rs b/src/libstd/managed.rs index 4cd99492ee4..bf73c05440c 100644 --- a/src/libstd/managed.rs +++ b/src/libstd/managed.rs @@ -12,13 +12,6 @@ #[cfg(not(test))] use cmp::*; -/// Returns the refcount of a shared box (as just before calling this) -#[inline] -pub fn refcount(t: @T) -> uint { - use raw::Repr; - unsafe { (*t.repr()).ref_count - 1 } -} - /// Determine if two shared boxes point to the same object #[inline] pub fn ptr_eq(a: @T, b: @T) -> bool { @@ -52,10 +45,7 @@ fn cmp(&self, other: &@T) -> Ordering { (**self).cmp(*other) } } #[cfg(not(test))] -impl TotalEq for @T { - #[inline] - fn equals(&self, other: &@T) -> bool { (**self).equals(*other) } -} +impl TotalEq for @T {} #[test] fn test() { @@ -66,14 +56,3 @@ fn test() { assert!((!ptr_eq::(x, y))); assert!((!ptr_eq::(y, x))); } - -#[test] -fn refcount_test() { - use clone::Clone; - - let x = @3; - assert_eq!(refcount(x), 1); - let y = x.clone(); - assert_eq!(refcount(x), 2); - assert_eq!(refcount(y), 2); -} diff --git a/src/libstd/option.rs b/src/libstd/option.rs index 5f733302d6f..23363a97845 100644 --- a/src/libstd/option.rs +++ b/src/libstd/option.rs @@ -650,7 +650,7 @@ struct R { #[unsafe_destructor] impl ::ops::Drop for R { fn drop(&mut self) { - let ii = self.i.deref(); + let ii = &*self.i; ii.set(ii.get() + 1); } } @@ -667,7 +667,7 @@ fn R(i: Rc>) -> R { let opt = Some(x); let _y = opt.unwrap(); } - assert_eq!(i.deref().get(), 1); + assert_eq!(i.get(), 1); } #[test] diff --git a/src/libstd/os.rs b/src/libstd/os.rs index d03757c1e69..f270c7e7a74 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -740,11 +740,16 @@ fn FormatMessageW(flags: DWORD, buf.len() as DWORD, ptr::null()); if res == 0 { - fail!("[{}] FormatMessage failure", errno()); + // Sometimes FormatMessageW can fail e.g. system doesn't like langId, + let fm_err = errno(); + return format!("OS Error {} (FormatMessageW() returned error {})", err, fm_err); } - str::from_utf16(str::truncate_utf16_at_nul(buf)) - .expect("FormatMessageW returned invalid UTF-16") + let msg = str::from_utf16(str::truncate_utf16_at_nul(buf)); + match msg { + Some(msg) => format!("OS Error {}: {}", err, msg), + None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", err), + } } } diff --git a/src/libstd/owned.rs b/src/libstd/owned.rs index dc8ea34c84b..1fa86c53117 100644 --- a/src/libstd/owned.rs +++ b/src/libstd/owned.rs @@ -53,7 +53,4 @@ fn cmp(&self, other: &~T) -> Ordering { (**self).cmp(*other) } } #[cfg(not(test))] -impl TotalEq for ~T { - #[inline] - fn equals(&self, other: &~T) -> bool { (**self).equals(*other) } -} +impl TotalEq for ~T {} diff --git a/src/libstd/path/posix.rs b/src/libstd/path/posix.rs index f654f59266a..3596a07eeb2 100644 --- a/src/libstd/path/posix.rs +++ b/src/libstd/path/posix.rs @@ -13,7 +13,7 @@ use container::Container; use c_str::{CString, ToCStr}; use clone::Clone; -use cmp::Eq; +use cmp::{Eq, TotalEq}; use from_str::FromStr; use io::Writer; use iter::{AdditiveIterator, Extendable, Iterator, Map}; @@ -69,6 +69,8 @@ fn eq(&self, other: &Path) -> bool { } } +impl TotalEq for Path {} + impl FromStr for Path { fn from_str(s: &str) -> Option { Path::new_opt(s) @@ -1177,13 +1179,13 @@ macro_rules! t( (s: $path:expr, $exp:expr) => ( { let path = Path::new($path); - let comps = path.components().to_owned_vec(); + let comps = path.components().collect::<~[&[u8]]>(); let exp: &[&str] = $exp; - let exps = exp.iter().map(|x| x.as_bytes()).to_owned_vec(); + let exps = exp.iter().map(|x| x.as_bytes()).collect::<~[&[u8]]>(); assert!(comps == exps, "components: Expected {:?}, found {:?}", comps, exps); - let comps = path.rev_components().to_owned_vec(); - let exps = exps.move_rev_iter().to_owned_vec(); + let comps = path.rev_components().collect::<~[&[u8]]>(); + let exps = exps.move_rev_iter().collect::<~[&[u8]]>(); assert!(comps == exps, "rev_components: Expected {:?}, found {:?}", comps, exps); } @@ -1191,12 +1193,12 @@ macro_rules! t( (v: [$($arg:expr),+], [$([$($exp:expr),*]),*]) => ( { let path = Path::new(b!($($arg),+)); - let comps = path.components().to_owned_vec(); + let comps = path.components().collect::<~[&[u8]]>(); let exp: &[&[u8]] = [$(b!($($exp),*)),*]; assert!(comps.as_slice() == exp, "components: Expected {:?}, found {:?}", comps.as_slice(), exp); - let comps = path.rev_components().to_owned_vec(); - let exp = exp.rev_iter().map(|&x|x).to_owned_vec(); + let comps = path.rev_components().collect::<~[&[u8]]>(); + let exp = exp.rev_iter().map(|&x|x).collect::<~[&[u8]]>(); assert!(comps.as_slice() == exp, "rev_components: Expected {:?}, found {:?}", comps.as_slice(), exp); @@ -1226,13 +1228,13 @@ macro_rules! t( (v: [$($arg:expr),+], $exp:expr) => ( { let path = Path::new(b!($($arg),+)); - let comps = path.str_components().to_owned_vec(); + let comps = path.str_components().collect::<~[Option<&str>]>(); let exp: &[Option<&str>] = $exp; assert!(comps.as_slice() == exp, "str_components: Expected {:?}, found {:?}", comps.as_slice(), exp); - let comps = path.rev_str_components().to_owned_vec(); - let exp = exp.rev_iter().map(|&x|x).to_owned_vec(); + let comps = path.rev_str_components().collect::<~[Option<&str>]>(); + let exp = exp.rev_iter().map(|&x|x).collect::<~[Option<&str>]>(); assert!(comps.as_slice() == exp, "rev_str_components: Expected {:?}, found {:?}", comps.as_slice(), exp); diff --git a/src/libstd/path/windows.rs b/src/libstd/path/windows.rs index dba8af4128b..9d65a99a0b5 100644 --- a/src/libstd/path/windows.rs +++ b/src/libstd/path/windows.rs @@ -15,7 +15,7 @@ use cast; use clone::Clone; use container::Container; -use cmp::Eq; +use cmp::{Eq, TotalEq}; use from_str::FromStr; use io::Writer; use iter::{AdditiveIterator, DoubleEndedIterator, Extendable, Rev, Iterator, Map}; @@ -93,6 +93,8 @@ fn eq(&self, other: &Path) -> bool { } } +impl TotalEq for Path {} + impl FromStr for Path { fn from_str(s: &str) -> Option { Path::new_opt(s) @@ -2224,13 +2226,15 @@ macro_rules! t( (s: $path:expr, $exp:expr) => ( { let path = Path::new($path); - let comps = path.str_components().map(|x|x.unwrap()).to_owned_vec(); + let comps = path.str_components().map(|x|x.unwrap()) + .collect::<~[&str]>(); let exp: &[&str] = $exp; assert!(comps.as_slice() == exp, "str_components: Expected {:?}, found {:?}", comps.as_slice(), exp); - let comps = path.rev_str_components().map(|x|x.unwrap()).to_owned_vec(); - let exp = exp.rev_iter().map(|&x|x).to_owned_vec(); + let comps = path.rev_str_components().map(|x|x.unwrap()) + .collect::<~[&str]>(); + let exp = exp.rev_iter().map(|&x|x).collect::<~[&str]>(); assert!(comps.as_slice() == exp, "rev_str_components: Expected {:?}, found {:?}", comps.as_slice(), exp); @@ -2239,13 +2243,14 @@ macro_rules! t( (v: [$($arg:expr),+], $exp:expr) => ( { let path = Path::new(b!($($arg),+)); - let comps = path.str_components().map(|x|x.unwrap()).to_owned_vec(); + let comps = path.str_components().map(|x|x.unwrap()).collect::<~[&str]>(); let exp: &[&str] = $exp; assert!(comps.as_slice() == exp, "str_components: Expected {:?}, found {:?}", comps.as_slice(), exp); - let comps = path.rev_str_components().map(|x|x.unwrap()).to_owned_vec(); - let exp = exp.rev_iter().map(|&x|x).to_owned_vec(); + let comps = path.rev_str_components().map(|x|x.unwrap()) + .collect::<~[&str]>(); + let exp = exp.rev_iter().map(|&x|x).collect::<~[&str]>(); assert!(comps.as_slice() == exp, "rev_str_components: Expected {:?}, found {:?}", comps.as_slice(), exp); @@ -2299,12 +2304,12 @@ macro_rules! t( (s: $path:expr, $exp:expr) => ( { let path = Path::new($path); - let comps = path.components().to_owned_vec(); + let comps = path.components().collect::<~[&[u8]]>(); let exp: &[&[u8]] = $exp; assert!(comps.as_slice() == exp, "components: Expected {:?}, found {:?}", comps.as_slice(), exp); - let comps = path.rev_components().to_owned_vec(); - let exp = exp.rev_iter().map(|&x|x).to_owned_vec(); + let comps = path.rev_components().collect::<~[&[u8]]>(); + let exp = exp.rev_iter().map(|&x|x).collect::<~[&[u8]]>(); assert!(comps.as_slice() == exp, "rev_components: Expected {:?}, found {:?}", comps.as_slice(), exp); diff --git a/src/libstd/prelude.rs b/src/libstd/prelude.rs index f8e56cf8a2f..d487aa638ac 100644 --- a/src/libstd/prelude.rs +++ b/src/libstd/prelude.rs @@ -20,7 +20,7 @@ */ // Reexported core operators -pub use kinds::{Freeze, Pod, Send, Sized, Share}; +pub use kinds::{Pod, Send, Sized, Share}; pub use ops::{Add, Sub, Mul, Div, Rem, Neg, Not}; pub use ops::{BitAnd, BitOr, BitXor}; pub use ops::{Drop, Deref, DerefMut}; diff --git a/src/libstd/ptr.rs b/src/libstd/ptr.rs index 179100255c4..504c613bf4c 100644 --- a/src/libstd/ptr.rs +++ b/src/libstd/ptr.rs @@ -19,7 +19,7 @@ use option::{Option, Some, None}; use intrinsics; -#[cfg(not(test))] use cmp::{Eq, Ord}; +#[cfg(not(test))] use cmp::{Eq, TotalEq, Ord}; /// Return the offset of the first null pointer in `buf`. #[inline] @@ -272,6 +272,9 @@ fn eq(&self, other: &*T) -> bool { fn ne(&self, other: &*T) -> bool { !self.eq(other) } } +#[cfg(not(test))] +impl TotalEq for *T {} + #[cfg(not(test))] impl Eq for *mut T { #[inline] @@ -282,6 +285,9 @@ fn eq(&self, other: &*mut T) -> bool { fn ne(&self, other: &*mut T) -> bool { !self.eq(other) } } +#[cfg(not(test))] +impl TotalEq for *mut T {} + // Equivalence for pointers #[cfg(not(test))] impl Equiv<*mut T> for *T { diff --git a/src/libstd/rc.rs b/src/libstd/rc.rs index 03be4fea5ee..d26038f508f 100644 --- a/src/libstd/rc.rs +++ b/src/libstd/rc.rs @@ -26,7 +26,7 @@ use cast::transmute; use cell::Cell; use clone::Clone; -use cmp::{Eq, Ord}; +use cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering}; use kinds::marker; use ops::{Deref, Drop}; use option::{Option, Some, None}; @@ -122,24 +122,30 @@ fn clone(&self) -> Rc { impl Eq for Rc { #[inline(always)] - fn eq(&self, other: &Rc) -> bool { *self.deref() == *other.deref() } - + fn eq(&self, other: &Rc) -> bool { **self == **other } #[inline(always)] - fn ne(&self, other: &Rc) -> bool { *self.deref() != *other.deref() } + fn ne(&self, other: &Rc) -> bool { **self != **other } } +impl TotalEq for Rc {} + impl Ord for Rc { #[inline(always)] - fn lt(&self, other: &Rc) -> bool { *self.deref() < *other.deref() } + fn lt(&self, other: &Rc) -> bool { **self < **other } #[inline(always)] - fn le(&self, other: &Rc) -> bool { *self.deref() <= *other.deref() } + fn le(&self, other: &Rc) -> bool { **self <= **other } #[inline(always)] - fn gt(&self, other: &Rc) -> bool { *self.deref() > *other.deref() } + fn gt(&self, other: &Rc) -> bool { **self > **other } #[inline(always)] - fn ge(&self, other: &Rc) -> bool { *self.deref() >= *other.deref() } + fn ge(&self, other: &Rc) -> bool { **self >= **other } +} + +impl TotalOrd for Rc { + #[inline] + fn cmp(&self, other: &Rc) -> Ordering { (**self).cmp(&**other) } } /// Weak reference to a reference-counted box @@ -236,21 +242,21 @@ fn test_clone() { #[test] fn test_simple() { let x = Rc::new(5); - assert_eq!(*x.deref(), 5); + assert_eq!(*x, 5); } #[test] fn test_simple_clone() { let x = Rc::new(5); let y = x.clone(); - assert_eq!(*x.deref(), 5); - assert_eq!(*y.deref(), 5); + assert_eq!(*x, 5); + assert_eq!(*y, 5); } #[test] fn test_destructor() { let x = Rc::new(~5); - assert_eq!(**x.deref(), 5); + assert_eq!(**x, 5); } #[test] @@ -273,7 +279,7 @@ fn gc_inside() { // see issue #11532 use gc::Gc; let a = Rc::new(RefCell::new(Gc::new(1))); - assert!(a.deref().try_borrow_mut().is_some()); + assert!(a.try_borrow_mut().is_some()); } #[test] @@ -284,7 +290,7 @@ struct Cycle { let a = Rc::new(Cycle { x: RefCell::new(None) }); let b = a.clone().downgrade(); - *a.deref().x.borrow_mut().get() = Some(b); + *a.x.borrow_mut() = Some(b); // hopefully we don't double-free (or leak)... } diff --git a/src/libstd/reference.rs b/src/libstd/reference.rs index fdbca2b9f33..eb615afd85f 100644 --- a/src/libstd/reference.rs +++ b/src/libstd/reference.rs @@ -54,8 +54,4 @@ fn cmp(&self, other: & &'a T) -> Ordering { (**self).cmp(*other) } } #[cfg(not(test))] -impl<'a, T: TotalEq> TotalEq for &'a T { - #[inline] - fn equals(&self, other: & &'a T) -> bool { (**self).equals(*other) } -} - +impl<'a, T: TotalEq> TotalEq for &'a T {} diff --git a/src/libstd/rt/args.rs b/src/libstd/rt/args.rs index 53b8db8499d..fc9e571b270 100644 --- a/src/libstd/rt/args.rs +++ b/src/libstd/rt/args.rs @@ -66,7 +66,6 @@ mod imp { use cast; use clone::Clone; use option::{Option, Some, None}; - use ptr::RawPtr; use iter::Iterator; use unstable::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT}; use mem; @@ -124,6 +123,7 @@ fn get_global_ptr() -> *mut Option<~~[~[u8]]> { #[cfg(not(test))] unsafe fn load_argc_and_argv(argc: int, argv: **u8) -> ~[~[u8]] { use c_str::CString; + use ptr::RawPtr; use {slice, libc}; use slice::CloneableVector; diff --git a/src/libstd/rt/task.rs b/src/libstd/rt/task.rs index 8c617c1b59b..cd047c815e9 100644 --- a/src/libstd/rt/task.rs +++ b/src/libstd/rt/task.rs @@ -433,8 +433,8 @@ fn unwind() { #[test] fn rng() { - use rand::{rng, Rng}; - let mut r = rng(); + use rand::{Rng, task_rng}; + let mut r = task_rng(); let _ = r.next_u32(); } @@ -471,7 +471,7 @@ struct List { { let mut a = a.borrow_mut(); - a.get().next = Some(b); + a.next = Some(b); } } diff --git a/src/libstd/slice.rs b/src/libstd/slice.rs index 12718c55923..985feaf6ab6 100644 --- a/src/libstd/slice.rs +++ b/src/libstd/slice.rs @@ -436,7 +436,7 @@ pub fn new(length: uint) -> ElementSwaps { emit_reset: true, sdir: range(0, length) .map(|i| SizeDirection{ size: i, dir: Neg }) - .to_owned_vec() + .collect::<~[_]>() } } } @@ -649,17 +649,9 @@ fn eq(&self, other: &~[T]) -> bool { self.as_slice() == *other } fn ne(&self, other: &~[T]) -> bool { !self.eq(other) } } - impl<'a,T:TotalEq> TotalEq for &'a [T] { - fn equals(&self, other: & &'a [T]) -> bool { - self.len() == other.len() && - order::equals(self.iter(), other.iter()) - } - } + impl<'a,T:TotalEq> TotalEq for &'a [T] {} - impl TotalEq for ~[T] { - #[inline] - fn equals(&self, other: &~[T]) -> bool { self.as_slice().equals(&other.as_slice()) } - } + impl TotalEq for ~[T] {} impl<'a,T:Eq, V: Vector> Equiv for &'a [T] { #[inline] @@ -3539,7 +3531,7 @@ fn test_sort_stability() { let n = task_rng().gen::() % 10; counts[n] += 1; (n, counts[n]) - }).to_owned_vec(); + }).collect::<~[(uint, int)]>(); // only sort on the first element, so an unstable sort // may mix up the counts. @@ -4207,7 +4199,7 @@ fn test_shrink_to_fit() { assert_eq!(xs.capacity(), 128); xs.shrink_to_fit(); assert_eq!(xs.capacity(), 100); - assert_eq!(xs, range(0, 100).to_owned_vec()); + assert_eq!(xs, range(0, 100).collect::<~[_]>()); } #[test] diff --git a/src/libstd/str.rs b/src/libstd/str.rs index 0cd5e647831..4466439bcbd 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -937,7 +937,7 @@ fn size_hint(&self) -> (uint, Option) { /// 0x0073, 0xDD1E, 0x0069, 0x0063, /// 0xD834]; /// -/// assert_eq!(str::utf16_items(v).to_owned_vec(), +/// assert_eq!(str::utf16_items(v).collect::<~[_]>(), /// ~[ScalarValue('𝄞'), /// ScalarValue('m'), ScalarValue('u'), ScalarValue('s'), /// LoneSurrogate(0xDD1E), @@ -1262,16 +1262,11 @@ fn into_maybe_owned(self) -> MaybeOwned<'a> { self } impl<'a> Eq for MaybeOwned<'a> { #[inline] fn eq(&self, other: &MaybeOwned) -> bool { - self.as_slice().equals(&other.as_slice()) + self.as_slice() == other.as_slice() } } -impl<'a> TotalEq for MaybeOwned<'a> { - #[inline] - fn equals(&self, other: &MaybeOwned) -> bool { - self.as_slice().equals(&other.as_slice()) - } -} +impl<'a> TotalEq for MaybeOwned<'a> {} impl<'a> Ord for MaybeOwned<'a> { #[inline] @@ -1290,7 +1285,7 @@ fn cmp(&self, other: &MaybeOwned) -> Ordering { impl<'a, S: Str> Equiv for MaybeOwned<'a> { #[inline] fn equiv(&self, other: &S) -> bool { - self.as_slice().equals(&other.as_slice()) + self.as_slice() == other.as_slice() } } @@ -1577,19 +1572,9 @@ fn eq(&self, other: &~str) -> bool { } } - impl<'a> TotalEq for &'a str { - #[inline] - fn equals(&self, other: & &'a str) -> bool { - eq_slice((*self), (*other)) - } - } + impl<'a> TotalEq for &'a str {} - impl TotalEq for ~str { - #[inline] - fn equals(&self, other: &~str) -> bool { - eq_slice((*self), (*other)) - } - } + impl TotalEq for ~str {} impl<'a> Ord for &'a str { #[inline] @@ -4450,11 +4435,9 @@ fn test_maybe_owned_traits() { assert_eq!(Owned(~""), Default::default()); assert!(s.cmp(&o) == Equal); - assert!(s.equals(&o)); assert!(s.equiv(&o)); assert!(o.cmp(&s) == Equal); - assert!(o.equals(&s)); assert!(o.equiv(&s)); } diff --git a/src/libstd/sync/atomics_stage0.rs b/src/libstd/sync/atomics_stage0.rs deleted file mode 100644 index b501972532d..00000000000 --- a/src/libstd/sync/atomics_stage0.rs +++ /dev/null @@ -1,930 +0,0 @@ -// Copyright 2012-2013 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. - -//! Atomic types -//! -//! Atomic types provide primitive shared-memory communication between -//! threads, and are the building blocks of other concurrent -//! types. -//! -//! This module defines atomic versions of a select number of primitive -//! types, including `AtomicBool`, `AtomicInt`, `AtomicUint`, and `AtomicOption`. -//! Atomic types present operations that, when used correctly, synchronize -//! updates between threads. -//! -//! Each method takes an `Ordering` which represents the strength of -//! the memory barrier for that operation. These orderings are the -//! same as [C++11 atomic orderings][1]. -//! -//! [1]: http://gcc.gnu.org/wiki/Atomic/GCCMM/AtomicSync -//! -//! Atomic variables are safe to share between threads (they implement `Share`) -//! but they do not themselves provide the mechanism for sharing. The most -//! common way to share an atomic variable is to put it into an `Arc` (an -//! atomically-reference-counted shared pointer). -//! -//! Most atomic types may be stored in static variables, initialized using -//! the provided static initializers like `INIT_ATOMIC_BOOL`. Atomic statics -//! are often used for lazy global initialization. -//! -//! -//! # Examples -//! -//! A simple spinlock: -//! -//! ```ignore -//! # // FIXME: Needs PR #12430 -//! extern crate sync; -//! -//! use sync::Arc; -//! use std::sync::atomics::{AtomicUint, SeqCst}; -//! use std::task::deschedule; -//! -//! fn main() { -//! let spinlock = Arc::new(AtomicUint::new(1)); -//! -//! let spinlock_clone = spinlock.clone(); -//! spawn(proc() { -//! spinlock_clone.store(0, SeqCst); -//! }); -//! -//! // Wait for the other task to release the lock -//! while spinlock.load(SeqCst) != 0 { -//! // Since tasks may not be preemptive (if they are green threads) -//! // yield to the scheduler to let the other task run. Low level -//! // concurrent code needs to take into account Rust's two threading -//! // models. -//! deschedule(); -//! } -//! } -//! ``` -//! -//! Transferring a heap object with `AtomicOption`: -//! -//! ```ignore -//! # // FIXME: Needs PR #12430 -//! extern crate sync; -//! -//! use sync::Arc; -//! use std::sync::atomics::{AtomicOption, SeqCst}; -//! -//! fn main() { -//! struct BigObject; -//! -//! let shared_big_object = Arc::new(AtomicOption::empty()); -//! -//! let shared_big_object_clone = shared_big_object.clone(); -//! spawn(proc() { -//! let unwrapped_big_object = shared_big_object_clone.take(SeqCst); -//! if unwrapped_big_object.is_some() { -//! println!("got a big object from another task"); -//! } else { -//! println!("other task hasn't sent big object yet"); -//! } -//! }); -//! -//! shared_big_object.swap(~BigObject, SeqCst); -//! } -//! ``` -//! -//! Keep a global count of live tasks: -//! -//! ``` -//! use std::sync::atomics::{AtomicUint, SeqCst, INIT_ATOMIC_UINT}; -//! -//! static mut GLOBAL_TASK_COUNT: AtomicUint = INIT_ATOMIC_UINT; -//! -//! unsafe { -//! let old_task_count = GLOBAL_TASK_COUNT.fetch_add(1, SeqCst); -//! println!("live tasks: {}", old_task_count + 1); -//! } -//! ``` - -#[allow(missing_doc)]; - -use intrinsics; -use cast; -use std::kinds::marker; -use option::{Option,Some,None}; -use ops::Drop; -use ty::Unsafe; - -/// An atomic boolean type. -pub struct AtomicBool { - priv v: Unsafe, - priv nopod: marker::NoPod -} - -/// A signed atomic integer type, supporting basic atomic arithmetic operations -pub struct AtomicInt { - priv v: Unsafe, - priv nopod: marker::NoPod -} - -/// An unsigned atomic integer type, supporting basic atomic arithmetic operations -pub struct AtomicUint { - priv v: Unsafe, - priv nopod: marker::NoPod -} - -/// An unsigned atomic integer type that is forced to be 64-bits. This does not -/// support all operations. -pub struct AtomicU64 { - priv v: Unsafe, - priv nopod: marker::NoPod -} - -/// An unsafe atomic pointer. Only supports basic atomic operations -pub struct AtomicPtr { - priv p: Unsafe, - priv nopod: marker::NoPod -} - -/// An atomic, nullable unique pointer -/// -/// This can be used as the concurrency primitive for operations that transfer -/// owned heap objects across tasks. -#[unsafe_no_drop_flag] -pub struct AtomicOption { - priv p: Unsafe, -} - -/// Atomic memory orderings -/// -/// Memory orderings limit the ways that both the compiler and CPU may reorder -/// instructions around atomic operations. At its most restrictive, -/// "sequentially consistent" atomics allow neither reads nor writes -/// to be moved either before or after the atomic operation; on the other end -/// "relaxed" atomics allow all reorderings. -/// -/// Rust's memory orderings are the same as in C++[1]. -/// -/// [1]: http://gcc.gnu.org/wiki/Atomic/GCCMM/AtomicSync -pub enum Ordering { - /// No ordering constraints, only atomic operations - Relaxed, - /// When coupled with a store, all previous writes become visible - /// to another thread that performs a load with `Acquire` ordering - /// on the same value - Release, - /// When coupled with a load, all subsequent loads will see data - /// written before a store with `Release` ordering on the same value - /// in another thread - Acquire, - /// When coupled with a load, uses `Acquire` ordering, and with a store - /// `Release` ordering - AcqRel, - /// Like `AcqRel` with the additional guarantee that all threads see all - /// sequentially consistent operations in the same order. - SeqCst -} - -/// An `AtomicBool` initialized to `false` -pub static INIT_ATOMIC_BOOL : AtomicBool = AtomicBool { v: Unsafe{value: 0, - marker1: marker::InvariantType}, - nopod: marker::NoPod }; -/// An `AtomicInt` initialized to `0` -pub static INIT_ATOMIC_INT : AtomicInt = AtomicInt { v: Unsafe{value: 0, - marker1: marker::InvariantType}, - nopod: marker::NoPod }; -/// An `AtomicUint` initialized to `0` -pub static INIT_ATOMIC_UINT : AtomicUint = AtomicUint { v: Unsafe{value: 0, - marker1: marker::InvariantType}, - nopod: marker::NoPod }; -/// An `AtomicU64` initialized to `0` -pub static INIT_ATOMIC_U64 : AtomicU64 = AtomicU64 { v: Unsafe{value: 0, - marker1: marker::InvariantType}, - nopod: marker::NoPod }; - - -// NB: Needs to be -1 (0b11111111...) to make fetch_nand work correctly -static UINT_TRUE: uint = -1; - -impl AtomicBool { - /// Create a new `AtomicBool` - pub fn new(v: bool) -> AtomicBool { - let val = if v { UINT_TRUE } else { 0 }; - AtomicBool { v: Unsafe::new(val), nopod: marker::NoPod } - } - - /// Load the value - #[inline] - pub fn load(&self, order: Ordering) -> bool { - unsafe { atomic_load(&*self.v.get(), order) > 0 } - } - - /// Store the value - #[inline] - pub fn store(&mut self, val: bool, order: Ordering) { - let val = if val { UINT_TRUE } else { 0 }; - - unsafe { atomic_store(&mut *self.v.get(), val, order); } - } - - /// Store a value, returning the old value - #[inline] - pub fn swap(&mut self, val: bool, order: Ordering) -> bool { - let val = if val { UINT_TRUE } else { 0 }; - - unsafe { atomic_swap(&mut *self.v.get(), val, order) > 0 } - } - - /// If the current value is the same as expected, store a new value - /// - /// Compare the current value with `old`; if they are the same then - /// replace the current value with `new`. Return the previous value. - /// If the return value is equal to `old` then the value was updated. - /// - /// # Examples - /// - /// ```ignore - /// # // FIXME: Needs PR #12430 - /// extern crate sync; - /// - /// use sync::Arc; - /// use std::sync::atomics::{AtomicBool, SeqCst}; - /// - /// fn main() { - /// let spinlock = Arc::new(AtomicBool::new(false)); - /// let spinlock_clone = spin_lock.clone(); - /// - /// spawn(proc() { - /// with_lock(&spinlock, || println!("task 1 in lock")); - /// }); - /// - /// spawn(proc() { - /// with_lock(&spinlock_clone, || println!("task 2 in lock")); - /// }); - /// } - /// - /// fn with_lock(spinlock: &Arc, f: || -> ()) { - /// // CAS loop until we are able to replace `false` with `true` - /// while spinlock.compare_and_swap(false, true, SeqCst) == false { - /// // Since tasks may not be preemptive (if they are green threads) - /// // yield to the scheduler to let the other task run. Low level - /// // concurrent code needs to take into account Rust's two threading - /// // models. - /// deschedule(); - /// } - /// - /// // Now we have the spinlock - /// f(); - /// - /// // Release the lock - /// spinlock.store(false); - /// } - /// ``` - #[inline] - pub fn compare_and_swap(&mut self, old: bool, new: bool, order: Ordering) -> bool { - let old = if old { UINT_TRUE } else { 0 }; - let new = if new { UINT_TRUE } else { 0 }; - - unsafe { atomic_compare_and_swap(&mut *self.v.get(), old, new, order) > 0 } - } - - /// A logical "and" operation - /// - /// Performs a logical "and" operation on the current value and the - /// argument `val`, and sets the new value to the result. - /// Returns the previous value. - /// - /// # Examples - /// - /// ``` - /// use std::sync::atomics::{AtomicBool, SeqCst}; - /// - /// let mut foo = AtomicBool::new(true); - /// assert_eq!(true, foo.fetch_and(false, SeqCst)); - /// assert_eq!(false, foo.load(SeqCst)); - /// - /// let mut foo = AtomicBool::new(true); - /// assert_eq!(true, foo.fetch_and(true, SeqCst)); - /// assert_eq!(true, foo.load(SeqCst)); - /// - /// let mut foo = AtomicBool::new(false); - /// assert_eq!(false, foo.fetch_and(false, SeqCst)); - /// assert_eq!(false, foo.load(SeqCst)); - /// ``` - #[inline] - pub fn fetch_and(&mut self, val: bool, order: Ordering) -> bool { - let val = if val { UINT_TRUE } else { 0 }; - - unsafe { atomic_and(&mut *self.v.get(), val, order) > 0 } - } - - /// A logical "nand" operation - /// - /// Performs a logical "nand" operation on the current value and the - /// argument `val`, and sets the new value to the result. - /// Returns the previous value. - /// - /// # Examples - /// - /// ``` - /// use std::sync::atomics::{AtomicBool, SeqCst}; - /// - /// let mut foo = AtomicBool::new(true); - /// assert_eq!(true, foo.fetch_nand(false, SeqCst)); - /// assert_eq!(true, foo.load(SeqCst)); - /// - /// let mut foo = AtomicBool::new(true); - /// assert_eq!(true, foo.fetch_nand(true, SeqCst)); - /// assert_eq!(0, foo.load(SeqCst) as int); - /// assert_eq!(false, foo.load(SeqCst)); - /// - /// let mut foo = AtomicBool::new(false); - /// assert_eq!(false, foo.fetch_nand(false, SeqCst)); - /// assert_eq!(true, foo.load(SeqCst)); - /// ``` - #[inline] - pub fn fetch_nand(&mut self, val: bool, order: Ordering) -> bool { - let val = if val { UINT_TRUE } else { 0 }; - - unsafe { atomic_nand(&mut *self.v.get(), val, order) > 0 } - } - - /// A logical "or" operation - /// - /// Performs a logical "or" operation on the current value and the - /// argument `val`, and sets the new value to the result. - /// Returns the previous value. - /// - /// # Examples - /// - /// ``` - /// use std::sync::atomics::{AtomicBool, SeqCst}; - /// - /// let mut foo = AtomicBool::new(true); - /// assert_eq!(true, foo.fetch_or(false, SeqCst)); - /// assert_eq!(true, foo.load(SeqCst)); - /// - /// let mut foo = AtomicBool::new(true); - /// assert_eq!(true, foo.fetch_or(true, SeqCst)); - /// assert_eq!(true, foo.load(SeqCst)); - /// - /// let mut foo = AtomicBool::new(false); - /// assert_eq!(false, foo.fetch_or(false, SeqCst)); - /// assert_eq!(false, foo.load(SeqCst)); - /// ``` - #[inline] - pub fn fetch_or(&mut self, val: bool, order: Ordering) -> bool { - let val = if val { UINT_TRUE } else { 0 }; - - unsafe { atomic_or(&mut *self.v.get(), val, order) > 0 } - } - - /// A logical "xor" operation - /// - /// Performs a logical "xor" operation on the current value and the - /// argument `val`, and sets the new value to the result. - /// Returns the previous value. - /// - /// # Examples - /// - /// ``` - /// use std::sync::atomics::{AtomicBool, SeqCst}; - /// - /// let mut foo = AtomicBool::new(true); - /// assert_eq!(true, foo.fetch_xor(false, SeqCst)); - /// assert_eq!(true, foo.load(SeqCst)); - /// - /// let mut foo = AtomicBool::new(true); - /// assert_eq!(true, foo.fetch_xor(true, SeqCst)); - /// assert_eq!(false, foo.load(SeqCst)); - /// - /// let mut foo = AtomicBool::new(false); - /// assert_eq!(false, foo.fetch_xor(false, SeqCst)); - /// assert_eq!(false, foo.load(SeqCst)); - /// ``` - #[inline] - pub fn fetch_xor(&mut self, val: bool, order: Ordering) -> bool { - let val = if val { UINT_TRUE } else { 0 }; - - unsafe { atomic_xor(&mut *self.v.get(), val, order) > 0 } - } -} - -impl AtomicInt { - /// Create a new `AtomicInt` - pub fn new(v: int) -> AtomicInt { - AtomicInt {v: Unsafe::new(v), nopod: marker::NoPod} - } - - /// Load the value - #[inline] - pub fn load(&self, order: Ordering) -> int { - unsafe { atomic_load(&*self.v.get(), order) } - } - - /// Store the value - #[inline] - pub fn store(&mut self, val: int, order: Ordering) { - unsafe { atomic_store(&mut *self.v.get(), val, order); } - } - - /// Store a value, returning the old value - #[inline] - pub fn swap(&mut self, val: int, order: Ordering) -> int { - unsafe { atomic_swap(&mut *self.v.get(), val, order) } - } - - /// If the current value is the same as expected, store a new value - /// - /// Compare the current value with `old`; if they are the same then - /// replace the current value with `new`. Return the previous value. - /// If the return value is equal to `old` then the value was updated. - #[inline] - pub fn compare_and_swap(&mut self, old: int, new: int, order: Ordering) -> int { - unsafe { atomic_compare_and_swap(&mut *self.v.get(), old, new, order) } - } - - /// Add to the current value, returning the previous - /// - /// # Examples - /// - /// ``` - /// use std::sync::atomics::{AtomicInt, SeqCst}; - /// - /// let mut foo = AtomicInt::new(0); - /// assert_eq!(0, foo.fetch_add(10, SeqCst)); - /// assert_eq!(10, foo.load(SeqCst)); - /// ``` - #[inline] - pub fn fetch_add(&mut self, val: int, order: Ordering) -> int { - unsafe { atomic_add(&mut *self.v.get(), val, order) } - } - - /// Subtract from the current value, returning the previous - /// - /// # Examples - /// - /// ``` - /// use std::sync::atomics::{AtomicInt, SeqCst}; - /// - /// let mut foo = AtomicInt::new(0); - /// assert_eq!(0, foo.fetch_sub(10, SeqCst)); - /// assert_eq!(-10, foo.load(SeqCst)); - /// ``` - #[inline] - pub fn fetch_sub(&mut self, val: int, order: Ordering) -> int { - unsafe { atomic_sub(&mut *self.v.get(), val, order) } - } -} - -// temporary workaround -// it causes link failure on MIPS target -// libgcc doesn't implement 64-bit atomic operations for MIPS32 -#[cfg(not(target_arch = "mips"))] -impl AtomicU64 { - pub fn new(v: u64) -> AtomicU64 { - AtomicU64 { v: Unsafe::new(v), nopod: marker::NoPod } - } - - #[inline] - pub fn load(&self, order: Ordering) -> u64 { - unsafe { atomic_load(&*self.v.get(), order) } - } - - #[inline] - pub fn store(&mut self, val: u64, order: Ordering) { - unsafe { atomic_store(&mut *self.v.get(), val, order); } - } - - #[inline] - pub fn swap(&mut self, val: u64, order: Ordering) -> u64 { - unsafe { atomic_swap(&mut *self.v.get(), val, order) } - } - - #[inline] - pub fn compare_and_swap(&mut self, old: u64, new: u64, order: Ordering) -> u64 { - unsafe { atomic_compare_and_swap(&mut *self.v.get(), old, new, order) } - } - - #[inline] - pub fn fetch_add(&mut self, val: u64, order: Ordering) -> u64 { - unsafe { atomic_add(&mut *self.v.get(), val, order) } - } - - #[inline] - pub fn fetch_sub(&mut self, val: u64, order: Ordering) -> u64 { - unsafe { atomic_sub(&mut *self.v.get(), val, order) } - } -} - -impl AtomicUint { - /// Create a new `AtomicUint` - pub fn new(v: uint) -> AtomicUint { - AtomicUint { v: Unsafe::new(v), nopod: marker::NoPod } - } - - /// Load the value - #[inline] - pub fn load(&self, order: Ordering) -> uint { - unsafe { atomic_load(&*self.v.get(), order) } - } - - /// Store the value - #[inline] - pub fn store(&mut self, val: uint, order: Ordering) { - unsafe { atomic_store(&mut *self.v.get(), val, order); } - } - - /// Store a value, returning the old value - #[inline] - pub fn swap(&mut self, val: uint, order: Ordering) -> uint { - unsafe { atomic_swap(&mut *self.v.get(), val, order) } - } - - /// If the current value is the same as expected, store a new value - /// - /// Compare the current value with `old`; if they are the same then - /// replace the current value with `new`. Return the previous value. - /// If the return value is equal to `old` then the value was updated. - #[inline] - pub fn compare_and_swap(&mut self, old: uint, new: uint, order: Ordering) -> uint { - unsafe { atomic_compare_and_swap(&mut *self.v.get(), old, new, order) } - } - - /// Add to the current value, returning the previous - /// - /// # Examples - /// - /// ``` - /// use std::sync::atomics::{AtomicUint, SeqCst}; - /// - /// let mut foo = AtomicUint::new(0); - /// assert_eq!(0, foo.fetch_add(10, SeqCst)); - /// assert_eq!(10, foo.load(SeqCst)); - /// ``` - #[inline] - pub fn fetch_add(&mut self, val: uint, order: Ordering) -> uint { - unsafe { atomic_add(&mut *self.v.get(), val, order) } - } - - /// Subtract from the current value, returning the previous - /// - /// # Examples - /// - /// ``` - /// use std::sync::atomics::{AtomicUint, SeqCst}; - /// - /// let mut foo = AtomicUint::new(10); - /// assert_eq!(10, foo.fetch_sub(10, SeqCst)); - /// assert_eq!(0, foo.load(SeqCst)); - /// ``` - #[inline] - pub fn fetch_sub(&mut self, val: uint, order: Ordering) -> uint { - unsafe { atomic_sub(&mut *self.v.get(), val, order) } - } -} - -impl AtomicPtr { - /// Create a new `AtomicPtr` - pub fn new(p: *mut T) -> AtomicPtr { - AtomicPtr { p: Unsafe::new(p as uint), nopod: marker::NoPod } - } - - /// Load the value - #[inline] - pub fn load(&self, order: Ordering) -> *mut T { - unsafe { - atomic_load(&*self.p.get(), order) as *mut T - } - } - - /// Store the value - #[inline] - pub fn store(&mut self, ptr: *mut T, order: Ordering) { - unsafe { atomic_store(&mut *self.p.get(), ptr as uint, order); } - } - - /// Store a value, returning the old value - #[inline] - pub fn swap(&mut self, ptr: *mut T, order: Ordering) -> *mut T { - unsafe { atomic_swap(&mut *self.p.get(), ptr as uint, order) as *mut T } - } - - /// If the current value is the same as expected, store a new value - /// - /// Compare the current value with `old`; if they are the same then - /// replace the current value with `new`. Return the previous value. - /// If the return value is equal to `old` then the value was updated. - #[inline] - pub fn compare_and_swap(&mut self, old: *mut T, new: *mut T, order: Ordering) -> *mut T { - unsafe { - atomic_compare_and_swap(&mut *self.p.get(), old as uint, - new as uint, order) as *mut T - } - } -} - -impl AtomicOption { - /// Create a new `AtomicOption` - pub fn new(p: ~T) -> AtomicOption { - unsafe { AtomicOption { p: Unsafe::new(cast::transmute(p)) } } - } - - /// Create a new `AtomicOption` that doesn't contain a value - pub fn empty() -> AtomicOption { AtomicOption { p: Unsafe::new(0) } } - - /// Store a value, returning the old value - #[inline] - pub fn swap(&mut self, val: ~T, order: Ordering) -> Option<~T> { - unsafe { - let val = cast::transmute(val); - - let p = atomic_swap(&mut *self.p.get(), val, order); - if p as uint == 0 { - None - } else { - Some(cast::transmute(p)) - } - } - } - - /// Remove the value, leaving the `AtomicOption` empty. - #[inline] - pub fn take(&mut self, order: Ordering) -> Option<~T> { - unsafe { self.swap(cast::transmute(0), order) } - } - - /// Replace an empty value with a non-empty value. - /// - /// Succeeds if the option is `None` and returns `None` if so. If - /// the option was already `Some`, returns `Some` of the rejected - /// value. - #[inline] - pub fn fill(&mut self, val: ~T, order: Ordering) -> Option<~T> { - unsafe { - let val = cast::transmute(val); - let expected = cast::transmute(0); - let oldval = atomic_compare_and_swap(&mut *self.p.get(), expected, val, order); - if oldval == expected { - None - } else { - Some(cast::transmute(val)) - } - } - } - - /// Returns `true` if the `AtomicOption` is empty. - /// - /// Be careful: The caller must have some external method of ensuring the - /// result does not get invalidated by another task after this returns. - #[inline] - pub fn is_empty(&mut self, order: Ordering) -> bool { - unsafe { atomic_load(&*self.p.get(), order) as uint == 0 } - } -} - -#[unsafe_destructor] -impl Drop for AtomicOption { - fn drop(&mut self) { - let _ = self.take(SeqCst); - } -} - -#[inline] -pub unsafe fn atomic_store(dst: &mut T, val: T, order:Ordering) { - match order { - Release => intrinsics::atomic_store_rel(dst, val), - Relaxed => intrinsics::atomic_store_relaxed(dst, val), - _ => intrinsics::atomic_store(dst, val) - } -} - -#[inline] -pub unsafe fn atomic_load(dst: &T, order:Ordering) -> T { - match order { - Acquire => intrinsics::atomic_load_acq(dst), - Relaxed => intrinsics::atomic_load_relaxed(dst), - _ => intrinsics::atomic_load(dst) - } -} - -#[inline] -pub unsafe fn atomic_swap(dst: &mut T, val: T, order: Ordering) -> T { - match order { - Acquire => intrinsics::atomic_xchg_acq(dst, val), - Release => intrinsics::atomic_xchg_rel(dst, val), - AcqRel => intrinsics::atomic_xchg_acqrel(dst, val), - Relaxed => intrinsics::atomic_xchg_relaxed(dst, val), - _ => intrinsics::atomic_xchg(dst, val) - } -} - -/// Returns the old value (like __sync_fetch_and_add). -#[inline] -pub unsafe fn atomic_add(dst: &mut T, val: T, order: Ordering) -> T { - match order { - Acquire => intrinsics::atomic_xadd_acq(dst, val), - Release => intrinsics::atomic_xadd_rel(dst, val), - AcqRel => intrinsics::atomic_xadd_acqrel(dst, val), - Relaxed => intrinsics::atomic_xadd_relaxed(dst, val), - _ => intrinsics::atomic_xadd(dst, val) - } -} - -/// Returns the old value (like __sync_fetch_and_sub). -#[inline] -pub unsafe fn atomic_sub(dst: &mut T, val: T, order: Ordering) -> T { - match order { - Acquire => intrinsics::atomic_xsub_acq(dst, val), - Release => intrinsics::atomic_xsub_rel(dst, val), - AcqRel => intrinsics::atomic_xsub_acqrel(dst, val), - Relaxed => intrinsics::atomic_xsub_relaxed(dst, val), - _ => intrinsics::atomic_xsub(dst, val) - } -} - -#[inline] -pub unsafe fn atomic_compare_and_swap(dst:&mut T, old:T, new:T, order: Ordering) -> T { - match order { - Acquire => intrinsics::atomic_cxchg_acq(dst, old, new), - Release => intrinsics::atomic_cxchg_rel(dst, old, new), - AcqRel => intrinsics::atomic_cxchg_acqrel(dst, old, new), - Relaxed => intrinsics::atomic_cxchg_relaxed(dst, old, new), - _ => intrinsics::atomic_cxchg(dst, old, new), - } -} - -#[inline] -pub unsafe fn atomic_and(dst: &mut T, val: T, order: Ordering) -> T { - match order { - Acquire => intrinsics::atomic_and_acq(dst, val), - Release => intrinsics::atomic_and_rel(dst, val), - AcqRel => intrinsics::atomic_and_acqrel(dst, val), - Relaxed => intrinsics::atomic_and_relaxed(dst, val), - _ => intrinsics::atomic_and(dst, val) - } -} - -#[inline] -pub unsafe fn atomic_nand(dst: &mut T, val: T, order: Ordering) -> T { - match order { - Acquire => intrinsics::atomic_nand_acq(dst, val), - Release => intrinsics::atomic_nand_rel(dst, val), - AcqRel => intrinsics::atomic_nand_acqrel(dst, val), - Relaxed => intrinsics::atomic_nand_relaxed(dst, val), - _ => intrinsics::atomic_nand(dst, val) - } -} - - -#[inline] -pub unsafe fn atomic_or(dst: &mut T, val: T, order: Ordering) -> T { - match order { - Acquire => intrinsics::atomic_or_acq(dst, val), - Release => intrinsics::atomic_or_rel(dst, val), - AcqRel => intrinsics::atomic_or_acqrel(dst, val), - Relaxed => intrinsics::atomic_or_relaxed(dst, val), - _ => intrinsics::atomic_or(dst, val) - } -} - - -#[inline] -pub unsafe fn atomic_xor(dst: &mut T, val: T, order: Ordering) -> T { - match order { - Acquire => intrinsics::atomic_xor_acq(dst, val), - Release => intrinsics::atomic_xor_rel(dst, val), - AcqRel => intrinsics::atomic_xor_acqrel(dst, val), - Relaxed => intrinsics::atomic_xor_relaxed(dst, val), - _ => intrinsics::atomic_xor(dst, val) - } -} - - -/// An atomic fence. -/// -/// A fence 'A' which has `Release` ordering semantics, synchronizes with a -/// fence 'B' with (at least) `Acquire` semantics, if and only if there exists -/// atomic operations X and Y, both operating on some atomic object 'M' such -/// that A is sequenced before X, Y is synchronized before B and Y observers -/// the change to M. This provides a happens-before dependence between A and B. -/// -/// Atomic operations with `Release` or `Acquire` semantics can also synchronize -/// with a fence. -/// -/// A fence with has `SeqCst` ordering, in addition to having both `Acquire` and -/// `Release` semantics, participates in the global program order of the other -/// `SeqCst` operations and/or fences. -/// -/// Accepts `Acquire`, `Release`, `AcqRel` and `SeqCst` orderings. -/// -/// # Failure -/// -/// Fails if `order` is `Relaxed` -#[inline] -pub fn fence(order: Ordering) { - unsafe { - match order { - Acquire => intrinsics::atomic_fence_acq(), - Release => intrinsics::atomic_fence_rel(), - AcqRel => intrinsics::atomic_fence_acqrel(), - SeqCst => intrinsics::atomic_fence(), - Relaxed => fail!("there is no such thing as a relaxed fence") - } - } -} - -#[cfg(test)] -mod test { - use option::*; - use super::*; - - #[test] - fn bool_() { - let mut a = AtomicBool::new(false); - assert_eq!(a.compare_and_swap(false, true, SeqCst), false); - assert_eq!(a.compare_and_swap(false, true, SeqCst), true); - - a.store(false, SeqCst); - assert_eq!(a.compare_and_swap(false, true, SeqCst), false); - } - - #[test] - fn option_empty() { - let mut option: AtomicOption<()> = AtomicOption::empty(); - assert!(option.is_empty(SeqCst)); - } - - #[test] - fn option_swap() { - let mut p = AtomicOption::new(~1); - let a = ~2; - - let b = p.swap(a, SeqCst); - - assert_eq!(b, Some(~1)); - assert_eq!(p.take(SeqCst), Some(~2)); - } - - #[test] - fn option_take() { - let mut p = AtomicOption::new(~1); - - assert_eq!(p.take(SeqCst), Some(~1)); - assert_eq!(p.take(SeqCst), None); - - let p2 = ~2; - p.swap(p2, SeqCst); - - assert_eq!(p.take(SeqCst), Some(~2)); - } - - #[test] - fn option_fill() { - let mut p = AtomicOption::new(~1); - assert!(p.fill(~2, SeqCst).is_some()); // should fail; shouldn't leak! - assert_eq!(p.take(SeqCst), Some(~1)); - - assert!(p.fill(~2, SeqCst).is_none()); // shouldn't fail - assert_eq!(p.take(SeqCst), Some(~2)); - } - - #[test] - fn bool_and() { - let mut a = AtomicBool::new(true); - assert_eq!(a.fetch_and(false, SeqCst),true); - assert_eq!(a.load(SeqCst),false); - } - - static mut S_BOOL : AtomicBool = INIT_ATOMIC_BOOL; - static mut S_INT : AtomicInt = INIT_ATOMIC_INT; - static mut S_UINT : AtomicUint = INIT_ATOMIC_UINT; - - #[test] - fn static_init() { - unsafe { - assert!(!S_BOOL.load(SeqCst)); - assert!(S_INT.load(SeqCst) == 0); - assert!(S_UINT.load(SeqCst) == 0); - } - } - - #[test] - fn different_sizes() { - unsafe { - let mut slot = 0u16; - assert_eq!(super::atomic_swap(&mut slot, 1, SeqCst), 0); - - let mut slot = 0u8; - assert_eq!(super::atomic_compare_and_swap(&mut slot, 1, 2, SeqCst), 0); - - let mut slot = 0u32; - assert_eq!(super::atomic_load(&mut slot, SeqCst), 0); - - let mut slot = 0u64; - super::atomic_store(&mut slot, 2, SeqCst); - } - } -} - diff --git a/src/libstd/sync/deque.rs b/src/libstd/sync/deque.rs index 658ee48af1a..80a5b9ce3bb 100644 --- a/src/libstd/sync/deque.rs +++ b/src/libstd/sync/deque.rs @@ -494,7 +494,7 @@ fn stampede(mut w: Worker<~int>, s: Stealer<~int>, } } }) - }).to_owned_vec(); + }).collect::<~[Thread<()>]>(); while remaining.load(SeqCst) > 0 { match w.pop() { @@ -525,7 +525,7 @@ fn many_stampede() { Thread::start(proc() { stampede(w, s, 4, 10000); }) - }).to_owned_vec(); + }).collect::<~[Thread<()>]>(); for thread in threads.move_iter() { thread.join(); @@ -556,7 +556,7 @@ fn stress() { } } }) - }).to_owned_vec(); + }).collect::<~[Thread<()>]>(); let mut rng = rand::task_rng(); let mut expected = 0; diff --git a/src/libstd/sync/mod.rs b/src/libstd/sync/mod.rs index 994d12b34e5..3213c538152 100644 --- a/src/libstd/sync/mod.rs +++ b/src/libstd/sync/mod.rs @@ -16,10 +16,6 @@ //! other types of concurrent primitives. pub mod arc; -#[cfg(stage0)] -#[path = "atomics_stage0.rs"] -pub mod atomics; -#[cfg(not(stage0))] pub mod atomics; pub mod deque; pub mod mpmc_bounded_queue; diff --git a/src/libstd/tuple.rs b/src/libstd/tuple.rs index e9125dde011..c4ce6b5ae66 100644 --- a/src/libstd/tuple.rs +++ b/src/libstd/tuple.rs @@ -75,12 +75,7 @@ fn ne(&self, other: &($($T,)+)) -> bool { } #[cfg(not(test))] - impl<$($T:TotalEq),+> TotalEq for ($($T,)+) { - #[inline] - fn equals(&self, other: &($($T,)+)) -> bool { - $(self.$refN().equals(other.$refN()))&&+ - } - } + impl<$($T:TotalEq),+> TotalEq for ($($T,)+) {} #[cfg(not(test))] impl<$($T:Ord + Eq),+> Ord for ($($T,)+) { @@ -338,12 +333,6 @@ fn test_tuple_cmp() { assert!(((1.0, 2.0) < (2.0, nan))); assert!(!((2.0, 2.0) < (2.0, nan))); - // TotalEq - assert!(small.equals(&small)); - assert!(big.equals(&big)); - assert!(!small.equals(&big)); - assert!(!big.equals(&small)); - // TotalOrd assert!(small.cmp(&small) == Equal); assert!(big.cmp(&big) == Equal); diff --git a/src/libstd/ty.rs b/src/libstd/ty.rs index 344235053f3..ae8be25205d 100644 --- a/src/libstd/ty.rs +++ b/src/libstd/ty.rs @@ -45,7 +45,6 @@ /// /// **NOTE:** Unsafe fields are public to allow static initializers. It is not recommended /// to access its fields directly, `get` should be used instead. -#[cfg(not(stage0))] #[lang="unsafe"] pub struct Unsafe { /// Wrapped value @@ -55,16 +54,6 @@ pub struct Unsafe { marker1: marker::InvariantType } -/// Unsafe type for stage0 -#[cfg(stage0)] -pub struct Unsafe { - /// Wrapped value - value: T, - - /// Invariance marker - marker1: marker::InvariantType -} - impl Unsafe { /// Static constructor diff --git a/src/libstd/unit.rs b/src/libstd/unit.rs index b23dafbca69..38307f415ac 100644 --- a/src/libstd/unit.rs +++ b/src/libstd/unit.rs @@ -37,10 +37,7 @@ fn cmp(&self, _other: &()) -> Ordering { Equal } } #[cfg(not(test))] -impl TotalEq for () { - #[inline] - fn equals(&self, _other: &()) -> bool { true } -} +impl TotalEq for () {} #[cfg(not(test))] impl Default for () { diff --git a/src/libstd/vec.rs b/src/libstd/vec.rs index 34e4256e538..4b2953204d0 100644 --- a/src/libstd/vec.rs +++ b/src/libstd/vec.rs @@ -339,12 +339,7 @@ fn lt(&self, other: &Vec) -> bool { } } -impl TotalEq for Vec { - #[inline] - fn equals(&self, other: &Vec) -> bool { - self.as_slice().equals(&other.as_slice()) - } -} +impl TotalEq for Vec {} impl TotalOrd for Vec { #[inline] @@ -951,6 +946,79 @@ pub fn mut_slice<'a>(&'a mut self, start: uint, end: uint) self.as_mut_slice().mut_slice(start, end) } + /// Returns a mutable slice of self from `start` to the end of the vec. + /// + /// # Failure + /// + /// Fails when `start` points outside the bounds of self. + /// + /// # Example + /// + /// ```rust + /// let mut vec = vec!(1, 2, 3, 4); + /// assert!(vec.mut_slice_from(2) == [3, 4]); + /// ``` + #[inline] + pub fn mut_slice_from<'a>(&'a mut self, start: uint) -> &'a mut [T] { + self.as_mut_slice().mut_slice_from(start) + } + + /// Returns a mutable slice of self from the start of the vec to `end`. + /// + /// # Failure + /// + /// Fails when `end` points outside the bounds of self. + /// + /// # Example + /// + /// ```rust + /// let mut vec = vec!(1, 2, 3, 4); + /// assert!(vec.mut_slice_to(2) == [1, 2]); + /// ``` + #[inline] + pub fn mut_slice_to<'a>(&'a mut self, end: uint) -> &'a mut [T] { + self.as_mut_slice().mut_slice_to(end) + } + + /// Returns a pair of mutable slices that divides the vec at an index. + /// + /// The first will contain all indices from `[0, mid)` (excluding + /// the index `mid` itself) and the second will contain all + /// indices from `[mid, len)` (excluding the index `len` itself). + /// + /// # Failure + /// + /// Fails if `mid > len`. + /// + /// # Example + /// + /// ```rust + /// let mut vec = vec!(1, 2, 3, 4, 5, 6); + /// + /// // scoped to restrict the lifetime of the borrows + /// { + /// let (left, right) = vec.mut_split_at(0); + /// assert!(left == &mut []); + /// assert!(right == &mut [1, 2, 3, 4, 5, 6]); + /// } + /// + /// { + /// let (left, right) = vec.mut_split_at(2); + /// assert!(left == &mut [1, 2]); + /// assert!(right == &mut [3, 4, 5, 6]); + /// } + /// + /// { + /// let (left, right) = vec.mut_split_at(6); + /// assert!(left == &mut [1, 2, 3, 4, 5, 6]); + /// assert!(right == &mut []); + /// } + /// ``` + #[inline] + pub fn mut_split_at<'a>(&'a mut self, mid: uint) -> (&'a mut [T], &'a mut [T]) { + self.as_mut_slice().mut_split_at(mid) + } + /// Reverse the order of elements in a vector, in place. /// /// # Example @@ -1292,7 +1360,8 @@ mod tests { use mem::{drop, size_of}; use ops::Drop; use option::{Some, None}; - use ptr; + use container::Container; + use slice::{Vector, MutableVector, ImmutableVector}; #[test] fn test_small_vec_struct() { @@ -1375,4 +1444,51 @@ fn test_extend() { assert_eq!(v, w); } + + #[test] + fn test_mut_slice_from() { + let mut values = Vec::from_slice([1u8,2,3,4,5]); + { + let slice = values.mut_slice_from(2); + assert!(slice == [3, 4, 5]); + for p in slice.mut_iter() { + *p += 2; + } + } + + assert!(values.as_slice() == [1, 2, 5, 6, 7]); + } + + #[test] + fn test_mut_slice_to() { + let mut values = Vec::from_slice([1u8,2,3,4,5]); + { + let slice = values.mut_slice_to(2); + assert!(slice == [1, 2]); + for p in slice.mut_iter() { + *p += 1; + } + } + + assert!(values.as_slice() == [2, 3, 3, 4, 5]); + } + + #[test] + fn test_mut_split_at() { + let mut values = Vec::from_slice([1u8,2,3,4,5]); + { + let (left, right) = values.mut_split_at(2); + assert!(left.slice(0, left.len()) == [1, 2]); + for p in left.mut_iter() { + *p += 1; + } + + assert!(right.slice(0, right.len()) == [3, 4, 5]); + for p in right.mut_iter() { + *p += 2; + } + } + + assert!(values == Vec::from_slice([2u8, 3, 5, 6, 7])); + } } diff --git a/src/libsync/arc.rs b/src/libsync/arc.rs index 0659e79433a..0bc3b121a88 100644 --- a/src/libsync/arc.rs +++ b/src/libsync/arc.rs @@ -50,13 +50,10 @@ use sync::{Mutex, RWLock}; use std::cast; -use std::kinds::marker; +use std::kinds::{Share, marker}; use std::sync::arc::UnsafeArc; use std::task; -#[cfg(stage0)] -use std::kinds::Share; - /// As sync::condvar, a mechanism for unlock-and-descheduling and /// signaling, for use with the Arc types. pub struct ArcCondvar<'a> { @@ -162,7 +159,6 @@ struct MutexArcInner { lock: Mutex, failed: bool, data: T } /// An Arc with mutable data protected by a blocking mutex. pub struct MutexArc { priv x: UnsafeArc>, - priv marker: marker::NoFreeze, } impl Clone for MutexArc { @@ -171,8 +167,7 @@ impl Clone for MutexArc { fn clone(&self) -> MutexArc { // NB: Cloning the underlying mutex is not necessary. Its reference // count would be exactly the same as the shared state's. - MutexArc { x: self.x.clone(), - marker: marker::NoFreeze, } + MutexArc { x: self.x.clone() } } } @@ -191,8 +186,7 @@ pub fn new_with_condvars(user_data: T, num_condvars: uint) -> MutexArc { lock: Mutex::new_with_condvars(num_condvars), failed: false, data: user_data }; - MutexArc { x: UnsafeArc::new(data), - marker: marker::NoFreeze, } + MutexArc { x: UnsafeArc::new(data) } } /** @@ -297,17 +291,17 @@ struct RWArcInner { lock: RWLock, failed: bool, data: T } */ pub struct RWArc { priv x: UnsafeArc>, - priv marker: marker::NoFreeze, - priv marker1: marker::NoShare, + priv marker: marker::NoShare, } impl Clone for RWArc { /// Duplicate a rwlock-protected Arc. See arc::clone for more details. #[inline] fn clone(&self) -> RWArc { - RWArc { x: self.x.clone(), - marker: marker::NoFreeze, - marker1: marker::NoShare, } + RWArc { + x: self.x.clone(), + marker: marker::NoShare + } } } @@ -327,9 +321,10 @@ pub fn new_with_condvars(user_data: T, num_condvars: uint) -> RWArc { lock: RWLock::new_with_condvars(num_condvars), failed: false, data: user_data }; - RWArc { x: UnsafeArc::new(data), - marker: marker::NoFreeze, - marker1: marker::NoShare, } + RWArc { + x: UnsafeArc::new(data), + marker: marker::NoShare + } } /** diff --git a/src/libsync/comm.rs b/src/libsync/comm.rs index f713c13d945..aecea37cce8 100644 --- a/src/libsync/comm.rs +++ b/src/libsync/comm.rs @@ -19,13 +19,13 @@ use std::comm; /// An extension of `pipes::stream` that allows both sending and receiving. -pub struct DuplexStream { - priv tx: Sender, - priv rx: Receiver, +pub struct DuplexStream { + priv tx: Sender, + priv rx: Receiver, } /// Creates a bidirectional stream. -pub fn duplex() -> (DuplexStream, DuplexStream) { +pub fn duplex() -> (DuplexStream, DuplexStream) { let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); (DuplexStream { tx: tx1, rx: rx2 }, @@ -33,54 +33,54 @@ pub fn duplex() -> (DuplexStream, DuplexStream) { } // Allow these methods to be used without import: -impl DuplexStream { - pub fn send(&self, x: T) { +impl DuplexStream { + pub fn send(&self, x: S) { self.tx.send(x) } - pub fn try_send(&self, x: T) -> bool { + pub fn try_send(&self, x: S) -> bool { self.tx.try_send(x) } - pub fn recv(&self) -> U { + pub fn recv(&self) -> R { self.rx.recv() } - pub fn try_recv(&self) -> comm::TryRecvResult { + pub fn try_recv(&self) -> comm::TryRecvResult { self.rx.try_recv() } - pub fn recv_opt(&self) -> Option { + pub fn recv_opt(&self) -> Option { self.rx.recv_opt() } } /// An extension of `pipes::stream` that provides synchronous message sending. -pub struct SyncSender { priv duplex_stream: DuplexStream } +pub struct SyncSender { priv duplex_stream: DuplexStream } /// An extension of `pipes::stream` that acknowledges each message received. -pub struct SyncReceiver { priv duplex_stream: DuplexStream<(), T> } +pub struct SyncReceiver { priv duplex_stream: DuplexStream<(), R> } -impl SyncSender { - pub fn send(&self, val: T) { +impl SyncSender { + pub fn send(&self, val: S) { assert!(self.try_send(val), "SyncSender.send: receiving port closed"); } /// Sends a message, or report if the receiver has closed the connection /// before receiving. - pub fn try_send(&self, val: T) -> bool { + pub fn try_send(&self, val: S) -> bool { self.duplex_stream.try_send(val) && self.duplex_stream.recv_opt().is_some() } } -impl SyncReceiver { - pub fn recv(&self) -> T { +impl SyncReceiver { + pub fn recv(&self) -> R { self.recv_opt().expect("SyncReceiver.recv: sending channel closed") } - pub fn recv_opt(&self) -> Option { + pub fn recv_opt(&self) -> Option { self.duplex_stream.recv_opt().map(|val| { self.duplex_stream.try_send(()); val }) } - pub fn try_recv(&self) -> comm::TryRecvResult { + pub fn try_recv(&self) -> comm::TryRecvResult { match self.duplex_stream.try_recv() { comm::Data(t) => { self.duplex_stream.try_send(()); comm::Data(t) } state => state, diff --git a/src/libsync/lib.rs b/src/libsync/lib.rs index 5e97b92e738..70874a029ac 100644 --- a/src/libsync/lib.rs +++ b/src/libsync/lib.rs @@ -20,7 +20,6 @@ html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://static.rust-lang.org/doc/master")]; #[feature(phase)]; -#[allow(deprecated_owned_vector)]; // NOTE: remove after stage0 #[cfg(test)] #[phase(syntax, link)] extern crate log; diff --git a/src/libsyntax/abi.rs b/src/libsyntax/abi.rs index b159920d929..b833eea6b56 100644 --- a/src/libsyntax/abi.rs +++ b/src/libsyntax/abi.rs @@ -14,7 +14,7 @@ #[deriving(Eq)] pub enum Os { OsWin32, OsMacos, OsLinux, OsAndroid, OsFreebsd, } -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] pub enum Abi { // NB: This ordering MUST match the AbiDatas array below. // (This is ensured by the test indices_are_correct().) @@ -65,7 +65,7 @@ pub enum AbiArchitecture { Archs(u32) // Multiple architectures (bitset) } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct AbiSet { priv bits: u32 // each bit represents one of the abis below } diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 41038705d4d..24b8a345776 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -113,7 +113,7 @@ fn decode(d: &mut D) -> Ident { /// Function name (not all functions have names) pub type FnIdent = Option; -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct Lifetime { id: NodeId, span: Span, @@ -124,7 +124,7 @@ pub struct Lifetime { // for instance: std::cmp::Eq . It's represented // as a sequence of identifiers, along with a bunch // of supporting information. -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct Path { span: Span, /// A `::foo` path, is relative to the crate root rather than current @@ -136,7 +136,7 @@ pub struct Path { /// A segment of a path: an identifier, an optional lifetime, and a set of /// types. -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct PathSegment { /// The identifier portion of this path segment. identifier: Ident, @@ -169,14 +169,14 @@ pub struct DefId { // The AST represents all type param bounds as types. // typeck::collect::compute_bounds matches these against // the "special" built-in traits (see middle::lang_items) and -// detects Copy, Send, Send, and Freeze. -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +// detects Copy, Send and Share. +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum TyParamBound { TraitTyParamBound(TraitRef), RegionTyParamBound } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct TyParam { ident: Ident, id: NodeId, @@ -184,7 +184,7 @@ pub struct TyParam { default: Option> } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct Generics { lifetimes: Vec, ty_params: OwnedSlice, @@ -202,13 +202,13 @@ pub fn is_type_parameterized(&self) -> bool { } } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum MethodProvenance { FromTrait(DefId), FromImpl(DefId), } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum Def { DefFn(DefId, Purity), DefStaticMethod(/* method */ DefId, MethodProvenance, Purity), @@ -245,7 +245,7 @@ pub enum Def { DefMethod(DefId /* method */, Option /* trait */), } -#[deriving(Clone, Eq, Hash, Encodable, Decodable, Show)] +#[deriving(Clone, Eq, TotalEq, Hash, Encodable, Decodable, Show)] pub enum DefRegion { DefStaticRegion, DefEarlyBoundRegion(/* index */ uint, /* lifetime decl */ NodeId), @@ -257,7 +257,7 @@ pub enum DefRegion { // used to drive conditional compilation pub type CrateConfig = Vec<@MetaItem> ; -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct Crate { module: Mod, attrs: Vec , @@ -267,7 +267,7 @@ pub struct Crate { pub type MetaItem = Spanned; -#[deriving(Clone, Encodable, Decodable, Hash)] +#[deriving(Clone, Encodable, Decodable, TotalEq, Hash)] pub enum MetaItem_ { MetaWord(InternedString), MetaList(InternedString, Vec<@MetaItem> ), @@ -299,7 +299,7 @@ fn eq(&self, other: &MetaItem_) -> bool { } } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct Block { view_items: Vec , stmts: Vec<@Stmt> , @@ -309,26 +309,26 @@ pub struct Block { span: Span, } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct Pat { id: NodeId, node: Pat_, span: Span, } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct FieldPat { ident: Ident, pat: @Pat, } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum BindingMode { BindByRef(Mutability), BindByValue(Mutability), } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum Pat_ { PatWild, PatWildMulti, @@ -353,13 +353,13 @@ pub enum Pat_ { PatVec(Vec<@Pat> , Option<@Pat>, Vec<@Pat> ) } -#[deriving(Clone, Eq, Encodable, Decodable, Hash, Show)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash, Show)] pub enum Mutability { MutMutable, MutImmutable, } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum Sigil { BorrowedSigil, OwnedSigil, @@ -376,14 +376,14 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum ExprVstore { ExprVstoreUniq, // ~[1,2,3,4] ExprVstoreSlice, // &[1,2,3,4] ExprVstoreMutSlice, // &mut [1,2,3,4] } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum BinOp { BiAdd, BiSub, @@ -405,7 +405,7 @@ pub enum BinOp { BiGt, } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum UnOp { UnBox, UnUniq, @@ -416,7 +416,7 @@ pub enum UnOp { pub type Stmt = Spanned; -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum Stmt_ { // could be an item or a local (let) binding: StmtDecl(@Decl, NodeId), @@ -434,7 +434,7 @@ pub enum Stmt_ { // FIXME (pending discussion of #1697, #2178...): local should really be // a refinement on pat. /// Local represents a `let` statement, e.g., `let : = ;` -#[deriving(Eq, Encodable, Decodable, Hash)] +#[deriving(Eq, TotalEq, Encodable, Decodable, Hash)] pub struct Local { ty: P, pat: @Pat, @@ -445,7 +445,7 @@ pub struct Local { pub type Decl = Spanned; -#[deriving(Eq, Encodable, Decodable, Hash)] +#[deriving(Eq, TotalEq, Encodable, Decodable, Hash)] pub enum Decl_ { // a local (let) binding: DeclLocal(@Local), @@ -453,14 +453,14 @@ pub enum Decl_ { DeclItem(@Item), } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct Arm { pats: Vec<@Pat> , guard: Option<@Expr>, body: @Expr, } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct Field { ident: SpannedIdent, expr: @Expr, @@ -469,26 +469,26 @@ pub struct Field { pub type SpannedIdent = Spanned; -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum BlockCheckMode { DefaultBlock, UnsafeBlock(UnsafeSource), } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum UnsafeSource { CompilerGenerated, UserProvided, } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct Expr { id: NodeId, node: Expr_, span: Span, } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum Expr_ { ExprVstore(@Expr, ExprVstore), // First expr is the place; second expr is the value. @@ -557,7 +557,7 @@ pub enum Expr_ { // else knows what to do with them, so you'll probably get a syntax // error. // -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] #[doc="For macro invocations; parsing is delegated to the macro"] pub enum TokenTree { // a single token @@ -631,7 +631,7 @@ pub enum TokenTree { // pub type Matcher = Spanned; -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum Matcher_ { // match one token MatchTok(::parse::token::Token), @@ -648,12 +648,12 @@ pub enum Matcher_ { // is being invoked, and the vector of token-trees contains the source // of the macro invocation. // There's only one flavor, now, so this could presumably be simplified. -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum Mac_ { MacInvocTT(Path, Vec , SyntaxContext), // new macro-invocation } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum StrStyle { CookedStr, RawStr(uint) @@ -661,7 +661,7 @@ pub enum StrStyle { pub type Lit = Spanned; -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum Lit_ { LitStr(InternedString, StrStyle), LitBinary(Rc >), @@ -677,20 +677,20 @@ pub enum Lit_ { // NB: If you change this, you'll probably want to change the corresponding // type structure in middle/ty.rs as well. -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct MutTy { ty: P, mutbl: Mutability, } -#[deriving(Eq, Encodable, Decodable, Hash)] +#[deriving(Eq, TotalEq, Encodable, Decodable, Hash)] pub struct TypeField { ident: Ident, mt: MutTy, span: Span, } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct TypeMethod { ident: Ident, attrs: Vec , @@ -705,13 +705,13 @@ pub struct TypeMethod { // A trait method is either required (meaning it doesn't have an // implementation, just a signature) or provided (meaning it has a default // implementation). -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum TraitMethod { Required(TypeMethod), Provided(@Method), } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum IntTy { TyI, TyI8, @@ -726,7 +726,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum UintTy { TyU, TyU8, @@ -741,7 +741,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum FloatTy { TyF32, TyF64, @@ -754,7 +754,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } // NB Eq method appears below. -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct Ty { id: NodeId, node: Ty_, @@ -762,7 +762,7 @@ pub struct Ty { } // Not represented directly in the AST, referred to by name through a ty_path. -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum PrimTy { TyInt(IntTy), TyUint(UintTy), @@ -772,7 +772,7 @@ pub enum PrimTy { TyChar } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum Onceness { Once, Many @@ -787,7 +787,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -#[deriving(Eq, Encodable, Decodable, Hash)] +#[deriving(Eq, TotalEq, Encodable, Decodable, Hash)] pub struct ClosureTy { sigil: Sigil, region: Option, @@ -802,7 +802,7 @@ pub struct ClosureTy { bounds: Option>, } -#[deriving(Eq, Encodable, Decodable, Hash)] +#[deriving(Eq, TotalEq, Encodable, Decodable, Hash)] pub struct BareFnTy { purity: Purity, abis: AbiSet, @@ -810,7 +810,7 @@ pub struct BareFnTy { decl: P } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum Ty_ { TyNil, TyBot, /* bottom type */ @@ -830,13 +830,13 @@ pub enum Ty_ { TyInfer, } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum AsmDialect { AsmAtt, AsmIntel } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct InlineAsm { asm: InternedString, asm_str_style: StrStyle, @@ -848,7 +848,7 @@ pub struct InlineAsm { dialect: AsmDialect } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct Arg { ty: P, pat: @Pat, @@ -875,7 +875,7 @@ pub fn new_self(span: Span, mutability: Mutability) -> Arg { } } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct FnDecl { inputs: Vec , output: P, @@ -883,7 +883,7 @@ pub struct FnDecl { variadic: bool } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum Purity { UnsafeFn, // declared with "unsafe fn" ImpureFn, // declared with "fn" @@ -900,14 +900,14 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { } } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum RetStyle { NoReturn, // functions with return type _|_ that always // raise an error or exit (i.e. never return to the caller) Return, // everything else } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum ExplicitSelf_ { SelfStatic, // no self SelfValue, // `self` @@ -917,7 +917,7 @@ pub enum ExplicitSelf_ { pub type ExplicitSelf = Spanned; -#[deriving(Eq, Encodable, Decodable, Hash)] +#[deriving(Eq, TotalEq, Encodable, Decodable, Hash)] pub struct Method { ident: Ident, attrs: Vec , @@ -931,37 +931,37 @@ pub struct Method { vis: Visibility, } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct Mod { view_items: Vec , items: Vec<@Item> , } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct ForeignMod { abis: AbiSet, view_items: Vec , items: Vec<@ForeignItem> , } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct VariantArg { ty: P, id: NodeId, } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum VariantKind { TupleVariantKind(Vec ), StructVariantKind(@StructDef), } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct EnumDef { variants: Vec> , } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct Variant_ { name: Ident, attrs: Vec , @@ -973,7 +973,7 @@ pub struct Variant_ { pub type Variant = Spanned; -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct PathListIdent_ { name: Ident, id: NodeId, @@ -983,7 +983,7 @@ pub struct PathListIdent_ { pub type ViewPath = Spanned; -#[deriving(Eq, Encodable, Decodable, Hash)] +#[deriving(Eq, TotalEq, Encodable, Decodable, Hash)] pub enum ViewPath_ { // quux = foo::bar::baz @@ -1000,7 +1000,7 @@ pub enum ViewPath_ { ViewPathList(Path, Vec , NodeId) } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct ViewItem { node: ViewItem_, attrs: Vec , @@ -1008,7 +1008,7 @@ pub struct ViewItem { span: Span, } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum ViewItem_ { // ident: name used to refer to this crate in the code // optional (InternedString,StrStyle): if present, this is a location @@ -1024,14 +1024,14 @@ pub enum ViewItem_ { // Distinguishes between Attributes that decorate items and Attributes that // are contained as statements within items. These two cases need to be // distinguished for pretty-printing. -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum AttrStyle { AttrOuter, AttrInner, } // doc-comments are promoted to attributes that have is_sugared_doc = true -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct Attribute_ { style: AttrStyle, value: @MetaItem, @@ -1045,13 +1045,13 @@ pub struct Attribute_ { If this impl is an ItemImpl, the impl_id is redundant (it could be the same as the impl's node id). */ -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct TraitRef { path: Path, ref_id: NodeId, } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum Visibility { Public, Private, @@ -1067,7 +1067,7 @@ pub fn inherit_from(&self, parent_visibility: Visibility) -> Visibility { } } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct StructField_ { kind: StructFieldKind, id: NodeId, @@ -1077,13 +1077,13 @@ pub struct StructField_ { pub type StructField = Spanned; -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum StructFieldKind { NamedField(Ident, Visibility), UnnamedField // element of a tuple-like struct } -#[deriving(Eq, Encodable, Decodable, Hash)] +#[deriving(Eq, TotalEq, Encodable, Decodable, Hash)] pub struct StructDef { fields: Vec , /* fields, not including ctor */ /* ID of the constructor. This is only used for tuple- or enum-like @@ -1095,7 +1095,7 @@ pub struct StructDef { FIXME (#3300): Should allow items to be anonymous. Right now we just use dummy names for anon items. */ -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct Item { ident: Ident, attrs: Vec , @@ -1105,7 +1105,7 @@ pub struct Item { span: Span, } -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub enum Item_ { ItemStatic(P, Mutability, @Expr), ItemFn(P, Purity, AbiSet, Generics, P), @@ -1123,7 +1123,7 @@ pub enum Item_ { ItemMac(Mac), } -#[deriving(Eq, Encodable, Decodable, Hash)] +#[deriving(Eq, TotalEq, Encodable, Decodable, Hash)] pub struct ForeignItem { ident: Ident, attrs: Vec , @@ -1133,7 +1133,7 @@ pub struct ForeignItem { vis: Visibility, } -#[deriving(Eq, Encodable, Decodable, Hash)] +#[deriving(Eq, TotalEq, Encodable, Decodable, Hash)] pub enum ForeignItem_ { ForeignItemFn(P, Generics), ForeignItemStatic(P, /* is_mutbl */ bool), @@ -1142,7 +1142,7 @@ pub enum ForeignItem_ { // The data we save and restore about an inlined item or method. This is not // part of the AST that we parse from a file, but it becomes part of the tree // that we trans. -#[deriving(Eq, Encodable, Decodable, Hash)] +#[deriving(Eq, TotalEq, Encodable, Decodable, Hash)] pub enum InlinedItem { IIItem(@Item), IIMethod(DefId /* impl id */, bool /* is provided */, @Method), diff --git a/src/libsyntax/ast_map.rs b/src/libsyntax/ast_map.rs index 0b9bf43f0ef..90c23a54426 100644 --- a/src/libsyntax/ast_map.rs +++ b/src/libsyntax/ast_map.rs @@ -40,7 +40,7 @@ pub fn name(&self) -> Name { impl fmt::Show for PathElem { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let slot = token::get_name(self.name()); - write!(f.buf, "{}", slot.get()) + write!(f.buf, "{}", slot) } } @@ -190,8 +190,8 @@ pub struct Map { impl Map { fn find_entry(&self, id: NodeId) -> Option { let map = self.map.borrow(); - if map.get().len() > id as uint { - Some(*map.get().get(id as uint)) + if map.len() > id as uint { + Some(*map.get(id as uint)) } else { None } @@ -395,8 +395,7 @@ pub struct Ctx<'a, F> { impl<'a, F> Ctx<'a, F> { fn insert(&self, id: NodeId, entry: MapEntry) { - let mut map = self.map.map.borrow_mut(); - map.get().grow_set(id as uint, &NotPresent, entry); + (*self.map.map.borrow_mut()).grow_set(id as uint, &NotPresent, entry); } } @@ -540,7 +539,7 @@ pub fn map_crate(krate: Crate, fold_ops: F) -> (Crate, Map) { let map = map.map.borrow(); // This only makes sense for ordered stores; note the // enumerate to count the number of entries. - let (entries_less_1, _) = map.get().iter().filter(|&x| { + let (entries_less_1, _) = (*map).iter().filter(|&x| { match *x { NotPresent => false, _ => true @@ -548,7 +547,7 @@ pub fn map_crate(krate: Crate, fold_ops: F) -> (Crate, Map) { }).enumerate().last().expect("AST map was empty after folding?"); let entries = entries_less_1 + 1; - let vector_length = map.get().len(); + let vector_length = (*map).len(); debug!("The AST map has {} entries with a maximum of {}: occupancy {:.1}%", entries, vector_length, (entries as f64 / vector_length as f64) * 100.); } diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index fca1e25648b..325df5fda60 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -22,7 +22,6 @@ */ use std::cell::RefCell; -use std::cmp; use std::rc::Rc; use serialize::{Encodable, Decodable, Encoder, Decoder}; @@ -33,7 +32,7 @@ pub trait Pos { /// A byte offset. Keep this small (currently 32-bits), as AST contains /// a lot of them. -#[deriving(Clone, Eq, Hash, Ord, Show)] +#[deriving(Clone, Eq, TotalEq, Hash, Ord, Show)] pub struct BytePos(u32); /// A character offset. Because of multibyte utf8 characters, a byte offset @@ -94,19 +93,21 @@ pub struct Span { pub static DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), expn_info: None }; -#[deriving(Clone, Eq, Encodable, Decodable, Hash)] +#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)] pub struct Spanned { node: T, span: Span, } -impl cmp::Eq for Span { +impl Eq for Span { fn eq(&self, other: &Span) -> bool { return (*self).lo == (*other).lo && (*self).hi == (*other).hi; } fn ne(&self, other: &Span) -> bool { !(*self).eq(other) } } +impl TotalEq for Span {} + impl Encodable for Span { /* Note #1972 -- spans are encoded but not decoded */ fn encode(&self, s: &mut S) { @@ -228,15 +229,15 @@ impl FileMap { pub fn next_line(&self, pos: BytePos) { // the new charpos must be > the last one (or it's the first one). let mut lines = self.lines.borrow_mut();; - let line_len = lines.get().len(); - assert!(line_len == 0 || (*lines.get().get(line_len - 1) < pos)) - lines.get().push(pos); + let line_len = lines.len(); + assert!(line_len == 0 || (*lines.get(line_len - 1) < pos)) + lines.push(pos); } // get a line from the list of pre-computed line-beginnings pub fn get_line(&self, line: int) -> ~str { let mut lines = self.lines.borrow_mut(); - let begin: BytePos = *lines.get().get(line as uint) - self.start_pos; + let begin: BytePos = *lines.get(line as uint) - self.start_pos; let begin = begin.to_uint(); let slice = self.src.slice_from(begin); match slice.find('\n') { @@ -251,7 +252,7 @@ pub fn record_multibyte_char(&self, pos: BytePos, bytes: uint) { pos: pos, bytes: bytes, }; - self.multibyte_chars.borrow_mut().get().push(mbc); + self.multibyte_chars.borrow_mut().push(mbc); } pub fn is_real_file(&self) -> bool { @@ -272,9 +273,9 @@ pub fn new() -> CodeMap { pub fn new_filemap(&self, filename: FileName, src: ~str) -> Rc { let mut files = self.files.borrow_mut(); - let start_pos = match files.get().last() { + let start_pos = match files.last() { None => 0, - Some(last) => last.deref().start_pos.to_uint() + last.deref().src.len(), + Some(last) => last.start_pos.to_uint() + last.src.len(), }; // Remove utf-8 BOM if any. @@ -302,14 +303,14 @@ pub fn new_filemap(&self, filename: FileName, src: ~str) -> Rc { multibyte_chars: RefCell::new(Vec::new()), }); - files.get().push(filemap.clone()); + files.push(filemap.clone()); filemap } pub fn mk_substr_filename(&self, sp: Span) -> ~str { let pos = self.lookup_char_pos(sp.lo); - format!("<{}:{}:{}>", pos.file.deref().name, pos.line, pos.col.to_uint() + 1) + format!("<{}:{}:{}>", pos.file.name, pos.line, pos.col.to_uint() + 1) } /// Lookup source information about a BytePos @@ -320,7 +321,7 @@ pub fn lookup_char_pos(&self, pos: BytePos) -> Loc { pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt { let loc = self.lookup_char_pos(pos); LocWithOpt { - filename: loc.file.deref().name.to_str(), + filename: loc.file.name.to_str(), line: loc.line, col: loc.col, file: Some(loc.file) @@ -328,7 +329,7 @@ pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt { } pub fn span_to_str(&self, sp: Span) -> ~str { - if self.files.borrow().get().len() == 0 && sp == DUMMY_SP { + if self.files.borrow().len() == 0 && sp == DUMMY_SP { return ~"no-location"; } @@ -339,7 +340,7 @@ pub fn span_to_str(&self, sp: Span) -> ~str { } pub fn span_to_filename(&self, sp: Span) -> FileName { - self.lookup_char_pos(sp.lo).file.deref().name.to_str() + self.lookup_char_pos(sp.lo).file.name.to_str() } pub fn span_to_lines(&self, sp: Span) -> FileLines { @@ -360,16 +361,16 @@ pub fn span_to_snippet(&self, sp: Span) -> Option<~str> { // it's testing isn't true for all spans in the AST, so to allow the // caller to not have to fail (and it can't catch it since the CodeMap // isn't sendable), return None - if begin.fm.deref().start_pos != end.fm.deref().start_pos { + if begin.fm.start_pos != end.fm.start_pos { None } else { - Some(begin.fm.deref().src.slice( begin.pos.to_uint(), end.pos.to_uint()).to_owned()) + Some(begin.fm.src.slice( begin.pos.to_uint(), end.pos.to_uint()).to_owned()) } } pub fn get_filemap(&self, filename: &str) -> Rc { - for fm in self.files.borrow().get().iter() { - if filename == fm.deref().name { + for fm in self.files.borrow().iter() { + if filename == fm.name { return fm.clone(); } } @@ -378,13 +379,13 @@ pub fn get_filemap(&self, filename: &str) -> Rc { fn lookup_filemap_idx(&self, pos: BytePos) -> uint { let files = self.files.borrow(); - let files = files.get(); + let files = files; let len = files.len(); let mut a = 0u; let mut b = len; while b - a > 1u { let m = (a + b) / 2u; - if files.get(m).deref().start_pos > pos { + if files.get(m).start_pos > pos { b = m; } else { a = m; @@ -394,8 +395,8 @@ fn lookup_filemap_idx(&self, pos: BytePos) -> uint { // filemap, but are not the filemaps we want (because they are length 0, they cannot // contain what we are looking for). So, rewind until we find a useful filemap. loop { - let lines = files.get(a).deref().lines.borrow(); - let lines = lines.get(); + let lines = files.get(a).lines.borrow(); + let lines = lines; if lines.len() > 0 { break; } @@ -415,14 +416,14 @@ fn lookup_line(&self, pos: BytePos) -> FileMapAndLine { let idx = self.lookup_filemap_idx(pos); let files = self.files.borrow(); - let f = files.get().get(idx).clone(); + let f = files.get(idx).clone(); let mut a = 0u; { - let mut lines = f.deref().lines.borrow_mut(); - let mut b = lines.get().len(); + let mut lines = f.lines.borrow_mut(); + let mut b = lines.len(); while b - a > 1u { let m = (a + b) / 2u; - if *lines.get().get(m) > pos { b = m; } else { a = m; } + if *lines.get(m) > pos { b = m; } else { a = m; } } } FileMapAndLine {fm: f, line: a} @@ -432,7 +433,7 @@ fn lookup_pos(&self, pos: BytePos) -> Loc { let FileMapAndLine {fm: f, line: a} = self.lookup_line(pos); let line = a + 1u; // Line numbers start at 1 let chpos = self.bytepos_to_file_charpos(pos); - let linebpos = *f.deref().lines.borrow().get().get(a); + let linebpos = *f.lines.borrow().get(a); let linechpos = self.bytepos_to_file_charpos(linebpos); debug!("codemap: byte pos {:?} is on the line at byte pos {:?}", pos, linebpos); @@ -449,8 +450,8 @@ fn lookup_pos(&self, pos: BytePos) -> Loc { fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos { let idx = self.lookup_filemap_idx(bpos); - let fm = self.files.borrow().get().get(idx).clone(); - let offset = bpos - fm.deref().start_pos; + let fm = self.files.borrow().get(idx).clone(); + let offset = bpos - fm.start_pos; FileMapAndBytePos {fm: fm, pos: offset} } @@ -459,12 +460,12 @@ fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos { debug!("codemap: converting {:?} to char pos", bpos); let idx = self.lookup_filemap_idx(bpos); let files = self.files.borrow(); - let map = files.get().get(idx); + let map = files.get(idx); // The number of extra bytes due to multibyte chars in the FileMap let mut total_extra_bytes = 0; - for mbc in map.deref().multibyte_chars.borrow().get().iter() { + for mbc in map.multibyte_chars.borrow().iter() { debug!("codemap: {:?}-byte char at {:?}", mbc.bytes, mbc.pos); if mbc.pos < bpos { // every character is at least one byte, so we only @@ -478,8 +479,8 @@ fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos { } } - assert!(map.deref().start_pos.to_uint() + total_extra_bytes <= bpos.to_uint()); - CharPos(bpos.to_uint() - map.deref().start_pos.to_uint() - total_extra_bytes) + assert!(map.start_pos.to_uint() + total_extra_bytes <= bpos.to_uint()); + CharPos(bpos.to_uint() - map.start_pos.to_uint() - total_extra_bytes) } } diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index c88c5a3c4e6..e19c4c3026a 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -84,11 +84,11 @@ pub struct Handler { impl Handler { pub fn fatal(&self, msg: &str) -> ! { - self.emit.borrow_mut().get().emit(None, msg, Fatal); + self.emit.borrow_mut().emit(None, msg, Fatal); fail!(FatalError); } pub fn err(&self, msg: &str) { - self.emit.borrow_mut().get().emit(None, msg, Error); + self.emit.borrow_mut().emit(None, msg, Error); self.bump_err_count(); } pub fn bump_err_count(&self) { @@ -113,13 +113,13 @@ pub fn abort_if_errors(&self) { self.fatal(s); } pub fn warn(&self, msg: &str) { - self.emit.borrow_mut().get().emit(None, msg, Warning); + self.emit.borrow_mut().emit(None, msg, Warning); } pub fn note(&self, msg: &str) { - self.emit.borrow_mut().get().emit(None, msg, Note); + self.emit.borrow_mut().emit(None, msg, Note); } pub fn bug(&self, msg: &str) -> ! { - self.emit.borrow_mut().get().emit(None, msg, Bug); + self.emit.borrow_mut().emit(None, msg, Bug); fail!(ExplicitBug); } pub fn unimpl(&self, msg: &str) -> ! { @@ -129,11 +129,11 @@ pub fn emit(&self, cmsp: Option<(&codemap::CodeMap, Span)>, msg: &str, lvl: Level) { - self.emit.borrow_mut().get().emit(cmsp, msg, lvl); + self.emit.borrow_mut().emit(cmsp, msg, lvl); } pub fn custom_emit(&self, cm: &codemap::CodeMap, sp: Span, msg: &str, lvl: Level) { - self.emit.borrow_mut().get().custom_emit(cm, sp, msg, lvl); + self.emit.borrow_mut().custom_emit(cm, sp, msg, lvl); } } @@ -301,7 +301,7 @@ fn highlight_lines(err: &mut EmitterWriter, sp: Span, lvl: Level, lines: codemap::FileLines) -> io::IoResult<()> { - let fm = lines.file.deref(); + let fm = &*lines.file; let mut elided = false; let mut display_lines = lines.lines.as_slice(); @@ -374,7 +374,7 @@ fn custom_highlight_lines(w: &mut EmitterWriter, sp: Span, lvl: Level, lines: codemap::FileLines) -> io::IoResult<()> { - let fm = lines.file.deref(); + let fm = &*lines.file; let lines = lines.lines.as_slice(); if lines.len() > MAX_LINES { diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index ccf98f031a1..2f502c1b55f 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -119,13 +119,31 @@ impl MacResult { pub fn raw_dummy_expr(sp: codemap::Span) -> @ast::Expr { @ast::Expr { id: ast::DUMMY_NODE_ID, - node: ast::ExprTup(Vec::new()), - span: sp + node: ast::ExprLit(@codemap::respan(sp, ast::LitNil)), + span: sp, } } pub fn dummy_expr(sp: codemap::Span) -> MacResult { MRExpr(MacResult::raw_dummy_expr(sp)) } + pub fn dummy_any(sp: codemap::Span) -> MacResult { + MRAny(~DummyMacResult { sp: sp }) + } +} +struct DummyMacResult { + sp: codemap::Span +} +impl AnyMacro for DummyMacResult { + fn make_expr(&self) -> @ast::Expr { + MacResult::raw_dummy_expr(self.sp) + } + fn make_items(&self) -> SmallVector<@ast::Item> { + SmallVector::zero() + } + fn make_stmt(&self) -> @ast::Stmt { + @codemap::respan(self.sp, + ast::StmtExpr(MacResult::raw_dummy_expr(self.sp), ast::DUMMY_NODE_ID)) + } } /// An enum representing the different kinds of syntax extensions. diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 1106dc61db7..bdb16f176c0 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -628,7 +628,7 @@ fn expr_fail(&self, span: Span, msg: InternedString) -> @ast::Expr { vec!( self.expr_str(span, msg), self.expr_str(span, - token::intern_and_get_ident(loc.file.deref().name)), + token::intern_and_get_ident(loc.file.name)), self.expr_uint(span, loc.line))) } diff --git a/src/libsyntax/ext/deriving/cmp/totaleq.rs b/src/libsyntax/ext/deriving/cmp/totaleq.rs index ffabed95db5..33512b3df5e 100644 --- a/src/libsyntax/ext/deriving/cmp/totaleq.rs +++ b/src/libsyntax/ext/deriving/cmp/totaleq.rs @@ -19,9 +19,18 @@ pub fn expand_deriving_totaleq(cx: &mut ExtCtxt, mitem: @MetaItem, item: @Item, push: |@Item|) { - fn cs_equals(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> @Expr { - cs_and(|cx, span, _, _| cx.expr_bool(span, false), - cx, span, substr) + fn cs_total_eq_assert(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> @Expr { + cs_same_method(|cx, span, exprs| { + // create `a.(); b.(); c.(); ...` + // (where method is `assert_receiver_is_total_eq`) + let stmts = exprs.move_iter().map(|e| cx.stmt_expr(e)).collect(); + let block = cx.block(span, stmts, None); + cx.expr_block(block) + }, + |cx, sp, _, _| cx.span_bug(sp, "non matching enums in deriving(TotalEq)?"), + cx, + span, + substr) } let trait_def = TraitDef { @@ -32,14 +41,14 @@ fn cs_equals(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> @Expr { generics: LifetimeBounds::empty(), methods: vec!( MethodDef { - name: "equals", + name: "assert_receiver_is_total_eq", generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), - args: vec!(borrowed_self()), - ret_ty: Literal(Path::new(vec!("bool"))), + args: vec!(), + ret_ty: nil_ty(), inline: true, const_nonmatching: true, - combine_substructure: cs_equals + combine_substructure: cs_total_eq_assert } ) }; diff --git a/src/libsyntax/ext/log_syntax.rs b/src/libsyntax/ext/log_syntax.rs index b94928238e9..1ce08b8303e 100644 --- a/src/libsyntax/ext/log_syntax.rs +++ b/src/libsyntax/ext/log_syntax.rs @@ -10,11 +10,10 @@ use ast; use codemap; -use ext::base::*; use ext::base; use print; -pub fn expand_syntax_ext(cx: &mut ExtCtxt, +pub fn expand_syntax_ext(cx: &mut base::ExtCtxt, sp: codemap::Span, tt: &[ast::TokenTree]) -> base::MacResult { @@ -23,13 +22,6 @@ pub fn expand_syntax_ext(cx: &mut ExtCtxt, println!("{}", print::pprust::tt_to_str(&ast::TTDelim( @tt.iter().map(|x| (*x).clone()).collect()))); - //trivial expression - MRExpr(@ast::Expr { - id: ast::DUMMY_NODE_ID, - node: ast::ExprLit(@codemap::Spanned { - node: ast::LitNil, - span: sp - }), - span: sp, - }) + // any so that `log_syntax` can be invoked as an expression and item. + base::MacResult::dummy_any(sp) } diff --git a/src/libsyntax/ext/mtwt.rs b/src/libsyntax/ext/mtwt.rs index 597e3584385..4ae9d436972 100644 --- a/src/libsyntax/ext/mtwt.rs +++ b/src/libsyntax/ext/mtwt.rs @@ -63,11 +63,10 @@ pub fn new_mark(m: Mrk, tail: SyntaxContext) -> SyntaxContext { // Extend a syntax context with a given mark and table fn new_mark_internal(m: Mrk, tail: SyntaxContext, table: &SCTable) -> SyntaxContext { let key = (tail, m); - let mut mark_memo = table.mark_memo.borrow_mut(); let new_ctxt = |_: &(SyntaxContext, Mrk)| - idx_push(table.table.borrow_mut().get(), Mark(m, tail)); + idx_push(&mut *table.table.borrow_mut(), Mark(m, tail)); - *mark_memo.get().find_or_insert_with(key, new_ctxt) + *table.mark_memo.borrow_mut().find_or_insert_with(key, new_ctxt) } /// Extend a syntax context with a given rename @@ -82,11 +81,10 @@ fn new_rename_internal(id: Ident, tail: SyntaxContext, table: &SCTable) -> SyntaxContext { let key = (tail,id,to); - let mut rename_memo = table.rename_memo.borrow_mut(); let new_ctxt = |_: &(SyntaxContext, Ident, Mrk)| - idx_push(table.table.borrow_mut().get(), Rename(id, to, tail)); + idx_push(&mut *table.table.borrow_mut(), Rename(id, to, tail)); - *rename_memo.get().find_or_insert_with(key, new_ctxt) + *table.rename_memo.borrow_mut().find_or_insert_with(key, new_ctxt) } /// Fetch the SCTable from TLS, create one if it doesn't yet exist. @@ -102,7 +100,7 @@ pub fn with_sctable(op: |&SCTable| -> T) -> T { } Some(ts) => ts.clone() }; - op(table.deref()) + op(&*table) }) } @@ -119,8 +117,7 @@ fn new_sctable_internal() -> SCTable { /// Print out an SCTable for debugging pub fn display_sctable(table: &SCTable) { error!("SC table:"); - let table = table.table.borrow(); - for (idx,val) in table.get().iter().enumerate() { + for (idx,val) in table.table.borrow().iter().enumerate() { error!("{:4u} : {:?}",idx,val); } } @@ -128,9 +125,9 @@ pub fn display_sctable(table: &SCTable) { /// Clear the tables from TLD to reclaim memory. pub fn clear_tables() { with_sctable(|table| { - *table.table.borrow_mut().get() = Vec::new(); - *table.mark_memo.borrow_mut().get() = HashMap::new(); - *table.rename_memo.borrow_mut().get() = HashMap::new(); + *table.table.borrow_mut() = Vec::new(); + *table.mark_memo.borrow_mut() = HashMap::new(); + *table.rename_memo.borrow_mut() = HashMap::new(); }); with_resolve_table_mut(|table| *table = HashMap::new()); } @@ -166,7 +163,7 @@ fn with_resolve_table_mut(op: |&mut ResolveTable| -> T) -> T { } Some(ts) => ts.clone() }; - op(table.deref().borrow_mut().get()) + op(&mut *table.borrow_mut()) }) } @@ -183,7 +180,7 @@ fn resolve_internal(id: Ident, } let resolved = { - let result = *table.table.borrow().get().get(id.ctxt as uint); + let result = *table.table.borrow().get(id.ctxt as uint); match result { EmptyCtxt => id.name, // ignore marks here: @@ -227,10 +224,7 @@ fn marksof_internal(ctxt: SyntaxContext, let mut result = Vec::new(); let mut loopvar = ctxt; loop { - let table_entry = { - let table = table.table.borrow(); - *table.get().get(loopvar as uint) - }; + let table_entry = *table.table.borrow().get(loopvar as uint); match table_entry { EmptyCtxt => { return result; @@ -257,7 +251,7 @@ fn marksof_internal(ctxt: SyntaxContext, /// FAILS when outside is not a mark. pub fn outer_mark(ctxt: SyntaxContext) -> Mrk { with_sctable(|sctable| { - match *sctable.table.borrow().get().get(ctxt as uint) { + match *sctable.table.borrow().get(ctxt as uint) { Mark(mrk, _) => mrk, _ => fail!("can't retrieve outer mark when outside is not a mark") } @@ -327,7 +321,7 @@ fn refold_test_sc(mut sc: SyntaxContext, table : &SCTable) -> Vec { let mut result = Vec::new(); loop { let table = table.table.borrow(); - match *table.get().get(sc as uint) { + match *table.get(sc as uint) { EmptyCtxt => {return result;}, Mark(mrk,tail) => { result.push(M(mrk)); @@ -351,9 +345,9 @@ fn refold_test_sc(mut sc: SyntaxContext, table : &SCTable) -> Vec { assert_eq!(unfold_test_sc(test_sc.clone(),EMPTY_CTXT,&mut t),4); { let table = t.table.borrow(); - assert!(*table.get().get(2) == Mark(9,0)); - assert!(*table.get().get(3) == Rename(id(101,0),14,2)); - assert!(*table.get().get(4) == Mark(3,3)); + assert!(*table.get(2) == Mark(9,0)); + assert!(*table.get(3) == Rename(id(101,0),14,2)); + assert!(*table.get(4) == Mark(3,3)); } assert_eq!(refold_test_sc(4,&t),test_sc); } @@ -372,8 +366,8 @@ fn unfold_marks(mrks: Vec , tail: SyntaxContext, table: &SCTable) assert_eq!(unfold_marks(vec!(3,7),EMPTY_CTXT,&mut t),3); { let table = t.table.borrow(); - assert!(*table.get().get(2) == Mark(7,0)); - assert!(*table.get().get(3) == Mark(3,2)); + assert!(*table.get(2) == Mark(7,0)); + assert!(*table.get(3) == Mark(3,2)); } } diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index 137cd89bf30..8931fb0f443 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -57,7 +57,7 @@ pub fn expand_file(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) let topmost = topmost_expn_info(cx.backtrace().unwrap()); let loc = cx.codemap().lookup_char_pos(topmost.call_site.lo); - let filename = token::intern_and_get_ident(loc.file.deref().name); + let filename = token::intern_and_get_ident(loc.file.name); base::MRExpr(cx.expr_str(topmost.call_site, filename)) } diff --git a/src/libsyntax/ext/trace_macros.rs b/src/libsyntax/ext/trace_macros.rs index fa49f06e516..173cf4c9ad9 100644 --- a/src/libsyntax/ext/trace_macros.rs +++ b/src/libsyntax/ext/trace_macros.rs @@ -12,33 +12,21 @@ use codemap::Span; use ext::base::ExtCtxt; use ext::base; -use parse::lexer::{new_tt_reader, Reader}; -use parse::parser::Parser; -use parse::token::keywords; +use parse::token::{keywords, is_keyword}; pub fn expand_trace_macros(cx: &mut ExtCtxt, sp: Span, tt: &[ast::TokenTree]) -> base::MacResult { - let sess = cx.parse_sess(); - let cfg = cx.cfg(); - let tt_rdr = new_tt_reader(&cx.parse_sess().span_diagnostic, - None, - tt.iter().map(|x| (*x).clone()).collect()); - let mut rust_parser = Parser(sess, cfg.clone(), tt_rdr.dup()); - - if rust_parser.is_keyword(keywords::True) { - cx.set_trace_macros(true); - } else if rust_parser.is_keyword(keywords::False) { - cx.set_trace_macros(false); - } else { - cx.span_err(sp, "trace_macros! only accepts `true` or `false`"); - return base::MacResult::dummy_expr(sp); + match tt { + [ast::TTTok(_, ref tok)] if is_keyword(keywords::True, tok) => { + cx.set_trace_macros(true); + } + [ast::TTTok(_, ref tok)] if is_keyword(keywords::False, tok) => { + cx.set_trace_macros(false); + } + _ => cx.span_err(sp, "trace_macros! accepts only `true` or `false`"), } - rust_parser.bump(); - - let mut rust_parser = Parser(sess, cfg, tt_rdr.dup()); - let result = rust_parser.parse_expr(); - base::MRExpr(result) + base::MacResult::dummy_any(sp) } diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index b2f4904ec8f..b3e3023388b 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -42,26 +42,23 @@ impl<'a> ParserAnyMacro<'a> { /// allowed to be there. fn ensure_complete_parse(&self, allow_semi: bool) { let mut parser = self.parser.borrow_mut(); - if allow_semi && parser.get().token == SEMI { - parser.get().bump() + if allow_semi && parser.token == SEMI { + parser.bump() } - if parser.get().token != EOF { - let token_str = parser.get().this_token_to_str(); + if parser.token != EOF { + let token_str = parser.this_token_to_str(); let msg = format!("macro expansion ignores token `{}` and any \ following", token_str); - let span = parser.get().span; - parser.get().span_err(span, msg); + let span = parser.span; + parser.span_err(span, msg); } } } impl<'a> AnyMacro for ParserAnyMacro<'a> { fn make_expr(&self) -> @ast::Expr { - let ret = { - let mut parser = self.parser.borrow_mut(); - parser.get().parse_expr() - }; + let ret = self.parser.borrow_mut().parse_expr(); self.ensure_complete_parse(true); ret } @@ -69,8 +66,8 @@ fn make_items(&self) -> SmallVector<@ast::Item> { let mut ret = SmallVector::zero(); loop { let mut parser = self.parser.borrow_mut(); - let attrs = parser.get().parse_outer_attributes(); - match parser.get().parse_item(attrs) { + let attrs = parser.parse_outer_attributes(); + match parser.parse_item(attrs) { Some(item) => ret.push(item), None => break } @@ -79,11 +76,8 @@ fn make_items(&self) -> SmallVector<@ast::Item> { ret } fn make_stmt(&self) -> @ast::Stmt { - let ret = { - let mut parser = self.parser.borrow_mut(); - let attrs = parser.get().parse_outer_attributes(); - parser.get().parse_stmt(attrs) - }; + let attrs = self.parser.borrow_mut().parse_outer_attributes(); + let ret = self.parser.borrow_mut().parse_stmt(attrs); self.ensure_complete_parse(true); ret } @@ -242,7 +236,7 @@ fn ms(m: Matcher_) -> Matcher { }; return MRDef(MacroDef { - name: token::get_ident(name).get().to_str(), + name: token::get_ident(name).to_str(), ext: NormalTT(exp, Some(sp)) }); } diff --git a/src/libsyntax/ext/tt/transcribe.rs b/src/libsyntax/ext/tt/transcribe.rs index e9db0bd0bd2..933fbe3d566 100644 --- a/src/libsyntax/ext/tt/transcribe.rs +++ b/src/libsyntax/ext/tt/transcribe.rs @@ -109,15 +109,11 @@ fn red(ad: @NamedMatch, idx: &uint) -> @NamedMatch { MatchedSeq(ref ads, _) => *ads.get(*idx) } } - let repeat_idx = r.repeat_idx.borrow(); - repeat_idx.get().iter().fold(start, red) + r.repeat_idx.borrow().iter().fold(start, red) } fn lookup_cur_matched(r: &TtReader, name: Ident) -> @NamedMatch { - let matched_opt = { - let interpolations = r.interpolations.borrow(); - interpolations.get().find_copy(&name) - }; + let matched_opt = r.interpolations.borrow().find_copy(&name); match matched_opt { Some(s) => lookup_cur_matched_by_matched(r, s), None => { @@ -178,19 +174,14 @@ pub fn tt_next_token(r: &TtReader) -> TokenAndSpan { sp: r.cur_span.get(), }; loop { - { - let mut stack = r.stack.borrow_mut(); - if stack.get().idx.get() < stack.get().forest.len() { - break; - } + if r.stack.borrow().idx.get() < r.stack.borrow().forest.len() { + break; } /* done with this set; pop or repeat? */ if !r.stack.get().dotdotdoted || { - let repeat_idx = r.repeat_idx.borrow(); - let repeat_len = r.repeat_len.borrow(); - *repeat_idx.get().last().unwrap() == - *repeat_len.get().last().unwrap() - 1 + *r.repeat_idx.borrow().last().unwrap() == + *r.repeat_len.borrow().last().unwrap() - 1 } { match r.stack.get().up { @@ -200,12 +191,8 @@ pub fn tt_next_token(r: &TtReader) -> TokenAndSpan { } Some(tt_f) => { if r.stack.get().dotdotdoted { - { - let mut repeat_idx = r.repeat_idx.borrow_mut(); - let mut repeat_len = r.repeat_len.borrow_mut(); - repeat_idx.get().pop().unwrap(); - repeat_len.get().pop().unwrap(); - } + r.repeat_idx.borrow_mut().pop().unwrap(); + r.repeat_len.borrow_mut().pop().unwrap(); } r.stack.set(tt_f); @@ -217,8 +204,8 @@ pub fn tt_next_token(r: &TtReader) -> TokenAndSpan { r.stack.get().idx.set(0u); { let mut repeat_idx = r.repeat_idx.borrow_mut(); - let last_repeat_idx = repeat_idx.get().len() - 1u; - *repeat_idx.get().get_mut(last_repeat_idx) += 1u; + let last_repeat_idx = repeat_idx.len() - 1u; + *repeat_idx.get_mut(last_repeat_idx) += 1u; } match r.stack.get().sep.clone() { Some(tk) => { @@ -276,19 +263,15 @@ pub fn tt_next_token(r: &TtReader) -> TokenAndSpan { r.stack.get().idx.set(r.stack.get().idx.get() + 1u); return tt_next_token(r); } else { - { - let mut repeat_idx = r.repeat_idx.borrow_mut(); - let mut repeat_len = r.repeat_len.borrow_mut(); - repeat_len.get().push(len); - repeat_idx.get().push(0u); - r.stack.set(@TtFrame { - forest: tts, - idx: Cell::new(0u), - dotdotdoted: true, - sep: sep, - up: Some(r.stack.get()) - }); - } + r.repeat_len.borrow_mut().push(len); + r.repeat_idx.borrow_mut().push(0u); + r.stack.set(@TtFrame { + forest: tts, + idx: Cell::new(0u), + dotdotdoted: true, + sep: sep, + up: Some(r.stack.get()) + }); } } } diff --git a/src/libsyntax/lib.rs b/src/libsyntax/lib.rs index 70fb96e4c5f..4de17dc598b 100644 --- a/src/libsyntax/lib.rs +++ b/src/libsyntax/lib.rs @@ -28,7 +28,6 @@ #[feature(macro_rules, globs, managed_boxes, default_type_params, phase, quote)]; -#[allow(deprecated_owned_vector)]; // NOTE: remove after stage0 #[allow(deprecated)]; extern crate serialize; diff --git a/src/libsyntax/owned_slice.rs b/src/libsyntax/owned_slice.rs index df38945f198..d5b90821897 100644 --- a/src/libsyntax/owned_slice.rs +++ b/src/libsyntax/owned_slice.rs @@ -119,6 +119,8 @@ fn eq(&self, other: &OwnedSlice) -> bool { } } +impl TotalEq for OwnedSlice {} + impl Container for OwnedSlice { fn len(&self) -> uint { self.len } } diff --git a/src/libsyntax/parse/lexer.rs b/src/libsyntax/parse/lexer.rs index ca2fbd24587..ccee21f6281 100644 --- a/src/libsyntax/parse/lexer.rs +++ b/src/libsyntax/parse/lexer.rs @@ -78,8 +78,8 @@ pub fn new_low_level_string_reader<'a>(span_diagnostic: &'a SpanHandler, let initial_char = '\n'; let r = StringReader { span_diagnostic: span_diagnostic, - pos: Cell::new(filemap.deref().start_pos), - last_pos: Cell::new(filemap.deref().start_pos), + pos: Cell::new(filemap.start_pos), + last_pos: Cell::new(filemap.start_pos), col: Cell::new(CharPos(0)), curr: Cell::new(Some(initial_char)), filemap: filemap, @@ -111,12 +111,9 @@ impl<'a> Reader for StringReader<'a> { fn is_eof(&self) -> bool { is_eof(self) } // return the next token. EFFECT: advances the string_reader. fn next_token(&self) -> TokenAndSpan { - let ret_val = { - let mut peek_tok = self.peek_tok.borrow_mut(); - TokenAndSpan { - tok: replace(peek_tok.get(), token::UNDERSCORE), - sp: self.peek_span.get(), - } + let ret_val = TokenAndSpan { + tok: replace(&mut *self.peek_tok.borrow_mut(), token::UNDERSCORE), + sp: self.peek_span.get(), }; string_advance_token(self); ret_val @@ -137,8 +134,7 @@ fn dup(&self) -> ~Reader: { ~dup_string_reader(self) as ~Reader: } impl<'a> Reader for TtReader<'a> { fn is_eof(&self) -> bool { - let cur_tok = self.cur_tok.borrow(); - *cur_tok.get() == token::EOF + *self.cur_tok.borrow() == token::EOF } fn next_token(&self) -> TokenAndSpan { let r = tt_next_token(self); @@ -191,7 +187,7 @@ fn fatal_span_verbose(rdr: &StringReader, -> ! { let mut m = m; m.push_str(": "); - let s = rdr.filemap.deref().src.slice( + let s = rdr.filemap.src.slice( byte_offset(rdr, from_pos).to_uint(), byte_offset(rdr, to_pos).to_uint()); m.push_str(s); @@ -220,7 +216,7 @@ fn string_advance_token(r: &StringReader) { } fn byte_offset(rdr: &StringReader, pos: BytePos) -> BytePos { - (pos - rdr.filemap.deref().start_pos) + (pos - rdr.filemap.start_pos) } /// Calls `f` with a string slice of the source text spanning from `start` @@ -242,7 +238,7 @@ fn with_str_from_to( end: BytePos, f: |s: &str| -> T) -> T { - f(rdr.filemap.deref().src.slice( + f(rdr.filemap.src.slice( byte_offset(rdr, start).to_uint(), byte_offset(rdr, end).to_uint())) } @@ -252,21 +248,21 @@ fn with_str_from_to( pub fn bump(rdr: &StringReader) { rdr.last_pos.set(rdr.pos.get()); let current_byte_offset = byte_offset(rdr, rdr.pos.get()).to_uint(); - if current_byte_offset < rdr.filemap.deref().src.len() { + if current_byte_offset < rdr.filemap.src.len() { assert!(rdr.curr.get().is_some()); let last_char = rdr.curr.get().unwrap(); - let next = rdr.filemap.deref().src.char_range_at(current_byte_offset); + let next = rdr.filemap.src.char_range_at(current_byte_offset); let byte_offset_diff = next.next - current_byte_offset; rdr.pos.set(rdr.pos.get() + Pos::from_uint(byte_offset_diff)); rdr.curr.set(Some(next.ch)); rdr.col.set(rdr.col.get() + CharPos(1u)); if last_char == '\n' { - rdr.filemap.deref().next_line(rdr.last_pos.get()); + rdr.filemap.next_line(rdr.last_pos.get()); rdr.col.set(CharPos(0u)); } if byte_offset_diff > 1 { - rdr.filemap.deref().record_multibyte_char(rdr.last_pos.get(), byte_offset_diff); + rdr.filemap.record_multibyte_char(rdr.last_pos.get(), byte_offset_diff); } } else { rdr.curr.set(None); @@ -279,8 +275,8 @@ pub fn is_eof(rdr: &StringReader) -> bool { pub fn nextch(rdr: &StringReader) -> Option { let offset = byte_offset(rdr, rdr.pos.get()).to_uint(); - if offset < rdr.filemap.deref().src.len() { - Some(rdr.filemap.deref().src.char_at(offset)) + if offset < rdr.filemap.src.len() { + Some(rdr.filemap.src.char_at(offset)) } else { None } @@ -397,7 +393,7 @@ fn consume_any_line_comment(rdr: &StringReader) // I guess this is the only way to figure out if // we're at the beginning of the file... let cmap = CodeMap::new(); - cmap.files.borrow_mut().get().push(rdr.filemap.clone()); + cmap.files.borrow_mut().push(rdr.filemap.clone()); let loc = cmap.lookup_char_pos_adj(rdr.last_pos.get()); if loc.line == 1u && loc.col == CharPos(0u) { while !rdr.curr_is('\n') && !is_eof(rdr) { bump(rdr); } diff --git a/src/libsyntax/parse/obsolete.rs b/src/libsyntax/parse/obsolete.rs index 1d7bf2ef6da..63b3fb09ee3 100644 --- a/src/libsyntax/parse/obsolete.rs +++ b/src/libsyntax/parse/obsolete.rs @@ -23,7 +23,7 @@ use parse::token; /// The specific types of unsupported syntax -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] pub enum ObsoleteSyntax { ObsoleteSwap, ObsoleteUnsafeBlock, diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index c8492cc4113..adf3ac0e17d 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -77,7 +77,6 @@ use parse::{new_sub_parser_from_file, ParseSess}; use owned_slice::OwnedSlice; -use std::cell::Cell; use collections::HashSet; use std::kinds::marker; use std::mem::replace; @@ -2202,12 +2201,12 @@ pub fn parse_matchers(&mut self) -> Vec { // unification of Matcher's and TokenTree's would vastly improve // the interpolation of Matcher's maybe_whole!(self, NtMatchers); - let name_idx = @Cell::new(0u); + let mut name_idx = 0u; match self.token { token::LBRACE | token::LPAREN | token::LBRACKET => { let other_delimiter = token::flip_delimiter(&self.token); self.bump(); - self.parse_matcher_subseq_upto(name_idx, &other_delimiter) + self.parse_matcher_subseq_upto(&mut name_idx, &other_delimiter) } _ => self.fatal("expected open delimiter") } @@ -2217,7 +2216,7 @@ pub fn parse_matchers(&mut self) -> Vec { // Otherwise, `$( ( )` would be a valid Matcher, and `$( () )` would be // invalid. It's similar to common::parse_seq. pub fn parse_matcher_subseq_upto(&mut self, - name_idx: @Cell, + name_idx: &mut uint, ket: &token::Token) -> Vec { let mut ret_val = Vec::new(); @@ -2234,13 +2233,13 @@ pub fn parse_matcher_subseq_upto(&mut self, return ret_val; } - pub fn parse_matcher(&mut self, name_idx: @Cell) -> Matcher { + pub fn parse_matcher(&mut self, name_idx: &mut uint) -> Matcher { let lo = self.span.lo; let m = if self.token == token::DOLLAR { self.bump(); if self.token == token::LPAREN { - let name_idx_lo = name_idx.get(); + let name_idx_lo = *name_idx; self.bump(); let ms = self.parse_matcher_subseq_upto(name_idx, &token::RPAREN); @@ -2248,13 +2247,13 @@ pub fn parse_matcher(&mut self, name_idx: @Cell) -> Matcher { self.fatal("repetition body must be nonempty"); } let (sep, zerok) = self.parse_sep_and_zerok(); - MatchSeq(ms, sep, zerok, name_idx_lo, name_idx.get()) + MatchSeq(ms, sep, zerok, name_idx_lo, *name_idx) } else { let bound_to = self.parse_ident(); self.expect(&token::COLON); let nt_name = self.parse_ident(); - let m = MatchNonterminal(bound_to, nt_name, name_idx.get()); - name_idx.set(name_idx.get() + 1u); + let m = MatchNonterminal(bound_to, nt_name, *name_idx); + *name_idx += 1; m } } else { @@ -4203,28 +4202,22 @@ fn eval_src_mod_from_path(&mut self, path: Path, outer_attrs: Vec , id_sp: Span) -> (ast::Item_, Vec ) { - { - let mut included_mod_stack = self.sess - .included_mod_stack - .borrow_mut(); - let maybe_i = included_mod_stack.get() - .iter() - .position(|p| *p == path); - match maybe_i { - Some(i) => { - let mut err = ~"circular modules: "; - let len = included_mod_stack.get().len(); - for p in included_mod_stack.get().slice(i, len).iter() { - err.push_str(p.display().as_maybe_owned().as_slice()); - err.push_str(" -> "); - } - err.push_str(path.display().as_maybe_owned().as_slice()); - self.span_fatal(id_sp, err); + let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut(); + match included_mod_stack.iter().position(|p| *p == path) { + Some(i) => { + let mut err = ~"circular modules: "; + let len = included_mod_stack.len(); + for p in included_mod_stack.slice(i, len).iter() { + err.push_str(p.display().as_maybe_owned().as_slice()); + err.push_str(" -> "); } - None => () + err.push_str(path.display().as_maybe_owned().as_slice()); + self.span_fatal(id_sp, err); } - included_mod_stack.get().push(path.clone()); + None => () } + included_mod_stack.push(path.clone()); + drop(included_mod_stack); let mut p0 = new_sub_parser_from_file(self.sess, @@ -4235,12 +4228,7 @@ fn eval_src_mod_from_path(&mut self, let mod_attrs = vec::append(outer_attrs, inner.as_slice()); let first_item_outer_attrs = next; let m0 = p0.parse_mod_items(token::EOF, first_item_outer_attrs); - { - let mut included_mod_stack = self.sess - .included_mod_stack - .borrow_mut(); - included_mod_stack.get().pop(); - } + self.sess.included_mod_stack.borrow_mut().pop(); return (ast::ItemMod(m0), mod_attrs); } diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index eebb98294d5..15525912955 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -24,7 +24,7 @@ use std::path::BytesContainer; #[allow(non_camel_case_types)] -#[deriving(Clone, Encodable, Decodable, Eq, Hash, Show)] +#[deriving(Clone, Encodable, Decodable, Eq, TotalEq, Hash, Show)] pub enum BinOp { PLUS, MINUS, @@ -39,7 +39,7 @@ pub enum BinOp { } #[allow(non_camel_case_types)] -#[deriving(Clone, Encodable, Decodable, Eq, Hash, Show)] +#[deriving(Clone, Encodable, Decodable, Eq, TotalEq, Hash, Show)] pub enum Token { /* Expression-operator symbols. */ EQ, @@ -103,7 +103,7 @@ pub enum Token { EOF, } -#[deriving(Clone, Encodable, Decodable, Eq, Hash)] +#[deriving(Clone, Encodable, Decodable, Eq, TotalEq, Hash)] /// For interpolation during macro expansion. pub enum Nonterminal { NtItem(@ast::Item), diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 9cecd5f6c2b..a9ab596b300 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -238,23 +238,23 @@ pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> ~str { impl<'a> State<'a> { pub fn ibox(&mut self, u: uint) -> IoResult<()> { - self.boxes.borrow_mut().get().push(pp::Inconsistent); + self.boxes.borrow_mut().push(pp::Inconsistent); pp::ibox(&mut self.s, u) } pub fn end(&mut self) -> IoResult<()> { - self.boxes.borrow_mut().get().pop().unwrap(); + self.boxes.borrow_mut().pop().unwrap(); pp::end(&mut self.s) } pub fn cbox(&mut self, u: uint) -> IoResult<()> { - self.boxes.borrow_mut().get().push(pp::Consistent); + self.boxes.borrow_mut().push(pp::Consistent); pp::cbox(&mut self.s, u) } // "raw box" pub fn rbox(&mut self, u: uint, b: pp::Breaks) -> IoResult<()> { - self.boxes.borrow_mut().get().push(b); + self.boxes.borrow_mut().push(b); pp::rbox(&mut self.s, u, b) } @@ -322,7 +322,7 @@ pub fn is_bol(&mut self) -> bool { } pub fn in_cbox(&mut self) -> bool { - match self.boxes.borrow().get().last() { + match self.boxes.borrow().last() { Some(&last_box) => last_box == pp::Consistent, None => false } @@ -2186,7 +2186,7 @@ pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> { ast::LitBinary(ref arr) => { try!(self.ibox(indent_unit)); try!(word(&mut self.s, "[")); - try!(self.commasep_cmnt(Inconsistent, arr.deref().as_slice(), + try!(self.commasep_cmnt(Inconsistent, arr.as_slice(), |s, u| word(&mut s.s, format!("{}", *u)), |_| lit.span)); try!(word(&mut self.s, "]")); diff --git a/src/libsyntax/util/interner.rs b/src/libsyntax/util/interner.rs index 2dea6f79ee6..969b9f81785 100644 --- a/src/libsyntax/util/interner.rs +++ b/src/libsyntax/util/interner.rs @@ -28,7 +28,7 @@ pub struct Interner { } // when traits can extend traits, we should extend index to get [] -impl Interner { +impl Interner { pub fn new() -> Interner { Interner { map: RefCell::new(HashMap::new()), @@ -46,47 +46,47 @@ pub fn prefill(init: &[T]) -> Interner { pub fn intern(&self, val: T) -> Name { let mut map = self.map.borrow_mut(); - match map.get().find(&val) { + match (*map).find(&val) { Some(&idx) => return idx, None => (), } let mut vect = self.vect.borrow_mut(); - let new_idx = vect.get().len() as Name; - map.get().insert(val.clone(), new_idx); - vect.get().push(val); + let new_idx = (*vect).len() as Name; + (*map).insert(val.clone(), new_idx); + (*vect).push(val); new_idx } pub fn gensym(&self, val: T) -> Name { let mut vect = self.vect.borrow_mut(); - let new_idx = vect.get().len() as Name; + let new_idx = (*vect).len() as Name; // leave out of .map to avoid colliding - vect.get().push(val); + (*vect).push(val); new_idx } pub fn get(&self, idx: Name) -> T { let vect = self.vect.borrow(); - (*vect.get().get(idx as uint)).clone() + (*(*vect).get(idx as uint)).clone() } pub fn len(&self) -> uint { let vect = self.vect.borrow(); - vect.get().len() + (*vect).len() } pub fn find_equiv>(&self, val: &Q) -> Option { let map = self.map.borrow(); - match map.get().find_equiv(val) { + match (*map).find_equiv(val) { Some(v) => Some(*v), None => None, } } pub fn clear(&self) { - *self.map.borrow_mut().get() = HashMap::new(); - *self.vect.borrow_mut().get() = Vec::new(); + *self.map.borrow_mut() = HashMap::new(); + *self.vect.borrow_mut() = Vec::new(); } } @@ -95,11 +95,7 @@ pub struct RcStr { priv string: Rc<~str>, } -impl TotalEq for RcStr { - fn equals(&self, other: &RcStr) -> bool { - self.as_slice().equals(&other.as_slice()) - } -} +impl TotalEq for RcStr {} impl TotalOrd for RcStr { fn cmp(&self, other: &RcStr) -> Ordering { @@ -110,13 +106,13 @@ fn cmp(&self, other: &RcStr) -> Ordering { impl Str for RcStr { #[inline] fn as_slice<'a>(&'a self) -> &'a str { - let s: &'a str = *self.string.deref(); + let s: &'a str = *self.string; s } #[inline] fn into_owned(self) -> ~str { - self.string.deref().to_owned() + self.string.to_owned() } } @@ -159,24 +155,22 @@ pub fn prefill(init: &[&str]) -> StrInterner { pub fn intern(&self, val: &str) -> Name { let mut map = self.map.borrow_mut(); - match map.get().find_equiv(&val) { + match map.find_equiv(&val) { Some(&idx) => return idx, None => (), } let new_idx = self.len() as Name; let val = RcStr::new(val); - map.get().insert(val.clone(), new_idx); - let mut vect = self.vect.borrow_mut(); - vect.get().push(val); + map.insert(val.clone(), new_idx); + self.vect.borrow_mut().push(val); new_idx } pub fn gensym(&self, val: &str) -> Name { let new_idx = self.len() as Name; // leave out of .map to avoid colliding - let mut vect = self.vect.borrow_mut(); - vect.get().push(RcStr::new(val)); + self.vect.borrow_mut().push(RcStr::new(val)); new_idx } @@ -194,42 +188,39 @@ pub fn gensym_copy(&self, idx : Name) -> Name { let new_idx = self.len() as Name; // leave out of map to avoid colliding let mut vect = self.vect.borrow_mut(); - let existing = (*vect.get().get(idx as uint)).clone(); - vect.get().push(existing); + let existing = (*vect.get(idx as uint)).clone(); + vect.push(existing); new_idx } pub fn get(&self, idx: Name) -> RcStr { - let vect = self.vect.borrow(); - (*vect.get().get(idx as uint)).clone() + (*self.vect.borrow().get(idx as uint)).clone() } /// Returns this string with lifetime tied to the interner. Since /// strings may never be removed from the interner, this is safe. pub fn get_ref<'a>(&'a self, idx: Name) -> &'a str { let vect = self.vect.borrow(); - let s: &str = vect.get().get(idx as uint).as_slice(); + let s: &str = vect.get(idx as uint).as_slice(); unsafe { cast::transmute(s) } } pub fn len(&self) -> uint { - let vect = self.vect.borrow(); - vect.get().len() + self.vect.borrow().len() } pub fn find_equiv>(&self, val: &Q) -> Option { - let map = self.map.borrow(); - match map.get().find_equiv(val) { + match (*self.map.borrow()).find_equiv(val) { Some(v) => Some(*v), None => None, } } pub fn clear(&self) { - *self.map.borrow_mut().get() = HashMap::new(); - *self.vect.borrow_mut().get() = Vec::new(); + *self.map.borrow_mut() = HashMap::new(); + *self.vect.borrow_mut() = Vec::new(); } } diff --git a/src/libterm/lib.rs b/src/libterm/lib.rs index 3148c9233ff..5ccc6bfb91e 100644 --- a/src/libterm/lib.rs +++ b/src/libterm/lib.rs @@ -20,7 +20,7 @@ html_root_url = "http://static.rust-lang.org/doc/master")]; #[feature(macro_rules)]; -#[allow(deprecated_owned_vector)]; // NOTE: remove after stage0 +#[deny(missing_doc)]; extern crate collections; @@ -35,7 +35,9 @@ // FIXME (#2807): Windows support. +/// Terminal color definitions pub mod color { + /// Number for a terminal color pub type Color = u16; pub static BLACK: Color = 0u16; @@ -57,8 +59,10 @@ pub mod color { pub static BRIGHT_WHITE: Color = 15u16; } +/// Terminal attributes pub mod attr { /// Terminal attributes for use with term.attr(). + /// /// Most attributes can only be turned on and must be turned off with term.reset(). /// The ones that can be turned off explicitly take a boolean value. /// Color is also represented as an attribute for convenience. @@ -104,6 +108,8 @@ fn cap_for_attr(attr: attr::Attr) -> &'static str { } } +/// A Terminal that knows how many colors it supports, with a reference to its +/// parsed TermInfo database record. pub struct Terminal { priv num_colors: u16, priv out: T, @@ -111,6 +117,14 @@ pub struct Terminal { } impl Terminal { + /// Returns a wrapped output stream (`Terminal`) as a `Result`. + /// + /// Returns `Err()` if the TERM environment variable is undefined. + /// TERM should be set to something like `xterm-color` or `screen-256color`. + /// + /// Returns `Err()` on failure to open the terminfo database correctly. + /// Also, in the event that the individual terminfo database entry can not + /// be parsed. pub fn new(out: T) -> Result, ~str> { let term = match os::getenv("TERM") { Some(t) => t, @@ -144,8 +158,8 @@ pub fn new(out: T) -> Result, ~str> { /// If the color is a bright color, but the terminal only supports 8 colors, /// the corresponding normal color will be used instead. /// - /// Returns Ok(true) if the color was set, Ok(false) otherwise, and Err(e) - /// if there was an I/O error + /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)` + /// if there was an I/O error. pub fn fg(&mut self, color: color::Color) -> io::IoResult { let color = self.dim_if_necessary(color); if self.num_colors > color { @@ -167,8 +181,8 @@ pub fn fg(&mut self, color: color::Color) -> io::IoResult { /// If the color is a bright color, but the terminal only supports 8 colors, /// the corresponding normal color will be used instead. /// - /// Returns Ok(true) if the color was set, Ok(false) otherwise, and Err(e) - /// if there was an I/O error + /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)` + /// if there was an I/O error. pub fn bg(&mut self, color: color::Color) -> io::IoResult { let color = self.dim_if_necessary(color); if self.num_colors > color { @@ -187,8 +201,8 @@ pub fn bg(&mut self, color: color::Color) -> io::IoResult { } /// Sets the given terminal attribute, if supported. - /// Returns Ok(true) if the attribute was supported, Ok(false) otherwise, - /// and Err(e) if there was an I/O error. + /// Returns `Ok(true)` if the attribute was supported, `Ok(false)` otherwise, + /// and `Err(e)` if there was an I/O error. pub fn attr(&mut self, attr: attr::Attr) -> io::IoResult { match attr { attr::ForegroundColor(c) => self.fg(c), @@ -224,6 +238,7 @@ pub fn supports_attr(&self, attr: attr::Attr) -> bool { } /// Resets all terminal attributes and color to the default. + /// Returns `Ok()`. pub fn reset(&mut self) -> io::IoResult<()> { let mut cap = self.ti.strings.find_equiv(&("sgr0")); if cap.is_none() { @@ -249,10 +264,13 @@ fn dim_if_necessary(&self, color: color::Color) -> color::Color { } else { color } } + /// Returns the contained stream pub fn unwrap(self) -> T { self.out } + /// Gets an immutable reference to the stream inside pub fn get_ref<'a>(&'a self) -> &'a T { &self.out } + /// Gets a mutable reference to the stream inside pub fn get_mut<'a>(&'a mut self) -> &'a mut T { &mut self.out } } diff --git a/src/libterm/terminfo/mod.rs b/src/libterm/terminfo/mod.rs index 26a819ef2bc..978a8a09d0a 100644 --- a/src/libterm/terminfo/mod.rs +++ b/src/libterm/terminfo/mod.rs @@ -8,11 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#[allow(missing_doc)]; +//! Terminfo database interface. use collections::HashMap; -/// A parsed terminfo entry. +/// A parsed terminfo database entry. pub struct TermInfo { /// Names for the terminal priv names: Vec<~str> , @@ -25,7 +25,10 @@ pub struct TermInfo { } pub mod searcher; + +/// TermInfo format parsing. pub mod parser { + //! ncurses-compatible compiled terminfo format parsing (term(5)) pub mod compiled; } pub mod parm; diff --git a/src/libterm/terminfo/parm.rs b/src/libterm/terminfo/parm.rs index 69752360929..a638a074271 100644 --- a/src/libterm/terminfo/parm.rs +++ b/src/libterm/terminfo/parm.rs @@ -38,8 +38,8 @@ enum FormatState { } /// Types of parameters a capability can use -#[deriving(Clone)] #[allow(missing_doc)] +#[deriving(Clone)] pub enum Param { String(~str), Number(int) diff --git a/src/libterm/terminfo/parser/compiled.rs b/src/libterm/terminfo/parser/compiled.rs index db615aaad62..66d322e079f 100644 --- a/src/libterm/terminfo/parser/compiled.rs +++ b/src/libterm/terminfo/parser/compiled.rs @@ -10,7 +10,7 @@ #[allow(non_uppercase_statics)]; -/// ncurses-compatible compiled terminfo format parsing (term(5)) +//! ncurses-compatible compiled terminfo format parsing (term(5)) use collections::HashMap; use std::io; diff --git a/src/libterm/terminfo/searcher.rs b/src/libterm/terminfo/searcher.rs index b29d7b2284e..b5792c66a0d 100644 --- a/src/libterm/terminfo/searcher.rs +++ b/src/libterm/terminfo/searcher.rs @@ -8,8 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -/// Implement ncurses-compatible database discovery -/// Does not support hashed database, only filesystem! +//! ncurses-compatible database discovery +//! +//! Does not support hashed database, only filesystem! use std::io::File; use std::os::getenv; diff --git a/src/libtest/stats.rs b/src/libtest/stats.rs index 8a3881e801a..222aff37465 100644 --- a/src/libtest/stats.rs +++ b/src/libtest/stats.rs @@ -424,7 +424,7 @@ pub fn write_boxplot(w: &mut io::Writer, s: &Summary, /// Returns a HashMap with the number of occurrences of every element in the /// sequence that the iterator exposes. -pub fn freq_count, U: Eq+Hash>(mut iter: T) -> hashmap::HashMap { +pub fn freq_count, U: TotalEq+Hash>(mut iter: T) -> hashmap::HashMap { let mut map: hashmap::HashMap = hashmap::HashMap::new(); for elem in iter { map.insert_or_update_with(elem, 1, |_, count| *count += 1); diff --git a/src/liburl/lib.rs b/src/liburl/lib.rs index 55d87000130..031c7fafa04 100644 --- a/src/liburl/lib.rs +++ b/src/liburl/lib.rs @@ -48,7 +48,7 @@ /// fragment: Some(~"quz") }; /// // https://username@example.com:8080/foo/bar?baz=qux#quz /// ``` -#[deriving(Clone, Eq)] +#[deriving(Clone, Eq, TotalEq)] pub struct Url { /// The scheme part of a URL, such as `https` in the above example. scheme: ~str, @@ -79,7 +79,7 @@ pub struct Path { } /// An optional subcomponent of a URI authority component. -#[deriving(Clone, Eq)] +#[deriving(Clone, Eq, TotalEq)] pub struct UserInfo { /// The user name. user: ~str, diff --git a/src/libuuid/lib.rs b/src/libuuid/lib.rs index 47602bfcdf2..d31b0f43a09 100644 --- a/src/libuuid/lib.rs +++ b/src/libuuid/lib.rs @@ -64,10 +64,6 @@ fn main() { #[feature(default_type_params)]; -// NOTE remove the following two attributes after the next snapshot. -#[allow(unrecognized_lint)]; -#[allow(default_type_param_usage)]; - // test harness access #[cfg(test)] extern crate test; @@ -491,14 +487,7 @@ fn eq(&self, other: &Uuid) -> bool { } } -/// Test two UUIDs for equality -/// -/// UUIDs are equal only when they are byte-for-byte identical -impl TotalEq for Uuid { - fn equals(&self, other: &Uuid) -> bool { - self.bytes == other.bytes - } -} +impl TotalEq for Uuid {} // FIXME #9845: Test these more thoroughly impl Encodable for Uuid { diff --git a/src/snapshots.txt b/src/snapshots.txt index 77c1cc68b17..f7f1c2d6aa3 100644 --- a/src/snapshots.txt +++ b/src/snapshots.txt @@ -1,3 +1,11 @@ +S 2014-03-22 94e4e91 + freebsd-x86_64 7793127e1b9ad22cb2e020f9bb01f34526cc4656 + linux-i386 aa53699d32d7acb86a6447f988c4ac73ac310bab + linux-x86_64 7ca5d5bfeec8d05ee3503bb48e4c5f6d75a6b49c + macos-i386 bc33e8fabe4d95848e91f5648268a6cc974d5468 + macos-x86_64 99da3ba5ec8924ccc0ad1fc17e2e04d1c29fccd0 + winnt-i386 578102567096d97b353b291076bdfa1e9da62513 + S 2014-03-19 4ca51ae freebsd-x86_64 3059005ca4ee2972bb705313bfb7848e859a20cd linux-i386 8907cd4ce8b8301d70a6bbc0100c955444270c19 diff --git a/src/test/auxiliary/cci_nested_lib.rs b/src/test/auxiliary/cci_nested_lib.rs index a9be1e62195..146ed261811 100644 --- a/src/test/auxiliary/cci_nested_lib.rs +++ b/src/test/auxiliary/cci_nested_lib.rs @@ -24,7 +24,7 @@ pub struct alist { pub fn alist_add(lst: &alist, k: A, v: B) { let mut data = lst.data.borrow_mut(); - data.get().push(Entry{key:k, value:v}); + (*data).push(Entry{key:k, value:v}); } pub fn alist_get B { let eq_fn = lst.eq_fn; let data = lst.data.borrow(); - for entry in data.get().iter() { + for entry in (*data).iter() { if eq_fn(entry.key.clone(), k.clone()) { return entry.value.clone(); } diff --git a/src/test/auxiliary/overloaded_autoderef_xc.rs b/src/test/auxiliary/overloaded_autoderef_xc.rs new file mode 100644 index 00000000000..65a404d1ff3 --- /dev/null +++ b/src/test/auxiliary/overloaded_autoderef_xc.rs @@ -0,0 +1,37 @@ +// 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::ops::Deref; + +struct DerefWithHelper { + helper: H +} + +trait Helper { + fn helper_borrow<'a>(&'a self) -> &'a T; +} + +impl Helper for Option { + fn helper_borrow<'a>(&'a self) -> &'a T { + self.as_ref().unwrap() + } +} + +impl> Deref for DerefWithHelper { + fn deref<'a>(&'a self) -> &'a T { + self.helper.helper_borrow() + } +} + +// Test cross-crate autoderef + vtable. +pub fn check(x: T, y: T) -> bool { + let d: DerefWithHelper, T> = DerefWithHelper { helper: Some(x) }; + d.eq(&y) +} diff --git a/src/test/auxiliary/trait_superkinds_in_metadata.rs b/src/test/auxiliary/trait_superkinds_in_metadata.rs index 2345724e8c2..e49ed1f9cf7 100644 --- a/src/test/auxiliary/trait_superkinds_in_metadata.rs +++ b/src/test/auxiliary/trait_superkinds_in_metadata.rs @@ -13,6 +13,6 @@ #[crate_type="lib"]; -pub trait RequiresFreeze : Freeze { } -pub trait RequiresRequiresFreezeAndSend : RequiresFreeze + Send { } +pub trait RequiresShare : Share { } +pub trait RequiresRequiresShareAndSend : RequiresShare + Send { } pub trait RequiresPod : Pod { } diff --git a/src/test/bench/shootout-binarytrees.rs b/src/test/bench/shootout-binarytrees.rs index 18df0786872..62b01779ac2 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) }) - }).to_owned_vec(); + }).collect::<~[Future<~str>]>(); for message in messages.mut_iter() { println!("{}", *message.get_ref()); diff --git a/src/test/compile-fail/borrowck-borrow-of-mut-base-ptr.rs b/src/test/compile-fail/borrowck-borrow-of-mut-base-ptr.rs deleted file mode 100644 index 954ec82e40f..00000000000 --- a/src/test/compile-fail/borrowck-borrow-of-mut-base-ptr.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2013 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. - -// Test that attempt to freeze an `&mut` pointer while referent is -// claimed yields an error. -// -// Example from src/middle/borrowck/doc.rs - -fn foo<'a>(mut t0: &'a mut int, - mut t1: &'a mut int) { - let p: &mut int = &mut *t0; // Claims `*t0` - let mut t2 = &t0; //~ ERROR cannot borrow `t0` - let q: &int = &**t2; // Freezes `*t0` but not through `*p` - *p += 1; // violates type of `*q` -} - -fn main() { -} diff --git a/src/test/compile-fail/builtin-superkinds-in-metadata.rs b/src/test/compile-fail/builtin-superkinds-in-metadata.rs index bd85141171e..e085b35cbb1 100644 --- a/src/test/compile-fail/builtin-superkinds-in-metadata.rs +++ b/src/test/compile-fail/builtin-superkinds-in-metadata.rs @@ -16,12 +16,12 @@ // Mostly tests correctness of metadata. extern crate trait_superkinds_in_metadata; -use trait_superkinds_in_metadata::{RequiresRequiresFreezeAndSend, RequiresFreeze}; +use trait_superkinds_in_metadata::{RequiresRequiresShareAndSend, RequiresShare}; struct X(T); -impl RequiresFreeze for X { } +impl RequiresShare for X { } -impl RequiresRequiresFreezeAndSend for X { } //~ ERROR cannot implement this trait +impl RequiresRequiresShareAndSend for X { } //~ ERROR cannot implement this trait fn main() { } diff --git a/src/test/compile-fail/builtin-superkinds-simple.rs b/src/test/compile-fail/builtin-superkinds-simple.rs index 962bf67f009..caf96861292 100644 --- a/src/test/compile-fail/builtin-superkinds-simple.rs +++ b/src/test/compile-fail/builtin-superkinds-simple.rs @@ -13,10 +13,7 @@ trait Foo : Send { } -impl <'a> Foo for &'a mut () { } //~ ERROR cannot implement this trait - -trait Bar : Freeze { } - -impl <'a> Bar for &'a mut () { } //~ ERROR cannot implement this trait +impl <'a> Foo for &'a mut () { } +//~^ ERROR which does not fulfill `Send`, cannot implement this trait fn main() { } diff --git a/src/test/compile-fail/closure-bounds-subtype.rs b/src/test/compile-fail/closure-bounds-subtype.rs index 9747a44cef0..5ffaebe405e 100644 --- a/src/test/compile-fail/closure-bounds-subtype.rs +++ b/src/test/compile-fail/closure-bounds-subtype.rs @@ -12,7 +12,7 @@ fn take_any(_: ||:) { } -fn take_const_owned(_: ||:Freeze+Send) { +fn take_const_owned(_: ||:Share+Send) { } fn give_any(f: ||:) { @@ -21,7 +21,7 @@ fn give_any(f: ||:) { fn give_owned(f: ||:Send) { take_any(f); - take_const_owned(f); //~ ERROR expected bounds `Send+Freeze` but found bounds `Send` + take_const_owned(f); //~ ERROR expected bounds `Send+Share` but found bounds `Send` } fn main() {} diff --git a/src/test/compile-fail/issue-11692.rs b/src/test/compile-fail/issue-11692.rs index aed2c4d579a..848deac4d55 100644 --- a/src/test/compile-fail/issue-11692.rs +++ b/src/test/compile-fail/issue-11692.rs @@ -15,5 +15,4 @@ fn main() { concat!(test!()); //~^ ERROR: macro undefined: 'test' - //~^^ ERROR: expected a literal } diff --git a/src/test/compile-fail/issue-7013.rs b/src/test/compile-fail/issue-7013.rs index 800549b7737..5c84cbe00a9 100644 --- a/src/test/compile-fail/issue-7013.rs +++ b/src/test/compile-fail/issue-7013.rs @@ -40,7 +40,7 @@ fn main() //~^ ERROR cannot pack type `~B`, which does not fulfill `Send` let v = Rc::new(RefCell::new(a)); let w = v.clone(); - let b = v.deref(); + let b = &*v; let mut b = b.borrow_mut(); - b.get().v.set(w.clone()); + b.v.set(w.clone()); } diff --git a/src/test/compile-fail/kindck-freeze.rs b/src/test/compile-fail/kindck-freeze.rs deleted file mode 100644 index 4da12478194..00000000000 --- a/src/test/compile-fail/kindck-freeze.rs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2012 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. - -// Test which of the builtin types are considered freezeable. - - -fn assert_freeze() { } -trait Dummy { } - -fn test<'a,T,U:Freeze>(_: &'a int) { - // lifetime pointers are ok... - assert_freeze::<&'static int>(); - assert_freeze::<&'a int>(); - assert_freeze::<&'a str>(); - assert_freeze::<&'a [int]>(); - - // ...unless they are mutable - assert_freeze::<&'static mut int>(); //~ ERROR does not fulfill `Freeze` - assert_freeze::<&'a mut int>(); //~ ERROR does not fulfill `Freeze` - - // ~ pointers are ok - assert_freeze::<~int>(); - assert_freeze::<~str>(); - assert_freeze:: >(); - - // but not if they own a bad thing - assert_freeze::<~&'a mut int>(); //~ ERROR does not fulfill `Freeze` - - // careful with object types, who knows what they close over... - assert_freeze::<&'a Dummy>(); //~ ERROR does not fulfill `Freeze` - assert_freeze::<~Dummy>(); //~ ERROR does not fulfill `Freeze` - - // ...unless they are properly bounded - assert_freeze::<&'a Dummy:Freeze>(); - assert_freeze::<&'static Dummy:Freeze>(); - assert_freeze::<~Dummy:Freeze>(); - - // ...but even then the pointer overrides - assert_freeze::<&'a mut Dummy:Freeze>(); //~ ERROR does not fulfill `Freeze` - - // closures are like an `&mut` object - assert_freeze::<||>(); //~ ERROR does not fulfill `Freeze` - - // unsafe ptrs are ok unless they point at unfreezeable things - assert_freeze::<*int>(); - assert_freeze::<*&'a mut int>(); //~ ERROR does not fulfill `Freeze` -} - -fn main() { -} diff --git a/src/test/compile-fail/mut-cant-alias.rs b/src/test/compile-fail/mut-cant-alias.rs index e3e2ace71ad..99d7258477a 100644 --- a/src/test/compile-fail/mut-cant-alias.rs +++ b/src/test/compile-fail/mut-cant-alias.rs @@ -13,6 +13,6 @@ fn main() { let m = RefCell::new(0); let mut b = m.borrow_mut(); - let b1 = b.get(); - let b2 = b.get(); //~ ERROR cannot borrow + let b1 = &mut *b; + let b2 = &mut *b; //~ ERROR cannot borrow } diff --git a/src/test/compile-fail/mut-ptr-cant-outlive-ref.rs b/src/test/compile-fail/mut-ptr-cant-outlive-ref.rs index 2e5cf1b504b..8e968d90a2f 100644 --- a/src/test/compile-fail/mut-ptr-cant-outlive-ref.rs +++ b/src/test/compile-fail/mut-ptr-cant-outlive-ref.rs @@ -15,6 +15,6 @@ fn main() { let p; { let b = m.borrow(); - p = b.get(); //~ ERROR `b` does not live long enough + p = &*b; //~ ERROR `b` does not live long enough } } diff --git a/src/test/compile-fail/mutable-enum-indirect.rs b/src/test/compile-fail/mutable-enum-indirect.rs index 501b17b202c..e480ebfd378 100644 --- a/src/test/compile-fail/mutable-enum-indirect.rs +++ b/src/test/compile-fail/mutable-enum-indirect.rs @@ -13,11 +13,11 @@ use std::kinds::marker; -enum Foo { A(marker::NoFreeze) } +enum Foo { A(marker::NoShare) } -fn bar(_: T) {} +fn bar(_: T) {} fn main() { - let x = A(marker::NoFreeze); + let x = A(marker::NoShare); bar(&x); //~ ERROR type parameter with an incompatible type } diff --git a/src/test/compile-fail/proc-bounds.rs b/src/test/compile-fail/proc-bounds.rs index c714bdb5b1b..e4d2c801070 100644 --- a/src/test/compile-fail/proc-bounds.rs +++ b/src/test/compile-fail/proc-bounds.rs @@ -9,7 +9,7 @@ // except according to those terms. fn is_send() {} -fn is_freeze() {} +fn is_freeze() {} fn is_static() {} fn main() { diff --git a/src/test/compile-fail/trace_macros-format.rs b/src/test/compile-fail/trace_macros-format.rs new file mode 100644 index 00000000000..557dcdc73c8 --- /dev/null +++ b/src/test/compile-fail/trace_macros-format.rs @@ -0,0 +1,29 @@ +// 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. + +// ignore-fast feature doesn't work +#[feature(macro_rules, trace_macros)]; + +fn main() { + trace_macros!(); //~ ERROR trace_macros! accepts only `true` or `false` + trace_macros!(1); //~ ERROR trace_macros! accepts only `true` or `false` + trace_macros!(ident); //~ ERROR trace_macros! accepts only `true` or `false` + trace_macros!(for); //~ ERROR trace_macros! accepts only `true` or `false` + trace_macros!(true,); //~ ERROR trace_macros! accepts only `true` or `false` + trace_macros!(false 1); //~ ERROR trace_macros! accepts only `true` or `false` + + + // should be fine: + macro_rules! expando { + ($x: ident) => { trace_macros!($x) } + } + + expando!(true); +} diff --git a/src/test/compile-fail/trait-bounds-cant-coerce.rs b/src/test/compile-fail/trait-bounds-cant-coerce.rs index 7f8a26716cd..958a97412bc 100644 --- a/src/test/compile-fail/trait-bounds-cant-coerce.rs +++ b/src/test/compile-fail/trait-bounds-cant-coerce.rs @@ -14,7 +14,7 @@ trait Foo { fn a(_x: ~Foo:Send) { } -fn c(x: ~Foo:Freeze+Send) { +fn c(x: ~Foo:Share+Send) { a(x); } diff --git a/src/test/compile-fail/trait-bounds-sugar.rs b/src/test/compile-fail/trait-bounds-sugar.rs index b9fb94e09ed..988057bc7b1 100644 --- a/src/test/compile-fail/trait-bounds-sugar.rs +++ b/src/test/compile-fail/trait-bounds-sugar.rs @@ -18,11 +18,11 @@ fn a(_x: ~Foo) { // should be same as ~Foo:Send fn b(_x: &'static Foo) { // should be same as &'static Foo:'static } -fn c(x: ~Foo:Freeze) { +fn c(x: ~Foo:Share) { a(x); //~ ERROR expected bounds `Send` } -fn d(x: &'static Foo:Freeze) { +fn d(x: &'static Foo:Share) { b(x); //~ ERROR expected bounds `'static` } diff --git a/src/test/pretty/path-type-bounds.rs b/src/test/pretty/path-type-bounds.rs index c5f24160db5..7b09c589320 100644 --- a/src/test/pretty/path-type-bounds.rs +++ b/src/test/pretty/path-type-bounds.rs @@ -13,11 +13,11 @@ trait Tr { } impl Tr for int { } -fn foo(x: ~Tr: Freeze) -> ~Tr: Freeze { x } +fn foo(x: ~Tr: Share) -> ~Tr: Share { x } fn main() { - let x: ~Tr: Freeze; + let x: ~Tr: Share; - ~1 as ~Tr: Freeze; + ~1 as ~Tr: Share; } diff --git a/src/test/run-make/output-type-permutations/Makefile b/src/test/run-make/output-type-permutations/Makefile index 72f96b21fa8..94e0ce83343 100644 --- a/src/test/run-make/output-type-permutations/Makefile +++ b/src/test/run-make/output-type-permutations/Makefile @@ -15,7 +15,6 @@ all: rm $(TMPDIR)/bar $(RUSTC) foo.rs --emit=asm,ir,bc,obj,link --crate-type=staticlib rm $(TMPDIR)/bar.ll - rm $(TMPDIR)/bar.bc rm $(TMPDIR)/bar.s rm $(TMPDIR)/bar.o rm $(TMPDIR)/$(call STATICLIB_GLOB,bar) @@ -37,6 +36,9 @@ all: rm $(TMPDIR)/foo $(RUSTC) foo.rs --crate-type=bin -o $(TMPDIR)/foo rm $(TMPDIR)/foo + mv $(TMPDIR)/bar.bc $(TMPDIR)/foo.bc $(RUSTC) foo.rs --emit=bc,link --crate-type=rlib + cmp $(TMPDIR)/foo.bc $(TMPDIR)/bar.bc rm $(TMPDIR)/bar.bc + rm $(TMPDIR)/foo.bc rm $(TMPDIR)/$(call RLIB_GLOB,bar) diff --git a/src/test/run-pass/builtin-superkinds-capabilities-xc.rs b/src/test/run-pass/builtin-superkinds-capabilities-xc.rs index dc7a0ce4eba..8c41e4f57c4 100644 --- a/src/test/run-pass/builtin-superkinds-capabilities-xc.rs +++ b/src/test/run-pass/builtin-superkinds-capabilities-xc.rs @@ -16,15 +16,15 @@ // even when using them cross-crate. extern crate trait_superkinds_in_metadata; -use trait_superkinds_in_metadata::{RequiresRequiresFreezeAndSend, RequiresFreeze}; +use trait_superkinds_in_metadata::{RequiresRequiresShareAndSend, RequiresShare}; #[deriving(Eq)] struct X(T); -impl RequiresFreeze for X { } -impl RequiresRequiresFreezeAndSend for X { } +impl RequiresShare for X { } +impl RequiresRequiresShareAndSend for X { } -fn foo(val: T, chan: Sender) { +fn foo(val: T, chan: Sender) { chan.send(val); } diff --git a/src/test/run-pass/builtin-superkinds-in-metadata.rs b/src/test/run-pass/builtin-superkinds-in-metadata.rs index 8cecd5019a3..7b2977d031c 100644 --- a/src/test/run-pass/builtin-superkinds-in-metadata.rs +++ b/src/test/run-pass/builtin-superkinds-in-metadata.rs @@ -15,14 +15,14 @@ // Tests (correct) usage of trait super-builtin-kinds cross-crate. extern crate trait_superkinds_in_metadata; -use trait_superkinds_in_metadata::{RequiresRequiresFreezeAndSend, RequiresFreeze}; +use trait_superkinds_in_metadata::{RequiresRequiresShareAndSend, RequiresShare}; use trait_superkinds_in_metadata::{RequiresPod}; struct X(T); -impl RequiresFreeze for X { } +impl RequiresShare for X { } -impl RequiresRequiresFreezeAndSend for X { } +impl RequiresRequiresShareAndSend for X { } impl RequiresPod for X { } diff --git a/src/test/run-pass/deriving-cmp-generic-enum.rs b/src/test/run-pass/deriving-cmp-generic-enum.rs index 094d17c100e..5d41e275cd3 100644 --- a/src/test/run-pass/deriving-cmp-generic-enum.rs +++ b/src/test/run-pass/deriving-cmp-generic-enum.rs @@ -39,9 +39,6 @@ pub fn main() { assert_eq!(*e1 == *e2, eq); assert_eq!(*e1 != *e2, !eq); - // TotalEq - assert_eq!(e1.equals(e2), eq); - // Ord assert_eq!(*e1 < *e2, lt); assert_eq!(*e1 > *e2, gt); diff --git a/src/test/run-pass/deriving-cmp-generic-struct-enum.rs b/src/test/run-pass/deriving-cmp-generic-struct-enum.rs index aedf4732afd..c2f0c269d62 100644 --- a/src/test/run-pass/deriving-cmp-generic-struct-enum.rs +++ b/src/test/run-pass/deriving-cmp-generic-struct-enum.rs @@ -35,9 +35,6 @@ pub fn main() { assert_eq!(*es1 == *es2, eq); assert_eq!(*es1 != *es2, !eq); - // TotalEq - assert_eq!(es1.equals(es2), eq); - // Ord assert_eq!(*es1 < *es2, lt); assert_eq!(*es1 > *es2, gt); diff --git a/src/test/run-pass/deriving-cmp-generic-struct.rs b/src/test/run-pass/deriving-cmp-generic-struct.rs index d04bdee34e6..4f62d1fa631 100644 --- a/src/test/run-pass/deriving-cmp-generic-struct.rs +++ b/src/test/run-pass/deriving-cmp-generic-struct.rs @@ -35,9 +35,6 @@ pub fn main() { assert_eq!(*s1 == *s2, eq); assert_eq!(*s1 != *s2, !eq); - // TotalEq - assert_eq!(s1.equals(s2), eq); - // Ord assert_eq!(*s1 < *s2, lt); assert_eq!(*s1 > *s2, gt); diff --git a/src/test/run-pass/deriving-cmp-generic-tuple-struct.rs b/src/test/run-pass/deriving-cmp-generic-tuple-struct.rs index 5d4cf7c7457..b8ba4c64616 100644 --- a/src/test/run-pass/deriving-cmp-generic-tuple-struct.rs +++ b/src/test/run-pass/deriving-cmp-generic-tuple-struct.rs @@ -33,9 +33,6 @@ pub fn main() { assert_eq!(*ts1 == *ts2, eq); assert_eq!(*ts1 != *ts2, !eq); - // TotalEq - assert_eq!(ts1.equals(ts2), eq); - // Ord assert_eq!(*ts1 < *ts2, lt); assert_eq!(*ts1 > *ts2, gt); diff --git a/src/test/run-pass/deriving-cmp-shortcircuit.rs b/src/test/run-pass/deriving-cmp-shortcircuit.rs index 431c856ee88..03e6d04d87f 100644 --- a/src/test/run-pass/deriving-cmp-shortcircuit.rs +++ b/src/test/run-pass/deriving-cmp-shortcircuit.rs @@ -21,9 +21,7 @@ impl Ord for FailCmp { fn lt(&self, _: &FailCmp) -> bool { fail!("lt") } } -impl TotalEq for FailCmp { - fn equals(&self, _: &FailCmp) -> bool { fail!("equals") } -} +impl TotalEq for FailCmp {} impl TotalOrd for FailCmp { fn cmp(&self, _: &FailCmp) -> Ordering { fail!("cmp") } @@ -41,6 +39,5 @@ pub fn main() { assert!(a != b); assert!(a < b); - assert!(!a.equals(&b)); assert_eq!(a.cmp(&b), ::std::cmp::Less); } diff --git a/src/test/run-pass/deriving-self-lifetime-totalord-totaleq.rs b/src/test/run-pass/deriving-self-lifetime-totalord-totaleq.rs index 723738495e7..1c921041042 100644 --- a/src/test/run-pass/deriving-self-lifetime-totalord-totaleq.rs +++ b/src/test/run-pass/deriving-self-lifetime-totalord-totaleq.rs @@ -19,10 +19,6 @@ struct A<'a> { pub fn main() { let (a, b) = (A { x: &1 }, A { x: &2 }); - assert!(a.equals(&a)); - assert!(b.equals(&b)); - - assert_eq!(a.cmp(&a), Equal); assert_eq!(b.cmp(&b), Equal); diff --git a/src/test/run-pass/format-ref-cell.rs b/src/test/run-pass/format-ref-cell.rs index 6428d496382..0926e640bc1 100644 --- a/src/test/run-pass/format-ref-cell.rs +++ b/src/test/run-pass/format-ref-cell.rs @@ -13,6 +13,6 @@ pub fn main() { let name = RefCell::new("rust"); let what = RefCell::new("rocks"); - let msg = format!("{name:?} {:?}", what.borrow().get(), name=name.borrow().get()); + let msg = format!("{name:?} {:?}", &*what.borrow(), name=&*name.borrow()); assert_eq!(msg, ~"&\"rust\" &\"rocks\""); } diff --git a/src/test/run-pass/issue-12860.rs b/src/test/run-pass/issue-12860.rs index 52eafaadfd4..3876aa45753 100644 --- a/src/test/run-pass/issue-12860.rs +++ b/src/test/run-pass/issue-12860.rs @@ -14,7 +14,7 @@ use collections::HashSet; -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] struct XYZ { x: int, y: int, diff --git a/src/test/run-pass/log_syntax-trace_macros-macro-locations.rs b/src/test/run-pass/log_syntax-trace_macros-macro-locations.rs new file mode 100644 index 00000000000..a00ba6067dc --- /dev/null +++ b/src/test/run-pass/log_syntax-trace_macros-macro-locations.rs @@ -0,0 +1,30 @@ +// 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. + +// ignore-fast feature doesn't work +#[feature(trace_macros, log_syntax)]; + +// make sure these macros can be used as in the various places that +// macros can occur. + +// items +trace_macros!(false) +log_syntax!() + +fn main() { + + // statements + trace_macros!(false); + log_syntax!(); + + // expressions + (trace_macros!(false), + log_syntax!()); +} diff --git a/src/test/run-pass/match-pattern-drop.rs b/src/test/run-pass/match-pattern-drop.rs deleted file mode 100644 index e00ee118295..00000000000 --- a/src/test/run-pass/match-pattern-drop.rs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2012 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(managed_boxes)]; - -enum t { make_t(@int), clam, } - -fn foo(s: @int) { - println!("{:?}", ::std::managed::refcount(s)); - let count = ::std::managed::refcount(s); - let x: t = make_t(s); // ref up - assert_eq!(::std::managed::refcount(s), count + 1u); - println!("{:?}", ::std::managed::refcount(s)); - - match x { - make_t(y) => { - println!("{:?}", y); // ref up then down - - } - _ => { println!("?"); fail!(); } - } - println!("{:?}", ::std::managed::refcount(s)); - assert_eq!(::std::managed::refcount(s), count + 1u); - let _ = ::std::managed::refcount(s); // don't get bitten by last-use. -} - -pub fn main() { - let s: @int = @0; // ref up - - let count = ::std::managed::refcount(s); - - foo(s); // ref up then down - - println!("{}", ::std::managed::refcount(s)); - let count2 = ::std::managed::refcount(s); - assert_eq!(count, count2); -} diff --git a/src/test/run-pass/overloaded-autoderef-vtable.rs b/src/test/run-pass/overloaded-autoderef-vtable.rs new file mode 100644 index 00000000000..15b5cca9cf8 --- /dev/null +++ b/src/test/run-pass/overloaded-autoderef-vtable.rs @@ -0,0 +1,42 @@ +// 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::ops::Deref; + +struct DerefWithHelper { + helper: H +} + +trait Helper { + fn helper_borrow<'a>(&'a self) -> &'a T; +} + +impl Helper for Option { + fn helper_borrow<'a>(&'a self) -> &'a T { + self.as_ref().unwrap() + } +} + +impl> Deref for DerefWithHelper { + fn deref<'a>(&'a self) -> &'a T { + self.helper.helper_borrow() + } +} + +struct Foo {x: int} + +impl Foo { + fn foo(&self) -> int {self.x} +} + +pub fn main() { + let x: DerefWithHelper, Foo> = DerefWithHelper { helper: Some(Foo {x: 5}) }; + assert!(x.foo() == 5); +} diff --git a/src/test/run-pass/overloaded-autoderef-xcrate.rs b/src/test/run-pass/overloaded-autoderef-xcrate.rs new file mode 100644 index 00000000000..fc969093d23 --- /dev/null +++ b/src/test/run-pass/overloaded-autoderef-xcrate.rs @@ -0,0 +1,18 @@ +// 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. + +// ignore-fast +// aux-build:overloaded_autoderef_xc.rs + +extern crate overloaded_autoderef_xc; + +fn main() { + assert!(overloaded_autoderef_xc::check(5, 5)); +} diff --git a/src/test/run-pass/proc-bounds.rs b/src/test/run-pass/proc-bounds.rs index 4a3e94704aa..900e266584b 100644 --- a/src/test/run-pass/proc-bounds.rs +++ b/src/test/run-pass/proc-bounds.rs @@ -12,18 +12,18 @@ fn foo() {} fn bar(_: T) {} fn is_send() {} -fn is_freeze() {} +fn is_freeze() {} fn is_static() {} pub fn main() { foo::(); foo::(); foo::(); - foo::(); - foo::(); + foo::(); + foo::(); is_send::(); - is_freeze::(); + is_freeze::(); is_static::(); diff --git a/src/test/run-pass/regions-mock-tcx.rs b/src/test/run-pass/regions-mock-tcx.rs index 7c87c858d42..c38df0f7a22 100644 --- a/src/test/run-pass/regions-mock-tcx.rs +++ b/src/test/run-pass/regions-mock-tcx.rs @@ -42,6 +42,8 @@ fn eq(&self, other: &TypeStructure<'tcx>) -> bool { } } +impl<'tcx> TotalEq for TypeStructure<'tcx> {} + struct TypeContext<'tcx, 'ast> { ty_arena: &'tcx Arena, types: Vec> , @@ -86,7 +88,7 @@ fn ast(&mut self, a: AstKind<'ast>) -> Ast<'ast> { } } -#[deriving(Eq, Hash)] +#[deriving(Eq, TotalEq, Hash)] struct NodeId { id: uint } diff --git a/src/test/run-pass/self-re-assign.rs b/src/test/run-pass/self-re-assign.rs index cba142680df..4e1a9b665d0 100644 --- a/src/test/run-pass/self-re-assign.rs +++ b/src/test/run-pass/self-re-assign.rs @@ -20,5 +20,5 @@ pub fn main() { let mut x = Rc::new(3); x = x; - assert!(*x.deref() == 3); + assert!(*x == 3); } diff --git a/src/test/run-pass/send_str_treemap.rs b/src/test/run-pass/send_str_treemap.rs index 5583d584f46..2f3ddb8589c 100644 --- a/src/test/run-pass/send_str_treemap.rs +++ b/src/test/run-pass/send_str_treemap.rs @@ -62,7 +62,7 @@ pub fn main() { assert!(map.pop(&Slice("foo")).is_some()); assert_eq!(map.move_iter().map(|(k, v)| k.to_str() + v.to_str()) - .to_owned_vec() + .collect::<~[~str]>() .concat(), ~"abc50bcd51cde52def53"); } diff --git a/src/test/run-pass/trait-bounds-basic.rs b/src/test/run-pass/trait-bounds-basic.rs index 9fef70a4dda..acc3ca508b2 100644 --- a/src/test/run-pass/trait-bounds-basic.rs +++ b/src/test/run-pass/trait-bounds-basic.rs @@ -17,7 +17,7 @@ fn a(_x: ~Foo:) { fn b(_x: ~Foo:Send) { } -fn c(x: ~Foo:Freeze+Send) { +fn c(x: ~Foo:Share+Send) { a(x); } diff --git a/src/test/run-pass/trait-bounds-in-arc.rs b/src/test/run-pass/trait-bounds-in-arc.rs index 338e06ba25a..7ba36cbc0df 100644 --- a/src/test/run-pass/trait-bounds-in-arc.rs +++ b/src/test/run-pass/trait-bounds-in-arc.rs @@ -11,7 +11,7 @@ // except according to those terms. // Tests that a heterogeneous list of existential types can be put inside an Arc -// and shared between tasks as long as all types fulfill Freeze+Send. +// and shared between tasks as long as all types fulfill Send. // ignore-fast diff --git a/src/test/run-pass/trait-cast.rs b/src/test/run-pass/trait-cast.rs index 339afb47fa6..490c77d98cd 100644 --- a/src/test/run-pass/trait-cast.rs +++ b/src/test/run-pass/trait-cast.rs @@ -42,8 +42,8 @@ impl to_str for Tree { fn to_str_(&self) -> ~str { let Tree(t) = *self; let this = t.borrow(); - let (l, r) = (this.get().left, this.get().right); - let val = &this.get().val; + let (l, r) = (this.left, this.right); + let val = &this.val; format!("[{}, {}, {}]", val.to_str_(), l.to_str_(), r.to_str_()) } } @@ -64,6 +64,6 @@ pub fn main() { { let Tree(t1_) = t1; let mut t1 = t1_.borrow_mut(); - t1.get().left = Some(t2); // create cycle + t1.left = Some(t2); // create cycle } } diff --git a/src/test/run-pass/trait-to-str.rs b/src/test/run-pass/trait-to-str.rs index 4bb217920f8..1cd31195b56 100644 --- a/src/test/run-pass/trait-to-str.rs +++ b/src/test/run-pass/trait-to-str.rs @@ -21,7 +21,7 @@ fn to_string(&self) -> ~str { self.to_str() } impl to_str for Vec { fn to_string(&self) -> ~str { - format!("[{}]", self.iter().map(|e| e.to_string()).to_owned_vec().connect(", ")) + format!("[{}]", self.iter().map(|e| e.to_string()).collect::<~[~str]>().connect(", ")) } } diff --git a/src/test/run-pass/uniq-cc-generic.rs b/src/test/run-pass/uniq-cc-generic.rs index 9efa6c1b964..41e921ff6e4 100644 --- a/src/test/run-pass/uniq-cc-generic.rs +++ b/src/test/run-pass/uniq-cc-generic.rs @@ -38,6 +38,6 @@ pub fn main() { let v = empty_pointy(); { let mut vb = v.borrow_mut(); - vb.get().a = p(v); + vb.a = p(v); } } diff --git a/src/test/run-pass/uniq-cc.rs b/src/test/run-pass/uniq-cc.rs index 23a27dece46..57fc9ac6773 100644 --- a/src/test/run-pass/uniq-cc.rs +++ b/src/test/run-pass/uniq-cc.rs @@ -35,6 +35,6 @@ pub fn main() { let v = empty_pointy(); { let mut vb = v.borrow_mut(); - vb.get().a = p(v); + vb.a = p(v); } } diff --git a/src/test/run-pass/unique-copy-box.rs b/src/test/run-pass/unique-copy-box.rs deleted file mode 100644 index 7bb0fe5faa1..00000000000 --- a/src/test/run-pass/unique-copy-box.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2012 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(managed_boxes)]; -#[allow(unused_variable)]; - -use std::managed; - -pub fn main() { - let i = ~@1; - let j = ~@2; - let rc1 = managed::refcount(*i); - let j = i.clone(); - let rc2 = managed::refcount(*i); - println!("rc1: {} rc2: {}", rc1, rc2); - assert_eq!(rc1 + 1u, rc2); -}