]> git.lizzy.rs Git - rust.git/commitdiff
Auto merge of #43605 - RalfJung:mapdoc, r=michaelwoerister
authorbors <bors@rust-lang.org>
Wed, 2 Aug 2017 13:40:35 +0000 (13:40 +0000)
committerbors <bors@rust-lang.org>
Wed, 2 Aug 2017 13:40:35 +0000 (13:40 +0000)
Improve hir::map::Map::get_parent_node doc

The documentation says
```
    /// Similar to get_parent, returns the parent node id or id if there is no
    /// parent.
    /// This function returns the immediate parent in the AST, whereas get_parent
    /// returns the enclosing item.
```
One would think that one can walk up the tree by repeatedly calling `get_parent_node` until it returns the argument, and then work on the `NodeId`s that arise. However, that is not true: `get_parent_node` will return id 0 (the crate itself) for items that sit directly in the crate; calling `get` on that `NodeId` will panic.

So, the fact that `get_parent_node` returns the root when passed the root is actually not really useful, because the root itself is already a somewhat degenerate node. This improves the doc so hopefully people writing code that "walks up the tree" don't run into this issue like I did...

15 files changed:
src/libcore/cell.rs
src/librustc/hir/map/definitions.rs
src/librustc/ty/mod.rs
src/librustc_data_structures/bitslice.rs
src/librustc_llvm/archive_ro.rs
src/librustc_trans/back/archive.rs
src/librustc_trans/base.rs
src/librustc_trans/metadata.rs
src/librustc_trans/partitioning.rs
src/librustdoc/html/static/rustdoc.css
src/libstd/collections/hash/set.rs
src/libstd/os/solaris/raw.rs
src/libsyntax/codemap.rs
src/libsyntax_pos/lib.rs
src/rustllvm/PassWrapper.cpp

index 35744f3f16b39240f970401eaf8b6bf0963ecad1..21b5557db99f27325ee83a82ce0f2afba123cd14 100644 (file)
 
 /// A mutable memory location.
 ///
+/// # Examples
+///
+/// Here you can see how using `Cell<T>` allows to use mutable field inside
+/// immutable struct (which is also called 'interior mutability').
+///
+/// ```
+/// use std::cell::Cell;
+///
+/// struct SomeStruct {
+///     regular_field: u8,
+///     special_field: Cell<u8>,
+/// }
+///
+/// let my_struct = SomeStruct {
+///     regular_field: 0,
+///     special_field: Cell::new(1),
+/// };
+///
+/// let new_value = 100;
+///
+/// // ERROR, because my_struct is immutable
+/// // my_struct.regular_field = new_value;
+///
+/// // WORKS, although `my_struct` is immutable, field `special_field` is mutable because it is Cell
+/// my_struct.special_field.set(new_value);
+/// assert_eq!(my_struct.special_field.get(), new_value);
+/// ```
+///
 /// See the [module-level documentation](index.html) for more.
 #[stable(feature = "rust1", since = "1.0.0")]
 pub struct Cell<T> {
index 91bce64243e3f0ae98f7d175d48374f7bcbb6ada..cdd5a6e3da7f1a6ff9d6a90abffaf6be1a787bb3 100644 (file)
@@ -18,7 +18,7 @@
 use hir::def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE, DefIndexAddressSpace,
                   CRATE_DEF_INDEX};
 use ich::Fingerprint;
-use rustc_data_structures::fx::{FxHashMap, FxHashSet};
+use rustc_data_structures::fx::FxHashMap;
 use rustc_data_structures::indexed_vec::IndexVec;
 use rustc_data_structures::stable_hasher::StableHasher;
 use serialize::{Encodable, Decodable, Encoder, Decoder};
@@ -153,7 +153,7 @@ pub struct Definitions {
     pub(super) node_to_hir_id: IndexVec<ast::NodeId, hir::HirId>,
     macro_def_scopes: FxHashMap<Mark, DefId>,
     expansions: FxHashMap<DefIndex, Mark>,
-    keys_created: FxHashSet<DefKey>,
+    next_disambiguator: FxHashMap<(DefIndex, DefPathData), u32>,
 }
 
 // Unfortunately we have to provide a manual impl of Clone because of the
@@ -170,7 +170,7 @@ fn clone(&self) -> Self {
             node_to_hir_id: self.node_to_hir_id.clone(),
             macro_def_scopes: self.macro_def_scopes.clone(),
             expansions: self.expansions.clone(),
-            keys_created: self.keys_created.clone(),
+            next_disambiguator: self.next_disambiguator.clone(),
         }
     }
 }
@@ -402,7 +402,7 @@ pub fn new() -> Definitions {
             node_to_hir_id: IndexVec::new(),
             macro_def_scopes: FxHashMap(),
             expansions: FxHashMap(),
-            keys_created: FxHashSet(),
+            next_disambiguator: FxHashMap(),
         }
     }
 
@@ -516,21 +516,21 @@ pub fn create_def_with_parent(&mut self,
         // The root node must be created with create_root_def()
         assert!(data != DefPathData::CrateRoot);
 
-        // Find a unique DefKey. This basically means incrementing the disambiguator
-        // until we get no match.
-        let mut key = DefKey {
+        // Find the next free disambiguator for this key.
+        let disambiguator = {
+            let next_disamb = self.next_disambiguator.entry((parent, data.clone())).or_insert(0);
+            let disambiguator = *next_disamb;
+            *next_disamb = next_disamb.checked_add(1).expect("disambiguator overflow");
+            disambiguator
+        };
+
+        let key = DefKey {
             parent: Some(parent),
             disambiguated_data: DisambiguatedDefPathData {
-                data,
-                disambiguator: 0
+                data, disambiguator
             }
         };
 
-        while self.keys_created.contains(&key) {
-            key.disambiguated_data.disambiguator += 1;
-        }
-        self.keys_created.insert(key.clone());
-
         let parent_hash = self.table.def_path_hash(parent);
         let def_path_hash = key.compute_stable_hash(parent_hash);
 
index e0b0aca1261bf10b034b0f3d9238c27e3f3b1941..f245b1503dab8dc214c6bf72c6d54d8db45cb980 100644 (file)
@@ -174,7 +174,7 @@ pub struct AssociatedItem {
     pub method_has_self_argument: bool,
 }
 
-#[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable)]
+#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, RustcEncodable, RustcDecodable)]
 pub enum AssociatedKind {
     Const,
     Method,
index ba53578e5791852ccc56486325bda181fff1f2e7..f74af6ee1632e793f8f6fef0922f9262443e2eb1 100644 (file)
@@ -134,9 +134,11 @@ pub trait BitwiseOperator {
 
 pub struct Union;
 impl BitwiseOperator for Union {
+    #[inline]
     fn join(&self, a: usize, b: usize) -> usize { a | b }
 }
 pub struct Subtract;
 impl BitwiseOperator for Subtract {
+    #[inline]
     fn join(&self, a: usize, b: usize) -> usize { a & !b }
 }
index b3f5f8e536052c09769d8bb246dcd68f8586d6ad..0b24e55541b07269f52f3f41d5e924c834d6cb74 100644 (file)
@@ -39,14 +39,14 @@ impl ArchiveRO {
     ///
     /// If this archive is used with a mutable method, then an error will be
     /// raised.
-    pub fn open(dst: &Path) -> Option<ArchiveRO> {
+    pub fn open(dst: &Path) -> Result<ArchiveRO, String> {
         return unsafe {
             let s = path2cstr(dst);
             let ar = ::LLVMRustOpenArchive(s.as_ptr());
             if ar.is_null() {
-                None
+                Err(::last_error().unwrap_or("failed to open archive".to_string()))
             } else {
-                Some(ArchiveRO { ptr: ar })
+                Ok(ArchiveRO { ptr: ar })
             }
         };
 
index 902065c8688d0d808fb6c2c29d25c82d8bbd219a..6ec40bd689c23eb963a6ee93679d0d710a2d5c33 100644 (file)
@@ -126,7 +126,7 @@ fn src_archive(&mut self) -> Option<&ArchiveRO> {
             Some(ref src) => src,
             None => return None,
         };
-        self.src_archive = Some(ArchiveRO::open(src));
+        self.src_archive = Some(ArchiveRO::open(src).ok());
         self.src_archive.as_ref().unwrap().as_ref()
     }
 
@@ -186,9 +186,8 @@ fn add_archive<F>(&mut self, archive: &Path, skip: F)
         where F: FnMut(&str) -> bool + 'static
     {
         let archive = match ArchiveRO::open(archive) {
-            Some(ar) => ar,
-            None => return Err(io::Error::new(io::ErrorKind::Other,
-                                              "failed to open archive")),
+            Ok(ar) => ar,
+            Err(e) => return Err(io::Error::new(io::ErrorKind::Other, e)),
         };
         self.additions.push(Addition::Archive {
             archive: archive,
index 14c73de64bc798f80e82768dac05c2f1956ea6fa..49a2885747f6d3dd1da669afab0560def96717b8 100644 (file)
@@ -1172,7 +1172,7 @@ fn module_translation<'a, 'tcx>(
 
         let cgu_name = String::from(cgu.name());
         let cgu_id = cgu.work_product_id();
-        let symbol_name_hash = cgu.compute_symbol_name_hash(scx, &exported_symbols);
+        let symbol_name_hash = cgu.compute_symbol_name_hash(scx);
 
         // Check whether there is a previous work-product we can
         // re-use.  Not only must the file exist, and the inputs not
index 2c0148dfbb371851958c0e4b0c10464818ab0b65..883808c59091a02d60e45f7308fc41af46d6ce08 100644 (file)
@@ -31,10 +31,10 @@ fn get_rlib_metadata(&self, _: &Target, filename: &Path) -> Result<ErasedBoxRef<
         // just keeping the archive along while the metadata is in use.
         let archive = ArchiveRO::open(filename)
             .map(|ar| OwningRef::new(box ar))
-            .ok_or_else(|| {
-                            debug!("llvm didn't like `{}`", filename.display());
-                            format!("failed to read rlib metadata: '{}'", filename.display())
-                        })?;
+            .map_err(|e| {
+                debug!("llvm didn't like `{}`: {}", filename.display(), e);
+                format!("failed to read rlib metadata in '{}': {}", filename.display(), e)
+            })?;
         let buf: OwningRef<_, [u8]> = archive
             .try_map(|ar| {
                 ar.iter()
@@ -42,10 +42,10 @@ fn get_rlib_metadata(&self, _: &Target, filename: &Path) -> Result<ErasedBoxRef<
                     .find(|sect| sect.name() == Some(METADATA_FILENAME))
                     .map(|s| s.data())
                     .ok_or_else(|| {
-                                    debug!("didn't find '{}' in the archive", METADATA_FILENAME);
-                                    format!("failed to read rlib metadata: '{}'",
-                                            filename.display())
-                                })
+                        debug!("didn't find '{}' in the archive", METADATA_FILENAME);
+                        format!("failed to read rlib metadata: '{}'",
+                                filename.display())
+                    })
             })?;
         Ok(buf.erase_owner())
     }
index 904cfb2acd74130da68b3043ce97aad838de2d9e..cff0eca02c60ee4ccaea654f6d436bc8c86721c5 100644 (file)
@@ -174,29 +174,16 @@ pub fn work_product_dep_node(&self) -> DepNode {
     }
 
     pub fn compute_symbol_name_hash<'a>(&self,
-                                        scx: &SharedCrateContext<'a, 'tcx>,
-                                        exported_symbols: &ExportedSymbols)
+                                        scx: &SharedCrateContext<'a, 'tcx>)
                                         -> u64 {
         let mut state = IchHasher::new();
-        let exported_symbols = exported_symbols.local_exports();
         let all_items = self.items_in_deterministic_order(scx.tcx());
-        for (item, _) in all_items {
+        for (item, (linkage, visibility)) in all_items {
             let symbol_name = item.symbol_name(scx.tcx());
             symbol_name.len().hash(&mut state);
             symbol_name.hash(&mut state);
-            let exported = match item {
-                TransItem::Fn(ref instance) => {
-                    let node_id =
-                        scx.tcx().hir.as_local_node_id(instance.def_id());
-                    node_id.map(|node_id| exported_symbols.contains(&node_id))
-                        .unwrap_or(false)
-                }
-                TransItem::Static(node_id) => {
-                    exported_symbols.contains(&node_id)
-                }
-                TransItem::GlobalAsm(..) => true,
-            };
-            exported.hash(&mut state);
+            linkage.hash(&mut state);
+            visibility.hash(&mut state);
         }
         state.finish().to_smaller_hash()
     }
index 858ef3bf411d481ee6b5b68db2b1d45918a9ea07..b6a342ea3b0dc8fb1a46b4efd35d33be9ef500bb 100644 (file)
@@ -274,9 +274,13 @@ nav.sub {
        border-bottom: 1px solid;
 }
 
-.docblock h1 { font-size: 1.3em; }
-.docblock h2 { font-size: 1.15em; }
-.docblock h3, .docblock h4, .docblock h5 { font-size: 1em; }
+#main > .docblock h1 { font-size: 1.3em; }
+#main > .docblock h2 { font-size: 1.15em; }
+#main > .docblock h3, #main > .docblock h4, #main > .docblock h5 { font-size: 1em; }
+
+.docblock h1 { font-size: 1em; }
+.docblock h2 { font-size: 0.95em; }
+.docblock h3, .docblock h4, .docblock h5 { font-size: 0.9em; }
 
 .docblock {
        margin-left: 24px;
index d80df5f18b610ba3f6df437aba1ac522371aa7f1..80a223c7d74eaae6dcf72231c747749c063afe4b 100644 (file)
@@ -123,13 +123,13 @@ pub struct HashSet<T, S = RandomState> {
 }
 
 impl<T: Hash + Eq> HashSet<T, RandomState> {
-    /// Creates an empty HashSet.
+    /// Creates an empty `HashSet`.
     ///
     /// # Examples
     ///
     /// ```
     /// use std::collections::HashSet;
-    /// let mut set: HashSet<i32> = HashSet::new();
+    /// let set: HashSet<i32> = HashSet::new();
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
@@ -146,7 +146,8 @@ pub fn new() -> HashSet<T, RandomState> {
     ///
     /// ```
     /// use std::collections::HashSet;
-    /// let mut set: HashSet<i32> = HashSet::with_capacity(10);
+    /// let set: HashSet<i32> = HashSet::with_capacity(10);
+    /// assert!(set.capacity() >= 10);
     /// ```
     #[inline]
     #[stable(feature = "rust1", since = "1.0.0")]
@@ -215,6 +216,17 @@ pub fn with_capacity_and_hasher(capacity: usize, hasher: S) -> HashSet<T, S> {
     /// Returns a reference to the set's [`BuildHasher`].
     ///
     /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::collections::HashSet;
+    /// use std::collections::hash_map::RandomState;
+    ///
+    /// let hasher = RandomState::new();
+    /// let set: HashSet<i32> = HashSet::with_hasher(hasher);
+    /// let hasher: &RandomState = set.hasher();
+    /// ```
     #[stable(feature = "hashmap_public_hasher", since = "1.9.0")]
     pub fn hasher(&self) -> &S {
         self.map.hasher()
@@ -249,6 +261,7 @@ pub fn capacity(&self) -> usize {
     /// use std::collections::HashSet;
     /// let mut set: HashSet<i32> = HashSet::new();
     /// set.reserve(10);
+    /// assert!(set.capacity() >= 10);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn reserve(&mut self, additional: usize) {
@@ -312,13 +325,13 @@ pub fn iter(&self) -> Iter<T> {
     ///     println!("{}", x); // Print 1
     /// }
     ///
-    /// let diff: HashSet<_> = a.difference(&b).cloned().collect();
-    /// assert_eq!(diff, [1].iter().cloned().collect());
+    /// let diff: HashSet<_> = a.difference(&b).collect();
+    /// assert_eq!(diff, [1].iter().collect());
     ///
     /// // Note that difference is not symmetric,
     /// // and `b - a` means something else:
-    /// let diff: HashSet<_> = b.difference(&a).cloned().collect();
-    /// assert_eq!(diff, [4].iter().cloned().collect());
+    /// let diff: HashSet<_> = b.difference(&a).collect();
+    /// assert_eq!(diff, [4].iter().collect());
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S> {
@@ -343,11 +356,11 @@ pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S
     ///     println!("{}", x);
     /// }
     ///
-    /// let diff1: HashSet<_> = a.symmetric_difference(&b).cloned().collect();
-    /// let diff2: HashSet<_> = b.symmetric_difference(&a).cloned().collect();
+    /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
+    /// let diff2: HashSet<_> = b.symmetric_difference(&a).collect();
     ///
     /// assert_eq!(diff1, diff2);
-    /// assert_eq!(diff1, [1, 4].iter().cloned().collect());
+    /// assert_eq!(diff1, [1, 4].iter().collect());
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn symmetric_difference<'a>(&'a self,
@@ -371,8 +384,8 @@ pub fn symmetric_difference<'a>(&'a self,
     ///     println!("{}", x);
     /// }
     ///
-    /// let intersection: HashSet<_> = a.intersection(&b).cloned().collect();
-    /// assert_eq!(intersection, [2, 3].iter().cloned().collect());
+    /// let intersection: HashSet<_> = a.intersection(&b).collect();
+    /// assert_eq!(intersection, [2, 3].iter().collect());
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S> {
@@ -397,8 +410,8 @@ pub fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a,
     ///     println!("{}", x);
     /// }
     ///
-    /// let union: HashSet<_> = a.union(&b).cloned().collect();
-    /// assert_eq!(union, [1, 2, 3, 4].iter().cloned().collect());
+    /// let union: HashSet<_> = a.union(&b).collect();
+    /// assert_eq!(union, [1, 2, 3, 4].iter().collect());
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S> {
@@ -440,6 +453,22 @@ pub fn is_empty(&self) -> bool {
     }
 
     /// Clears the set, returning all elements in an iterator.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::collections::HashSet;
+    ///
+    /// let mut set: HashSet<_> = [1, 2, 3].iter().cloned().collect();
+    /// assert!(!set.is_empty());
+    ///
+    /// // print 1, 2, 3 in an arbitrary order
+    /// for i in set.drain() {
+    ///     println!("{}", i);
+    /// }
+    ///
+    /// assert!(set.is_empty());
+    /// ```
     #[inline]
     #[stable(feature = "drain", since = "1.6.0")]
     pub fn drain(&mut self) -> Drain<T> {
index b84fdba9ca25cdb024989fa05ffce38ada0d3935..5a813c5c76bcaea3a24f2e1f0e0339f956799995 100644 (file)
@@ -32,7 +32,7 @@
 #[stable(feature = "raw_ext", since = "1.1.0")] pub type time_t = i64;
 
 #[stable(feature = "pthread_t", since = "1.8.0")]
-pub type pthread_t = usize;
+pub type pthread_t = u32;
 
 #[repr(C)]
 #[derive(Clone)]
index b3d9cf9da36c7669320cb43b956040b5fab6c36d..bfdcae7641dd52f2af9d07454b55982dcbb79eee 100644 (file)
@@ -561,8 +561,9 @@ fn call_span_if_macro(&self, sp: Span) -> Span {
         sp
     }
     fn ensure_filemap_source_present(&self, file_map: Rc<FileMap>) -> bool {
-        let src = self.file_loader.read_file(Path::new(&file_map.name)).ok();
-        return file_map.add_external_src(src)
+        file_map.add_external_src(
+            || self.file_loader.read_file(Path::new(&file_map.name)).ok()
+        )
     }
 }
 
index 3a701f91314b6b2a3084054b1fddec81580940fc..7006f45455e38830f484b10b97aaa287268d63cf 100644 (file)
@@ -618,8 +618,11 @@ pub fn next_line(&self, pos: BytePos) {
     /// If the hash of the input doesn't match or no input is supplied via None,
     /// it is interpreted as an error and the corresponding enum variant is set.
     /// The return value signifies whether some kind of source is present.
-    pub fn add_external_src(&self, src: Option<String>) -> bool {
+    pub fn add_external_src<F>(&self, get_src: F) -> bool
+        where F: FnOnce() -> Option<String>
+    {
         if *self.external_src.borrow() == ExternalSource::AbsentOk {
+            let src = get_src();
             let mut external_src = self.external_src.borrow_mut();
             if let Some(src) = src {
                 let mut hasher: StableHasher<u128> = StableHasher::new();
index 57e90be27748f3e1ca24ffb557007454661b5aa9..bca0881c08c5a35a433f9b61dea2e17e9e8fe178 100644 (file)
@@ -178,10 +178,10 @@ GEN_SUBTARGETS
 
 extern "C" bool LLVMRustHasFeature(LLVMTargetMachineRef TM,
                                    const char *Feature) {
+#if LLVM_RUSTLLVM
   TargetMachine *Target = unwrap(TM);
   const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
   const FeatureBitset &Bits = MCInfo->getFeatureBits();
-#if LLVM_VERSION_GE(4, 0)
   const ArrayRef<SubtargetFeatureKV> FeatTable = MCInfo->getFeatureTable();
 
   for (auto &FeatureEntry : FeatTable)