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.
}
}
- if tool_path.equals(&~"") {
+ if tool_path.is_empty() {
fatal(~"cannot found android cross path");
}
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)
}
~~~
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; }
}
+}
# }
~~~~
* 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)
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
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`
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
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
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
// 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";
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;
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};
}
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()
}
}
priv head: Chunk,
priv pod_head: Chunk,
priv chunks: RefCell<@List<Chunk>>,
- priv no_freeze: marker::NoFreeze,
}
impl Arena {
head: chunk(initial_size, false),
pod_head: chunk(initial_size, true),
chunks: RefCell::new(@Nil),
- no_freeze: marker::NoFreeze,
}
}
}
impl<K: TotalOrd, V: TotalEq> Eq for BTree<K, V> {
fn eq(&self, other: &BTree<K, V>) -> bool {
- self.equals(other)
- }
-}
-
-impl<K: TotalOrd, V: TotalEq> TotalEq for BTree<K, V> {
- ///Testing equality on BTrees by comparing the root.
- fn equals(&self, other: &BTree<K, V>) -> bool {
self.root.cmp(&other.root) == Equal
}
}
+impl<K: TotalOrd, V: TotalEq> TotalEq for BTree<K, V> {}
+
impl<K: TotalOrd, V: TotalEq> Ord for BTree<K, V> {
fn lt(&self, other: &BTree<K, V>) -> bool {
self.cmp(other) == Less
impl<K: TotalOrd, V: TotalEq> Eq for Node<K, V> {
fn eq(&self, other: &Node<K, V>) -> bool {
- self.equals(other)
- }
-}
-
-impl<K: TotalOrd, V: TotalEq> TotalEq for Node<K, V> {
- ///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<K, V>) -> bool{
match *self{
BranchNode(ref branch) => {
if other.is_leaf() {
}
}
+impl<K: TotalOrd, V: TotalEq> TotalEq for Node<K, V> {}
+
impl<K: TotalOrd, V: TotalEq> Ord for Node<K, V> {
fn lt(&self, other: &Node<K, V>) -> bool {
self.cmp(other) == Less
impl<K: TotalOrd, V: TotalEq> Eq for Leaf<K, V> {
fn eq(&self, other: &Leaf<K, V>) -> bool {
- self.equals(other)
+ self.elts == other.elts
}
}
-impl<K: TotalOrd, V: TotalEq> TotalEq for Leaf<K, V> {
- ///Implementation of equals function for leaves that compares LeafElts.
- fn equals(&self, other: &Leaf<K, V>) -> bool {
- self.elts.equals(&other.elts)
- }
-}
+impl<K: TotalOrd, V: TotalEq> TotalEq for Leaf<K, V> {}
impl<K: TotalOrd, V: TotalEq> Ord for Leaf<K, V> {
fn lt(&self, other: &Leaf<K, V>) -> bool {
impl<K: TotalOrd, V: TotalEq> Eq for Branch<K, V> {
fn eq(&self, other: &Branch<K, V>) -> bool {
- self.equals(other)
+ self.elts == other.elts
}
}
-impl<K: TotalOrd, V: TotalEq> TotalEq for Branch<K, V> {
- ///Equals function for Branches--compares all the elements in each branch
- fn equals(&self, other: &Branch<K, V>) -> bool {
- self.elts.equals(&other.elts)
- }
-}
+impl<K: TotalOrd, V: TotalEq> TotalEq for Branch<K, V> {}
impl<K: TotalOrd, V: TotalEq> Ord for Branch<K, V> {
fn lt(&self, other: &Branch<K, V>) -> bool {
impl<K: TotalOrd, V: TotalEq> Eq for LeafElt<K, V> {
fn eq(&self, other: &LeafElt<K, V>) -> bool {
- self.equals(other)
+ self.key == other.key && self.value == other.value
}
}
-impl<K: TotalOrd, V: TotalEq> TotalEq for LeafElt<K, V> {
- ///TotalEq for LeafElts
- fn equals(&self, other: &LeafElt<K, V>) -> bool {
- self.key.equals(&other.key) && self.value.equals(&other.value)
- }
-}
+impl<K: TotalOrd, V: TotalEq> TotalEq for LeafElt<K, V> {}
impl<K: TotalOrd, V: TotalEq> Ord for LeafElt<K, V> {
fn lt(&self, other: &LeafElt<K, V>) -> bool {
impl<K: TotalOrd, V: TotalEq> Eq for BranchElt<K, V>{
fn eq(&self, other: &BranchElt<K, V>) -> bool {
- self.equals(other)
+ self.key == other.key && self.value == other.value
}
}
-impl<K: TotalOrd, V: TotalEq> TotalEq for BranchElt<K, V>{
- ///TotalEq for BranchElts
- fn equals(&self, other: &BranchElt<K, V>) -> bool {
- self.key.equals(&other.key)&&self.value.equals(&other.value)
- }
-}
+impl<K: TotalOrd, V: TotalEq> TotalEq for BranchElt<K, V>{}
impl<K: TotalOrd, V: TotalEq> Ord for BranchElt<K, V> {
fn lt(&self, other: &BranchElt<K, V>) -> bool {
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.
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<E> {
// We must maintain the invariant that no bits are set
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;
}
/// A hash that is not zero, since we use that to represent empty buckets.
+ #[deriving(Eq)]
pub struct SafeHash {
priv hash: u64,
}
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.
fraction_mul(capacity, load_factor)
}
-impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
+impl<K: TotalEq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
/// 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 {
}
}
-impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> Container for HashMap<K, V, H> {
+impl<K: TotalEq + Hash<S>, V, S, H: Hasher<S>> Container for HashMap<K, V, H> {
/// Return the number of elements in the map
fn len(&self) -> uint { self.table.size() }
}
-impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> Mutable for HashMap<K, V, H> {
+impl<K: TotalEq + Hash<S>, V, S, H: Hasher<S>> Mutable for HashMap<K, V, H> {
/// Clear the map, removing all key-value pairs.
fn clear(&mut self) {
self.minimum_capacity = self.table.size();
}
-impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> Map<K, V> for HashMap<K, V, H> {
+impl<K: TotalEq + Hash<S>, V, S, H: Hasher<S>> Map<K, V> for HashMap<K, V, H> {
fn find<'a>(&'a self, k: &K) -> Option<&'a V> {
self.search(k).map(|idx| {
let (_, v) = self.table.read(&idx);
}
}
-impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> MutableMap<K, V> for HashMap<K, V, H> {
+impl<K: TotalEq + Hash<S>, V, S, H: Hasher<S>> MutableMap<K, V> for HashMap<K, V, H> {
fn find_mut<'a>(&'a mut self, k: &K) -> Option<&'a mut V> {
match self.search(k) {
None => None,
}
}
-impl<K: Hash + Eq, V> HashMap<K, V, sip::SipHasher> {
+impl<K: Hash + TotalEq, V> HashMap<K, V, sip::SipHasher> {
/// Create an empty HashMap.
pub fn new() -> HashMap<K, V, sip::SipHasher> {
HashMap::with_capacity(INITIAL_CAPACITY)
}
}
-impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
+impl<K: TotalEq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
pub fn with_hasher(hasher: H) -> HashMap<K, V, H> {
HashMap::with_capacity_and_hasher(INITIAL_CAPACITY, hasher)
}
}
}
-impl<K: Eq + Hash<S>, V: Clone, S, H: Hasher<S>> HashMap<K, V, H> {
+impl<K: TotalEq + Hash<S>, V: Clone, S, H: Hasher<S>> HashMap<K, V, H> {
/// Like `find`, but returns a copy of the value.
pub fn find_copy(&self, k: &K) -> Option<V> {
self.find(k).map(|v| (*v).clone())
}
}
-impl<K: Eq + Hash<S>, V: Eq, S, H: Hasher<S>> Eq for HashMap<K, V, H> {
+impl<K: TotalEq + Hash<S>, V: Eq, S, H: Hasher<S>> Eq for HashMap<K, V, H> {
fn eq(&self, other: &HashMap<K, V, H>) -> bool {
if self.len() != other.len() { return false; }
}
}
-impl<K: Eq + Hash<S> + Show, V: Show, S, H: Hasher<S>> Show for HashMap<K, V, H> {
+impl<K: TotalEq + Hash<S> + Show, V: Show, S, H: Hasher<S>> Show for HashMap<K, V, H> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f.buf, r"\{"));
}
}
-impl<K: Eq + Hash<S>, V, S, H: Hasher<S> + Default> Default for HashMap<K, V, H> {
+impl<K: TotalEq + Hash<S>, V, S, H: Hasher<S> + Default> Default for HashMap<K, V, H> {
fn default() -> HashMap<K, V, H> {
HashMap::with_capacity_and_hasher(INITIAL_CAPACITY, Default::default())
}
pub type Values<'a, K, V> =
iter::Map<'static, (&'a K, &'a V), &'a V, Entries<'a, K, V>>;
-impl<K: Eq + Hash<S>, V, S, H: Hasher<S> + Default> FromIterator<(K, V)> for HashMap<K, V, H> {
+impl<K: TotalEq + Hash<S>, V, S, H: Hasher<S> + Default> FromIterator<(K, V)> for HashMap<K, V, H> {
fn from_iterator<T: Iterator<(K, V)>>(iter: &mut T) -> HashMap<K, V, H> {
let (lower, _) = iter.size_hint();
let mut map = HashMap::with_capacity_and_hasher(lower, Default::default());
}
}
-impl<K: Eq + Hash<S>, V, S, H: Hasher<S> + Default> Extendable<(K, V)> for HashMap<K, V, H> {
+impl<K: TotalEq + Hash<S>, V, S, H: Hasher<S> + Default> Extendable<(K, V)> for HashMap<K, V, H> {
fn extend<T: Iterator<(K, V)>>(&mut self, iter: &mut T) {
for (k, v) in *iter {
self.insert(k, v);
priv map: HashMap<T, (), H>
}
-impl<T: Eq + Hash<S>, S, H: Hasher<S>> Eq for HashSet<T, H> {
+impl<T: TotalEq + Hash<S>, S, H: Hasher<S>> Eq for HashSet<T, H> {
// 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.
}
}
-impl<T: Eq + Hash<S>, S, H: Hasher<S>> Container for HashSet<T, H> {
+impl<T: TotalEq + Hash<S>, S, H: Hasher<S>> Container for HashSet<T, H> {
/// Return the number of elements in the set
fn len(&self) -> uint { self.map.len() }
}
-impl<T: Eq + Hash<S>, S, H: Hasher<S>> Mutable for HashSet<T, H> {
+impl<T: TotalEq + Hash<S>, S, H: Hasher<S>> Mutable for HashSet<T, H> {
/// Clear the set, removing all values.
fn clear(&mut self) { self.map.clear() }
}
-impl<T: Eq + Hash<S>, S, H: Hasher<S>> Set<T> for HashSet<T, H> {
+impl<T: TotalEq + Hash<S>, S, H: Hasher<S>> Set<T> for HashSet<T, H> {
/// Return true if the set contains a value
fn contains(&self, value: &T) -> bool { self.map.search(value).is_some() }
}
}
-impl<T: Eq + Hash<S>, S, H: Hasher<S>> MutableSet<T> for HashSet<T, H> {
+impl<T: TotalEq + Hash<S>, S, H: Hasher<S>> MutableSet<T> for HashSet<T, H> {
/// 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, ()) }
fn remove(&mut self, value: &T) -> bool { self.map.remove(value) }
}
-impl<T: Hash + Eq> HashSet<T, sip::SipHasher> {
+impl<T: Hash + TotalEq> HashSet<T, sip::SipHasher> {
/// Create an empty HashSet
pub fn new() -> HashSet<T, sip::SipHasher> {
HashSet::with_capacity(INITIAL_CAPACITY)
}
}
-impl<T: Eq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> {
+impl<T: TotalEq + Hash<S>, S, H: Hasher<S>> HashSet<T, H> {
pub fn with_hasher(hasher: H) -> HashSet<T, H> {
HashSet::with_capacity_and_hasher(INITIAL_CAPACITY, hasher)
}
}
-impl<T: Eq + Hash<S> + fmt::Show, S, H: Hasher<S>> fmt::Show for HashSet<T, H> {
+impl<T: TotalEq + Hash<S> + fmt::Show, S, H: Hasher<S>> fmt::Show for HashSet<T, H> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f.buf, r"\{"));
}
}
-impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> FromIterator<T> for HashSet<T, H> {
+impl<T: TotalEq + Hash<S>, S, H: Hasher<S> + Default> FromIterator<T> for HashSet<T, H> {
fn from_iterator<I: Iterator<T>>(iter: &mut I) -> HashSet<T, H> {
let (lower, _) = iter.size_hint();
let mut set = HashSet::with_capacity_and_hasher(lower, Default::default());
}
}
-impl<T: Eq + Hash<S>, S, H: Hasher<S> + Default> Extendable<T> for HashSet<T, H> {
+impl<T: TotalEq + Hash<S>, S, H: Hasher<S> + Default> Extendable<T> for HashSet<T, H> {
fn extend<I: Iterator<T>>(&mut self, iter: &mut I) {
for k in *iter {
self.insert(k);
}
}
-impl<T: Eq + Hash> Default for HashSet<T, sip::SipHasher> {
+impl<T: TotalEq + Hash> Default for HashSet<T, sip::SipHasher> {
fn default() -> HashSet<T> { HashSet::new() }
}
local_data_key!(drop_vector: vec::Vec<int>)
- #[deriving(Hash, Eq)]
+ #[deriving(Hash, Eq, TotalEq)]
struct Dropable {
k: int
}
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;
}
}
+impl<K: TotalEq> TotalEq for KeyRef<K> {}
+
impl<K, V> LruEntry<K, V> {
fn new() -> LruEntry<K, V> {
LruEntry {
}
}
-impl<K: Hash + Eq, V> LruCache<K, V> {
+impl<K: Hash + TotalEq, V> LruCache<K, V> {
/// Create an LRU Cache that holds at most `capacity` items.
pub fn new(capacity: uint) -> LruCache<K, V> {
let cache = LruCache {
}
}
-impl<A: fmt::Show + Hash + Eq, B: fmt::Show> fmt::Show for LruCache<A, B> {
+impl<A: fmt::Show + Hash + TotalEq, B: fmt::Show> fmt::Show for LruCache<A, B> {
/// 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 {
}
}
-impl<K: Hash + Eq, V> Container for LruCache<K, V> {
+impl<K: Hash + TotalEq, V> Container for LruCache<K, V> {
/// Return the number of key-value pairs in the cache.
fn len(&self) -> uint {
self.map.len()
}
}
-impl<K: Hash + Eq, V> Mutable for LruCache<K, V> {
+impl<K: Hash + TotalEq, V> Mutable for LruCache<K, V> {
/// Clear the cache of all key-value pairs.
fn clear(&mut self) {
self.map.clear();
*/
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;
// 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;
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
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]
}
/// 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<Sign> for Sign {
/// Negate Sign value.
#[inline]
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 {
cmp_impl!(impl $imp, $($method -> bool),+)
};
// return something other than a Ratio<T>
- (impl $imp:ident, $($method:ident -> $res:ty),+) => {
+ (impl $imp:ident, $($method:ident -> $res:ty),*) => {
impl<T: Mul<T,T> + $imp> $imp for Ratio<T> {
$(
#[inline]
fn $method(&self, other: &Ratio<T>) -> $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 */
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;
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);
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 }
// 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);
}
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
}
outputs: &OutputFilenames,
id: &CrateId) -> Vec<Path> {
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);
}
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();
// 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) => {
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);
// 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;
// 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());
}
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);
}
// 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 => {}
_ => {
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();
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);
}
// 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
}
};
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 {
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)
}
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()));
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());
}
}
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
}
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 {
#[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;
}
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<Type> {
- 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 {
};
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> {
} 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()),
} else {
None
})
- .to_owned_vec();
+ .collect::<~[&ast::Attribute]>();
for m in link_args.iter() {
match m.meta_item_list() {
Some(items) => {
fn existing_match(e: &Env, crate_id: &CrateId,
hash: Option<&Svh>) -> Option<ast::CrateNum> {
- 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 => {}
// 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.
}
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 {
}
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<CrateSource> {
- 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())
}
ordering: &mut Vec<ast::CrateNum>) {
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(),
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)
}
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());
}
}
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<ast::CrateNum> {
- 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)
}
}
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,
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());
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 {
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);
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 {
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() {
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);
ctor_id: NodeId,
index: @RefCell<Vec<entry<i64>> >,
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));
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);
}
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();
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();
fn add_to_index(item: &Item, ebml_w: &writer::Encoder,
index: @RefCell<Vec<entry<i64>> >) {
- 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(),
});
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));
// 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);
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,
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);
index: @RefCell<Vec<entry<i64>> >,
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));
-> Vec<entry<i64>> {
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,
}
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();
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 => {
}
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);
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
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 => ()
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));
'S' => {
param_bounds.builtin_bounds.add(ty::BoundSend);
}
- 'K' => {
- param_bounds.builtin_bounds.add(ty::BoundFreeze);
- }
'O' => {
param_bounds.builtin_bounds.add(ty::BoundStatic);
}
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);
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;
}
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"),
// 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)
})
- }
+ })
})
}
}
// ______________________________________________________________________
// 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) {
}
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;
}
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 {
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);
})
})
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(
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)
};
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;
}
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,
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) => {
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,
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(())
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);
}
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
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.
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 => { }
// 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,
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);
//
// 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
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
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))
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))
}
fn node_method_ty(&self, method_call: typeck::MethodCall) -> Option<ty::t> {
- 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<ast::NodeId> {
}
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)
}
}
}
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 {
* 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,
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
}
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<MovePathIndex> {
- 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,
* 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);
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,
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 {
};
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);
}
}
* 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");
}
}
}
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);
*/
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))
})
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
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,
};
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 {
}
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 {
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)
}
}
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");
}
"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(_, _, _)) |
}
}
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.
_ => {
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), ());
// 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();
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)) => {
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)
}
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 }
}
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 {
}
}
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();
}
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);
}
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 {
}
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)
}
}
} 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,
},
_ => None
};
- tcx.extern_const_variants.borrow_mut().get().insert(variant_def, e);
+ tcx.extern_const_variants.borrow_mut().insert(variant_def, e);
return e;
}
}
}
}
} 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,
},
_ => 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;
}
}
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),
}
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,
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]) {
}
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
};
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) => {
// 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;
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 => {}
}
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) {
}
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;
}
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
}
// 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
}
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);
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);
}
// 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()
}
_ => {
}
}
};
- 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 \
}
// 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(..) |
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()) {
// 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".
//
}
pub fn to_builtin_kind(&self, id: ast::DefId) -> Option<ty::BuiltinBound> {
- 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)
lets_do_this! {
// Variant name, Name, Method name;
- FreezeTraitLangItem, "freeze", freeze_trait;
SendTraitLangItem, "send", send_trait;
SizedTraitLangItem, "sized", sized_trait;
PodTraitLangItem, "pod", pod_trait;
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;
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 \
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;
}
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.
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");
}
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");
}
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, .. }) => {
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 {
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) => {
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() {
// 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))
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));
// 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));
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")
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);
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);
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
}
// different kinds of pointers:
-#[deriving(Eq, Hash)]
+#[deriving(Eq, TotalEq, Hash)]
pub enum PointerKind {
OwnedPtr,
GcPtr,
// 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.
}
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)
}
// 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)
}
}
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() {
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);
// `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);
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);
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;
}
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
}
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
}
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);
// 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);
}
}
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 {
// 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
// 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"),
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);
}
}
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 \
}
}
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,
}
}
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,
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)
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,
}
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) {
// 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);
}
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);
}
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) {
*/
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<ast::NodeId> {
//! 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); }
}
/*!
* 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); }
}
//! 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);
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;
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);
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 {
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);
ArgumentIrrefutableMode,
}
-#[deriving(Eq, Hash)]
+#[deriving(Eq, TotalEq, Hash)]
enum Namespace {
TypeNS,
ValueNS
}
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()
}
}
/// 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
}
// 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) => {
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() &&
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"),
}
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);
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
}
}
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"),
}
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.
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");
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);
}
}
}
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);
}
}
}
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.
// 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);
}
}
}
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
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 =
// 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 {
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))}
},
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))}
},
// 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(),
}
// 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 =
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) => {
// 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 => {}
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) => {
// 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.
}
// 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 =
// 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.
}
}
}
// 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 {
// 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 =
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_);
}
}
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);
}
}
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);
}
fn add_exports_for_module(&mut self,
exports2: &mut Vec<Export2> ,
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
}
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),
// 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
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);
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,
}
});
- 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) => {
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;
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);
}
}
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,
block: P<Block>) {
// 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| {
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,
// 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,
}
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() {
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 \
// 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");
}
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) => {
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));
}
}
}
// 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) => {
// 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() {
};
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) => {
span: Span)
-> Option<Def> {
// 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)) => {
let mut maybes: Vec<token::InternedString> = Vec::new();
let mut values: Vec<uint> = 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);
}
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, ());
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 `{}`",
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 {
// 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
// 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,
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
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 = ~""; }
fn subst_spanned(&self, tcx: &ty::ctxt,
substs: &ty::substs,
span: Option<Span>) -> Rc<T> {
- Rc::new(self.deref().subst_spanned(tcx, substs, span))
+ Rc::new((**self).subst_spanned(tcx, substs, span))
}
}
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() {
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())
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;
}
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,
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(..)) => {
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)
})
}
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
bcx: &'a Block<'a>,
sp: Span,
msg: InternedString,
- finished: @Cell<Option<BasicBlockRef>>,
+ finished: Cell<Option<BasicBlockRef>>,
}
impl<'a> DynamicFailureHandler<'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,
}
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;
}
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,
// 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(
BindLocal => bcx.fcx.lllocals.borrow_mut(),
BindArgument => bcx.fcx.llargs.borrow_mut()
};
- llmap.get().insert(p_id, datum);
+ llmap.insert(p_id, datum);
bcx
}
}
}
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,
}
}
}
- 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.
}
}
}
- Some(&ast::DefStatic(_, false)) => {
+ Some(ast::DefStatic(_, false)) => {
}
_ => {
// Nothing to do here.
/// 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;
}
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);
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
}
}
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;
}
// 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);
}
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())
}
}
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)
}
}
}
}
_ => {
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)
}
}
}
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");
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);
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,
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);
}
}
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);
}
}
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
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);
})
}
}
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()));
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)
}
};
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)),
* 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;
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();
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();
}
* 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 {
/*!
* 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) => {
}
fn top_nonempty_cleanup_scope(&self) -> Option<uint> {
- 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
}
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> {
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<R>(&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,
// 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 => {
}
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(
// 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
}
};
- {
- 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();
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 {
}
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!(
// 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,
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
}
}
}
// 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_id> >),
mono_any,
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)
}
}
-#[deriving(Eq, Hash)]
+#[deriving(Eq, TotalEq, Hash)]
pub struct mono_id_ {
def: ast::DefId,
params: Vec<mono_param_id> }
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)
}
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()
}
};
}
}
-pub fn node_vtables(bcx: &Block, id: ast::NodeId)
+pub fn node_vtables(bcx: &Block, id: typeck::MethodCall)
-> Option<typeck::vtable_res> {
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))
}
-> (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)
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
}
}
}
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
};
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);
}
}
- 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) {
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 {
}
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| {
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,
};
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),
}
}
}
- }).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))
})
// 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) {
}
}
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);
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);
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))
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));
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,
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));
}
};
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));
}
};
}
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);
};
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);
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);
}
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);
});
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;
}
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);
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,
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);
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),
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
{
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);
}
}
];
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,
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,
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,
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<DIType> =
Vec::with_capacity(signature.inputs.len() + 1);
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);
-> 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,
_ => 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
}
}
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!");
}
}
&mut HashMap<ast::NodeId, DIScope>|) {
// 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 {
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 {
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 => {
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
}
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));
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()));
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))
}
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));
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;
}
}
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
}
}
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!(
}
}
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!(
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);
// 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);
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 => {
rhs: Option<(Datum<Expr>, ast::NodeId)>,
dest: Option<Dest>)
-> 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),
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"));
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) => {
// 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
}
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());
}
}
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,
_ => { }
}
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");
// 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
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
}
}
|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);
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 {
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;
}
}
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);
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()));
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) {
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
}
// 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())
// 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.
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;
}
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());
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);
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
};
"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| {
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
};
}
};
- {
- 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)
// 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 {
}
};
- 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);
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;
}
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 {
//
// (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)
}
// Data types
-#[deriving(Eq, Hash)]
+#[deriving(Eq, TotalEq, Hash)]
pub struct field {
ident: ast::Ident,
mt: mt
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
// 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,
}
}
+impl TotalEq for intern_key {}
+
impl<W:Writer> Hash<W> for intern_key {
fn hash(&self, s: &mut W) {
unsafe { (*self.sty).hash(s) }
// 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 {
}
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,
* - `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<t>,
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
* 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,
* 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<ty::Region>)
* - `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<ty::t>,
tps: Vec<t>,
// 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,
ty_unboxed_vec(mt),
}
-#[deriving(Clone, Eq, Hash)]
+#[deriving(Clone, Eq, TotalEq, Hash)]
pub struct TyTrait {
def_id: DefId,
substs: substs,
bounds: BuiltinBounds
}
-#[deriving(Eq, Hash)]
+#[deriving(Eq, TotalEq, Hash)]
pub struct TraitRef {
def_id: DefId,
substs: substs
terr_variadic_mismatch(expected_found<bool>)
}
-#[deriving(Eq, Hash)]
+#[deriving(Eq, TotalEq, Hash)]
pub struct ParamBounds {
builtin_bounds: BuiltinBounds,
trait_bounds: Vec<@TraitRef> }
pub type BuiltinBounds = EnumSet<BuiltinBound>;
-#[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,
let mut set = EnumSet::empty();
set.add(BoundStatic);
set.add(BoundSend);
- set.add(BoundFreeze);
set.add(BoundSized);
set.add(BoundShare);
set
}
}
-#[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)
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()
}
}
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;
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);
// 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;
}
// 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,
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),
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)
}
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()
}
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,
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
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())
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
tc = tc - match bound {
BoundStatic => TC::Nonstatic,
BoundSend => TC::Nonsendable,
- BoundFreeze => TC::Nonfreezable,
BoundSized => TC::Nonsized,
BoundPod => TC::Nonpod,
BoundShare => TC::Nonsharable,
// 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;
}
}
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 `{}`",
}
pub fn try_node_id_to_type(cx: &ctxt, id: ast::NodeId) -> Option<t> {
- 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 {
}
pub fn node_id_to_type_opt(cx: &ctxt, id: ast::NodeId) -> Option<t> {
- 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
}
// 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<t> {
- 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 {
*/
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)
})
}
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!(
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 {
}
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
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"),
};
}
pub fn provided_source(cx: &ctxt, id: ast::DefId) -> Option<ast::DefId> {
- 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> {
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
// 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;
}
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<DefId> {
- 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 {
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,
/* 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");
}
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 {
}
};
- {
- 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
}
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
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;
}
}
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)
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 {
pub fn get_tydesc_ty(tcx: &ctxt) -> Result<t, ~str> {
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<t, ~str> {
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")
})
}
}
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))
}
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
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,
// 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);
}
}
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
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,
// 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.
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),
/// Otherwise, return `None`.
pub fn trait_method_of_method(tcx: &ctxt,
def_id: ast::DefId) -> Option<ast::DefId> {
- 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) => {
pub fn ast_ty_to_prim_ty(tcx: &ty::ctxt, ast_ty: &ast::Ty) -> Option<ty::t> {
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
// Note that the "bounds must be empty if path is not a trait"
// restriction is enforced in the below case for ty_path, which
// will run after this as long as the path isn't a trait.
- let def_map = tcx.def_map.borrow();
- match def_map.get().find(&id) {
+ match tcx.def_map.borrow().find(&id) {
Some(&ast::DefPrimTy(ast::TyStr)) if
a_seq_ty.mutbl == ast::MutImmutable => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
let tcx = this.tcx();
- {
- let mut ast_ty_to_ty_cache = tcx.ast_ty_to_ty_cache.borrow_mut();
- match ast_ty_to_ty_cache.get().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");
- }
- 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(),
ty::mk_closure(tcx, fn_decl)
}
ast::TyPath(ref path, ref bounds, 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
}
});
- let mut ast_ty_to_ty_cache = tcx.ast_ty_to_ty_cache.borrow_mut();
- ast_ty_to_ty_cache.get().insert(ast_ty.id, ty::atttce_resolved(typ));
+ tcx.ast_ty_to_ty_cache.borrow_mut().insert(ast_ty.id, ty::atttce_resolved(typ));
return typ;
}
let class_fields = ty::lookup_struct_fields(tcx, struct_id);
// Check to ensure that the struct is the one 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::DefStruct(supplied_def_id))
if supplied_def_id == struct_id => {
// OK.
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.
}
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);
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,
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);
}
}
// 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);
}
}
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);
}
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);
}
}
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()),
}
}
// 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);
}
}
}
_ => 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, ());
}
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)));
}
_ => {}
}
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);
}
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(
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) {
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);
}
}
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) {
}
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 {}",
}
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(
}
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(
}
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(
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
}
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 => {}
}
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 => {
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)
}
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);
expected: Option<ty::t>) {
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, || {
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);
}
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");
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);
(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,
}
}
fn resolve_method_type(&self, method_call: MethodCall) -> Option<ty::t> {
- 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))
}
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))
}
}
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<ast::NodeId> {
}
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)
}
}
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}) => {
// 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);
// 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(\
// 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()),
// 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);
}
// 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);
}
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);
}
// 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.
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) {
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
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,
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
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);
}
}
}
}
// 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,
b);
resolve_object_cast(ex, object_ty);
}
- AutoAddEnv(..) | AutoDerefRef(..) => {}
+ AutoAddEnv(..) => {}
}
}
None => {}
};
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.
pub fn trans_resolve_method(tcx: &ty::ctxt, id: ast::NodeId,
substs: &ty::substs) -> Option<vtable_res> {
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),
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;
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));
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)
+ }
}
- }
+ }))
}
}
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) => {
// 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(..)) |
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);
}
}
}
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| {
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);
}
}
}
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, _) => {
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) => {
};
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);
}
}
- 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
};
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);
}
}
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,
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);
}
}
}
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);
}
}
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
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;
}
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;
// 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
};
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;
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.
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() {
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);
}
&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
});
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.
}
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));
// 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),
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),
// 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();
}
}
- 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
}
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
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,
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:
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);
},
// 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
+ });
}
}
}
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,
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;
}
_ => {
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 {
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 => {
-> 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, _) => {
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 = {
}
};
- 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) => {
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(..) => {
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(_) |
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,
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()),
* 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 {
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;
}
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);
}
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,
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
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();
}
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);
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
})
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);
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
}
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
}
mod doc;
-#[deriving(Eq, Hash)]
+#[deriving(Eq, TotalEq, Hash)]
pub enum Constraint {
ConstrainVarSubVar(RegionVid, RegionVid),
ConstrainRegSubVar(Region, RegionVid),
ConstrainRegSubReg(Region, Region),
}
-#[deriving(Eq, Hash)]
+#[deriving(Eq, TotalEq, Hash)]
pub struct TwoRegions {
a: Region,
b: Region,
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));
}
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,
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));
}
}
}
}
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!"))
}
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)));
pub fn vars_created_since_snapshot(&self, snapshot: uint)
-> Vec<RegionVid> {
- 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
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
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
}
};
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
}
}
}
(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));
}
(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));
}
&self,
errors: &mut Vec<RegionResolutionError>)
{
- 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(..) |
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));
}
}
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);
}
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()),
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,
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,
}
}
- 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,
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)
});
}
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 {}",
let tcx = self.tcx;
let vb = UnifyVid::appropriate_vals_and_bindings(self);
- let mut vb = vb.borrow_mut();
- return helper(tcx, vb.get(), vid);
+ return helper(tcx, &mut *vb.borrow_mut(), vid);
fn helper<T:Clone, V:Clone+Eq+Vid>(
tcx: &ty::ctxt,
let vb = UnifyVid::appropriate_vals_and_bindings(self);
let mut vb = vb.borrow_mut();
- let old_v = (*vb.get().vals.get(&vid.to_uint())).clone();
- vb.get().bindings.push((vid.clone(), old_v));
- vb.get().vals.insert(vid.to_uint(), new_v);
+ let old_v = (*vb.vals.get(&vid.to_uint())).clone();
+ vb.bindings.push((vid.clone(), old_v));
+ vb.vals.insert(vid.to_uint(), new_v);
}
fn unify<T:Clone + InferStr,
use util::common::time;
use util::ppaux::Repr;
use util::ppaux;
-use util::nodemap::{DefIdMap, FnvHashMap, NodeMap};
+use util::nodemap::{DefIdMap, FnvHashMap};
use std::cell::RefCell;
use std::rc::Rc;
substs: ty::substs
}
-#[deriving(Clone, Eq, Hash)]
+#[deriving(Clone, Eq, TotalEq, Hash, Show)]
pub struct MethodCall {
expr_id: ast::NodeId,
autoderef: u32
}
}
-pub type vtable_map = @RefCell<NodeMap<vtable_res>>;
+pub type vtable_map = @RefCell<FnvHashMap<MethodCall, vtable_res>>;
// Information about the vtable resolutions for a trait impl.
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,
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,
}
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")
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
};
// "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);
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);
}
}
pub mod FnvHashMap {
use std::hash::Hash;
use collections::HashMap;
- pub fn new<K: Hash<super::FnvState> + Eq, V>() -> super::FnvHashMap<K, V> {
+ pub fn new<K: Hash<super::FnvState> + TotalEq, V>() -> super::FnvHashMap<K, V> {
HashMap::with_hasher(super::FnvHasher)
}
}
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)
res.push(match b {
ty::BoundStatic => ~"'static",
ty::BoundSend => ~"Send",
- ty::BoundFreeze => ~"Freeze",
ty::BoundSized => ~"Sized",
ty::BoundPod => ~"Pod",
ty::BoundShare => ~"Share",
match *self {
ty::BoundStatic => ~"'static",
ty::BoundSend => ~"Send",
- ty::BoundFreeze => ~"Freeze",
ty::BoundSized => ~"Sized",
ty::BoundPod => ~"Pod",
ty::BoundShare => ~"Share",
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(),
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),
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
}
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(),
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)};
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);
})
}
///
/// 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
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, "\\{ \\}"));
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, "<h2 id='methods'>Methods</h2>"));
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
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() {
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);
Ok(())
});
- let slot = chan.deref().borrow();
- match *slot.get() { (_, n) => n }
+ match *chan.borrow() { (_, n) => n }
}
#[test]
#[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";
impl<
E: Encoder,
- K: Encodable<E> + Hash<S> + Eq,
+ K: Encodable<E> + Hash<S> + TotalEq,
V: Encodable<E>,
S,
H: Hasher<S>
impl<
D: Decoder,
- K: Decodable<D> + Hash<S> + Eq,
+ K: Decodable<D> + Hash<S> + TotalEq,
V: Decodable<D>,
S,
H: Hasher<S> + Default
impl<
E: Encoder,
- T: Encodable<E> + Hash<S> + Eq,
+ T: Encodable<E> + Hash<S> + TotalEq,
S,
H: Hasher<S>
> Encodable<E> for HashSet<T, H> {
impl<
D: Decoder,
- T: Decodable<D> + Hash<S> + Eq,
+ T: Decodable<D> + Hash<S> + TotalEq,
S,
H: Hasher<S> + Default
> Decodable<D> for HashSet<T, H> {
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)]
impl<S:Encoder,T:Encodable<S>> Encodable<S> for Rc<T> {
#[inline]
fn encode(&self, s: &mut S) {
- self.deref().encode(s)
+ (**self).encode(s)
}
}
}
}
-impl<S:Encoder,T0:Encodable<S>,T1:Encodable<S>> Encodable<S> 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<D:Decoder,$($name:Decodable<D>),*> Decodable<D> 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<D:Decoder,T0:Decodable<D>,T1:Decodable<D>> Decodable<D> 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<S>,
- T1: Encodable<S>,
- T2: Encodable<S>
-> Encodable<S> 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<S:Encoder,$($name:Encodable<S>),*> Encodable<S> 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<D>,
- T1: Decodable<D>,
- T2: Decodable<D>
-> Decodable<D> 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<S>,
- T1: Encodable<S>,
- T2: Encodable<S>,
- T3: Encodable<S>
-> Encodable<S> 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<D>,
- T1: Decodable<D>,
- T2: Decodable<D>,
- T3: Decodable<D>
-> Decodable<D> 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<S>,
- T1: Encodable<S>,
- T2: Encodable<S>,
- T3: Encodable<S>,
- T4: Encodable<S>
-> Encodable<S> 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<D>,
- T1: Decodable<D>,
- T2: Decodable<D>,
- T3: Decodable<D>,
- T4: Decodable<D>
-> Decodable<D> 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<E: Encoder> Encodable<E> for path::posix::Path {
fn encode(&self, e: &mut E) {
#[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)
}
/// A mutable memory location that admits only `Pod` data.
pub struct Cell<T> {
priv value: Unsafe<T>,
- priv marker1: marker::NoFreeze,
- priv marker2: marker::NoShare,
+ priv noshare: marker::NoShare,
}
impl<T:Pod> Cell<T> {
pub fn new(value: T) -> Cell<T> {
Cell {
value: Unsafe::new(value),
- marker1: marker::NoFreeze,
- marker2: marker::NoShare,
+ noshare: marker::NoShare,
}
}
pub struct RefCell<T> {
priv value: Unsafe<T>,
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
/// Create a new `RefCell` containing `value`
pub fn new(value: T) -> RefCell<T> {
RefCell {
- marker1: marker::NoFreeze,
- marker2: marker::NoPod,
- marker3: marker::NoShare,
value: Unsafe::new(value),
+ nopod: marker::NoPod,
+ noshare: marker::NoShare,
borrow: UNUSED,
}
}
/// 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;
}
}
/// 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<T: Clone> Clone for RefCell<T> {
fn clone(&self) -> RefCell<T> {
- let x = self.borrow();
- RefCell::new(x.get().clone())
+ RefCell::new(self.get())
}
}
impl<T: Eq> Eq for RefCell<T> {
fn eq(&self, other: &RefCell<T>) -> bool {
- let a = self.borrow();
- let b = other.borrow();
- a.get() == b.get()
+ *self.borrow() == *other.borrow()
}
}
}
}
-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<T> for Ref<'b, T> {
#[inline]
fn deref<'a>(&'a self) -> &'a T {
}
}
-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<T> for RefMut<'b, T> {
#[inline]
fn deref<'a>(&'a self) -> &'a T {
}
/// 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.
macro_rules! totaleq_impl(
($t:ty) => {
- impl TotalEq for $t {
- #[inline]
- fn equals(&self, other: &$t) -> bool { *self == *other }
- }
+ impl TotalEq for $t {}
}
)
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 {
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);
priv inner: Flavor<T>,
priv receives: Cell<uint>,
// 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
priv inner: Flavor<T>,
priv sends: Cell<uint>,
// 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
impl<T: Send> Sender<T> {
fn my_new(inner: Flavor<T>) -> Sender<T> {
- 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
impl<T: Send> Receiver<T> {
fn my_new(inner: Flavor<T>) -> Receiver<T> {
- 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
priv tail: *mut Handle<'static, ()>,
priv next_id: Cell<uint>,
priv marker1: marker::NoSend,
- priv marker2: marker::NoFreeze,
}
/// A handle to a receiver which is currently a member of a `Select` set of
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),
}
/// 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),
/// 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
use container::Container;
use io::Writer;
use iter::Iterator;
-use ops::Deref;
use option::{Option, Some, None};
use rc::Rc;
use str::{Str, StrSlice};
impl<S: Writer, T: Hash<S>> Hash<S> for Rc<T> {
#[inline]
fn hash(&self, state: &mut S) {
- self.deref().hash(state);
+ (**self).hash(state);
}
}
fn visit_self(&mut self) -> bool;
}
-#[cfg(stage0)]
-extern "rust-intrinsic" {
- pub fn atomic_cxchg<T>(dst: &mut T, old: T, src: T) -> T;
- pub fn atomic_cxchg_acq<T>(dst: &mut T, old: T, src: T) -> T;
- pub fn atomic_cxchg_rel<T>(dst: &mut T, old: T, src: T) -> T;
- pub fn atomic_cxchg_acqrel<T>(dst: &mut T, old: T, src: T) -> T;
- pub fn atomic_cxchg_relaxed<T>(dst: &mut T, old: T, src: T) -> T;
-
- pub fn atomic_load<T>(src: &T) -> T;
- pub fn atomic_load_acq<T>(src: &T) -> T;
- pub fn atomic_load_relaxed<T>(src: &T) -> T;
-
- pub fn atomic_store<T>(dst: &mut T, val: T);
- pub fn atomic_store_rel<T>(dst: &mut T, val: T);
- pub fn atomic_store_relaxed<T>(dst: &mut T, val: T);
-
- pub fn atomic_xchg<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_xchg_acq<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_xchg_rel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_xchg_acqrel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_xchg_relaxed<T>(dst: &mut T, src: T) -> T;
-
- pub fn atomic_xadd<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_xadd_acq<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_xadd_rel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_xadd_acqrel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_xadd_relaxed<T>(dst: &mut T, src: T) -> T;
-
- pub fn atomic_xsub<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_xsub_acq<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_xsub_rel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_xsub_acqrel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_xsub_relaxed<T>(dst: &mut T, src: T) -> T;
-
- pub fn atomic_and<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_and_acq<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_and_rel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_and_acqrel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_and_relaxed<T>(dst: &mut T, src: T) -> T;
-
- pub fn atomic_nand<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_nand_acq<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_nand_rel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_nand_acqrel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_nand_relaxed<T>(dst: &mut T, src: T) -> T;
-
- pub fn atomic_or<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_or_acq<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_or_rel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_or_acqrel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_or_relaxed<T>(dst: &mut T, src: T) -> T;
-
- pub fn atomic_xor<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_xor_acq<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_xor_rel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_xor_acqrel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_xor_relaxed<T>(dst: &mut T, src: T) -> T;
-
- pub fn atomic_max<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_max_acq<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_max_rel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_max_acqrel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_max_relaxed<T>(dst: &mut T, src: T) -> T;
-
- pub fn atomic_min<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_min_acq<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_min_rel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_min_acqrel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_min_relaxed<T>(dst: &mut T, src: T) -> T;
-
- pub fn atomic_umin<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_umin_acq<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_umin_rel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_umin_acqrel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_umin_relaxed<T>(dst: &mut T, src: T) -> T;
-
- pub fn atomic_umax<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_umax_acq<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_umax_rel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_umax_acqrel<T>(dst: &mut T, src: T) -> T;
- pub fn atomic_umax_relaxed<T>(dst: &mut T, src: T) -> T;
-}
-#[cfg(not(stage0))]
extern "rust-intrinsic" {
// NB: These intrinsics take unsafe pointers because they mutate aliased
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
///
/// ```
pub struct BufferedReader<R> {
priv inner: R,
- priv buf: ~[u8],
+ priv buf: Vec<u8>,
priv pos: uint,
priv cap: uint,
- priv eof: bool,
}
impl<R: Reader> BufferedReader<R> {
// 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,
}
}
/// 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 }
impl<R: Reader> Buffer for BufferedReader<R> {
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))
/// 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
/// ```
pub struct BufferedWriter<W> {
priv inner: Option<W>,
- priv buf: ~[u8],
+ priv buf: Vec<u8>,
priv pos: uint
}
/// Creates a new `BufferedWriter` with the specified buffer capacity
pub fn with_capacity(cap: uint, inner: W) -> BufferedWriter<W> {
// 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),
/// 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 {
/// 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() }
/// 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
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.
}
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();
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.
///
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<A: TotalEq, T: Iterator<A>>(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 },
}
}
}
// 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 {
}
/// Types that can be safely shared between threads, hence thread-safe.
-#[cfg(stage0)]
-pub trait Share {
- // Empty
-}
-
-#[cfg(stage0)]
-impl<T> Share for T {}
-
-/// Types that can be safely shared between threads, hence thread-safe.
-#[cfg(not(stage0))]
#[lang="share"]
pub trait Share {
// Empty
#[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
#[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
#[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
pub mod ptr;
pub mod owned;
-pub mod managed;
+mod managed;
mod reference;
pub mod rc;
pub mod gc;
#[cfg(not(test))] use cmp::*;
-/// Returns the refcount of a shared box (as just before calling this)
-#[inline]
-pub fn refcount<T>(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<T>(a: @T, b: @T) -> bool {
}
#[cfg(not(test))]
-impl<T: TotalEq> TotalEq for @T {
- #[inline]
- fn equals(&self, other: &@T) -> bool { (**self).equals(*other) }
-}
+impl<T: TotalEq> TotalEq for @T {}
#[test]
fn test() {
assert!((!ptr_eq::<int>(x, y)));
assert!((!ptr_eq::<int>(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);
-}
#[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);
}
}
let opt = Some(x);
let _y = opt.unwrap();
}
- assert_eq!(i.deref().get(), 1);
+ assert_eq!(i.get(), 1);
}
#[test]
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),
+ }
}
}
}
#[cfg(not(test))]
-impl<T: TotalEq> TotalEq for ~T {
- #[inline]
- fn equals(&self, other: &~T) -> bool { (**self).equals(*other) }
-}
+impl<T: TotalEq> TotalEq for ~T {}
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};
}
}
+impl TotalEq for Path {}
+
impl FromStr for Path {
fn from_str(s: &str) -> Option<Path> {
Path::new_opt(s)
(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);
}
(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);
(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);
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};
}
}
+impl TotalEq for Path {}
+
impl FromStr for Path {
fn from_str(s: &str) -> Option<Path> {
Path::new_opt(s)
(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);
(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);
(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);
*/
// 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};
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]
fn ne(&self, other: &*T) -> bool { !self.eq(other) }
}
+#[cfg(not(test))]
+impl<T> TotalEq for *T {}
+
#[cfg(not(test))]
impl<T> Eq for *mut T {
#[inline]
fn ne(&self, other: &*mut T) -> bool { !self.eq(other) }
}
+#[cfg(not(test))]
+impl<T> TotalEq for *mut T {}
+
// Equivalence for pointers
#[cfg(not(test))]
impl<T> Equiv<*mut T> for *T {
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};
impl<T: Eq> Eq for Rc<T> {
#[inline(always)]
- fn eq(&self, other: &Rc<T>) -> bool { *self.deref() == *other.deref() }
-
+ fn eq(&self, other: &Rc<T>) -> bool { **self == **other }
#[inline(always)]
- fn ne(&self, other: &Rc<T>) -> bool { *self.deref() != *other.deref() }
+ fn ne(&self, other: &Rc<T>) -> bool { **self != **other }
}
+impl<T: TotalEq> TotalEq for Rc<T> {}
+
impl<T: Ord> Ord for Rc<T> {
#[inline(always)]
- fn lt(&self, other: &Rc<T>) -> bool { *self.deref() < *other.deref() }
+ fn lt(&self, other: &Rc<T>) -> bool { **self < **other }
#[inline(always)]
- fn le(&self, other: &Rc<T>) -> bool { *self.deref() <= *other.deref() }
+ fn le(&self, other: &Rc<T>) -> bool { **self <= **other }
#[inline(always)]
- fn gt(&self, other: &Rc<T>) -> bool { *self.deref() > *other.deref() }
+ fn gt(&self, other: &Rc<T>) -> bool { **self > **other }
#[inline(always)]
- fn ge(&self, other: &Rc<T>) -> bool { *self.deref() >= *other.deref() }
+ fn ge(&self, other: &Rc<T>) -> bool { **self >= **other }
+}
+
+impl<T: TotalOrd> TotalOrd for Rc<T> {
+ #[inline]
+ fn cmp(&self, other: &Rc<T>) -> Ordering { (**self).cmp(&**other) }
}
/// Weak reference to a reference-counted box
#[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]
// 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]
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)...
}
}
#[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 {}
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;
#[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;
#[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();
}
{
let mut a = a.borrow_mut();
- a.get().next = Some(b);
+ a.next = Some(b);
}
}
emit_reset: true,
sdir: range(0, length)
.map(|i| SizeDirection{ size: i, dir: Neg })
- .to_owned_vec()
+ .collect::<~[_]>()
}
}
}
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<T:TotalEq> TotalEq for ~[T] {
- #[inline]
- fn equals(&self, other: &~[T]) -> bool { self.as_slice().equals(&other.as_slice()) }
- }
+ impl<T:TotalEq> TotalEq for ~[T] {}
impl<'a,T:Eq, V: Vector<T>> Equiv<V> for &'a [T] {
#[inline]
let n = task_rng().gen::<uint>() % 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.
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]
/// 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),
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]
impl<'a, S: Str> Equiv<S> for MaybeOwned<'a> {
#[inline]
fn equiv(&self, other: &S) -> bool {
- self.as_slice().equals(&other.as_slice())
+ self.as_slice() == other.as_slice()
}
}
}
}
- 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]
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));
}
+++ /dev/null
-// 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 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-//! 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<uint>,
- priv nopod: marker::NoPod
-}
-
-/// A signed atomic integer type, supporting basic atomic arithmetic operations
-pub struct AtomicInt {
- priv v: Unsafe<int>,
- priv nopod: marker::NoPod
-}
-
-/// An unsigned atomic integer type, supporting basic atomic arithmetic operations
-pub struct AtomicUint {
- priv v: Unsafe<uint>,
- 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<u64>,
- priv nopod: marker::NoPod
-}
-
-/// An unsafe atomic pointer. Only supports basic atomic operations
-pub struct AtomicPtr<T> {
- priv p: Unsafe<uint>,
- 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<T> {
- priv p: Unsafe<uint>,
-}
-
-/// 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<AtomicBool>, 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<T> AtomicPtr<T> {
- /// Create a new `AtomicPtr`
- pub fn new(p: *mut T) -> AtomicPtr<T> {
- 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<T> AtomicOption<T> {
- /// Create a new `AtomicOption`
- pub fn new(p: ~T) -> AtomicOption<T> {
- unsafe { AtomicOption { p: Unsafe::new(cast::transmute(p)) } }
- }
-
- /// Create a new `AtomicOption` that doesn't contain a value
- pub fn empty() -> AtomicOption<T> { 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<T> Drop for AtomicOption<T> {
- fn drop(&mut self) {
- let _ = self.take(SeqCst);
- }
-}
-
-#[inline]
-pub unsafe fn atomic_store<T>(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<T>(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<T>(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<T>(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<T>(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<T>(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<T>(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<T>(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<T>(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<T>(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);
- }
- }
-}
-
}
}
})
- }).to_owned_vec();
+ }).collect::<~[Thread<()>]>();
while remaining.load(SeqCst) > 0 {
match w.pop() {
Thread::start(proc() {
stampede(w, s, 4, 10000);
})
- }).to_owned_vec();
+ }).collect::<~[Thread<()>]>();
for thread in threads.move_iter() {
thread.join();
}
}
})
- }).to_owned_vec();
+ }).collect::<~[Thread<()>]>();
let mut rng = rand::task_rng();
let mut expected = 0;
//! 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;
}
#[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,)+) {
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);
///
/// **NOTE:** Unsafe<T> 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<T> {
/// Wrapped value
marker1: marker::InvariantType<T>
}
-/// Unsafe type for stage0
-#[cfg(stage0)]
-pub struct Unsafe<T> {
- /// Wrapped value
- value: T,
-
- /// Invariance marker
- marker1: marker::InvariantType<T>
-}
-
impl<T> Unsafe<T> {
/// Static constructor
}
#[cfg(not(test))]
-impl TotalEq for () {
- #[inline]
- fn equals(&self, _other: &()) -> bool { true }
-}
+impl TotalEq for () {}
#[cfg(not(test))]
impl Default for () {
}
}
-impl<T: TotalEq> TotalEq for Vec<T> {
- #[inline]
- fn equals(&self, other: &Vec<T>) -> bool {
- self.as_slice().equals(&other.as_slice())
- }
-}
+impl<T: TotalEq> TotalEq for Vec<T> {}
impl<T: TotalOrd> TotalOrd for Vec<T> {
#[inline]
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
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() {
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]));
+ }
}
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> {
/// An Arc with mutable data protected by a blocking mutex.
pub struct MutexArc<T> {
priv x: UnsafeArc<MutexArcInner<T>>,
- priv marker: marker::NoFreeze,
}
impl<T:Send> Clone for MutexArc<T> {
fn clone(&self) -> MutexArc<T> {
// 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() }
}
}
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) }
}
/**
*/
pub struct RWArc<T> {
priv x: UnsafeArc<RWArcInner<T>>,
- priv marker: marker::NoFreeze,
- priv marker1: marker::NoShare,
+ priv marker: marker::NoShare,
}
impl<T: Share + Send> Clone for RWArc<T> {
/// Duplicate a rwlock-protected Arc. See arc::clone for more details.
#[inline]
fn clone(&self) -> RWArc<T> {
- RWArc { x: self.x.clone(),
- marker: marker::NoFreeze,
- marker1: marker::NoShare, }
+ RWArc {
+ x: self.x.clone(),
+ marker: marker::NoShare
+ }
}
}
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
+ }
}
/**
use std::comm;
/// An extension of `pipes::stream` that allows both sending and receiving.
-pub struct DuplexStream<T, U> {
- priv tx: Sender<T>,
- priv rx: Receiver<U>,
+pub struct DuplexStream<S, R> {
+ priv tx: Sender<S>,
+ priv rx: Receiver<R>,
}
/// Creates a bidirectional stream.
-pub fn duplex<T: Send, U: Send>() -> (DuplexStream<T, U>, DuplexStream<U, T>) {
+pub fn duplex<S: Send, R: Send>() -> (DuplexStream<S, R>, DuplexStream<R, S>) {
let (tx1, rx1) = channel();
let (tx2, rx2) = channel();
(DuplexStream { tx: tx1, rx: rx2 },
}
// Allow these methods to be used without import:
-impl<T:Send,U:Send> DuplexStream<T, U> {
- pub fn send(&self, x: T) {
+impl<S:Send,R:Send> DuplexStream<S, R> {
+ 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<U> {
+ pub fn try_recv(&self) -> comm::TryRecvResult<R> {
self.rx.try_recv()
}
- pub fn recv_opt(&self) -> Option<U> {
+ pub fn recv_opt(&self) -> Option<R> {
self.rx.recv_opt()
}
}
/// An extension of `pipes::stream` that provides synchronous message sending.
-pub struct SyncSender<T> { priv duplex_stream: DuplexStream<T, ()> }
+pub struct SyncSender<S> { priv duplex_stream: DuplexStream<S, ()> }
/// An extension of `pipes::stream` that acknowledges each message received.
-pub struct SyncReceiver<T> { priv duplex_stream: DuplexStream<(), T> }
+pub struct SyncReceiver<R> { priv duplex_stream: DuplexStream<(), R> }
-impl<T: Send> SyncSender<T> {
- pub fn send(&self, val: T) {
+impl<S: Send> SyncSender<S> {
+ 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<T: Send> SyncReceiver<T> {
- pub fn recv(&self) -> T {
+impl<R: Send> SyncReceiver<R> {
+ pub fn recv(&self) -> R {
self.recv_opt().expect("SyncReceiver.recv: sending channel closed")
}
- pub fn recv_opt(&self) -> Option<T> {
+ pub fn recv_opt(&self) -> Option<R> {
self.duplex_stream.recv_opt().map(|val| {
self.duplex_stream.try_send(());
val
})
}
- pub fn try_recv(&self) -> comm::TryRecvResult<T> {
+ pub fn try_recv(&self) -> comm::TryRecvResult<R> {
match self.duplex_stream.try_recv() {
comm::Data(t) => { self.duplex_stream.try_send(()); comm::Data(t) }
state => state,
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;
#[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().)
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
}
/// Function name (not all functions have names)
pub type FnIdent = Option<Ident>;
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct Lifetime {
id: NodeId,
span: Span,
// 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
/// 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,
// 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,
default: Option<P<Ty>>
}
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct Generics {
lifetimes: Vec<Lifetime>,
ty_params: OwnedSlice<TyParam>,
}
}
-#[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),
DefMethod(DefId /* method */, Option<DefId> /* 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),
// 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<Attribute> ,
pub type MetaItem = Spanned<MetaItem_>;
-#[deriving(Clone, Encodable, Decodable, Hash)]
+#[deriving(Clone, Encodable, Decodable, TotalEq, Hash)]
pub enum MetaItem_ {
MetaWord(InternedString),
MetaList(InternedString, Vec<@MetaItem> ),
}
}
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct Block {
view_items: Vec<ViewItem> ,
stmts: Vec<@Stmt> ,
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,
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,
}
}
-#[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,
BiGt,
}
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub enum UnOp {
UnBox,
UnUniq,
pub type Stmt = Spanned<Stmt_>;
-#[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),
// FIXME (pending discussion of #1697, #2178...): local should really be
// a refinement on pat.
/// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`
-#[deriving(Eq, Encodable, Decodable, Hash)]
+#[deriving(Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct Local {
ty: P<Ty>,
pat: @Pat,
pub type Decl = Spanned<Decl_>;
-#[deriving(Eq, Encodable, Decodable, Hash)]
+#[deriving(Eq, TotalEq, Encodable, Decodable, Hash)]
pub enum Decl_ {
// a local (let) binding:
DeclLocal(@Local),
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,
pub type SpannedIdent = Spanned<Ident>;
-#[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.
// 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
//
pub type Matcher = Spanned<Matcher_>;
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub enum Matcher_ {
// match one token
MatchTok(::parse::token::Token),
// 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<TokenTree> , SyntaxContext), // new macro-invocation
}
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub enum StrStyle {
CookedStr,
RawStr(uint)
pub type Lit = Spanned<Lit_>;
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub enum Lit_ {
LitStr(InternedString, StrStyle),
LitBinary(Rc<Vec<u8> >),
// 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<Ty>,
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<Attribute> ,
// 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,
}
}
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub enum UintTy {
TyU,
TyU8,
}
}
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub enum FloatTy {
TyF32,
TyF64,
}
// 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_,
}
// 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),
TyChar
}
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub enum Onceness {
Once,
Many
}
}
-#[deriving(Eq, Encodable, Decodable, Hash)]
+#[deriving(Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct ClosureTy {
sigil: Sigil,
region: Option<Lifetime>,
bounds: Option<OwnedSlice<TyParamBound>>,
}
-#[deriving(Eq, Encodable, Decodable, Hash)]
+#[deriving(Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct BareFnTy {
purity: Purity,
abis: AbiSet,
decl: P<FnDecl>
}
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub enum Ty_ {
TyNil,
TyBot, /* bottom type */
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,
dialect: AsmDialect
}
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct Arg {
ty: P<Ty>,
pat: @Pat,
}
}
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct FnDecl {
inputs: Vec<Arg> ,
output: P<Ty>,
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"
}
}
-#[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`
pub type ExplicitSelf = Spanned<ExplicitSelf_>;
-#[deriving(Eq, Encodable, Decodable, Hash)]
+#[deriving(Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct Method {
ident: Ident,
attrs: Vec<Attribute> ,
vis: Visibility,
}
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct Mod {
view_items: Vec<ViewItem> ,
items: Vec<@Item> ,
}
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct ForeignMod {
abis: AbiSet,
view_items: Vec<ViewItem> ,
items: Vec<@ForeignItem> ,
}
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct VariantArg {
ty: P<Ty>,
id: NodeId,
}
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub enum VariantKind {
TupleVariantKind(Vec<VariantArg> ),
StructVariantKind(@StructDef),
}
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct EnumDef {
variants: Vec<P<Variant>> ,
}
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct Variant_ {
name: Ident,
attrs: Vec<Attribute> ,
pub type Variant = Spanned<Variant_>;
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct PathListIdent_ {
name: Ident,
id: NodeId,
pub type ViewPath = Spanned<ViewPath_>;
-#[deriving(Eq, Encodable, Decodable, Hash)]
+#[deriving(Eq, TotalEq, Encodable, Decodable, Hash)]
pub enum ViewPath_ {
// quux = foo::bar::baz
ViewPathList(Path, Vec<PathListIdent> , NodeId)
}
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct ViewItem {
node: ViewItem_,
attrs: Vec<Attribute> ,
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
// 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,
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,
}
}
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct StructField_ {
kind: StructFieldKind,
id: NodeId,
pub type StructField = Spanned<StructField_>;
-#[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<StructField> , /* fields, not including ctor */
/* ID of the constructor. This is only used for tuple- or enum-like
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<Attribute> ,
span: Span,
}
-#[deriving(Clone, Eq, Encodable, Decodable, Hash)]
+#[deriving(Clone, Eq, TotalEq, Encodable, Decodable, Hash)]
pub enum Item_ {
ItemStatic(P<Ty>, Mutability, @Expr),
ItemFn(P<FnDecl>, Purity, AbiSet, Generics, P<Block>),
ItemMac(Mac),
}
-#[deriving(Eq, Encodable, Decodable, Hash)]
+#[deriving(Eq, TotalEq, Encodable, Decodable, Hash)]
pub struct ForeignItem {
ident: Ident,
attrs: Vec<Attribute> ,
vis: Visibility,
}
-#[deriving(Eq, Encodable, Decodable, Hash)]
+#[deriving(Eq, TotalEq, Encodable, Decodable, Hash)]
pub enum ForeignItem_ {
ForeignItemFn(P<FnDecl>, Generics),
ForeignItemStatic(P<Ty>, /* is_mutbl */ bool),
// 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),
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)
}
}
impl Map {
fn find_entry(&self, id: NodeId) -> Option<MapEntry> {
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
}
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);
}
}
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
}).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.);
}
*/
use std::cell::RefCell;
-use std::cmp;
use std::rc::Rc;
use serialize::{Encodable, Decodable, Encoder, Decoder};
/// 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
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<T> {
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<S:Encoder> Encodable<S> for Span {
/* Note #1972 -- spans are encoded but not decoded */
fn encode(&self, s: &mut S) {
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') {
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 {
pub fn new_filemap(&self, filename: FileName, src: ~str) -> Rc<FileMap> {
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.
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
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)
}
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";
}
}
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 {
// 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<FileMap> {
- 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();
}
}
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;
// 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;
}
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}
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);
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}
}
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
}
}
- 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)
}
}
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) {
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) -> ! {
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);
}
}
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();
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 {
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.
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)))
}
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.<method>(); b.<method>(); c.<method>(); ...`
+ // (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 {
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
}
)
};
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 {
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)
}
// 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
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.
}
Some(ts) => ts.clone()
};
- op(table.deref())
+ op(&*table)
})
}
/// 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);
}
}
/// 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());
}
}
Some(ts) => ts.clone()
};
- op(table.deref().borrow_mut().get())
+ op(&mut *table.borrow_mut())
})
}
}
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:
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;
/// 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")
}
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));
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);
}
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));
}
}
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))
}
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)
}
/// 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
}
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
}
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
}
};
return MRDef(MacroDef {
- name: token::get_ident(name).get().to_str(),
+ name: token::get_ident(name).to_str(),
ext: NormalTT(exp, Some(sp))
});
}
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 => {
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 {
}
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);
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) => {
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())
+ });
}
}
}
#[feature(macro_rules, globs, managed_boxes, default_type_params, phase,
quote)];
-#[allow(deprecated_owned_vector)]; // NOTE: remove after stage0
#[allow(deprecated)];
extern crate serialize;
}
}
+impl<T: TotalEq> TotalEq for OwnedSlice<T> {}
+
impl<T> Container for OwnedSlice<T> {
fn len(&self) -> uint { self.len }
}
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,
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
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);
-> ! {
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);
}
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`
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()))
}
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);
pub fn nextch(rdr: &StringReader) -> Option<char> {
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
}
// 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); }
use parse::token;
/// The specific types of unsupported syntax
-#[deriving(Eq, Hash)]
+#[deriving(Eq, TotalEq, Hash)]
pub enum ObsoleteSyntax {
ObsoleteSwap,
ObsoleteUnsafeBlock,
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;
// 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")
}
// 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<uint>,
+ name_idx: &mut uint,
ket: &token::Token)
-> Vec<Matcher> {
let mut ret_val = Vec::new();
return ret_val;
}
- pub fn parse_matcher(&mut self, name_idx: @Cell<uint>) -> 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);
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 {
path: Path,
outer_attrs: Vec<ast::Attribute> ,
id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
- {
- 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,
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);
}
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,
}
#[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,
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),
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)
}
}
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
}
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, "]"));
}
// when traits can extend traits, we should extend index<Name,T> to get []
-impl<T: Eq + Hash + Clone + 'static> Interner<T> {
+impl<T: TotalEq + Hash + Clone + 'static> Interner<T> {
pub fn new() -> Interner<T> {
Interner {
map: RefCell::new(HashMap::new()),
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<Q:Hash + Equiv<T>>(&self, val: &Q) -> Option<Name> {
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();
}
}
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 {
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()
}
}
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
}
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<Q:Hash + Equiv<RcStr>>(&self, val: &Q) -> Option<Name> {
- 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();
}
}
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;
// FIXME (#2807): Windows support.
+/// Terminal color definitions
pub mod color {
+ /// Number for a terminal color
pub type Color = u16;
pub static BLACK: Color = 0u16;
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.
}
}
+/// A Terminal that knows how many colors it supports, with a reference to its
+/// parsed TermInfo database record.
pub struct Terminal<T> {
priv num_colors: u16,
priv out: T,
}
impl<T: Writer> Terminal<T> {
+ /// Returns a wrapped output stream (`Terminal<T>`) 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<Terminal<T>, ~str> {
let term = match os::getenv("TERM") {
Some(t) => t,
/// 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<bool> {
let color = self.dim_if_necessary(color);
if self.num_colors > color {
/// 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<bool> {
let color = self.dim_if_necessary(color);
if self.num_colors > color {
}
/// 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<bool> {
match attr {
attr::ForegroundColor(c) => self.fg(c),
}
/// 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() {
} 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 }
}
// 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> ,
}
pub mod searcher;
+
+/// TermInfo format parsing.
pub mod parser {
+ //! ncurses-compatible compiled terminfo format parsing (term(5))
pub mod compiled;
}
pub mod parm;
}
/// Types of parameters a capability can use
-#[deriving(Clone)]
#[allow(missing_doc)]
+#[deriving(Clone)]
pub enum Param {
String(~str),
Number(int)
#[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;
// 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;
/// Returns a HashMap with the number of occurrences of every element in the
/// sequence that the iterator exposes.
-pub fn freq_count<T: Iterator<U>, U: Eq+Hash>(mut iter: T) -> hashmap::HashMap<U, uint> {
+pub fn freq_count<T: Iterator<U>, U: TotalEq+Hash>(mut iter: T) -> hashmap::HashMap<U, uint> {
let mut map: hashmap::HashMap<U,uint> = hashmap::HashMap::new();
for elem in iter {
map.insert_or_update_with(elem, 1, |_, count| *count += 1);
/// 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,
}
/// An optional subcomponent of a URI authority component.
-#[deriving(Clone, Eq)]
+#[deriving(Clone, Eq, TotalEq)]
pub struct UserInfo {
/// The user name.
user: ~str,
#[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;
}
}
-/// 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<T: Encoder> Encodable<T> for Uuid {
+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
pub fn alist_add<A:'static,B:'static>(lst: &alist<A,B>, 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<A:Clone + 'static,
-> 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();
}
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use std::ops::Deref;
+
+struct DerefWithHelper<H, T> {
+ helper: H
+}
+
+trait Helper<T> {
+ fn helper_borrow<'a>(&'a self) -> &'a T;
+}
+
+impl<T> Helper<T> for Option<T> {
+ fn helper_borrow<'a>(&'a self) -> &'a T {
+ self.as_ref().unwrap()
+ }
+}
+
+impl<T, H: Helper<T>> Deref<T> for DerefWithHelper<H, T> {
+ fn deref<'a>(&'a self) -> &'a T {
+ self.helper.helper_borrow()
+ }
+}
+
+// Test cross-crate autoderef + vtable.
+pub fn check<T: Eq>(x: T, y: T) -> bool {
+ let d: DerefWithHelper<Option<T>, T> = DerefWithHelper { helper: Some(x) };
+ d.eq(&y)
+}
#[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 { }
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());
+++ /dev/null
-// 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 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// 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() {
-}
// 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>(T);
-impl <T:Freeze> RequiresFreeze for X<T> { }
+impl <T:Share> RequiresShare for X<T> { }
-impl <T:Freeze> RequiresRequiresFreezeAndSend for X<T> { } //~ ERROR cannot implement this trait
+impl <T:Share> RequiresRequiresShareAndSend for X<T> { } //~ ERROR cannot implement this trait
fn main() { }
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() { }
fn take_any(_: ||:) {
}
-fn take_const_owned(_: ||:Freeze+Send) {
+fn take_const_owned(_: ||:Share+Send) {
}
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() {}
concat!(test!());
//~^ ERROR: macro undefined: 'test'
- //~^^ ERROR: expected a literal
}
//~^ 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());
}
+++ /dev/null
-// 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 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-// Test which of the builtin types are considered freezeable.
-
-
-fn assert_freeze<T: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::<Vec<int> >();
-
- // 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() {
-}
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
}
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
}
}
use std::kinds::marker;
-enum Foo { A(marker::NoFreeze) }
+enum Foo { A(marker::NoShare) }
-fn bar<T: Freeze>(_: T) {}
+fn bar<T: Share>(_: T) {}
fn main() {
- let x = A(marker::NoFreeze);
+ let x = A(marker::NoShare);
bar(&x); //~ ERROR type parameter with an incompatible type
}
// except according to those terms.
fn is_send<T: Send>() {}
-fn is_freeze<T: Freeze>() {}
+fn is_freeze<T: Share>() {}
fn is_static<T: 'static>() {}
fn main() {
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// 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);
+}
fn a(_x: ~Foo:Send) {
}
-fn c(x: ~Foo:Freeze+Send) {
+fn c(x: ~Foo:Share+Send) {
a(x);
}
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`
}
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;
}
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)
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)
// 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>(T);
-impl <T: Freeze> RequiresFreeze for X<T> { }
-impl <T: Freeze+Send> RequiresRequiresFreezeAndSend for X<T> { }
+impl <T: Share> RequiresShare for X<T> { }
+impl <T: Share+Send> RequiresRequiresShareAndSend for X<T> { }
-fn foo<T: RequiresRequiresFreezeAndSend>(val: T, chan: Sender<T>) {
+fn foo<T: RequiresRequiresShareAndSend>(val: T, chan: Sender<T>) {
chan.send(val);
}
// 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>(T);
-impl <T:Freeze> RequiresFreeze for X<T> { }
+impl <T:Share> RequiresShare for X<T> { }
-impl <T:Freeze+Send> RequiresRequiresFreezeAndSend for X<T> { }
+impl <T:Share+Send> RequiresRequiresShareAndSend for X<T> { }
impl <T:Pod> RequiresPod for X<T> { }
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);
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);
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);
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);
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") }
assert!(a != b);
assert!(a < b);
- assert!(!a.equals(&b));
assert_eq!(a.cmp(&b), ::std::cmp::Less);
}
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);
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\"");
}
use collections::HashSet;
-#[deriving(Eq, Hash)]
+#[deriving(Eq, TotalEq, Hash)]
struct XYZ {
x: int,
y: int,
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// 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!());
+}
+++ /dev/null
-// 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 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-#[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);
-}
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use std::ops::Deref;
+
+struct DerefWithHelper<H, T> {
+ helper: H
+}
+
+trait Helper<T> {
+ fn helper_borrow<'a>(&'a self) -> &'a T;
+}
+
+impl<T> Helper<T> for Option<T> {
+ fn helper_borrow<'a>(&'a self) -> &'a T {
+ self.as_ref().unwrap()
+ }
+}
+
+impl<T, H: Helper<T>> Deref<T> for DerefWithHelper<H, T> {
+ 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<Option<Foo>, Foo> = DerefWithHelper { helper: Some(Foo {x: 5}) };
+ assert!(x.foo() == 5);
+}
--- /dev/null
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// ignore-fast
+// aux-build:overloaded_autoderef_xc.rs
+
+extern crate overloaded_autoderef_xc;
+
+fn main() {
+ assert!(overloaded_autoderef_xc::check(5, 5));
+}
fn bar<T>(_: T) {}
fn is_send<T: Send>() {}
-fn is_freeze<T: Freeze>() {}
+fn is_freeze<T: Share>() {}
fn is_static<T: 'static>() {}
pub fn main() {
foo::<proc()>();
foo::<proc:()>();
foo::<proc:Send()>();
- foo::<proc:Send + Freeze()>();
- foo::<proc:'static + Send + Freeze()>();
+ foo::<proc:Send + Share()>();
+ foo::<proc:'static + Send + Share()>();
is_send::<proc:Send()>();
- is_freeze::<proc:Freeze()>();
+ is_freeze::<proc:Share()>();
is_static::<proc:'static()>();
}
}
+impl<'tcx> TotalEq for TypeStructure<'tcx> {}
+
struct TypeContext<'tcx, 'ast> {
ty_arena: &'tcx Arena,
types: Vec<Type<'tcx>> ,
}
}
-#[deriving(Eq, Hash)]
+#[deriving(Eq, TotalEq, Hash)]
struct NodeId {
id: uint
}
let mut x = Rc::new(3);
x = x;
- assert!(*x.deref() == 3);
+ assert!(*x == 3);
}
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");
}
fn b(_x: ~Foo:Send) {
}
-fn c(x: ~Foo:Freeze+Send) {
+fn c(x: ~Foo:Share+Send) {
a(x);
}
// 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
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_())
}
}
{
let Tree(t1_) = t1;
let mut t1 = t1_.borrow_mut();
- t1.get().left = Some(t2); // create cycle
+ t1.left = Some(t2); // create cycle
}
}
impl<T:to_str> to_str for Vec<T> {
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(", "))
}
}
let v = empty_pointy();
{
let mut vb = v.borrow_mut();
- vb.get().a = p(v);
+ vb.a = p(v);
}
}
let v = empty_pointy();
{
let mut vb = v.borrow_mut();
- vb.get().a = p(v);
+ vb.a = p(v);
}
}
+++ /dev/null
-// 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 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-#[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);
-}