diff --git a/src/doc/book b/src/doc/book index 6fb3705e52303..c8841f2841a2d 160000 --- a/src/doc/book +++ b/src/doc/book @@ -1 +1 @@ -Subproject commit 6fb3705e5230311b096d47f7e2c91f9ce24393d0 +Subproject commit c8841f2841a2d26124319ddadd1b6a245f9a1856 diff --git a/src/doc/nomicon b/src/doc/nomicon index 9f797e65e6bcc..411197b0e7759 160000 --- a/src/doc/nomicon +++ b/src/doc/nomicon @@ -1 +1 @@ -Subproject commit 9f797e65e6bcc79419975b17aff8e21c9adc039f +Subproject commit 411197b0e77590c967e37e8f6ec681abd359afe8 diff --git a/src/doc/reference b/src/doc/reference index e2f11fe4d6a5e..89dd146154474 160000 --- a/src/doc/reference +++ b/src/doc/reference @@ -1 +1 @@ -Subproject commit e2f11fe4d6a5ecb471c70323197da43c70cb96b6 +Subproject commit 89dd146154474559536d5d4049a03831c501deea diff --git a/src/doc/rust-by-example b/src/doc/rust-by-example index cb369ae95ca36..edd2a7e687358 160000 --- a/src/doc/rust-by-example +++ b/src/doc/rust-by-example @@ -1 +1 @@ -Subproject commit cb369ae95ca36b841960182d26f6d5d9b2e3cc18 +Subproject commit edd2a7e687358712608896730c083cb76c7b401a diff --git a/src/liballoc/benches/btree/set.rs b/src/liballoc/benches/btree/set.rs index d9e75ab7fa4ef..2518506b9b5f3 100644 --- a/src/liballoc/benches/btree/set.rs +++ b/src/liballoc/benches/btree/set.rs @@ -62,6 +62,22 @@ pub fn clone_100_and_clear(b: &mut Bencher) { b.iter(|| src.clone().clear()) } +#[bench] +pub fn clone_100_and_drain_all(b: &mut Bencher) { + let src = pos(100); + b.iter(|| src.clone().drain_filter(|_| true).count()) +} + +#[bench] +pub fn clone_100_and_drain_half(b: &mut Bencher) { + let src = pos(100); + b.iter(|| { + let mut set = src.clone(); + assert_eq!(set.drain_filter(|i| i % 2 == 0).count(), 100 / 2); + assert_eq!(set.len(), 100 / 2); + }) +} + #[bench] pub fn clone_100_and_into_iter(b: &mut Bencher) { let src = pos(100); @@ -115,6 +131,22 @@ pub fn clone_10k_and_clear(b: &mut Bencher) { b.iter(|| src.clone().clear()) } +#[bench] +pub fn clone_10k_and_drain_all(b: &mut Bencher) { + let src = pos(10_000); + b.iter(|| src.clone().drain_filter(|_| true).count()) +} + +#[bench] +pub fn clone_10k_and_drain_half(b: &mut Bencher) { + let src = pos(10_000); + b.iter(|| { + let mut set = src.clone(); + assert_eq!(set.drain_filter(|i| i % 2 == 0).count(), 10_000 / 2); + assert_eq!(set.len(), 10_000 / 2); + }) +} + #[bench] pub fn clone_10k_and_into_iter(b: &mut Bencher) { let src = pos(10_000); diff --git a/src/liballoc/benches/lib.rs b/src/liballoc/benches/lib.rs index 951477a24c8ed..f31717d9fd517 100644 --- a/src/liballoc/benches/lib.rs +++ b/src/liballoc/benches/lib.rs @@ -1,3 +1,4 @@ +#![feature(btree_drain_filter)] #![feature(map_first_last)] #![feature(repr_simd)] #![feature(test)] diff --git a/src/liballoc/collections/btree/map.rs b/src/liballoc/collections/btree/map.rs index bde66c406af7f..bbeced1751d14 100644 --- a/src/liballoc/collections/btree/map.rs +++ b/src/liballoc/collections/btree/map.rs @@ -1256,6 +1256,48 @@ impl BTreeMap { right } + /// Creates an iterator which uses a closure to determine if an element should be removed. + /// + /// If the closure returns true, the element is removed from the map and yielded. + /// If the closure returns false, or panics, the element remains in the map and will not be + /// yielded. + /// + /// Note that `drain_filter` lets you mutate every value in the filter closure, regardless of + /// whether you choose to keep or remove it. + /// + /// If the iterator is only partially consumed or not consumed at all, each of the remaining + /// elements will still be subjected to the closure and removed and dropped if it returns true. + /// + /// It is unspecified how many more elements will be subjected to the closure + /// if a panic occurs in the closure, or a panic occurs while dropping an element, + /// or if the `DrainFilter` value is leaked. + /// + /// # Examples + /// + /// Splitting a map into even and odd keys, reusing the original map: + /// + /// ``` + /// #![feature(btree_drain_filter)] + /// use std::collections::BTreeMap; + /// + /// let mut map: BTreeMap = (0..8).map(|x| (x, x)).collect(); + /// let evens: BTreeMap<_, _> = map.drain_filter(|k, _v| k % 2 == 0).collect(); + /// let odds = map; + /// assert_eq!(evens.keys().copied().collect::>(), vec![0, 2, 4, 6]); + /// assert_eq!(odds.keys().copied().collect::>(), vec![1, 3, 5, 7]); + /// ``` + #[unstable(feature = "btree_drain_filter", issue = "70530")] + pub fn drain_filter(&mut self, pred: F) -> DrainFilter<'_, K, V, F> + where + F: FnMut(&K, &mut V) -> bool, + { + DrainFilter { pred, inner: self.drain_filter_inner() } + } + pub(super) fn drain_filter_inner(&mut self) -> DrainFilterInner<'_, K, V> { + let front = self.root.as_mut().map(|r| r.as_mut().first_leaf_edge()); + DrainFilterInner { length: &mut self.length, cur_leaf_edge: front } + } + /// Calculates the number of elements if it is incorrect. fn recalc_length(&mut self) { fn dfs<'a, K, V>(node: NodeRef, K, V, marker::LeafOrInternal>) -> usize @@ -1653,6 +1695,124 @@ impl Clone for Values<'_, K, V> { } } +/// An iterator produced by calling `drain_filter` on BTreeMap. +#[unstable(feature = "btree_drain_filter", issue = "70530")] +pub struct DrainFilter<'a, K, V, F> +where + K: 'a + Ord, // This Ord bound should be removed before stabilization. + V: 'a, + F: 'a + FnMut(&K, &mut V) -> bool, +{ + pred: F, + inner: DrainFilterInner<'a, K, V>, +} +pub(super) struct DrainFilterInner<'a, K, V> +where + K: 'a + Ord, + V: 'a, +{ + length: &'a mut usize, + cur_leaf_edge: Option, K, V, marker::Leaf>, marker::Edge>>, +} + +#[unstable(feature = "btree_drain_filter", issue = "70530")] +impl<'a, K, V, F> Drop for DrainFilter<'a, K, V, F> +where + K: 'a + Ord, + V: 'a, + F: 'a + FnMut(&K, &mut V) -> bool, +{ + fn drop(&mut self) { + self.for_each(drop); + } +} + +#[unstable(feature = "btree_drain_filter", issue = "70530")] +impl<'a, K, V, F> fmt::Debug for DrainFilter<'a, K, V, F> +where + K: 'a + fmt::Debug + Ord, + V: 'a + fmt::Debug, + F: 'a + FnMut(&K, &mut V) -> bool, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("DrainFilter").field(&self.inner.peek()).finish() + } +} + +#[unstable(feature = "btree_drain_filter", issue = "70530")] +impl<'a, K, V, F> Iterator for DrainFilter<'a, K, V, F> +where + K: 'a + Ord, + V: 'a, + F: 'a + FnMut(&K, &mut V) -> bool, +{ + type Item = (K, V); + + fn next(&mut self) -> Option<(K, V)> { + self.inner.next(&mut self.pred) + } + + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } +} + +impl<'a, K, V> DrainFilterInner<'a, K, V> +where + K: 'a + Ord, + V: 'a, +{ + /// Allow Debug implementations to predict the next element. + pub(super) fn peek(&self) -> Option<(&K, &V)> { + let edge = self.cur_leaf_edge.as_ref()?; + edge.reborrow().next_kv().ok().map(|kv| kv.into_kv()) + } + + unsafe fn next_kv( + &mut self, + ) -> Option, K, V, marker::LeafOrInternal>, marker::KV>> { + let edge = self.cur_leaf_edge.as_ref()?; + ptr::read(edge).next_kv().ok() + } + + /// Implementation of a typical `DrainFilter::next` method, given the predicate. + pub(super) fn next(&mut self, pred: &mut F) -> Option<(K, V)> + where + F: FnMut(&K, &mut V) -> bool, + { + while let Some(kv) = unsafe { self.next_kv() } { + let (k, v) = unsafe { ptr::read(&kv) }.into_kv_mut(); + if pred(k, v) { + *self.length -= 1; + let (k, v, leaf_edge_location) = kv.remove_kv_tracking(); + // `remove_kv_tracking` has either preserved or invalidated `self.cur_leaf_edge` + if let Some(node) = leaf_edge_location { + match search::search_tree(node, &k) { + search::SearchResult::Found(_) => unreachable!(), + search::SearchResult::GoDown(leaf) => self.cur_leaf_edge = Some(leaf), + } + }; + return Some((k, v)); + } + self.cur_leaf_edge = Some(kv.next_leaf_edge()); + } + None + } + + /// Implementation of a typical `DrainFilter::size_hint` method. + pub(super) fn size_hint(&self) -> (usize, Option) { + (0, Some(*self.length)) + } +} + +#[unstable(feature = "btree_drain_filter", issue = "70530")] +impl FusedIterator for DrainFilter<'_, K, V, F> +where + K: Ord, + F: FnMut(&K, &mut V) -> bool, +{ +} + #[stable(feature = "btree_range", since = "1.17.0")] impl<'a, K, V> Iterator for Range<'a, K, V> { type Item = (&'a K, &'a V); @@ -2531,12 +2691,31 @@ impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> { fn remove_kv(self) -> (K, V) { *self.length -= 1; - let (small_leaf, old_key, old_val) = match self.handle.force() { + let (old_key, old_val, _) = self.handle.remove_kv_tracking(); + (old_key, old_val) + } +} + +impl<'a, K: 'a, V: 'a> Handle, K, V, marker::LeafOrInternal>, marker::KV> { + /// Removes a key/value-pair from the map, and returns that pair, as well as + /// the whereabouts of the leaf edge corresponding to that former pair: + /// if None is returned, the leaf edge is still the left leaf edge of the KV handle; + /// if a node is returned, it heads the subtree where the leaf edge may be found. + fn remove_kv_tracking( + self, + ) -> (K, V, Option, K, V, marker::LeafOrInternal>>) { + let mut levels_down_handled: isize; + let (small_leaf, old_key, old_val) = match self.force() { Leaf(leaf) => { + levels_down_handled = 1; // handled at same level, but affects only the right side let (hole, old_key, old_val) = leaf.remove(); (hole.into_node(), old_key, old_val) } Internal(mut internal) => { + // Replace the location freed in the internal node with the next KV, + // and remove that next KV from its leaf. + levels_down_handled = unsafe { ptr::read(&internal).into_node().height() } as isize; + let key_loc = internal.kv_mut().0 as *mut K; let val_loc = internal.kv_mut().1 as *mut V; @@ -2556,27 +2735,39 @@ impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> { let mut cur_node = small_leaf.forget_type(); while cur_node.len() < node::MIN_LEN { match handle_underfull_node(cur_node) { - AtRoot => break, + AtRoot(root) => { + cur_node = root; + break; + } EmptyParent(_) => unreachable!(), Merged(parent) => { + levels_down_handled -= 1; if parent.len() == 0 { // We must be at the root - parent.into_root_mut().pop_level(); + let root = parent.into_root_mut(); + root.pop_level(); + cur_node = root.as_mut(); break; } else { cur_node = parent.forget_type(); } } - Stole(_) => break, + Stole(internal_node) => { + levels_down_handled -= 1; + cur_node = internal_node.forget_type(); + // This internal node might be underfull, but only if it's the root. + break; + } } } - (old_key, old_val) + let leaf_edge_location = if levels_down_handled > 0 { None } else { Some(cur_node) }; + (old_key, old_val, leaf_edge_location) } } enum UnderflowResult<'a, K, V> { - AtRoot, + AtRoot(NodeRef, K, V, marker::LeafOrInternal>), EmptyParent(NodeRef, K, V, marker::Internal>), Merged(NodeRef, K, V, marker::Internal>), Stole(NodeRef, K, V, marker::Internal>), @@ -2585,10 +2776,9 @@ enum UnderflowResult<'a, K, V> { fn handle_underfull_node( node: NodeRef, K, V, marker::LeafOrInternal>, ) -> UnderflowResult<'_, K, V> { - let parent = if let Ok(parent) = node.ascend() { - parent - } else { - return AtRoot; + let parent = match node.ascend() { + Ok(parent) => parent, + Err(root) => return AtRoot(root), }; let (is_left, mut handle) = match parent.left_kv() { diff --git a/src/liballoc/collections/btree/set.rs b/src/liballoc/collections/btree/set.rs index b100ce754caad..0b02223def4f8 100644 --- a/src/liballoc/collections/btree/set.rs +++ b/src/liballoc/collections/btree/set.rs @@ -8,8 +8,8 @@ use core::fmt::{self, Debug}; use core::iter::{FromIterator, FusedIterator, Peekable}; use core::ops::{BitAnd, BitOr, BitXor, RangeBounds, Sub}; +use super::map::{BTreeMap, Keys}; use super::Recover; -use crate::collections::btree_map::{self, BTreeMap, Keys}; // FIXME(conventions): implement bounded iterators @@ -102,7 +102,7 @@ impl fmt::Debug for Iter<'_, T> { #[stable(feature = "rust1", since = "1.0.0")] #[derive(Debug)] pub struct IntoIter { - iter: btree_map::IntoIter, + iter: super::map::IntoIter, } /// An iterator over a sub-range of items in a `BTreeSet`. @@ -115,7 +115,7 @@ pub struct IntoIter { #[derive(Debug)] #[stable(feature = "btree_range", since = "1.17.0")] pub struct Range<'a, T: 'a> { - iter: btree_map::Range<'a, T, ()>, + iter: super::map::Range<'a, T, ()>, } /// Core of SymmetricDifference and Union. @@ -944,6 +944,41 @@ impl BTreeSet { { BTreeSet { map: self.map.split_off(key) } } + + /// Creates an iterator which uses a closure to determine if a value should be removed. + /// + /// If the closure returns true, then the value is removed and yielded. + /// If the closure returns false, the value will remain in the list and will not be yielded + /// by the iterator. + /// + /// If the iterator is only partially consumed or not consumed at all, each of the remaining + /// values will still be subjected to the closure and removed and dropped if it returns true. + /// + /// It is unspecified how many more values will be subjected to the closure + /// if a panic occurs in the closure, or if a panic occurs while dropping a value, or if the + /// `DrainFilter` itself is leaked. + /// + /// # Examples + /// + /// Splitting a set into even and odd values, reusing the original set: + /// + /// ``` + /// #![feature(btree_drain_filter)] + /// use std::collections::BTreeSet; + /// + /// let mut set: BTreeSet = (0..8).collect(); + /// let evens: BTreeSet<_> = set.drain_filter(|v| v % 2 == 0).collect(); + /// let odds = set; + /// assert_eq!(evens.into_iter().collect::>(), vec![0, 2, 4, 6]); + /// assert_eq!(odds.into_iter().collect::>(), vec![1, 3, 5, 7]); + /// ``` + #[unstable(feature = "btree_drain_filter", issue = "70530")] + pub fn drain_filter<'a, F>(&'a mut self, pred: F) -> DrainFilter<'a, T, F> + where + F: 'a + FnMut(&T) -> bool, + { + DrainFilter { pred, inner: self.map.drain_filter_inner() } + } } impl BTreeSet { @@ -1055,6 +1090,66 @@ impl<'a, T> IntoIterator for &'a BTreeSet { } } +/// An iterator produced by calling `drain_filter` on BTreeSet. +#[unstable(feature = "btree_drain_filter", issue = "70530")] +pub struct DrainFilter<'a, T, F> +where + T: 'a + Ord, + F: 'a + FnMut(&T) -> bool, +{ + pred: F, + inner: super::map::DrainFilterInner<'a, T, ()>, +} + +#[unstable(feature = "btree_drain_filter", issue = "70530")] +impl<'a, T, F> Drop for DrainFilter<'a, T, F> +where + T: 'a + Ord, + F: 'a + FnMut(&T) -> bool, +{ + fn drop(&mut self) { + self.for_each(drop); + } +} + +#[unstable(feature = "btree_drain_filter", issue = "70530")] +impl<'a, T, F> fmt::Debug for DrainFilter<'a, T, F> +where + T: 'a + Ord + fmt::Debug, + F: 'a + FnMut(&T) -> bool, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("DrainFilter").field(&self.inner.peek().map(|(k, _)| k)).finish() + } +} + +#[unstable(feature = "btree_drain_filter", issue = "70530")] +impl<'a, 'f, T, F> Iterator for DrainFilter<'a, T, F> +where + T: 'a + Ord, + F: 'a + 'f + FnMut(&T) -> bool, +{ + type Item = T; + + fn next(&mut self) -> Option { + let pred = &mut self.pred; + let mut mapped_pred = |k: &T, _v: &mut ()| pred(k); + self.inner.next(&mut mapped_pred).map(|(k, _)| k) + } + + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } +} + +#[unstable(feature = "btree_drain_filter", issue = "70530")] +impl<'a, T, F> FusedIterator for DrainFilter<'a, T, F> +where + T: 'a + Ord, + F: 'a + FnMut(&T) -> bool, +{ +} + #[stable(feature = "rust1", since = "1.0.0")] impl Extend for BTreeSet { #[inline] diff --git a/src/liballoc/macros.rs b/src/liballoc/macros.rs index 422d3486f92b2..4bc0c3a079d5c 100644 --- a/src/liballoc/macros.rs +++ b/src/liballoc/macros.rs @@ -36,6 +36,9 @@ #[stable(feature = "rust1", since = "1.0.0")] #[allow_internal_unstable(box_syntax)] macro_rules! vec { + () => ( + $crate::vec::Vec::new() + ); ($elem:expr; $n:expr) => ( $crate::vec::from_elem($elem, $n) ); @@ -51,6 +54,9 @@ macro_rules! vec { // NB see the slice::hack module in slice.rs for more information #[cfg(test)] macro_rules! vec { + () => ( + $crate::vec::Vec::new() + ); ($elem:expr; $n:expr) => ( $crate::vec::from_elem($elem, $n) ); diff --git a/src/liballoc/tests/btree/map.rs b/src/liballoc/tests/btree/map.rs index e28b71510ce71..14f12ca2d779a 100644 --- a/src/liballoc/tests/btree/map.rs +++ b/src/liballoc/tests/btree/map.rs @@ -5,7 +5,7 @@ use std::fmt::Debug; use std::iter::FromIterator; use std::ops::Bound::{self, Excluded, Included, Unbounded}; use std::ops::RangeBounds; -use std::panic::catch_unwind; +use std::panic::{catch_unwind, AssertUnwindSafe}; use std::rc::Rc; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -609,6 +609,263 @@ fn test_range_mut() { } } +mod test_drain_filter { + use super::*; + + #[test] + fn empty() { + let mut map: BTreeMap = BTreeMap::new(); + map.drain_filter(|_, _| unreachable!("there's nothing to decide on")); + assert!(map.is_empty()); + } + + #[test] + fn consuming_nothing() { + let pairs = (0..3).map(|i| (i, i)); + let mut map: BTreeMap<_, _> = pairs.collect(); + assert!(map.drain_filter(|_, _| false).eq(std::iter::empty())); + } + + #[test] + fn consuming_all() { + let pairs = (0..3).map(|i| (i, i)); + let mut map: BTreeMap<_, _> = pairs.clone().collect(); + assert!(map.drain_filter(|_, _| true).eq(pairs)); + } + + #[test] + fn mutating_and_keeping() { + let pairs = (0..3).map(|i| (i, i)); + let mut map: BTreeMap<_, _> = pairs.collect(); + assert!( + map.drain_filter(|_, v| { + *v += 6; + false + }) + .eq(std::iter::empty()) + ); + assert!(map.keys().copied().eq(0..3)); + assert!(map.values().copied().eq(6..9)); + } + + #[test] + fn mutating_and_removing() { + let pairs = (0..3).map(|i| (i, i)); + let mut map: BTreeMap<_, _> = pairs.collect(); + assert!( + map.drain_filter(|_, v| { + *v += 6; + true + }) + .eq((0..3).map(|i| (i, i + 6))) + ); + assert!(map.is_empty()); + } + + #[test] + fn underfull_keeping_all() { + let pairs = (0..3).map(|i| (i, i)); + let mut map: BTreeMap<_, _> = pairs.collect(); + map.drain_filter(|_, _| false); + assert!(map.keys().copied().eq(0..3)); + } + + #[test] + fn underfull_removing_one() { + let pairs = (0..3).map(|i| (i, i)); + for doomed in 0..3 { + let mut map: BTreeMap<_, _> = pairs.clone().collect(); + map.drain_filter(|i, _| *i == doomed); + assert_eq!(map.len(), 2); + } + } + + #[test] + fn underfull_keeping_one() { + let pairs = (0..3).map(|i| (i, i)); + for sacred in 0..3 { + let mut map: BTreeMap<_, _> = pairs.clone().collect(); + map.drain_filter(|i, _| *i != sacred); + assert!(map.keys().copied().eq(sacred..=sacred)); + } + } + + #[test] + fn underfull_removing_all() { + let pairs = (0..3).map(|i| (i, i)); + let mut map: BTreeMap<_, _> = pairs.collect(); + map.drain_filter(|_, _| true); + assert!(map.is_empty()); + } + + #[test] + fn height_0_keeping_all() { + let pairs = (0..NODE_CAPACITY).map(|i| (i, i)); + let mut map: BTreeMap<_, _> = pairs.collect(); + map.drain_filter(|_, _| false); + assert!(map.keys().copied().eq(0..NODE_CAPACITY)); + } + + #[test] + fn height_0_removing_one() { + let pairs = (0..NODE_CAPACITY).map(|i| (i, i)); + for doomed in 0..NODE_CAPACITY { + let mut map: BTreeMap<_, _> = pairs.clone().collect(); + map.drain_filter(|i, _| *i == doomed); + assert_eq!(map.len(), NODE_CAPACITY - 1); + } + } + + #[test] + fn height_0_keeping_one() { + let pairs = (0..NODE_CAPACITY).map(|i| (i, i)); + for sacred in 0..NODE_CAPACITY { + let mut map: BTreeMap<_, _> = pairs.clone().collect(); + map.drain_filter(|i, _| *i != sacred); + assert!(map.keys().copied().eq(sacred..=sacred)); + } + } + + #[test] + fn height_0_removing_all() { + let pairs = (0..NODE_CAPACITY).map(|i| (i, i)); + let mut map: BTreeMap<_, _> = pairs.collect(); + map.drain_filter(|_, _| true); + assert!(map.is_empty()); + } + + #[test] + fn height_0_keeping_half() { + let mut map: BTreeMap<_, _> = (0..16).map(|i| (i, i)).collect(); + assert_eq!(map.drain_filter(|i, _| *i % 2 == 0).count(), 8); + assert_eq!(map.len(), 8); + } + + #[test] + fn height_1_removing_all() { + let pairs = (0..MIN_INSERTS_HEIGHT_1).map(|i| (i, i)); + let mut map: BTreeMap<_, _> = pairs.collect(); + map.drain_filter(|_, _| true); + assert!(map.is_empty()); + } + + #[test] + fn height_1_removing_one() { + let pairs = (0..MIN_INSERTS_HEIGHT_1).map(|i| (i, i)); + for doomed in 0..MIN_INSERTS_HEIGHT_1 { + let mut map: BTreeMap<_, _> = pairs.clone().collect(); + map.drain_filter(|i, _| *i == doomed); + assert_eq!(map.len(), MIN_INSERTS_HEIGHT_1 - 1); + } + } + + #[test] + fn height_1_keeping_one() { + let pairs = (0..MIN_INSERTS_HEIGHT_1).map(|i| (i, i)); + for sacred in 0..MIN_INSERTS_HEIGHT_1 { + let mut map: BTreeMap<_, _> = pairs.clone().collect(); + map.drain_filter(|i, _| *i != sacred); + assert!(map.keys().copied().eq(sacred..=sacred)); + } + } + + #[cfg(not(miri))] // Miri is too slow + #[test] + fn height_2_removing_one() { + let pairs = (0..MIN_INSERTS_HEIGHT_2).map(|i| (i, i)); + for doomed in (0..MIN_INSERTS_HEIGHT_2).step_by(12) { + let mut map: BTreeMap<_, _> = pairs.clone().collect(); + map.drain_filter(|i, _| *i == doomed); + assert_eq!(map.len(), MIN_INSERTS_HEIGHT_2 - 1); + } + } + + #[cfg(not(miri))] // Miri is too slow + #[test] + fn height_2_keeping_one() { + let pairs = (0..MIN_INSERTS_HEIGHT_2).map(|i| (i, i)); + for sacred in (0..MIN_INSERTS_HEIGHT_2).step_by(12) { + let mut map: BTreeMap<_, _> = pairs.clone().collect(); + map.drain_filter(|i, _| *i != sacred); + assert!(map.keys().copied().eq(sacred..=sacred)); + } + } + + #[test] + fn height_2_removing_all() { + let pairs = (0..MIN_INSERTS_HEIGHT_2).map(|i| (i, i)); + let mut map: BTreeMap<_, _> = pairs.collect(); + map.drain_filter(|_, _| true); + assert!(map.is_empty()); + } + + #[test] + fn drop_panic_leak() { + static PREDS: AtomicUsize = AtomicUsize::new(0); + static DROPS: AtomicUsize = AtomicUsize::new(0); + + struct D; + impl Drop for D { + fn drop(&mut self) { + if DROPS.fetch_add(1, Ordering::SeqCst) == 1 { + panic!("panic in `drop`"); + } + } + } + + let mut map = BTreeMap::new(); + map.insert(0, D); + map.insert(4, D); + map.insert(8, D); + + catch_unwind(move || { + drop(map.drain_filter(|i, _| { + PREDS.fetch_add(1usize << i, Ordering::SeqCst); + true + })) + }) + .ok(); + + assert_eq!(PREDS.load(Ordering::SeqCst), 0x011); + assert_eq!(DROPS.load(Ordering::SeqCst), 3); + } + + #[test] + fn pred_panic_leak() { + static PREDS: AtomicUsize = AtomicUsize::new(0); + static DROPS: AtomicUsize = AtomicUsize::new(0); + + struct D; + impl Drop for D { + fn drop(&mut self) { + DROPS.fetch_add(1, Ordering::SeqCst); + } + } + + let mut map = BTreeMap::new(); + map.insert(0, D); + map.insert(4, D); + map.insert(8, D); + + catch_unwind(AssertUnwindSafe(|| { + drop(map.drain_filter(|i, _| { + PREDS.fetch_add(1usize << i, Ordering::SeqCst); + match i { + 0 => true, + _ => panic!(), + } + })) + })) + .ok(); + + assert_eq!(PREDS.load(Ordering::SeqCst), 0x011); + assert_eq!(DROPS.load(Ordering::SeqCst), 1); + assert_eq!(map.len(), 2); + assert_eq!(map.first_entry().unwrap().key(), &4); + assert_eq!(map.last_entry().unwrap().key(), &8); + } +} + #[test] fn test_borrow() { // make sure these compile -- using the Borrow trait diff --git a/src/liballoc/tests/btree/set.rs b/src/liballoc/tests/btree/set.rs index 1a2b62d026b2e..136018b9f7df5 100644 --- a/src/liballoc/tests/btree/set.rs +++ b/src/liballoc/tests/btree/set.rs @@ -1,5 +1,7 @@ use std::collections::BTreeSet; use std::iter::FromIterator; +use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::sync::atomic::{AtomicU32, Ordering}; use super::DeterministicRng; @@ -302,6 +304,85 @@ fn test_is_subset() { assert_eq!(is_subset(&[99, 100], &large), false); } +#[test] +fn test_drain_filter() { + let mut x: BTreeSet<_> = [1].iter().copied().collect(); + let mut y: BTreeSet<_> = [1].iter().copied().collect(); + + x.drain_filter(|_| true); + y.drain_filter(|_| false); + assert_eq!(x.len(), 0); + assert_eq!(y.len(), 1); +} + +#[test] +fn test_drain_filter_drop_panic_leak() { + static PREDS: AtomicU32 = AtomicU32::new(0); + static DROPS: AtomicU32 = AtomicU32::new(0); + + #[derive(PartialEq, Eq, PartialOrd, Ord)] + struct D(i32); + impl Drop for D { + fn drop(&mut self) { + if DROPS.fetch_add(1, Ordering::SeqCst) == 1 { + panic!("panic in `drop`"); + } + } + } + + let mut set = BTreeSet::new(); + set.insert(D(0)); + set.insert(D(4)); + set.insert(D(8)); + + catch_unwind(move || { + drop(set.drain_filter(|d| { + PREDS.fetch_add(1u32 << d.0, Ordering::SeqCst); + true + })) + }) + .ok(); + + assert_eq!(PREDS.load(Ordering::SeqCst), 0x011); + assert_eq!(DROPS.load(Ordering::SeqCst), 3); +} + +#[test] +fn test_drain_filter_pred_panic_leak() { + static PREDS: AtomicU32 = AtomicU32::new(0); + static DROPS: AtomicU32 = AtomicU32::new(0); + + #[derive(PartialEq, Eq, PartialOrd, Ord)] + struct D(i32); + impl Drop for D { + fn drop(&mut self) { + DROPS.fetch_add(1, Ordering::SeqCst); + } + } + + let mut set = BTreeSet::new(); + set.insert(D(0)); + set.insert(D(4)); + set.insert(D(8)); + + catch_unwind(AssertUnwindSafe(|| { + drop(set.drain_filter(|d| { + PREDS.fetch_add(1u32 << d.0, Ordering::SeqCst); + match d.0 { + 0 => true, + _ => panic!(), + } + })) + })) + .ok(); + + assert_eq!(PREDS.load(Ordering::SeqCst), 0x011); + assert_eq!(DROPS.load(Ordering::SeqCst), 1); + assert_eq!(set.len(), 2); + assert_eq!(set.first().unwrap().0, 4); + assert_eq!(set.last().unwrap().0, 8); +} + #[test] fn test_clear() { let mut x = BTreeSet::new(); diff --git a/src/liballoc/tests/lib.rs b/src/liballoc/tests/lib.rs index ea75f8903c368..ad6feaeebc67f 100644 --- a/src/liballoc/tests/lib.rs +++ b/src/liballoc/tests/lib.rs @@ -1,5 +1,6 @@ #![feature(allocator_api)] #![feature(box_syntax)] +#![feature(btree_drain_filter)] #![feature(drain_filter)] #![feature(exact_size_is_empty)] #![feature(map_first_last)] diff --git a/src/libcore/array/iter.rs b/src/libcore/array/iter.rs index 80eaae0d4afb5..f6b8d4ba08146 100644 --- a/src/libcore/array/iter.rs +++ b/src/libcore/array/iter.rs @@ -39,7 +39,7 @@ where alive: Range, } -impl IntoIter +impl IntoIter where [T; N]: LengthAtMost32, { @@ -99,7 +99,7 @@ where } #[stable(feature = "array_value_iter_impls", since = "1.40.0")] -impl Iterator for IntoIter +impl Iterator for IntoIter where [T; N]: LengthAtMost32, { @@ -146,7 +146,7 @@ where } #[stable(feature = "array_value_iter_impls", since = "1.40.0")] -impl DoubleEndedIterator for IntoIter +impl DoubleEndedIterator for IntoIter where [T; N]: LengthAtMost32, { @@ -182,7 +182,7 @@ where } #[stable(feature = "array_value_iter_impls", since = "1.40.0")] -impl Drop for IntoIter +impl Drop for IntoIter where [T; N]: LengthAtMost32, { @@ -195,7 +195,7 @@ where } #[stable(feature = "array_value_iter_impls", since = "1.40.0")] -impl ExactSizeIterator for IntoIter +impl ExactSizeIterator for IntoIter where [T; N]: LengthAtMost32, { @@ -210,17 +210,17 @@ where } #[stable(feature = "array_value_iter_impls", since = "1.40.0")] -impl FusedIterator for IntoIter where [T; N]: LengthAtMost32 {} +impl FusedIterator for IntoIter where [T; N]: LengthAtMost32 {} // The iterator indeed reports the correct length. The number of "alive" // elements (that will still be yielded) is the length of the range `alive`. // This range is decremented in length in either `next` or `next_back`. It is // always decremented by 1 in those methods, but only if `Some(_)` is returned. #[stable(feature = "array_value_iter_impls", since = "1.40.0")] -unsafe impl TrustedLen for IntoIter where [T; N]: LengthAtMost32 {} +unsafe impl TrustedLen for IntoIter where [T; N]: LengthAtMost32 {} #[stable(feature = "array_value_iter_impls", since = "1.40.0")] -impl Clone for IntoIter +impl Clone for IntoIter where [T; N]: LengthAtMost32, { @@ -249,7 +249,7 @@ where } #[stable(feature = "array_value_iter_impls", since = "1.40.0")] -impl fmt::Debug for IntoIter +impl fmt::Debug for IntoIter where [T; N]: LengthAtMost32, { diff --git a/src/librustc_codegen_llvm/abi.rs b/src/librustc_codegen_llvm/abi.rs index 38dd879de7d59..4b667001ad133 100644 --- a/src/librustc_codegen_llvm/abi.rs +++ b/src/librustc_codegen_llvm/abi.rs @@ -10,17 +10,15 @@ use rustc_codegen_ssa::mir::place::PlaceRef; use rustc_codegen_ssa::traits::*; use rustc_codegen_ssa::MemFlags; use rustc_middle::bug; -use rustc_middle::ty::layout::{self}; +pub use rustc_middle::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA}; use rustc_middle::ty::Ty; use rustc_target::abi::call::ArgAbi; -use rustc_target::abi::{HasDataLayout, LayoutOf}; - -use libc::c_uint; - -pub use rustc_middle::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA}; pub use rustc_target::abi::call::*; +use rustc_target::abi::{self, HasDataLayout, Int, LayoutOf}; pub use rustc_target::spec::abi::Abi; +use libc::c_uint; + macro_rules! for_each_kind { ($flags: ident, $f: ident, $($kind: ident),+) => ({ $(if $flags.contains(ArgAttribute::$kind) { $f(llvm::Attribute::$kind) })+ @@ -443,11 +441,11 @@ impl<'tcx> FnAbiLlvmExt<'tcx> for FnAbi<'tcx, Ty<'tcx>> { PassMode::Indirect(ref attrs, _) => apply(attrs, Some(self.ret.layout.llvm_type(bx))), _ => {} } - if let layout::Abi::Scalar(ref scalar) = self.ret.layout.abi { + if let abi::Abi::Scalar(ref scalar) = self.ret.layout.abi { // If the value is a boolean, the range is 0..2 and that ultimately // become 0..0 when the type becomes i1, which would be rejected // by the LLVM verifier. - if let layout::Int(..) = scalar.value { + if let Int(..) = scalar.value { if !scalar.is_bool() { let range = scalar.valid_range_exclusive(bx); if range.start != range.end { diff --git a/src/librustc_codegen_llvm/builder.rs b/src/librustc_codegen_llvm/builder.rs index 35946fb71c3e0..da9060f043f81 100644 --- a/src/librustc_codegen_llvm/builder.rs +++ b/src/librustc_codegen_llvm/builder.rs @@ -16,9 +16,10 @@ use rustc_codegen_ssa::MemFlags; use rustc_data_structures::const_cstr; use rustc_data_structures::small_c_str::SmallCStr; use rustc_hir::def_id::DefId; -use rustc_middle::ty::layout::{self, Align, Size, TyAndLayout}; +use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_session::config::{self, Sanitizer}; +use rustc_target::abi::{self, Align, Size}; use rustc_target::spec::{HasTargetSpec, Target}; use std::borrow::Cow; use std::ffi::CStr; @@ -60,8 +61,8 @@ impl BackendTypes for Builder<'_, 'll, 'tcx> { type DIVariable = as BackendTypes>::DIVariable; } -impl ty::layout::HasDataLayout for Builder<'_, '_, '_> { - fn data_layout(&self) -> &ty::layout::TargetDataLayout { +impl abi::HasDataLayout for Builder<'_, '_, '_> { + fn data_layout(&self) -> &abi::TargetDataLayout { self.cx.data_layout() } } @@ -84,7 +85,7 @@ impl HasTargetSpec for Builder<'_, '_, 'tcx> { } } -impl ty::layout::LayoutOf for Builder<'_, '_, 'tcx> { +impl abi::LayoutOf for Builder<'_, '_, 'tcx> { type Ty = Ty<'tcx>; type TyAndLayout = TyAndLayout<'tcx>; @@ -435,17 +436,17 @@ impl BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { fn scalar_load_metadata<'a, 'll, 'tcx>( bx: &mut Builder<'a, 'll, 'tcx>, load: &'ll Value, - scalar: &layout::Scalar, + scalar: &abi::Scalar, ) { let vr = scalar.valid_range.clone(); match scalar.value { - layout::Int(..) => { + abi::Int(..) => { let range = scalar.valid_range_exclusive(bx); if range.start != range.end { bx.range_metadata(load, range); } } - layout::Pointer if vr.start() < vr.end() && !vr.contains(&0) => { + abi::Pointer if vr.start() < vr.end() && !vr.contains(&0) => { bx.nonnull_metadata(load); } _ => {} @@ -465,16 +466,16 @@ impl BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { } let llval = const_llval.unwrap_or_else(|| { let load = self.load(place.llval, place.align); - if let layout::Abi::Scalar(ref scalar) = place.layout.abi { + if let abi::Abi::Scalar(ref scalar) = place.layout.abi { scalar_load_metadata(self, load, scalar); } load }); OperandValue::Immediate(to_immediate(self, llval, place.layout)) - } else if let layout::Abi::ScalarPair(ref a, ref b) = place.layout.abi { + } else if let abi::Abi::ScalarPair(ref a, ref b) = place.layout.abi { let b_offset = a.value.size(self).align_to(b.value.align(self).abi); - let mut load = |i, scalar: &layout::Scalar, align| { + let mut load = |i, scalar: &abi::Scalar, align| { let llptr = self.struct_gep(place.llval, i as u64); let load = self.load(llptr, align); scalar_load_metadata(self, load, scalar); diff --git a/src/librustc_codegen_llvm/common.rs b/src/librustc_codegen_llvm/common.rs index 01c8e02fdc2ba..1415fedf11a27 100644 --- a/src/librustc_codegen_llvm/common.rs +++ b/src/librustc_codegen_llvm/common.rs @@ -2,26 +2,24 @@ //! Code that is useful in various codegen modules. -use crate::consts; +use crate::consts::{self, const_alloc_to_llvm}; +pub use crate::context::CodegenCx; use crate::llvm::{self, BasicBlock, Bool, ConstantInt, False, OperandBundleDef, True}; use crate::type_::Type; use crate::type_of::LayoutLlvmExt; use crate::value::Value; -use log::debug; -use rustc_codegen_ssa::traits::*; -use rustc_middle::bug; -use crate::consts::const_alloc_to_llvm; +use rustc_ast::ast::Mutability; use rustc_codegen_ssa::mir::place::PlaceRef; +use rustc_codegen_ssa::traits::*; +use rustc_middle::bug; use rustc_middle::mir::interpret::{Allocation, GlobalAlloc, Scalar}; -use rustc_middle::ty::layout::{self, HasDataLayout, LayoutOf, Size, TyAndLayout}; - -use libc::{c_char, c_uint}; - -use rustc_ast::ast::Mutability; +use rustc_middle::ty::layout::TyAndLayout; use rustc_span::symbol::Symbol; +use rustc_target::abi::{self, HasDataLayout, LayoutOf, Pointer, Size}; -pub use crate::context::CodegenCx; +use libc::{c_char, c_uint}; +use log::debug; /* * A note on nomenclature of linking: "extern", "foreign", and "upcall". @@ -229,12 +227,7 @@ impl ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> { }) } - fn scalar_to_backend( - &self, - cv: Scalar, - layout: &layout::Scalar, - llty: &'ll Type, - ) -> &'ll Value { + fn scalar_to_backend(&self, cv: Scalar, layout: &abi::Scalar, llty: &'ll Type) -> &'ll Value { let bitsize = if layout.is_bool() { 1 } else { layout.value.size(self).bits() }; match cv { Scalar::Raw { size: 0, .. } => { @@ -244,7 +237,7 @@ impl ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> { Scalar::Raw { data, size } => { assert_eq!(size as u64, layout.value.size(self).bytes()); let llval = self.const_uint_big(self.type_ix(bitsize), data); - if layout.value == layout::Pointer { + if layout.value == Pointer { unsafe { llvm::LLVMConstIntToPtr(llval, llty) } } else { self.const_bitcast(llval, llty) @@ -278,7 +271,7 @@ impl ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> { 1, ) }; - if layout.value != layout::Pointer { + if layout.value != Pointer { unsafe { llvm::LLVMConstPtrToInt(llval, llty) } } else { self.const_bitcast(llval, llty) diff --git a/src/librustc_codegen_llvm/consts.rs b/src/librustc_codegen_llvm/consts.rs index db92f3d382f6e..2d5564abfb2c8 100644 --- a/src/librustc_codegen_llvm/consts.rs +++ b/src/librustc_codegen_llvm/consts.rs @@ -16,12 +16,11 @@ use rustc_middle::mir::interpret::{ read_target_uint, Allocation, ConstValue, ErrorHandled, Pointer, }; use rustc_middle::mir::mono::MonoItem; -use rustc_middle::ty::layout::{self, Align, LayoutOf, Size}; use rustc_middle::ty::{self, Instance, Ty}; use rustc_middle::{bug, span_bug}; use rustc_span::symbol::{sym, Symbol}; use rustc_span::Span; -use rustc_target::abi::HasDataLayout; +use rustc_target::abi::{Align, HasDataLayout, LayoutOf, Primitive, Scalar, Size}; use std::ffi::CStr; @@ -56,7 +55,7 @@ pub fn const_alloc_to_llvm(cx: &CodegenCx<'ll, '_>, alloc: &Allocation) -> &'ll as u64; llvals.push(cx.scalar_to_backend( Pointer::new(alloc_id, Size::from_bytes(ptr_offset)).into(), - &layout::Scalar { value: layout::Primitive::Pointer, valid_range: 0..=!0 }, + &Scalar { value: Primitive::Pointer, valid_range: 0..=!0 }, cx.type_i8p(), )); next_offset = offset + pointer_size; diff --git a/src/librustc_codegen_llvm/context.rs b/src/librustc_codegen_llvm/context.rs index add1f46a56d37..99a825823c3cd 100644 --- a/src/librustc_codegen_llvm/context.rs +++ b/src/librustc_codegen_llvm/context.rs @@ -14,14 +14,13 @@ use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::small_c_str::SmallCStr; use rustc_middle::bug; use rustc_middle::mir::mono::CodegenUnit; -use rustc_middle::ty::layout::{ - HasParamEnv, LayoutError, LayoutOf, PointeeInfo, Size, TyAndLayout, VariantIdx, -}; +use rustc_middle::ty::layout::{HasParamEnv, LayoutError, TyAndLayout}; use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; use rustc_session::config::{self, CFGuard, DebugInfo}; use rustc_session::Session; use rustc_span::source_map::{Span, DUMMY_SP}; use rustc_span::symbol::Symbol; +use rustc_target::abi::{HasDataLayout, LayoutOf, PointeeInfo, Size, TargetDataLayout, VariantIdx}; use rustc_target::spec::{HasTargetSpec, Target}; use std::cell::{Cell, RefCell}; @@ -817,8 +816,8 @@ impl<'b, 'tcx> CodegenCx<'b, 'tcx> { } } -impl ty::layout::HasDataLayout for CodegenCx<'ll, 'tcx> { - fn data_layout(&self) -> &ty::layout::TargetDataLayout { +impl HasDataLayout for CodegenCx<'ll, 'tcx> { + fn data_layout(&self) -> &TargetDataLayout { &self.tcx.data_layout } } diff --git a/src/librustc_codegen_llvm/debuginfo/metadata.rs b/src/librustc_codegen_llvm/debuginfo/metadata.rs index b90c7e51ccd69..a9e21c056a3eb 100644 --- a/src/librustc_codegen_llvm/debuginfo/metadata.rs +++ b/src/librustc_codegen_llvm/debuginfo/metadata.rs @@ -34,9 +34,7 @@ use rustc_middle::ich::NodeIdHashingMode; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::mir::interpret::truncate; use rustc_middle::mir::{self, Field, GeneratorLayout}; -use rustc_middle::ty::layout::{ - self, Align, Integer, IntegerExt, LayoutOf, PrimitiveExt, Size, TyAndLayout, VariantIdx, -}; +use rustc_middle::ty::layout::{self, IntegerExt, PrimitiveExt, TyAndLayout}; use rustc_middle::ty::subst::{GenericArgKind, SubstsRef}; use rustc_middle::ty::Instance; use rustc_middle::ty::{self, AdtKind, ParamEnv, Ty, TyCtxt}; @@ -44,7 +42,9 @@ use rustc_middle::{bug, span_bug}; use rustc_session::config::{self, DebugInfo}; use rustc_span::symbol::{Interner, Symbol}; use rustc_span::{self, FileName, Span}; -use rustc_target::abi::HasDataLayout; +use rustc_target::abi::{Abi, Align, DiscriminantKind, HasDataLayout, Integer, LayoutOf}; +use rustc_target::abi::{Int, Pointer, F32, F64}; +use rustc_target::abi::{Primitive, Size, VariantIdx, Variants}; use libc::{c_longlong, c_uint}; use std::collections::hash_map::Entry; @@ -1364,7 +1364,7 @@ impl EnumMemberDescriptionFactory<'ll, 'tcx> { }; match self.layout.variants { - layout::Variants::Single { index } => { + Variants::Single { index } => { if let ty::Adt(adt, _) = &self.enum_type.kind { if adt.variants.is_empty() { return vec![]; @@ -1399,8 +1399,8 @@ impl EnumMemberDescriptionFactory<'ll, 'tcx> { discriminant: None, }] } - layout::Variants::Multiple { - discr_kind: layout::DiscriminantKind::Tag, + Variants::Multiple { + discr_kind: DiscriminantKind::Tag, discr_index, ref variants, .. @@ -1457,9 +1457,9 @@ impl EnumMemberDescriptionFactory<'ll, 'tcx> { }) .collect() } - layout::Variants::Multiple { + Variants::Multiple { discr_kind: - layout::DiscriminantKind::Niche { ref niche_variants, niche_start, dataful_variant }, + DiscriminantKind::Niche { ref niche_variants, niche_start, dataful_variant }, ref discr, ref variants, discr_index, @@ -1592,7 +1592,7 @@ impl EnumMemberDescriptionFactory<'ll, 'tcx> { // Creates `MemberDescription`s for the fields of a single enum variant. struct VariantMemberDescriptionFactory<'ll, 'tcx> { /// Cloned from the `layout::Struct` describing the variant. - offsets: Vec, + offsets: Vec, args: Vec<(String, Ty<'tcx>)>, discriminant_type_metadata: Option<&'ll DIType>, span: Span, @@ -1777,7 +1777,7 @@ fn prepare_enum_metadata( // let file_metadata = unknown_file_metadata(cx); - let discriminant_type_metadata = |discr: layout::Primitive| { + let discriminant_type_metadata = |discr: Primitive| { let enumerators_metadata: Vec<_> = match enum_type.kind { ty::Adt(def, _) => def .discriminants(cx.tcx) @@ -1870,10 +1870,8 @@ fn prepare_enum_metadata( let layout = cx.layout_of(enum_type); if let ( - &layout::Abi::Scalar(_), - &layout::Variants::Multiple { - discr_kind: layout::DiscriminantKind::Tag, ref discr, .. - }, + &Abi::Scalar(_), + &Variants::Multiple { discr_kind: DiscriminantKind::Tag, ref discr, .. }, ) = (&layout.abi, &layout.variants) { return FinalMetadata(discriminant_type_metadata(discr.value)); @@ -1881,16 +1879,11 @@ fn prepare_enum_metadata( if use_enum_fallback(cx) { let discriminant_type_metadata = match layout.variants { - layout::Variants::Single { .. } - | layout::Variants::Multiple { - discr_kind: layout::DiscriminantKind::Niche { .. }, - .. - } => None, - layout::Variants::Multiple { - discr_kind: layout::DiscriminantKind::Tag, - ref discr, - .. - } => Some(discriminant_type_metadata(discr.value)), + Variants::Single { .. } + | Variants::Multiple { discr_kind: DiscriminantKind::Niche { .. }, .. } => None, + Variants::Multiple { discr_kind: DiscriminantKind::Tag, ref discr, .. } => { + Some(discriminant_type_metadata(discr.value)) + } }; let enum_metadata = { @@ -1938,10 +1931,10 @@ fn prepare_enum_metadata( }; let discriminator_metadata = match layout.variants { // A single-variant enum has no discriminant. - layout::Variants::Single { .. } => None, + Variants::Single { .. } => None, - layout::Variants::Multiple { - discr_kind: layout::DiscriminantKind::Niche { .. }, + Variants::Multiple { + discr_kind: DiscriminantKind::Niche { .. }, ref discr, discr_index, .. @@ -1951,10 +1944,10 @@ fn prepare_enum_metadata( let align = discr.value.align(cx); let discr_type = match discr.value { - layout::Int(t, _) => t, - layout::F32 => Integer::I32, - layout::F64 => Integer::I64, - layout::Pointer => cx.data_layout().ptr_sized_integer(), + Int(t, _) => t, + F32 => Integer::I32, + F64 => Integer::I64, + Pointer => cx.data_layout().ptr_sized_integer(), } .to_ty(cx.tcx, false); @@ -1976,11 +1969,8 @@ fn prepare_enum_metadata( } } - layout::Variants::Multiple { - discr_kind: layout::DiscriminantKind::Tag, - ref discr, - discr_index, - .. + Variants::Multiple { + discr_kind: DiscriminantKind::Tag, ref discr, discr_index, .. } => { let discr_type = discr.value.to_ty(cx.tcx); let (size, align) = cx.size_and_align_of(discr_type); @@ -2005,8 +1995,8 @@ fn prepare_enum_metadata( }; let mut outer_fields = match layout.variants { - layout::Variants::Single { .. } => vec![], - layout::Variants::Multiple { .. } => { + Variants::Single { .. } => vec![], + Variants::Multiple { .. } => { let tuple_mdf = TupleMemberDescriptionFactory { ty: enum_type, component_types: outer_field_tys, diff --git a/src/librustc_codegen_llvm/debuginfo/mod.rs b/src/librustc_codegen_llvm/debuginfo/mod.rs index 848c973c15b51..f04ac58650411 100644 --- a/src/librustc_codegen_llvm/debuginfo/mod.rs +++ b/src/librustc_codegen_llvm/debuginfo/mod.rs @@ -8,35 +8,35 @@ use self::namespace::mangled_name_of_instance; use self::type_names::compute_debuginfo_type_name; use self::utils::{create_DIArray, is_node_local_to_unit, DIB}; +use crate::abi::FnAbi; +use crate::builder::Builder; +use crate::common::CodegenCx; use crate::llvm; use crate::llvm::debuginfo::{ DIArray, DIBuilder, DIFile, DIFlags, DILexicalBlock, DISPFlags, DIScope, DIType, DIVariable, }; -use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LOCAL_CRATE}; -use rustc_middle::ty::subst::{GenericArgKind, SubstsRef}; - -use crate::abi::FnAbi; -use crate::builder::Builder; -use crate::common::CodegenCx; use crate::value::Value; + +use rustc_ast::ast; use rustc_codegen_ssa::debuginfo::type_names; use rustc_codegen_ssa::mir::debuginfo::{DebugScope, FunctionDebugContext, VariableKind}; +use rustc_codegen_ssa::traits::*; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; +use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LOCAL_CRATE}; use rustc_index::vec::IndexVec; use rustc_middle::mir; +use rustc_middle::ty::layout::HasTyCtxt; +use rustc_middle::ty::subst::{GenericArgKind, SubstsRef}; use rustc_middle::ty::{self, Instance, ParamEnv, Ty}; use rustc_session::config::{self, DebugInfo}; +use rustc_span::symbol::Symbol; +use rustc_span::{self, BytePos, Span}; +use rustc_target::abi::{LayoutOf, Primitive, Size}; use libc::c_uint; use log::debug; -use std::cell::RefCell; - -use rustc_ast::ast; -use rustc_codegen_ssa::traits::*; -use rustc_middle::ty::layout::{self, HasTyCtxt, LayoutOf, Size}; -use rustc_span::symbol::Symbol; -use rustc_span::{self, BytePos, Span}; use smallvec::SmallVec; +use std::cell::RefCell; mod create_scope_map; pub mod gdb; @@ -60,7 +60,7 @@ pub struct CrateDebugContext<'a, 'tcx> { llmod: &'a llvm::Module, builder: &'a mut DIBuilder<'a>, created_files: RefCell, Option), &'a DIFile>>, - created_enum_disr_types: RefCell>, + created_enum_disr_types: RefCell>, type_map: RefCell>, namespace_map: RefCell>, diff --git a/src/librustc_codegen_llvm/intrinsic.rs b/src/librustc_codegen_llvm/intrinsic.rs index 23f6c0a942036..bc7a9c566b476 100644 --- a/src/librustc_codegen_llvm/intrinsic.rs +++ b/src/librustc_codegen_llvm/intrinsic.rs @@ -7,23 +7,22 @@ use crate::type_::Type; use crate::type_of::LayoutLlvmExt; use crate::va_arg::emit_va_arg; use crate::value::Value; + use rustc_ast::ast; use rustc_codegen_ssa::base::{compare_simd_types, to_immediate, wants_msvc_seh}; +use rustc_codegen_ssa::common::span_invalid_monomorphization_error; use rustc_codegen_ssa::common::{IntPredicate, TypeKind}; use rustc_codegen_ssa::glue; use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue}; use rustc_codegen_ssa::mir::place::PlaceRef; +use rustc_codegen_ssa::traits::*; use rustc_codegen_ssa::MemFlags; use rustc_hir as hir; -use rustc_middle::ty::layout::{self, FnAbiExt, HasTyCtxt, LayoutOf, Primitive}; +use rustc_middle::ty::layout::{FnAbiExt, HasTyCtxt}; use rustc_middle::ty::{self, Ty}; use rustc_middle::{bug, span_bug}; -use rustc_target::abi::HasDataLayout; - -use rustc_codegen_ssa::common::span_invalid_monomorphization_error; -use rustc_codegen_ssa::traits::*; - use rustc_span::Span; +use rustc_target::abi::{self, HasDataLayout, LayoutOf, Primitive}; use std::cmp::Ordering; use std::{i128, iter, u128}; @@ -145,7 +144,7 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> { } "va_arg" => { match fn_abi.ret.layout.abi { - layout::Abi::Scalar(ref scalar) => { + abi::Abi::Scalar(ref scalar) => { match scalar.value { Primitive::Int(..) => { if self.cx().size_of(ret_ty).bytes() < 4 { diff --git a/src/librustc_codegen_llvm/lib.rs b/src/librustc_codegen_llvm/lib.rs index 8a16d098a8bef..939f9e9c2a0c7 100644 --- a/src/librustc_codegen_llvm/lib.rs +++ b/src/librustc_codegen_llvm/lib.rs @@ -23,11 +23,10 @@ use rustc_codegen_ssa::back::write::{CodegenContext, FatLTOInput, ModuleConfig}; use rustc_codegen_ssa::traits::*; use rustc_codegen_ssa::ModuleCodegen; use rustc_codegen_ssa::{CodegenResults, CompiledModule}; -use rustc_errors::{FatalError, Handler}; +use rustc_errors::{ErrorReported, FatalError, Handler}; use rustc_middle::dep_graph::{DepGraph, WorkProduct}; use rustc_middle::middle::cstore::{EncodedMetadata, MetadataLoaderDyn}; use rustc_middle::ty::{self, TyCtxt}; -use rustc_middle::util::common::ErrorReported; use rustc_serialize::json; use rustc_session::config::{self, OptLevel, OutputFilenames, PrintRequest}; use rustc_session::Session; diff --git a/src/librustc_codegen_llvm/mono_item.rs b/src/librustc_codegen_llvm/mono_item.rs index fe1537fbd021d..326e2f1bab046 100644 --- a/src/librustc_codegen_llvm/mono_item.rs +++ b/src/librustc_codegen_llvm/mono_item.rs @@ -7,11 +7,11 @@ use crate::type_of::LayoutLlvmExt; use log::debug; use rustc_codegen_ssa::traits::*; use rustc_hir::def_id::{DefId, LOCAL_CRATE}; +pub use rustc_middle::mir::mono::MonoItem; use rustc_middle::mir::mono::{Linkage, Visibility}; -use rustc_middle::ty::layout::{FnAbiExt, LayoutOf}; +use rustc_middle::ty::layout::FnAbiExt; use rustc_middle::ty::{Instance, TypeFoldable}; - -pub use rustc_middle::mir::mono::MonoItem; +use rustc_target::abi::LayoutOf; impl PreDefineMethods<'tcx> for CodegenCx<'ll, 'tcx> { fn predefine_static( diff --git a/src/librustc_codegen_llvm/type_.rs b/src/librustc_codegen_llvm/type_.rs index c06d2e6a01ac2..854eff3173380 100644 --- a/src/librustc_codegen_llvm/type_.rs +++ b/src/librustc_codegen_llvm/type_.rs @@ -12,9 +12,10 @@ use rustc_codegen_ssa::common::TypeKind; use rustc_codegen_ssa::traits::*; use rustc_data_structures::small_c_str::SmallCStr; use rustc_middle::bug; -use rustc_middle::ty::layout::{self, Align, Size, TyAndLayout}; +use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::Ty; use rustc_target::abi::call::{CastTarget, FnAbi, Reg}; +use rustc_target::abi::{Align, Integer, Size}; use std::fmt; use std::ptr; @@ -114,14 +115,14 @@ impl CodegenCx<'ll, 'tcx> { crate fn type_pointee_for_align(&self, align: Align) -> &'ll Type { // FIXME(eddyb) We could find a better approximation if ity.align < align. - let ity = layout::Integer::approximate_align(self, align); + let ity = Integer::approximate_align(self, align); self.type_from_integer(ity) } /// Return a LLVM type that has at most the required alignment, /// and exactly the required size, as a best-effort padding array. crate fn type_padding_filler(&self, size: Size, align: Align) -> &'ll Type { - let unit = layout::Integer::approximate_align(self, align); + let unit = Integer::approximate_align(self, align); let size = size.bytes(); let unit_size = unit.size().bytes(); assert_eq!(size % unit_size, 0); diff --git a/src/librustc_codegen_llvm/type_of.rs b/src/librustc_codegen_llvm/type_of.rs index 350f7be5a9d8d..d9e71f0c2212e 100644 --- a/src/librustc_codegen_llvm/type_of.rs +++ b/src/librustc_codegen_llvm/type_of.rs @@ -4,10 +4,12 @@ use crate::type_::Type; use log::debug; use rustc_codegen_ssa::traits::*; use rustc_middle::bug; -use rustc_middle::ty::layout::{self, Align, FnAbiExt, LayoutOf, PointeeInfo, Size, TyAndLayout}; +use rustc_middle::ty::layout::{FnAbiExt, TyAndLayout}; use rustc_middle::ty::print::obsolete::DefPathBasedNames; use rustc_middle::ty::{self, Ty, TypeFoldable}; -use rustc_target::abi::TyAndLayoutMethods; +use rustc_target::abi::{Abi, Align, FieldPlacement}; +use rustc_target::abi::{Int, Pointer, F32, F64}; +use rustc_target::abi::{LayoutOf, PointeeInfo, Scalar, Size, TyAndLayoutMethods, Variants}; use std::fmt::Write; @@ -17,8 +19,8 @@ fn uncached_llvm_type<'a, 'tcx>( defer: &mut Option<(&'a Type, TyAndLayout<'tcx>)>, ) -> &'a Type { match layout.abi { - layout::Abi::Scalar(_) => bug!("handled elsewhere"), - layout::Abi::Vector { ref element, count } => { + Abi::Scalar(_) => bug!("handled elsewhere"), + Abi::Vector { ref element, count } => { // LLVM has a separate type for 64-bit SIMD vectors on X86 called // `x86_mmx` which is needed for some SIMD operations. As a bit of a // hack (all SIMD definitions are super unstable anyway) we @@ -37,7 +39,7 @@ fn uncached_llvm_type<'a, 'tcx>( return cx.type_vector(element, count); } } - layout::Abi::ScalarPair(..) => { + Abi::ScalarPair(..) => { return cx.type_struct( &[ layout.scalar_pair_element_llvm_type(cx, 0, false), @@ -46,7 +48,7 @@ fn uncached_llvm_type<'a, 'tcx>( false, ); } - layout::Abi::Uninhabited | layout::Abi::Aggregate { .. } => {} + Abi::Uninhabited | Abi::Aggregate { .. } => {} } let name = match layout.ty.kind { @@ -61,14 +63,14 @@ fn uncached_llvm_type<'a, 'tcx>( let mut name = String::with_capacity(32); let printer = DefPathBasedNames::new(cx.tcx, true, true); printer.push_type_name(layout.ty, &mut name, false); - if let (&ty::Adt(def, _), &layout::Variants::Single { index }) + if let (&ty::Adt(def, _), &Variants::Single { index }) = (&layout.ty.kind, &layout.variants) { if def.is_enum() && !def.variants.is_empty() { write!(&mut name, "::{}", def.variants[index].ident).unwrap(); } } - if let (&ty::Generator(_, substs, _), &layout::Variants::Single { index }) + if let (&ty::Generator(_, substs, _), &Variants::Single { index }) = (&layout.ty.kind, &layout.variants) { write!(&mut name, "::{}", substs.as_generator().variant_name(index)).unwrap(); @@ -79,7 +81,7 @@ fn uncached_llvm_type<'a, 'tcx>( }; match layout.fields { - layout::FieldPlacement::Union(_) => { + FieldPlacement::Union(_) => { let fill = cx.type_padding_filler(layout.size, layout.align.abi); let packed = false; match name { @@ -91,10 +93,10 @@ fn uncached_llvm_type<'a, 'tcx>( } } } - layout::FieldPlacement::Array { count, .. } => { + FieldPlacement::Array { count, .. } => { cx.type_array(layout.field(cx, 0).llvm_type(cx), count) } - layout::FieldPlacement::Arbitrary { .. } => match name { + FieldPlacement::Arbitrary { .. } => match name { None => { let (llfields, packed) = struct_llfields(cx, layout); cx.type_struct(&llfields, packed) @@ -189,7 +191,7 @@ pub trait LayoutLlvmExt<'tcx> { fn scalar_llvm_type_at<'a>( &self, cx: &CodegenCx<'a, 'tcx>, - scalar: &layout::Scalar, + scalar: &Scalar, offset: Size, ) -> &'a Type; fn scalar_pair_element_llvm_type<'a>( @@ -205,19 +207,16 @@ pub trait LayoutLlvmExt<'tcx> { impl<'tcx> LayoutLlvmExt<'tcx> for TyAndLayout<'tcx> { fn is_llvm_immediate(&self) -> bool { match self.abi { - layout::Abi::Scalar(_) | layout::Abi::Vector { .. } => true, - layout::Abi::ScalarPair(..) => false, - layout::Abi::Uninhabited | layout::Abi::Aggregate { .. } => self.is_zst(), + Abi::Scalar(_) | Abi::Vector { .. } => true, + Abi::ScalarPair(..) => false, + Abi::Uninhabited | Abi::Aggregate { .. } => self.is_zst(), } } fn is_llvm_scalar_pair(&self) -> bool { match self.abi { - layout::Abi::ScalarPair(..) => true, - layout::Abi::Uninhabited - | layout::Abi::Scalar(_) - | layout::Abi::Vector { .. } - | layout::Abi::Aggregate { .. } => false, + Abi::ScalarPair(..) => true, + Abi::Uninhabited | Abi::Scalar(_) | Abi::Vector { .. } | Abi::Aggregate { .. } => false, } } @@ -233,7 +232,7 @@ impl<'tcx> LayoutLlvmExt<'tcx> for TyAndLayout<'tcx> { /// of that field's type - this is useful for taking the address of /// that field and ensuring the struct has the right alignment. fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type { - if let layout::Abi::Scalar(ref scalar) = self.abi { + if let Abi::Scalar(ref scalar) = self.abi { // Use a different cache for scalars because pointers to DSTs // can be either fat or thin (data pointers of fat pointers). if let Some(&llty) = cx.scalar_lltypes.borrow().get(&self.ty) { @@ -255,7 +254,7 @@ impl<'tcx> LayoutLlvmExt<'tcx> for TyAndLayout<'tcx> { // Check the cache. let variant_index = match self.variants { - layout::Variants::Single { index } => Some(index), + Variants::Single { index } => Some(index), _ => None, }; if let Some(&llty) = cx.lltypes.borrow().get(&(self.ty, variant_index)) { @@ -293,7 +292,7 @@ impl<'tcx> LayoutLlvmExt<'tcx> for TyAndLayout<'tcx> { } fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type { - if let layout::Abi::Scalar(ref scalar) = self.abi { + if let Abi::Scalar(ref scalar) = self.abi { if scalar.is_bool() { return cx.type_i1(); } @@ -304,14 +303,14 @@ impl<'tcx> LayoutLlvmExt<'tcx> for TyAndLayout<'tcx> { fn scalar_llvm_type_at<'a>( &self, cx: &CodegenCx<'a, 'tcx>, - scalar: &layout::Scalar, + scalar: &Scalar, offset: Size, ) -> &'a Type { match scalar.value { - layout::Int(i, _) => cx.type_from_integer(i), - layout::F32 => cx.type_f32(), - layout::F64 => cx.type_f64(), - layout::Pointer => { + Int(i, _) => cx.type_from_integer(i), + F32 => cx.type_f32(), + F64 => cx.type_f64(), + Pointer => { // If we know the alignment, pick something better than i8. let pointee = if let Some(pointee) = self.pointee_info_at(cx, offset) { cx.type_pointee_for_align(pointee.align) @@ -343,7 +342,7 @@ impl<'tcx> LayoutLlvmExt<'tcx> for TyAndLayout<'tcx> { } let (a, b) = match self.abi { - layout::Abi::ScalarPair(ref a, ref b) => (a, b), + Abi::ScalarPair(ref a, ref b) => (a, b), _ => bug!("TyAndLayout::scalar_pair_element_llty({:?}): not applicable", self), }; let scalar = [a, b][index]; @@ -365,21 +364,19 @@ impl<'tcx> LayoutLlvmExt<'tcx> for TyAndLayout<'tcx> { fn llvm_field_index(&self, index: usize) -> u64 { match self.abi { - layout::Abi::Scalar(_) | layout::Abi::ScalarPair(..) => { + Abi::Scalar(_) | Abi::ScalarPair(..) => { bug!("TyAndLayout::llvm_field_index({:?}): not applicable", self) } _ => {} } match self.fields { - layout::FieldPlacement::Union(_) => { + FieldPlacement::Union(_) => { bug!("TyAndLayout::llvm_field_index({:?}): not applicable", self) } - layout::FieldPlacement::Array { .. } => index as u64, + FieldPlacement::Array { .. } => index as u64, - layout::FieldPlacement::Arbitrary { .. } => { - 1 + (self.fields.memory_index(index) as u64) * 2 - } + FieldPlacement::Arbitrary { .. } => 1 + (self.fields.memory_index(index) as u64) * 2, } } diff --git a/src/librustc_codegen_llvm/va_arg.rs b/src/librustc_codegen_llvm/va_arg.rs index 42e9f60e95cb5..8bc3579800ea8 100644 --- a/src/librustc_codegen_llvm/va_arg.rs +++ b/src/librustc_codegen_llvm/va_arg.rs @@ -6,8 +6,9 @@ use rustc_codegen_ssa::mir::operand::OperandRef; use rustc_codegen_ssa::traits::{ BaseTypeMethods, BuilderMethods, ConstMethods, DerivedTypeMethods, }; -use rustc_middle::ty::layout::{Align, HasDataLayout, HasTyCtxt, LayoutOf, Size}; +use rustc_middle::ty::layout::HasTyCtxt; use rustc_middle::ty::Ty; +use rustc_target::abi::{Align, HasDataLayout, LayoutOf, Size}; #[allow(dead_code)] fn round_pointer_up_to_alignment( diff --git a/src/librustc_codegen_ssa/base.rs b/src/librustc_codegen_ssa/base.rs index 9e6a3b23323d8..0297415155553 100644 --- a/src/librustc_codegen_ssa/base.rs +++ b/src/librustc_codegen_ssa/base.rs @@ -31,14 +31,14 @@ use rustc_data_structures::profiling::print_time_passes_entry; use rustc_data_structures::sync::{par_iter, Lock, ParallelIterator}; use rustc_hir as hir; use rustc_hir::def_id::{DefId, LOCAL_CRATE}; +use rustc_hir::lang_items::StartFnLangItem; use rustc_index::vec::Idx; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs; use rustc_middle::middle::cstore::EncodedMetadata; use rustc_middle::middle::cstore::{self, LinkagePreference}; use rustc_middle::middle::lang_items; -use rustc_middle::middle::lang_items::StartFnLangItem; use rustc_middle::mir::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem}; -use rustc_middle::ty::layout::{self, Align, HasTyCtxt, LayoutOf, TyAndLayout, VariantIdx}; +use rustc_middle::ty::layout::{self, HasTyCtxt, TyAndLayout}; use rustc_middle::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA}; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; @@ -47,6 +47,7 @@ use rustc_session::config::{self, EntryFnType, Lto}; use rustc_session::Session; use rustc_span::Span; use rustc_symbol_mangling::test as symbol_names_test; +use rustc_target::abi::{Abi, Align, LayoutOf, Scalar, VariantIdx}; use std::cmp; use std::ops::{Deref, DerefMut}; @@ -343,7 +344,7 @@ pub fn to_immediate<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( val: Bx::Value, layout: layout::TyAndLayout<'_>, ) -> Bx::Value { - if let layout::Abi::Scalar(ref scalar) = layout.abi { + if let Abi::Scalar(ref scalar) = layout.abi { return to_immediate_scalar(bx, val, scalar); } val @@ -352,7 +353,7 @@ pub fn to_immediate<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( pub fn to_immediate_scalar<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( bx: &mut Bx, val: Bx::Value, - scalar: &layout::Scalar, + scalar: &Scalar, ) -> Bx::Value { if scalar.is_bool() { return bx.trunc(val, bx.cx().type_i1()); diff --git a/src/librustc_codegen_ssa/common.rs b/src/librustc_codegen_ssa/common.rs index 8de04b730e170..0d0321ec4ae5e 100644 --- a/src/librustc_codegen_ssa/common.rs +++ b/src/librustc_codegen_ssa/common.rs @@ -1,17 +1,16 @@ #![allow(non_camel_case_types, non_snake_case)] use rustc_errors::struct_span_err; +use rustc_hir as hir; +use rustc_hir::def_id::DefId; +use rustc_hir::LangItem; use rustc_middle::ty::{Ty, TyCtxt}; use rustc_session::Session; use rustc_span::Span; use crate::base; -use crate::traits::*; -use rustc_hir::def_id::DefId; -use rustc_middle::middle::lang_items::LangItem; - use crate::traits::BuilderMethods; -use rustc_hir as hir; +use crate::traits::*; pub enum IntPredicate { IntEQ, diff --git a/src/librustc_codegen_ssa/lib.rs b/src/librustc_codegen_ssa/lib.rs index bf2f92a473fe8..bf8441562c55b 100644 --- a/src/librustc_codegen_ssa/lib.rs +++ b/src/librustc_codegen_ssa/lib.rs @@ -21,10 +21,10 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::svh::Svh; use rustc_data_structures::sync::Lrc; use rustc_hir::def_id::CrateNum; +use rustc_hir::LangItem; use rustc_middle::dep_graph::WorkProduct; use rustc_middle::middle::cstore::{CrateSource, LibSource, NativeLibrary}; use rustc_middle::middle::dependency_format::Dependencies; -use rustc_middle::middle::lang_items::LangItem; use rustc_middle::ty::query::Providers; use rustc_session::config::{OutputFilenames, OutputType, RUST_CGU_EXT}; use rustc_span::symbol::Symbol; diff --git a/src/librustc_codegen_ssa/mir/analyze.rs b/src/librustc_codegen_ssa/mir/analyze.rs index ec3de274b8a83..221f36fed362d 100644 --- a/src/librustc_codegen_ssa/mir/analyze.rs +++ b/src/librustc_codegen_ssa/mir/analyze.rs @@ -12,7 +12,8 @@ use rustc_middle::mir::visit::{ }; use rustc_middle::mir::{self, Location, TerminatorKind}; use rustc_middle::ty; -use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf}; +use rustc_middle::ty::layout::HasTyCtxt; +use rustc_target::abi::LayoutOf; pub fn non_ssa_locals<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( fx: &FunctionCx<'a, 'tcx, Bx>, diff --git a/src/librustc_codegen_ssa/mir/block.rs b/src/librustc_codegen_ssa/mir/block.rs index e71a63b7f3080..aab1a51cdd737 100644 --- a/src/librustc_codegen_ssa/mir/block.rs +++ b/src/librustc_codegen_ssa/mir/block.rs @@ -9,14 +9,15 @@ use crate::meth; use crate::traits::*; use crate::MemFlags; +use rustc_hir::lang_items; use rustc_index::vec::Idx; -use rustc_middle::middle::lang_items; use rustc_middle::mir; use rustc_middle::mir::AssertKind; -use rustc_middle::ty::layout::{self, FnAbiExt, HasTyCtxt, LayoutOf}; +use rustc_middle::ty::layout::{FnAbiExt, HasTyCtxt}; use rustc_middle::ty::{self, Instance, Ty, TypeFoldable}; use rustc_span::{source_map::Span, symbol::Symbol}; use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode}; +use rustc_target::abi::{self, LayoutOf}; use rustc_target::spec::abi::Abi; use std::borrow::Cow; @@ -591,7 +592,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { // we can do what we like. Here, we declare that transmuting // into an uninhabited type is impossible, so anything following // it must be unreachable. - assert_eq!(fn_abi.ret.layout.abi, layout::Abi::Uninhabited); + assert_eq!(fn_abi.ret.layout.abi, abi::Abi::Uninhabited); bx.unreachable(); } return; @@ -994,7 +995,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { // the load would just produce `OperandValue::Ref` instead // of the `OperandValue::Immediate` we need for the call. llval = bx.load(llval, align); - if let layout::Abi::Scalar(ref scalar) = arg.layout.abi { + if let abi::Abi::Scalar(ref scalar) = arg.layout.abi { if scalar.is_bool() { bx.range_metadata(llval, 0..2); } diff --git a/src/librustc_codegen_ssa/mir/constant.rs b/src/librustc_codegen_ssa/mir/constant.rs index 9770d04aa99dd..298aa25f0321f 100644 --- a/src/librustc_codegen_ssa/mir/constant.rs +++ b/src/librustc_codegen_ssa/mir/constant.rs @@ -3,9 +3,10 @@ use crate::traits::*; use rustc_index::vec::Idx; use rustc_middle::mir; use rustc_middle::mir::interpret::{ConstValue, ErrorHandled}; -use rustc_middle::ty::layout::{self, HasTyCtxt}; +use rustc_middle::ty::layout::HasTyCtxt; use rustc_middle::ty::{self, Ty}; use rustc_span::source_map::Span; +use rustc_target::abi::Abi; use super::FunctionCx; @@ -87,7 +88,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { if let Some(prim) = field.try_to_scalar() { let layout = bx.layout_of(field_ty); let scalar = match layout.abi { - layout::Abi::Scalar(ref x) => x, + Abi::Scalar(ref x) => x, _ => bug!("from_const: invalid ByVal layout: {:#?}", layout), }; bx.scalar_to_backend(prim, scalar, bx.immediate_backend_type(layout)) diff --git a/src/librustc_codegen_ssa/mir/debuginfo.rs b/src/librustc_codegen_ssa/mir/debuginfo.rs index 4eefb37ba0d42..5501ed5128d4d 100644 --- a/src/librustc_codegen_ssa/mir/debuginfo.rs +++ b/src/librustc_codegen_ssa/mir/debuginfo.rs @@ -3,11 +3,10 @@ use rustc_hir::def_id::CrateNum; use rustc_index::vec::IndexVec; use rustc_middle::mir; use rustc_middle::ty; -use rustc_middle::ty::layout::{LayoutOf, Size}; use rustc_session::config::DebugInfo; - use rustc_span::symbol::{kw, Symbol}; use rustc_span::{BytePos, Span}; +use rustc_target::abi::{LayoutOf, Size}; use super::operand::OperandValue; use super::place::PlaceRef; diff --git a/src/librustc_codegen_ssa/mir/operand.rs b/src/librustc_codegen_ssa/mir/operand.rs index 7545882a0eacb..69f11ed57ac5d 100644 --- a/src/librustc_codegen_ssa/mir/operand.rs +++ b/src/librustc_codegen_ssa/mir/operand.rs @@ -8,8 +8,9 @@ use crate::MemFlags; use rustc_middle::mir; use rustc_middle::mir::interpret::{ConstValue, ErrorHandled, Pointer, Scalar}; -use rustc_middle::ty::layout::{self, Align, LayoutOf, Size, TyAndLayout}; +use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::Ty; +use rustc_target::abi::{Abi, Align, LayoutOf, Size}; use std::fmt; @@ -78,7 +79,7 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> { let val = match val { ConstValue::Scalar(x) => { let scalar = match layout.abi { - layout::Abi::Scalar(ref x) => x, + Abi::Scalar(ref x) => x, _ => bug!("from_const: invalid ByVal layout: {:#?}", layout), }; let llval = bx.scalar_to_backend(x, scalar, bx.immediate_backend_type(layout)); @@ -86,7 +87,7 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> { } ConstValue::Slice { data, start, end } => { let a_scalar = match layout.abi { - layout::Abi::ScalarPair(ref a, _) => a, + Abi::ScalarPair(ref a, _) => a, _ => bug!("from_const: invalid ScalarPair layout: {:#?}", layout), }; let a = Scalar::from(Pointer::new( @@ -161,7 +162,7 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> { llval: V, layout: TyAndLayout<'tcx>, ) -> Self { - let val = if let layout::Abi::ScalarPair(ref a, ref b) = layout.abi { + let val = if let Abi::ScalarPair(ref a, ref b) = layout.abi { debug!("Operand::from_immediate_or_packed_pair: unpacking {:?} @ {:?}", llval, layout); // Deconstruct the immediate aggregate. @@ -199,7 +200,7 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> { } // Extract a scalar component from a pair. - (OperandValue::Pair(a_llval, b_llval), &layout::Abi::ScalarPair(ref a, ref b)) => { + (OperandValue::Pair(a_llval, b_llval), &Abi::ScalarPair(ref a, ref b)) => { if offset.bytes() == 0 { assert_eq!(field.size, a.value.size(bx.cx())); OperandValue::Immediate(a_llval) @@ -211,7 +212,7 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> { } // `#[repr(simd)]` types are also immediate. - (OperandValue::Immediate(llval), &layout::Abi::Vector { .. }) => { + (OperandValue::Immediate(llval), &Abi::Vector { .. }) => { OperandValue::Immediate(bx.extract_element(llval, bx.cx().const_usize(i as u64))) } @@ -305,7 +306,7 @@ impl<'a, 'tcx, V: CodegenObject> OperandValue { } OperandValue::Pair(a, b) => { let (a_scalar, b_scalar) = match dest.layout.abi { - layout::Abi::ScalarPair(ref a, ref b) => (a, b), + Abi::ScalarPair(ref a, ref b) => (a, b), _ => bug!("store_with_flags: invalid ScalarPair layout: {:#?}", dest.layout), }; let b_offset = a_scalar.value.size(bx).align_to(b_scalar.value.align(bx).abi); diff --git a/src/librustc_codegen_ssa/mir/place.rs b/src/librustc_codegen_ssa/mir/place.rs index 1237e70aa36f1..9b1148df65135 100644 --- a/src/librustc_codegen_ssa/mir/place.rs +++ b/src/librustc_codegen_ssa/mir/place.rs @@ -8,8 +8,10 @@ use crate::MemFlags; use rustc_middle::mir; use rustc_middle::mir::tcx::PlaceTy; -use rustc_middle::ty::layout::{self, Align, HasTyCtxt, LayoutOf, TyAndLayout, VariantIdx}; +use rustc_middle::ty::layout::{HasTyCtxt, TyAndLayout}; use rustc_middle::ty::{self, Ty}; +use rustc_target::abi::{Abi, Align, DiscriminantKind, FieldPlacement, Int}; +use rustc_target::abi::{LayoutOf, VariantIdx, Variants}; #[derive(Copy, Clone, Debug)] pub struct PlaceRef<'tcx, V> { @@ -66,7 +68,7 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { } pub fn len>(&self, cx: &Cx) -> V { - if let layout::FieldPlacement::Array { count, .. } = self.layout.fields { + if let FieldPlacement::Array { count, .. } = self.layout.fields { if self.layout.is_unsized() { assert_eq!(count, 0); self.llextra.unwrap() @@ -94,7 +96,7 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { // Unions and newtypes only use an offset of 0. let llval = if offset.bytes() == 0 { self.llval - } else if let layout::Abi::ScalarPair(ref a, ref b) = self.layout.abi { + } else if let Abi::ScalarPair(ref a, ref b) = self.layout.abi { // Offsets have to match either first or second field. assert_eq!(offset, a.value.size(bx.cx()).align_to(b.value.align(bx.cx()).abi)); bx.struct_gep(self.llval, 1) @@ -198,7 +200,7 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { return bx.cx().const_undef(cast_to); } let (discr_scalar, discr_kind, discr_index) = match self.layout.variants { - layout::Variants::Single { index } => { + Variants::Single { index } => { let discr_val = self .layout .ty @@ -206,7 +208,7 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { .map_or(index.as_u32() as u128, |discr| discr.val); return bx.cx().const_uint_big(cast_to, discr_val); } - layout::Variants::Multiple { ref discr, ref discr_kind, discr_index, .. } => { + Variants::Multiple { ref discr, ref discr_kind, discr_index, .. } => { (discr, discr_kind, discr_index) } }; @@ -217,22 +219,18 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { // Decode the discriminant (specifically if it's niche-encoded). match *discr_kind { - layout::DiscriminantKind::Tag => { + DiscriminantKind::Tag => { let signed = match discr_scalar.value { // We use `i1` for bytes that are always `0` or `1`, // e.g., `#[repr(i8)] enum E { A, B }`, but we can't // let LLVM interpret the `i1` as signed, because // then `i1 1` (i.e., `E::B`) is effectively `i8 -1`. - layout::Int(_, signed) => !discr_scalar.is_bool() && signed, + Int(_, signed) => !discr_scalar.is_bool() && signed, _ => false, }; bx.intcast(encoded_discr.immediate(), cast_to, signed) } - layout::DiscriminantKind::Niche { - dataful_variant, - ref niche_variants, - niche_start, - } => { + DiscriminantKind::Niche { dataful_variant, ref niche_variants, niche_start } => { // Rebase from niche values to discriminants, and check // whether the result is in range for the niche variants. let niche_llty = bx.cx().immediate_backend_type(encoded_discr.layout); @@ -311,14 +309,10 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { return; } match self.layout.variants { - layout::Variants::Single { index } => { + Variants::Single { index } => { assert_eq!(index, variant_index); } - layout::Variants::Multiple { - discr_kind: layout::DiscriminantKind::Tag, - discr_index, - .. - } => { + Variants::Multiple { discr_kind: DiscriminantKind::Tag, discr_index, .. } => { let ptr = self.project_field(bx, discr_index); let to = self.layout.ty.discriminant_for_variant(bx.tcx(), variant_index).unwrap().val; @@ -328,9 +322,9 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { ptr.align, ); } - layout::Variants::Multiple { + Variants::Multiple { discr_kind: - layout::DiscriminantKind::Niche { dataful_variant, ref niche_variants, niche_start }, + DiscriminantKind::Niche { dataful_variant, ref niche_variants, niche_start }, discr_index, .. } => { diff --git a/src/librustc_codegen_ssa/mir/rvalue.rs b/src/librustc_codegen_ssa/mir/rvalue.rs index 66ce50c482a6f..6543b33822f71 100644 --- a/src/librustc_codegen_ssa/mir/rvalue.rs +++ b/src/librustc_codegen_ssa/mir/rvalue.rs @@ -8,13 +8,14 @@ use crate::traits::*; use crate::MemFlags; use rustc_apfloat::{ieee, Float, Round, Status}; -use rustc_middle::middle::lang_items::ExchangeMallocFnLangItem; +use rustc_hir::lang_items::ExchangeMallocFnLangItem; use rustc_middle::mir; use rustc_middle::ty::cast::{CastTy, IntTy}; -use rustc_middle::ty::layout::{self, HasTyCtxt, LayoutOf}; +use rustc_middle::ty::layout::HasTyCtxt; use rustc_middle::ty::{self, adjustment::PointerCast, Instance, Ty, TyCtxt}; use rustc_span::source_map::{Span, DUMMY_SP}; use rustc_span::symbol::sym; +use rustc_target::abi::{Abi, Int, LayoutOf, Variants}; use std::{i128, u128}; @@ -292,7 +293,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let r_t_out = CastTy::from_ty(cast.ty).expect("bad output type for cast"); let ll_t_in = bx.cx().immediate_backend_type(operand.layout); match operand.layout.variants { - layout::Variants::Single { index } => { + Variants::Single { index } => { if let Some(discr) = operand.layout.ty.discriminant_for_variant(bx.tcx(), index) { @@ -311,13 +312,13 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { ); } } - layout::Variants::Multiple { .. } => {} + Variants::Multiple { .. } => {} } let llval = operand.immediate(); let mut signed = false; - if let layout::Abi::Scalar(ref scalar) = operand.layout.abi { - if let layout::Int(_, s) = scalar.value { + if let Abi::Scalar(ref scalar) = operand.layout.abi { + if let Int(_, s) = scalar.value { // We use `i1` for bytes that are always `0` or `1`, // e.g., `#[repr(i8)] enum E { A, B }`, but we can't // let LLVM interpret the `i1` as signed, because diff --git a/src/librustc_codegen_ssa/traits/backend.rs b/src/librustc_codegen_ssa/traits/backend.rs index 1474edd8aa09a..91be123beb0bc 100644 --- a/src/librustc_codegen_ssa/traits/backend.rs +++ b/src/librustc_codegen_ssa/traits/backend.rs @@ -3,17 +3,18 @@ use super::CodegenObject; use crate::ModuleCodegen; use rustc_ast::expand::allocator::AllocatorKind; +use rustc_errors::ErrorReported; use rustc_middle::dep_graph::DepGraph; use rustc_middle::middle::cstore::{EncodedMetadata, MetadataLoaderDyn}; -use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout}; +use rustc_middle::ty::layout::{HasTyCtxt, TyAndLayout}; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{Ty, TyCtxt}; -use rustc_middle::util::common::ErrorReported; use rustc_session::{ config::{self, OutputFilenames, PrintRequest}, Session, }; use rustc_span::symbol::Symbol; +use rustc_target::abi::LayoutOf; pub use rustc_data_structures::sync::MetadataRef; diff --git a/src/librustc_codegen_ssa/traits/builder.rs b/src/librustc_codegen_ssa/traits/builder.rs index d59ea387b86ba..caba7ebef593b 100644 --- a/src/librustc_codegen_ssa/traits/builder.rs +++ b/src/librustc_codegen_ssa/traits/builder.rs @@ -12,8 +12,9 @@ use crate::mir::operand::OperandRef; use crate::mir::place::PlaceRef; use crate::MemFlags; -use rustc_middle::ty::layout::{Align, HasParamEnv, Size}; +use rustc_middle::ty::layout::HasParamEnv; use rustc_middle::ty::Ty; +use rustc_target::abi::{Align, Size}; use rustc_target::spec::HasTargetSpec; use std::iter::TrustedLen; diff --git a/src/librustc_codegen_ssa/traits/consts.rs b/src/librustc_codegen_ssa/traits/consts.rs index e5e1aa658e62e..6b58dea794bcb 100644 --- a/src/librustc_codegen_ssa/traits/consts.rs +++ b/src/librustc_codegen_ssa/traits/consts.rs @@ -1,9 +1,9 @@ use super::BackendTypes; use crate::mir::place::PlaceRef; -use rustc_middle::mir::interpret::Allocation; -use rustc_middle::mir::interpret::Scalar; -use rustc_middle::ty::layout; +use rustc_middle::mir::interpret::{Allocation, Scalar}; +use rustc_middle::ty::layout::TyAndLayout; use rustc_span::Symbol; +use rustc_target::abi::{self, Size}; pub trait ConstMethods<'tcx>: BackendTypes { // Constant constructors @@ -26,17 +26,12 @@ pub trait ConstMethods<'tcx>: BackendTypes { fn const_to_opt_uint(&self, v: Self::Value) -> Option; fn const_to_opt_u128(&self, v: Self::Value, sign_ext: bool) -> Option; - fn scalar_to_backend( - &self, - cv: Scalar, - layout: &layout::Scalar, - llty: Self::Type, - ) -> Self::Value; + fn scalar_to_backend(&self, cv: Scalar, layout: &abi::Scalar, llty: Self::Type) -> Self::Value; fn from_const_alloc( &self, - layout: layout::TyAndLayout<'tcx>, + layout: TyAndLayout<'tcx>, alloc: &Allocation, - offset: layout::Size, + offset: Size, ) -> PlaceRef<'tcx, Self::Value>; fn const_ptrcast(&self, val: Self::Value, ty: Self::Type) -> Self::Value; diff --git a/src/librustc_codegen_ssa/traits/debuginfo.rs b/src/librustc_codegen_ssa/traits/debuginfo.rs index 4e84c096822ef..34be1cfdd8844 100644 --- a/src/librustc_codegen_ssa/traits/debuginfo.rs +++ b/src/librustc_codegen_ssa/traits/debuginfo.rs @@ -3,10 +3,10 @@ use crate::mir::debuginfo::{FunctionDebugContext, VariableKind}; use rustc_ast::ast::Name; use rustc_hir::def_id::CrateNum; use rustc_middle::mir; -use rustc_middle::ty::layout::Size; use rustc_middle::ty::{Instance, Ty}; use rustc_span::{SourceFile, Span}; use rustc_target::abi::call::FnAbi; +use rustc_target::abi::Size; pub trait DebugInfoMethods<'tcx>: BackendTypes { fn create_vtable_metadata(&self, ty: Ty<'tcx>, vtable: Self::Value); diff --git a/src/librustc_codegen_ssa/traits/statics.rs b/src/librustc_codegen_ssa/traits/statics.rs index 50df08614345f..a6462b358347b 100644 --- a/src/librustc_codegen_ssa/traits/statics.rs +++ b/src/librustc_codegen_ssa/traits/statics.rs @@ -1,6 +1,6 @@ use super::BackendTypes; use rustc_hir::def_id::DefId; -use rustc_middle::ty::layout::Align; +use rustc_target::abi::Align; pub trait StaticMethods: BackendTypes { fn static_addr_of(&self, cv: Self::Value, align: Align, kind: Option<&str>) -> Self::Value; diff --git a/src/librustc_codegen_ssa/traits/type_.rs b/src/librustc_codegen_ssa/traits/type_.rs index 383be6dfcb5ea..703479b74bef8 100644 --- a/src/librustc_codegen_ssa/traits/type_.rs +++ b/src/librustc_codegen_ssa/traits/type_.rs @@ -3,10 +3,11 @@ use super::Backend; use super::HasCodegen; use crate::common::TypeKind; use crate::mir::place::PlaceRef; -use rustc_middle::ty::layout::{self, TyAndLayout}; +use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::{self, Ty}; use rustc_span::DUMMY_SP; use rustc_target::abi::call::{ArgAbi, CastTarget, FnAbi, Reg}; +use rustc_target::abi::Integer; // This depends on `Backend` and not `BackendTypes`, because consumers will probably want to use // `LayoutOf` or `HasTyCtxt`. This way, they don't have to add a constraint on it themselves. @@ -53,8 +54,8 @@ pub trait DerivedTypeMethods<'tcx>: BaseTypeMethods<'tcx> + MiscMethods<'tcx> { } } - fn type_from_integer(&self, i: layout::Integer) -> Self::Type { - use rustc_middle::ty::layout::Integer::*; + fn type_from_integer(&self, i: Integer) -> Self::Type { + use Integer::*; match i { I8 => self.type_i8(), I16 => self.type_i16(), diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index 8f8c2eae6e27d..ccbce01d6c12e 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -22,10 +22,8 @@ use rustc_ast::ast; use rustc_codegen_ssa::{traits::CodegenBackend, CodegenResults}; use rustc_data_structures::profiling::print_time_passes_entry; use rustc_data_structures::sync::SeqCst; -use rustc_errors::{ - registry::{InvalidErrorCode, Registry}, - PResult, -}; +use rustc_errors::registry::{InvalidErrorCode, Registry}; +use rustc_errors::{ErrorReported, PResult}; use rustc_feature::{find_gated_cfg, UnstableFeatures}; use rustc_hir::def_id::LOCAL_CRATE; use rustc_interface::util::{collect_crate_types, get_builtin_codegen_backend}; @@ -34,7 +32,6 @@ use rustc_lint::LintStore; use rustc_metadata::locator; use rustc_middle::middle::cstore::MetadataLoader; use rustc_middle::ty::TyCtxt; -use rustc_middle::util::common::ErrorReported; use rustc_save_analysis as save; use rustc_save_analysis::DumpHandler; use rustc_serialize::json::{self, ToJson}; diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 87777bd674bf2..78a271810b288 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -2,12 +2,12 @@ use rustc_ast::ast; use rustc_ast_pretty::pprust; +use rustc_errors::ErrorReported; use rustc_hir as hir; use rustc_hir::def_id::LOCAL_CRATE; use rustc_hir_pretty as pprust_hir; use rustc_middle::hir::map as hir_map; use rustc_middle::ty::{self, TyCtxt}; -use rustc_middle::util::common::ErrorReported; use rustc_mir::util::{write_mir_graphviz, write_mir_pretty}; use rustc_session::config::{Input, PpMode, PpSourceMode}; use rustc_session::Session; diff --git a/src/librustc_infer/infer/error_reporting/nice_region_error/different_lifetimes.rs b/src/librustc_infer/infer/error_reporting/nice_region_error/different_lifetimes.rs index 3836bd9afa8b6..d206a30d526cb 100644 --- a/src/librustc_infer/infer/error_reporting/nice_region_error/different_lifetimes.rs +++ b/src/librustc_infer/infer/error_reporting/nice_region_error/different_lifetimes.rs @@ -5,9 +5,8 @@ use crate::infer::error_reporting::nice_region_error::util::AnonymousParamInfo; use crate::infer::error_reporting::nice_region_error::NiceRegionError; use crate::infer::lexical_region_resolve::RegionResolutionError; use crate::infer::SubregionOrigin; -use rustc_middle::util::common::ErrorReported; -use rustc_errors::struct_span_err; +use rustc_errors::{struct_span_err, ErrorReported}; impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { /// Print the error message for lifetime errors when both the concerned regions are anonymous. diff --git a/src/librustc_infer/infer/error_reporting/nice_region_error/mod.rs b/src/librustc_infer/infer/error_reporting/nice_region_error/mod.rs index 4613c43ba07af..2aed3d9a469fb 100644 --- a/src/librustc_infer/infer/error_reporting/nice_region_error/mod.rs +++ b/src/librustc_infer/infer/error_reporting/nice_region_error/mod.rs @@ -1,9 +1,8 @@ use crate::infer::lexical_region_resolve::RegionResolutionError; use crate::infer::lexical_region_resolve::RegionResolutionError::*; use crate::infer::InferCtxt; -use rustc_errors::DiagnosticBuilder; +use rustc_errors::{DiagnosticBuilder, ErrorReported}; use rustc_middle::ty::{self, TyCtxt}; -use rustc_middle::util::common::ErrorReported; use rustc_span::source_map::Span; mod different_lifetimes; diff --git a/src/librustc_infer/infer/error_reporting/nice_region_error/outlives_closure.rs b/src/librustc_infer/infer/error_reporting/nice_region_error/outlives_closure.rs index 028148b17db18..70c302710430b 100644 --- a/src/librustc_infer/infer/error_reporting/nice_region_error/outlives_closure.rs +++ b/src/librustc_infer/infer/error_reporting/nice_region_error/outlives_closure.rs @@ -4,9 +4,9 @@ use crate::infer::error_reporting::nice_region_error::NiceRegionError; use crate::infer::lexical_region_resolve::RegionResolutionError::SubSupConflict; use crate::infer::SubregionOrigin; +use rustc_errors::ErrorReported; use rustc_hir::{Expr, ExprKind::Closure, Node}; use rustc_middle::ty::RegionKind; -use rustc_middle::util::common::ErrorReported; impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { /// Print the error message for lifetime errors when binding escapes a closure. diff --git a/src/librustc_infer/infer/error_reporting/nice_region_error/static_impl_trait.rs b/src/librustc_infer/infer/error_reporting/nice_region_error/static_impl_trait.rs index 34653f2dc0db8..7f3ec852e41de 100644 --- a/src/librustc_infer/infer/error_reporting/nice_region_error/static_impl_trait.rs +++ b/src/librustc_infer/infer/error_reporting/nice_region_error/static_impl_trait.rs @@ -3,9 +3,8 @@ use crate::infer::error_reporting::msg_span_from_free_region; use crate::infer::error_reporting::nice_region_error::NiceRegionError; use crate::infer::lexical_region_resolve::RegionResolutionError; -use rustc_errors::Applicability; +use rustc_errors::{Applicability, ErrorReported}; use rustc_middle::ty::{BoundRegion, FreeRegion, RegionKind}; -use rustc_middle::util::common::ErrorReported; impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { /// Print the error message for lifetime errors when the return type is a static impl Trait. diff --git a/src/librustc_infer/infer/error_reporting/nice_region_error/trait_impl_difference.rs b/src/librustc_infer/infer/error_reporting/nice_region_error/trait_impl_difference.rs index a2cd54b48d520..695f3e47fb5d7 100644 --- a/src/librustc_infer/infer/error_reporting/nice_region_error/trait_impl_difference.rs +++ b/src/librustc_infer/infer/error_reporting/nice_region_error/trait_impl_difference.rs @@ -4,8 +4,8 @@ use crate::infer::error_reporting::nice_region_error::NiceRegionError; use crate::infer::lexical_region_resolve::RegionResolutionError; use crate::infer::{Subtype, ValuePairs}; use crate::traits::ObligationCauseCode::CompareImplMethodObligation; +use rustc_errors::ErrorReported; use rustc_middle::ty::Ty; -use rustc_middle::util::common::ErrorReported; use rustc_span::Span; impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { diff --git a/src/librustc_interface/interface.rs b/src/librustc_interface/interface.rs index a50e802ac2ec6..8e929b7daa850 100644 --- a/src/librustc_interface/interface.rs +++ b/src/librustc_interface/interface.rs @@ -8,9 +8,9 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::sync::Lrc; use rustc_data_structures::OnDrop; use rustc_errors::registry::Registry; +use rustc_errors::ErrorReported; use rustc_lint::LintStore; use rustc_middle::ty; -use rustc_middle::util::common::ErrorReported; use rustc_parse::new_parser_from_source_str; use rustc_session::config::{self, ErrorOutputType, Input, OutputFilenames}; use rustc_session::early_error; diff --git a/src/librustc_interface/passes.rs b/src/librustc_interface/passes.rs index e3fc4fa52fb61..609c80a2b7905 100644 --- a/src/librustc_interface/passes.rs +++ b/src/librustc_interface/passes.rs @@ -9,7 +9,7 @@ use rustc_codegen_ssa::back::link::emit_metadata; use rustc_codegen_ssa::traits::CodegenBackend; use rustc_data_structures::sync::{par_iter, Lrc, Once, ParallelIterator, WorkerLocal}; use rustc_data_structures::{box_region_allow_access, declare_box_region_type, parallel}; -use rustc_errors::PResult; +use rustc_errors::{ErrorReported, PResult}; use rustc_expand::base::ExtCtxt; use rustc_hir::def_id::{CrateNum, LOCAL_CRATE}; use rustc_hir::definitions::Definitions; @@ -21,7 +21,6 @@ use rustc_middle::middle; use rustc_middle::middle::cstore::{CrateStore, MetadataLoader, MetadataLoaderDyn}; use rustc_middle::ty::steal::Steal; use rustc_middle::ty::{self, GlobalCtxt, ResolverOutputs, TyCtxt}; -use rustc_middle::util::common::ErrorReported; use rustc_mir as mir; use rustc_mir_build as mir_build; use rustc_parse::{parse_crate_from_file, parse_crate_from_source_str}; diff --git a/src/librustc_interface/queries.rs b/src/librustc_interface/queries.rs index 995776552dd18..6a62d754f2891 100644 --- a/src/librustc_interface/queries.rs +++ b/src/librustc_interface/queries.rs @@ -4,6 +4,7 @@ use crate::passes::{self, BoxedResolver, QueryContext}; use rustc_ast::{self, ast}; use rustc_codegen_ssa::traits::CodegenBackend; use rustc_data_structures::sync::{Lrc, Once, WorkerLocal}; +use rustc_errors::ErrorReported; use rustc_hir::def_id::LOCAL_CRATE; use rustc_hir::Crate; use rustc_incremental::DepGraphFuture; @@ -12,7 +13,6 @@ use rustc_middle::arena::Arena; use rustc_middle::dep_graph::DepGraph; use rustc_middle::ty::steal::Steal; use rustc_middle::ty::{GlobalCtxt, ResolverOutputs, TyCtxt}; -use rustc_middle::util::common::ErrorReported; use rustc_session::config::{OutputFilenames, OutputType}; use rustc_session::{output::find_crate_name, Session}; use rustc_span::symbol::sym; diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index 646febec72334..cff86e8f21837 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -36,12 +36,13 @@ use rustc_hir::def_id::DefId; use rustc_hir::{GenericParamKind, PatKind}; use rustc_hir::{HirIdSet, Node}; use rustc_middle::lint::LintDiagnosticBuilder; -use rustc_middle::ty::{self, layout::VariantIdx, Ty, TyCtxt}; +use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_session::lint::FutureIncompatibleInfo; use rustc_span::edition::Edition; use rustc_span::source_map::Spanned; use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::{BytePos, Span}; +use rustc_target::abi::VariantIdx; use rustc_trait_selection::traits::misc::can_type_implement_copy; use crate::nonstandard_style::{method_context, MethodLateContext}; diff --git a/src/librustc_lint/context.rs b/src/librustc_lint/context.rs index 12543cf83ddb2..1747a78d36a4c 100644 --- a/src/librustc_lint/context.rs +++ b/src/librustc_lint/context.rs @@ -29,12 +29,13 @@ use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData}; use rustc_middle::lint::LintDiagnosticBuilder; use rustc_middle::middle::privacy::AccessLevels; use rustc_middle::middle::stability; -use rustc_middle::ty::layout::{LayoutError, LayoutOf, TyAndLayout}; +use rustc_middle::ty::layout::{LayoutError, TyAndLayout}; use rustc_middle::ty::{self, print::Printer, subst::GenericArg, Ty, TyCtxt}; use rustc_session::lint::{add_elided_lifetime_in_path_suggestion, BuiltinLintDiagnostics}; use rustc_session::lint::{FutureIncompatibleInfo, Level, Lint, LintBuffer, LintId}; use rustc_session::Session; use rustc_span::{symbol::Symbol, MultiSpan, Span, DUMMY_SP}; +use rustc_target::abi::LayoutOf; use std::slice; diff --git a/src/librustc_lint/early.rs b/src/librustc_lint/early.rs index 34da29c974777..018e9da243c70 100644 --- a/src/librustc_lint/early.rs +++ b/src/librustc_lint/early.rs @@ -104,6 +104,11 @@ impl<'a, T: EarlyLintPass> ast_visit::Visitor<'a> for EarlyContextAndPass<'a, T> run_early_pass!(self, check_pat_post, p); } + fn visit_anon_const(&mut self, c: &'a ast::AnonConst) { + run_early_pass!(self, check_anon_const, c); + ast_visit::walk_anon_const(self, c); + } + fn visit_expr(&mut self, e: &'a ast::Expr) { self.with_lint_attrs(e.id, &e.attrs, |cx| { run_early_pass!(cx, check_expr, e); diff --git a/src/librustc_lint/lib.rs b/src/librustc_lint/lib.rs index 97261759aeb28..af1fad2c6608b 100644 --- a/src/librustc_lint/lib.rs +++ b/src/librustc_lint/lib.rs @@ -104,6 +104,7 @@ macro_rules! early_lint_passes { $args, [ UnusedParens: UnusedParens, + UnusedBraces: UnusedBraces, UnusedImportBraces: UnusedImportBraces, UnsafeCode: UnsafeCode, AnonymousParameters: AnonymousParameters, @@ -275,6 +276,7 @@ fn register_builtins(store: &mut LintStore, no_interleave_lints: bool) { UNUSED_FEATURES, UNUSED_LABELS, UNUSED_PARENS, + UNUSED_BRACES, REDUNDANT_SEMICOLONS ); diff --git a/src/librustc_lint/passes.rs b/src/librustc_lint/passes.rs index ace154714458e..c9e12afedbbab 100644 --- a/src/librustc_lint/passes.rs +++ b/src/librustc_lint/passes.rs @@ -170,6 +170,7 @@ macro_rules! early_lint_methods { fn check_stmt(a: &ast::Stmt); fn check_arm(a: &ast::Arm); fn check_pat(a: &ast::Pat); + fn check_anon_const(a: &ast::AnonConst); fn check_pat_post(a: &ast::Pat); fn check_expr(a: &ast::Expr); fn check_expr_post(a: &ast::Expr); diff --git a/src/librustc_lint/types.rs b/src/librustc_lint/types.rs index 52ec8cd938156..a6e1ed84c8708 100644 --- a/src/librustc_lint/types.rs +++ b/src/librustc_lint/types.rs @@ -10,12 +10,13 @@ use rustc_hir::def_id::DefId; use rustc_hir::{is_range_literal, ExprKind, Node}; use rustc_index::vec::Idx; use rustc_middle::mir::interpret::{sign_extend, truncate}; -use rustc_middle::ty::layout::{self, IntegerExt, LayoutOf, SizeSkeleton, VariantIdx}; +use rustc_middle::ty::layout::{IntegerExt, SizeSkeleton}; use rustc_middle::ty::subst::SubstsRef; use rustc_middle::ty::{self, AdtKind, ParamEnv, Ty, TyCtxt}; use rustc_span::source_map; use rustc_span::symbol::sym; use rustc_span::Span; +use rustc_target::abi::{DiscriminantKind, Integer, LayoutOf, VariantIdx, Variants}; use rustc_target::spec::abi::Abi; use log::debug; @@ -150,7 +151,7 @@ fn report_bin_hex_error( val: u128, negative: bool, ) { - let size = layout::Integer::from_attr(&cx.tcx, ty).size(); + let size = Integer::from_attr(&cx.tcx, ty).size(); cx.struct_span_lint(OVERFLOWING_LITERALS, expr.span, |lint| { let (t, actually) = match ty { attr::IntType::SignedInt(t) => { @@ -1034,8 +1035,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VariantSizeDifferences { | Err(ty::layout::LayoutError::SizeOverflow(_)) => return, }; let (variants, tag) = match layout.variants { - layout::Variants::Multiple { - discr_kind: layout::DiscriminantKind::Tag, + Variants::Multiple { + discr_kind: DiscriminantKind::Tag, ref discr, ref variants, .. diff --git a/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs index 78a67ae6afe73..c74b399555a8a 100644 --- a/src/librustc_lint/unused.rs +++ b/src/librustc_lint/unused.rs @@ -1,5 +1,7 @@ +use crate::Lint; use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext}; use rustc_ast::ast; +use rustc_ast::ast::{ExprKind, StmtKind}; use rustc_ast::attr; use rustc_ast::util::parser; use rustc_ast_pretty::pprust; @@ -315,16 +317,58 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes { } } -declare_lint! { - pub(super) UNUSED_PARENS, - Warn, - "`if`, `match`, `while` and `return` do not need parentheses" +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +enum UnusedDelimsCtx { + FunctionArg, + MethodArg, + AssignedValue, + IfCond, + WhileCond, + ForIterExpr, + MatchScrutineeExpr, + ReturnValue, + BlockRetValue, + LetScrutineeExpr, + ArrayLenExpr, + AnonConst, } -declare_lint_pass!(UnusedParens => [UNUSED_PARENS]); +impl From for &'static str { + fn from(ctx: UnusedDelimsCtx) -> &'static str { + match ctx { + UnusedDelimsCtx::FunctionArg => "function argument", + UnusedDelimsCtx::MethodArg => "method argument", + UnusedDelimsCtx::AssignedValue => "assigned value", + UnusedDelimsCtx::IfCond => "`if` condition", + UnusedDelimsCtx::WhileCond => "`while` condition", + UnusedDelimsCtx::ForIterExpr => "`for` iterator expression", + UnusedDelimsCtx::MatchScrutineeExpr => "`match` scrutinee expression", + UnusedDelimsCtx::ReturnValue => "`return` value", + UnusedDelimsCtx::BlockRetValue => "block return value", + UnusedDelimsCtx::LetScrutineeExpr => "`let` scrutinee expression", + UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression", + } + } +} -impl UnusedParens { - fn is_expr_parens_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool { +/// Used by both `UnusedParens` and `UnusedBraces` to prevent code duplication. +trait UnusedDelimLint { + const DELIM_STR: &'static str; + + // this cannot be a constant is it refers to a static. + fn lint(&self) -> &'static Lint; + + fn check_unused_delims_expr( + &self, + cx: &EarlyContext<'_>, + value: &ast::Expr, + ctx: UnusedDelimsCtx, + followed_by_block: bool, + left_pos: Option, + right_pos: Option, + ); + + fn is_expr_delims_necessary(inner: &ast::Expr, followed_by_block: bool) -> bool { followed_by_block && match inner.kind { ast::ExprKind::Ret(_) | ast::ExprKind::Break(..) => true, @@ -332,98 +376,41 @@ impl UnusedParens { } } - fn check_unused_parens_expr( + fn emit_unused_delims_expr( &self, cx: &EarlyContext<'_>, value: &ast::Expr, - msg: &str, - followed_by_block: bool, + ctx: UnusedDelimsCtx, left_pos: Option, right_pos: Option, ) { - match value.kind { - ast::ExprKind::Paren(ref inner) => { - if !Self::is_expr_parens_necessary(inner, followed_by_block) - && value.attrs.is_empty() - && !value.span.from_expansion() - { - let expr_text = - if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) { - snippet - } else { - pprust::expr_to_string(value) - }; - let keep_space = ( - left_pos.map(|s| s >= value.span.lo()).unwrap_or(false), - right_pos.map(|s| s <= value.span.hi()).unwrap_or(false), - ); - Self::remove_outer_parens(cx, value.span, &expr_text, msg, keep_space); - } - } - ast::ExprKind::Let(_, ref expr) => { - // FIXME(#60336): Properly handle `let true = (false && true)` - // actually needing the parenthesis. - self.check_unused_parens_expr( - cx, - expr, - "`let` head expression", - followed_by_block, - None, - None, - ); - } - _ => {} - } + let expr_text = if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) { + snippet + } else { + pprust::expr_to_string(value) + }; + let keep_space = ( + left_pos.map(|s| s >= value.span.lo()).unwrap_or(false), + right_pos.map(|s| s <= value.span.hi()).unwrap_or(false), + ); + self.emit_unused_delims(cx, value.span, &expr_text, ctx.into(), keep_space); } - fn check_unused_parens_pat( + fn emit_unused_delims( &self, - cx: &EarlyContext<'_>, - value: &ast::Pat, - avoid_or: bool, - avoid_mut: bool, - ) { - use ast::{BindingMode, Mutability, PatKind}; - - if let PatKind::Paren(inner) = &value.kind { - match inner.kind { - // The lint visitor will visit each subpattern of `p`. We do not want to lint - // any range pattern no matter where it occurs in the pattern. For something like - // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume - // that if there are unnecessary parens they serve a purpose of readability. - PatKind::Range(..) => return, - // Avoid `p0 | .. | pn` if we should. - PatKind::Or(..) if avoid_or => return, - // Avoid `mut x` and `mut x @ p` if we should: - PatKind::Ident(BindingMode::ByValue(Mutability::Mut), ..) if avoid_mut => return, - // Otherwise proceed with linting. - _ => {} - } - - let pattern_text = - if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) { - snippet - } else { - pprust::pat_to_string(value) - }; - Self::remove_outer_parens(cx, value.span, &pattern_text, "pattern", (false, false)); - } - } - - fn remove_outer_parens( cx: &EarlyContext<'_>, span: Span, pattern: &str, msg: &str, keep_space: (bool, bool), ) { - cx.struct_span_lint(UNUSED_PARENS, span, |lint| { - let span_msg = format!("unnecessary parentheses around {}", msg); + cx.struct_span_lint(self.lint(), span, |lint| { + let span_msg = format!("unnecessary {} around {}", Self::DELIM_STR, msg); let mut err = lint.build(&span_msg); let mut ate_left_paren = false; let mut ate_right_paren = false; let parens_removed = pattern.trim_matches(|c| match c { - '(' => { + '(' | '{' => { if ate_left_paren { false } else { @@ -431,7 +418,7 @@ impl UnusedParens { true } } - ')' => { + ')' | '}' => { if ate_right_paren { false } else { @@ -457,61 +444,51 @@ impl UnusedParens { replace }; - err.span_suggestion_short( - span, - "remove these parentheses", - replace, - Applicability::MachineApplicable, - ); + let suggestion = format!("remove these {}", Self::DELIM_STR); + + err.span_suggestion_short(span, &suggestion, replace, Applicability::MachineApplicable); err.emit(); }); } -} -impl EarlyLintPass for UnusedParens { fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) { use rustc_ast::ast::ExprKind::*; - let (value, msg, followed_by_block, left_pos, right_pos) = match e.kind { - Let(ref pat, ..) => { - self.check_unused_parens_pat(cx, pat, false, false); - return; - } - + let (value, ctx, followed_by_block, left_pos, right_pos) = match e.kind { If(ref cond, ref block, ..) => { let left = e.span.lo() + rustc_span::BytePos(2); let right = block.span.lo(); - (cond, "`if` condition", true, Some(left), Some(right)) + (cond, UnusedDelimsCtx::IfCond, true, Some(left), Some(right)) } While(ref cond, ref block, ..) => { let left = e.span.lo() + rustc_span::BytePos(5); let right = block.span.lo(); - (cond, "`while` condition", true, Some(left), Some(right)) + (cond, UnusedDelimsCtx::WhileCond, true, Some(left), Some(right)) } - ForLoop(ref pat, ref cond, ref block, ..) => { - self.check_unused_parens_pat(cx, pat, false, false); - (cond, "`for` head expression", true, None, Some(block.span.lo())) + ForLoop(_, ref cond, ref block, ..) => { + (cond, UnusedDelimsCtx::ForIterExpr, true, None, Some(block.span.lo())) } Match(ref head, _) => { let left = e.span.lo() + rustc_span::BytePos(5); - (head, "`match` head expression", true, Some(left), None) + (head, UnusedDelimsCtx::MatchScrutineeExpr, true, Some(left), None) } Ret(Some(ref value)) => { let left = e.span.lo() + rustc_span::BytePos(3); - (value, "`return` value", false, Some(left), None) + (value, UnusedDelimsCtx::ReturnValue, false, Some(left), None) } - Assign(_, ref value, _) => (value, "assigned value", false, None, None), - AssignOp(.., ref value) => (value, "assigned value", false, None, None), + Assign(_, ref value, _) | AssignOp(.., ref value) => { + (value, UnusedDelimsCtx::AssignedValue, false, None, None) + } // either function/method call, or something this lint doesn't care about ref call_or_other => { - let (args_to_check, call_kind) = match *call_or_other { - Call(_, ref args) => (&args[..], "function"), - // first "argument" is self (which sometimes needs parens) - MethodCall(_, ref args) => (&args[1..], "method"), + let (args_to_check, ctx) = match *call_or_other { + Call(_, ref args) => (&args[..], UnusedDelimsCtx::FunctionArg), + // first "argument" is self (which sometimes needs delims) + MethodCall(_, ref args) => (&args[1..], UnusedDelimsCtx::MethodArg), // actual catch-all arm _ => { return; @@ -524,14 +501,152 @@ impl EarlyLintPass for UnusedParens { if e.span.ctxt().outer_expn_data().call_site.from_expansion() { return; } - let msg = format!("{} argument", call_kind); for arg in args_to_check { - self.check_unused_parens_expr(cx, arg, &msg, false, None, None); + self.check_unused_delims_expr(cx, arg, ctx, false, None, None); } return; } }; - self.check_unused_parens_expr(cx, &value, msg, followed_by_block, left_pos, right_pos); + self.check_unused_delims_expr(cx, &value, ctx, followed_by_block, left_pos, right_pos); + } + + fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) { + match s.kind { + StmtKind::Local(ref local) => { + if let Some(ref value) = local.init { + self.check_unused_delims_expr( + cx, + &value, + UnusedDelimsCtx::AssignedValue, + false, + None, + None, + ); + } + } + StmtKind::Expr(ref expr) => { + self.check_unused_delims_expr( + cx, + &expr, + UnusedDelimsCtx::BlockRetValue, + false, + None, + None, + ); + } + _ => {} + } + } + + fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) { + use ast::ItemKind::*; + + if let Const(.., Some(expr)) | Static(.., Some(expr)) = &item.kind { + self.check_unused_delims_expr( + cx, + expr, + UnusedDelimsCtx::AssignedValue, + false, + None, + None, + ); + } + } +} + +declare_lint! { + pub(super) UNUSED_PARENS, + Warn, + "`if`, `match`, `while` and `return` do not need parentheses" +} + +declare_lint_pass!(UnusedParens => [UNUSED_PARENS]); + +impl UnusedDelimLint for UnusedParens { + const DELIM_STR: &'static str = "parentheses"; + + fn lint(&self) -> &'static Lint { + UNUSED_PARENS + } + + fn check_unused_delims_expr( + &self, + cx: &EarlyContext<'_>, + value: &ast::Expr, + ctx: UnusedDelimsCtx, + followed_by_block: bool, + left_pos: Option, + right_pos: Option, + ) { + match value.kind { + ast::ExprKind::Paren(ref inner) => { + if !Self::is_expr_delims_necessary(inner, followed_by_block) + && value.attrs.is_empty() + && !value.span.from_expansion() + { + self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos) + } + } + ast::ExprKind::Let(_, ref expr) => { + // FIXME(#60336): Properly handle `let true = (false && true)` + // actually needing the parenthesis. + self.check_unused_delims_expr( + cx, + expr, + UnusedDelimsCtx::LetScrutineeExpr, + followed_by_block, + None, + None, + ); + } + _ => {} + } + } +} + +impl UnusedParens { + fn check_unused_parens_pat( + &self, + cx: &EarlyContext<'_>, + value: &ast::Pat, + avoid_or: bool, + avoid_mut: bool, + ) { + use ast::{BindingMode, Mutability, PatKind}; + + if let PatKind::Paren(inner) = &value.kind { + match inner.kind { + // The lint visitor will visit each subpattern of `p`. We do not want to lint + // any range pattern no matter where it occurs in the pattern. For something like + // `&(a..=b)`, there is a recursive `check_pat` on `a` and `b`, but we will assume + // that if there are unnecessary parens they serve a purpose of readability. + PatKind::Range(..) => return, + // Avoid `p0 | .. | pn` if we should. + PatKind::Or(..) if avoid_or => return, + // Avoid `mut x` and `mut x @ p` if we should: + PatKind::Ident(BindingMode::ByValue(Mutability::Mut), ..) if avoid_mut => return, + // Otherwise proceed with linting. + _ => {} + } + + let pattern_text = + if let Ok(snippet) = cx.sess().source_map().span_to_snippet(value.span) { + snippet + } else { + pprust::pat_to_string(value) + }; + self.emit_unused_delims(cx, value.span, &pattern_text, "pattern", (false, false)); + } + } +} + +impl EarlyLintPass for UnusedParens { + fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) { + if let ExprKind::Let(ref pat, ..) | ExprKind::ForLoop(ref pat, ..) = e.kind { + self.check_unused_parens_pat(cx, pat, false, false); + } + + ::check_expr(self, cx, e) } fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat) { @@ -556,22 +671,16 @@ impl EarlyLintPass for UnusedParens { } } - fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) { - use ast::StmtKind::*; - - match s.kind { - Local(ref local) => { - self.check_unused_parens_pat(cx, &local.pat, false, false); + fn check_anon_const(&mut self, cx: &EarlyContext<'_>, c: &ast::AnonConst) { + self.check_unused_delims_expr(cx, &c.value, UnusedDelimsCtx::AnonConst, false, None, None); + } - if let Some(ref value) = local.init { - self.check_unused_parens_expr(cx, &value, "assigned value", false, None, None); - } - } - Expr(ref expr) => { - self.check_unused_parens_expr(cx, &expr, "block return value", false, None, None); - } - _ => {} + fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) { + if let StmtKind::Local(ref local) = s.kind { + self.check_unused_parens_pat(cx, &local.pat, false, false); } + + ::check_stmt(self, cx, s) } fn check_param(&mut self, cx: &EarlyContext<'_>, param: &ast::Param) { @@ -587,6 +696,16 @@ impl EarlyLintPass for UnusedParens { match &r.kind { &ast::TyKind::TraitObject(..) => {} &ast::TyKind::ImplTrait(_, ref bounds) if bounds.len() > 1 => {} + &ast::TyKind::Array(_, ref len) => { + self.check_unused_delims_expr( + cx, + &len.value, + UnusedDelimsCtx::ArrayLenExpr, + false, + None, + None, + ); + } _ => { let pattern_text = if let Ok(snippet) = cx.sess().source_map().span_to_snippet(ty.span) { @@ -595,19 +714,134 @@ impl EarlyLintPass for UnusedParens { pprust::ty_to_string(ty) }; - Self::remove_outer_parens(cx, ty.span, &pattern_text, "type", (false, false)); + self.emit_unused_delims(cx, ty.span, &pattern_text, "type", (false, false)); } } } } fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) { - use ast::ItemKind::*; + ::check_item(self, cx, item) + } +} - if let Const(.., Some(expr)) | Static(.., Some(expr)) = &item.kind { - self.check_unused_parens_expr(cx, expr, "assigned value", false, None, None); +declare_lint! { + pub(super) UNUSED_BRACES, + Warn, + "unnecessary braces around an expression" +} + +declare_lint_pass!(UnusedBraces => [UNUSED_BRACES]); + +impl UnusedDelimLint for UnusedBraces { + const DELIM_STR: &'static str = "braces"; + + fn lint(&self) -> &'static Lint { + UNUSED_BRACES + } + + fn check_unused_delims_expr( + &self, + cx: &EarlyContext<'_>, + value: &ast::Expr, + ctx: UnusedDelimsCtx, + followed_by_block: bool, + left_pos: Option, + right_pos: Option, + ) { + match value.kind { + ast::ExprKind::Block(ref inner, None) + if inner.rules == ast::BlockCheckMode::Default => + { + // emit a warning under the following conditions: + // + // - the block does not have a label + // - the block is not `unsafe` + // - the block contains exactly one expression (do not lint `{ expr; }`) + // - `followed_by_block` is true and the internal expr may contain a `{` + // - the block is not multiline (do not lint multiline match arms) + // ``` + // match expr { + // Pattern => { + // somewhat_long_expression + // } + // // ... + // } + // ``` + // - the block has no attribute and was not created inside a macro + // - if the block is an `anon_const`, the inner expr must be a literal + // (do not lint `struct A; let _: A<{ 2 + 3 }>;`) + // + // FIXME(const_generics): handle paths when #67075 is fixed. + if let [stmt] = inner.stmts.as_slice() { + if let ast::StmtKind::Expr(ref expr) = stmt.kind { + if !Self::is_expr_delims_necessary(expr, followed_by_block) + && (ctx != UnusedDelimsCtx::AnonConst + || matches!(expr.kind, ast::ExprKind::Lit(_))) + // array length expressions are checked during `check_anon_const` and `check_ty`, + // once as `ArrayLenExpr` and once as `AnonConst`. + // + // As we do not want to lint this twice, we do not emit an error for + // `ArrayLenExpr` if `AnonConst` would do the same. + && (ctx != UnusedDelimsCtx::ArrayLenExpr + || !matches!(expr.kind, ast::ExprKind::Lit(_))) + && !cx.sess().source_map().is_multiline(value.span) + && value.attrs.is_empty() + && !value.span.from_expansion() + { + self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos) + } + } + } + } + ast::ExprKind::Let(_, ref expr) => { + // FIXME(#60336): Properly handle `let true = (false && true)` + // actually needing the parenthesis. + self.check_unused_delims_expr( + cx, + expr, + UnusedDelimsCtx::LetScrutineeExpr, + followed_by_block, + None, + None, + ); + } + _ => {} + } + } +} + +impl EarlyLintPass for UnusedBraces { + fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) { + ::check_expr(self, cx, e) + } + + fn check_anon_const(&mut self, cx: &EarlyContext<'_>, c: &ast::AnonConst) { + self.check_unused_delims_expr(cx, &c.value, UnusedDelimsCtx::AnonConst, false, None, None); + } + + fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) { + ::check_stmt(self, cx, s) + } + + fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) { + if let &ast::TyKind::Paren(ref r) = &ty.kind { + if let ast::TyKind::Array(_, ref len) = r.kind { + self.check_unused_delims_expr( + cx, + &len.value, + UnusedDelimsCtx::ArrayLenExpr, + false, + None, + None, + ); + } } } + + fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) { + ::check_item(self, cx, item) + } } declare_lint! { diff --git a/src/librustc_macros/src/query.rs b/src/librustc_macros/src/query.rs index 08dc854e9ff59..7ed77304a90e1 100644 --- a/src/librustc_macros/src/query.rs +++ b/src/librustc_macros/src/query.rs @@ -356,9 +356,11 @@ fn add_query_description_impl( quote! { #t } }) .unwrap_or(quote! { _ }); + // expr is a `Block`, meaning that `{ #expr }` gets expanded + // to `{ { stmts... } }`, which triggers the `unused_braces` lint. quote! { #[inline] - #[allow(unused_variables)] + #[allow(unused_variables, unused_braces)] fn cache_on_disk( #tcx: TyCtxt<'tcx>, #key: Self::Key, diff --git a/src/librustc_metadata/rmeta/decoder.rs b/src/librustc_metadata/rmeta/decoder.rs index 004c5f2ebb7f4..1cb5dcb465c72 100644 --- a/src/librustc_metadata/rmeta/decoder.rs +++ b/src/librustc_metadata/rmeta/decoder.rs @@ -18,13 +18,13 @@ use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res}; use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE}; use rustc_hir::definitions::DefPathTable; use rustc_hir::definitions::{DefKey, DefPath, DefPathData, DefPathHash}; +use rustc_hir::lang_items; use rustc_index::vec::{Idx, IndexVec}; use rustc_middle::dep_graph::{self, DepNode, DepNodeExt, DepNodeIndex}; use rustc_middle::hir::exports::Export; use rustc_middle::middle::cstore::{CrateSource, ExternCrate}; use rustc_middle::middle::cstore::{ForeignModule, LinkagePreference, NativeLibrary}; use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel}; -use rustc_middle::middle::lang_items; use rustc_middle::mir::interpret::{AllocDecodingSession, AllocDecodingState}; use rustc_middle::mir::{self, interpret, BodyAndCache, Promoted}; use rustc_middle::ty::codec::TyDecoder; diff --git a/src/librustc_metadata/rmeta/encoder.rs b/src/librustc_metadata/rmeta/encoder.rs index f6e2730cb5761..417c548690779 100644 --- a/src/librustc_metadata/rmeta/encoder.rs +++ b/src/librustc_metadata/rmeta/encoder.rs @@ -15,6 +15,7 @@ use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, use rustc_hir::definitions::DefPathTable; use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor}; use rustc_hir::itemlikevisit::{ItemLikeVisitor, ParItemLikeVisitor}; +use rustc_hir::lang_items; use rustc_hir::{AnonConst, GenericParamKind}; use rustc_index::vec::Idx; use rustc_middle::hir::map::Map; @@ -25,17 +26,16 @@ use rustc_middle::middle::dependency_format::Linkage; use rustc_middle::middle::exported_symbols::{ metadata_symbol_name, ExportedSymbol, SymbolExportLevel, }; -use rustc_middle::middle::lang_items; use rustc_middle::mir::{self, interpret}; use rustc_middle::traits::specialization_graph; use rustc_middle::ty::codec::{self as ty_codec, TyEncoder}; -use rustc_middle::ty::layout::VariantIdx; use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt}; use rustc_serialize::{opaque, Encodable, Encoder, SpecializedEncoder}; use rustc_session::config::{self, CrateType}; use rustc_span::source_map::Spanned; use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::{self, ExternalSource, FileName, SourceFile, Span}; +use rustc_target::abi::VariantIdx; use std::hash::Hash; use std::num::NonZeroUsize; use std::path::Path; diff --git a/src/librustc_metadata/rmeta/mod.rs b/src/librustc_metadata/rmeta/mod.rs index d0ad76b0fc7ea..d6260c536aa18 100644 --- a/src/librustc_metadata/rmeta/mod.rs +++ b/src/librustc_metadata/rmeta/mod.rs @@ -8,11 +8,11 @@ use rustc_data_structures::sync::MetadataRef; use rustc_hir as hir; use rustc_hir::def::CtorKind; use rustc_hir::def_id::{DefId, DefIndex}; +use rustc_hir::lang_items; use rustc_index::vec::IndexVec; use rustc_middle::hir::exports::Export; use rustc_middle::middle::cstore::{DepKind, ForeignModule, LinkagePreference, NativeLibrary}; use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel}; -use rustc_middle::middle::lang_items; use rustc_middle::mir; use rustc_middle::ty::{self, ReprOptions, Ty}; use rustc_serialize::opaque::Encoder; diff --git a/src/librustc_middle/arena.rs b/src/librustc_middle/arena.rs index fcf6989043a54..e3dec59478c1f 100644 --- a/src/librustc_middle/arena.rs +++ b/src/librustc_middle/arena.rs @@ -11,7 +11,7 @@ macro_rules! arena_types { ($macro:path, $args:tt, $tcx:lifetime) => ( $macro!($args, [ - [] layouts: rustc_middle::ty::layout::Layout, + [] layouts: rustc_target::abi::Layout, [] generics: rustc_middle::ty::Generics, [] trait_def: rustc_middle::ty::TraitDef, [] adt_def: rustc_middle::ty::AdtDef, @@ -106,7 +106,7 @@ macro_rules! arena_types { String >, [few] get_lib_features: rustc_middle::middle::lib_features::LibFeatures, - [few] defined_lib_features: rustc_middle::middle::lang_items::LanguageItems, + [few] defined_lib_features: rustc_hir::lang_items::LanguageItems, [few] visible_parent_map: rustc_hir::def_id::DefIdMap, [few] foreign_module: rustc_middle::middle::cstore::ForeignModule, [few] foreign_modules: Vec, diff --git a/src/librustc_middle/ich/mod.rs b/src/librustc_middle/ich/mod.rs index 516e3ed979c7c..c8fb2bf39cc80 100644 --- a/src/librustc_middle/ich/mod.rs +++ b/src/librustc_middle/ich/mod.rs @@ -4,7 +4,6 @@ pub use self::hcx::{ hash_stable_trait_impls, NodeIdHashingMode, StableHashingContext, StableHashingContextProvider, }; use rustc_span::symbol::{sym, Symbol}; -pub use rustc_span::CachingSourceMapView; mod hcx; diff --git a/src/librustc_middle/middle/lang_items.rs b/src/librustc_middle/middle/lang_items.rs index 36560371587a5..0f98c338c16b1 100644 --- a/src/librustc_middle/middle/lang_items.rs +++ b/src/librustc_middle/middle/lang_items.rs @@ -7,17 +7,13 @@ //! * Traits that represent operators; e.g., `Add`, `Sub`, `Index`. //! * Functions called by the compiler itself. -pub use self::LangItem::*; - use crate::ty::{self, TyCtxt}; use rustc_hir::def_id::DefId; +use rustc_hir::LangItem; use rustc_span::Span; use rustc_target::spec::PanicStrategy; -pub use rustc_hir::weak_lang_items::link_name; -pub use rustc_hir::{LangItem, LanguageItems}; - impl<'tcx> TyCtxt<'tcx> { /// Returns the `DefId` for a given `LangItem`. /// If not found, fatally aborts compilation. diff --git a/src/librustc_middle/mir/interpret/allocation.rs b/src/librustc_middle/mir/interpret/allocation.rs index 0e75f34629e0e..8b9f09774853a 100644 --- a/src/librustc_middle/mir/interpret/allocation.rs +++ b/src/librustc_middle/mir/interpret/allocation.rs @@ -7,14 +7,12 @@ use std::ops::{Deref, DerefMut, Range}; use rustc_ast::ast::Mutability; use rustc_data_structures::sorted_map::SortedMap; -use rustc_target::abi::HasDataLayout; +use rustc_target::abi::{Align, HasDataLayout, Size}; use super::{ read_target_uint, write_target_uint, AllocId, InterpResult, Pointer, Scalar, ScalarMaybeUndef, }; -use crate::ty::layout::{Align, Size}; - // NOTE: When adding new fields, make sure to adjust the `Snapshot` impl in // `src/librustc_mir/interpret/snapshot.rs`. #[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)] diff --git a/src/librustc_middle/mir/interpret/error.rs b/src/librustc_middle/mir/interpret/error.rs index c46ab89d0049c..135665ee012a9 100644 --- a/src/librustc_middle/mir/interpret/error.rs +++ b/src/librustc_middle/mir/interpret/error.rs @@ -1,7 +1,7 @@ use super::{AllocId, CheckInAllocMsg, Pointer, RawConst, ScalarMaybeUndef}; use crate::mir::interpret::ConstValue; -use crate::ty::layout::{Align, LayoutError, Size}; +use crate::ty::layout::LayoutError; use crate::ty::query::TyCtxtAt; use crate::ty::tls; use crate::ty::{self, layout, Ty}; @@ -14,6 +14,7 @@ use rustc_hir::definitions::DefPathData; use rustc_macros::HashStable; use rustc_session::CtfeBacktrace; use rustc_span::{def_id::DefId, Pos, Span}; +use rustc_target::abi::{Align, Size}; use std::{any::Any, fmt, mem}; #[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable, RustcEncodable, RustcDecodable)] diff --git a/src/librustc_middle/mir/interpret/mod.rs b/src/librustc_middle/mir/interpret/mod.rs index 10c3a06da0810..96bf694d8fa67 100644 --- a/src/librustc_middle/mir/interpret/mod.rs +++ b/src/librustc_middle/mir/interpret/mod.rs @@ -109,10 +109,10 @@ use rustc_data_structures::tiny_list::TinyList; use rustc_hir::def_id::DefId; use rustc_macros::HashStable; use rustc_serialize::{Decodable, Encodable, Encoder}; +use rustc_target::abi::{Endian, Size}; use crate::mir; use crate::ty::codec::TyDecoder; -use crate::ty::layout::{self, Size}; use crate::ty::subst::GenericArgKind; use crate::ty::{self, Instance, Ty, TyCtxt}; @@ -521,22 +521,22 @@ impl<'tcx> AllocMap<'tcx> { #[inline] pub fn write_target_uint( - endianness: layout::Endian, + endianness: Endian, mut target: &mut [u8], data: u128, ) -> Result<(), io::Error> { let len = target.len(); match endianness { - layout::Endian::Little => target.write_uint128::(data, len), - layout::Endian::Big => target.write_uint128::(data, len), + Endian::Little => target.write_uint128::(data, len), + Endian::Big => target.write_uint128::(data, len), } } #[inline] -pub fn read_target_uint(endianness: layout::Endian, mut source: &[u8]) -> Result { +pub fn read_target_uint(endianness: Endian, mut source: &[u8]) -> Result { match endianness { - layout::Endian::Little => source.read_uint128::(source.len()), - layout::Endian::Big => source.read_uint128::(source.len()), + Endian::Little => source.read_uint128::(source.len()), + Endian::Big => source.read_uint128::(source.len()), } } diff --git a/src/librustc_middle/mir/interpret/pointer.rs b/src/librustc_middle/mir/interpret/pointer.rs index d22207bd81651..7549d902dfbfe 100644 --- a/src/librustc_middle/mir/interpret/pointer.rs +++ b/src/librustc_middle/mir/interpret/pointer.rs @@ -1,8 +1,7 @@ use super::{AllocId, InterpResult}; -use crate::ty::layout::{self, HasDataLayout, Size}; - use rustc_macros::HashStable; +use rustc_target::abi::{HasDataLayout, Size}; use std::convert::TryFrom; use std::fmt::{self, Display}; @@ -37,7 +36,7 @@ impl Display for CheckInAllocMsg { // Pointer arithmetic //////////////////////////////////////////////////////////////////////////////// -pub trait PointerArithmetic: layout::HasDataLayout { +pub trait PointerArithmetic: HasDataLayout { // These are not supposed to be overridden. #[inline(always)] @@ -100,7 +99,7 @@ pub trait PointerArithmetic: layout::HasDataLayout { } } -impl PointerArithmetic for T {} +impl PointerArithmetic for T {} /// `Pointer` is generic over the type that represents a reference to `Allocation`s, /// thus making it possible for the most convenient representation to be used in diff --git a/src/librustc_middle/mir/interpret/value.rs b/src/librustc_middle/mir/interpret/value.rs index bf4ee8488238f..f3c1c87dad484 100644 --- a/src/librustc_middle/mir/interpret/value.rs +++ b/src/librustc_middle/mir/interpret/value.rs @@ -6,12 +6,9 @@ use rustc_apfloat::{ Float, }; use rustc_macros::HashStable; -use rustc_target::abi::TargetDataLayout; +use rustc_target::abi::{HasDataLayout, Size, TargetDataLayout}; -use crate::ty::{ - layout::{HasDataLayout, Size}, - ParamEnv, Ty, TyCtxt, -}; +use crate::ty::{ParamEnv, Ty, TyCtxt}; use super::{sign_extend, truncate, AllocId, Allocation, InterpResult, Pointer, PointerArithmetic}; diff --git a/src/librustc_middle/mir/mod.rs b/src/librustc_middle/mir/mod.rs index 9ba9d816d0f3f..20ac2970ad3a5 100644 --- a/src/librustc_middle/mir/mod.rs +++ b/src/librustc_middle/mir/mod.rs @@ -6,7 +6,6 @@ use crate::mir::interpret::{GlobalAlloc, Scalar}; use crate::mir::visit::MirVisitable; use crate::ty::adjustment::PointerCast; use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor}; -use crate::ty::layout::VariantIdx; use crate::ty::print::{FmtPrinter, Printer}; use crate::ty::subst::{Subst, SubstsRef}; use crate::ty::{ @@ -16,6 +15,7 @@ use rustc_hir as hir; use rustc_hir::def::{CtorKind, Namespace}; use rustc_hir::def_id::DefId; use rustc_hir::{self, GeneratorKind}; +use rustc_target::abi::VariantIdx; use polonius_engine::Atom; pub use rustc_ast::ast::Mutability; diff --git a/src/librustc_middle/mir/tcx.rs b/src/librustc_middle/mir/tcx.rs index feb6631926712..06b27c5e8b329 100644 --- a/src/librustc_middle/mir/tcx.rs +++ b/src/librustc_middle/mir/tcx.rs @@ -4,11 +4,11 @@ */ use crate::mir::*; -use crate::ty::layout::VariantIdx; use crate::ty::subst::Subst; use crate::ty::util::IntTypeExt; use crate::ty::{self, Ty, TyCtxt}; use rustc_hir as hir; +use rustc_target::abi::VariantIdx; #[derive(Copy, Clone, Debug, TypeFoldable)] pub struct PlaceTy<'tcx> { diff --git a/src/librustc_middle/query/mod.rs b/src/librustc_middle/query/mod.rs index c1ece6275092d..2ffbbfb1762d3 100644 --- a/src/librustc_middle/query/mod.rs +++ b/src/librustc_middle/query/mod.rs @@ -738,7 +738,7 @@ rustc_queries! { query layout_raw( env: ty::ParamEnvAnd<'tcx, Ty<'tcx>> - ) -> Result<&'tcx ty::layout::Layout, ty::layout::LayoutError<'tcx>> { + ) -> Result<&'tcx rustc_target::abi::Layout, ty::layout::LayoutError<'tcx>> { desc { "computing layout of `{}`", env.value } } } diff --git a/src/librustc_middle/ty/context.rs b/src/librustc_middle/ty/context.rs index be889f66228d5..95d0c758d08de 100644 --- a/src/librustc_middle/ty/context.rs +++ b/src/librustc_middle/ty/context.rs @@ -11,8 +11,6 @@ use crate::lint::{struct_lint_level, LintSource}; use crate::middle; use crate::middle::cstore::CrateStoreDyn; use crate::middle::cstore::EncodedMetadata; -use crate::middle::lang_items; -use crate::middle::lang_items::PanicLocationLangItem; use crate::middle::resolve_lifetime::{self, ObjectLifetimeDefault}; use crate::middle::stability; use crate::mir::interpret::{Allocation, ConstValue, Scalar}; @@ -21,7 +19,6 @@ use crate::mir::{ }; use crate::traits; use crate::traits::{Clause, Clauses, Goal, GoalKind, Goals}; -use crate::ty::layout::{Layout, TargetDataLayout, VariantIdx}; use crate::ty::query; use crate::ty::steal::Steal; use crate::ty::subst::{GenericArg, InternalSubsts, Subst, SubstsRef}; @@ -38,7 +35,6 @@ use crate::ty::{ConstVid, FloatVar, FloatVid, IntVar, IntVid, TyVar, TyVid}; use crate::ty::{ExistentialPredicate, InferTy, ParamTy, PolyFnSig, Predicate, ProjectionTy}; use crate::ty::{InferConst, ParamConst}; use crate::ty::{List, TyKind, TyS}; -use crate::util::common::ErrorReported; use rustc_ast::ast; use rustc_ast::expand::allocator::AllocatorKind; use rustc_ast::node_id::NodeMap; @@ -50,10 +46,13 @@ use rustc_data_structures::stable_hasher::{ hash_stable_hashmap, HashStable, StableHasher, StableVec, }; use rustc_data_structures::sync::{self, Lock, Lrc, WorkerLocal}; +use rustc_errors::ErrorReported; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIdSet, LocalDefId, LOCAL_CRATE}; use rustc_hir::definitions::{DefPathData, DefPathHash, Definitions}; +use rustc_hir::lang_items; +use rustc_hir::lang_items::PanicLocationLangItem; use rustc_hir::{HirId, Node, TraitCandidate}; use rustc_hir::{ItemKind, ItemLocalId, ItemLocalMap, ItemLocalSet}; use rustc_index::vec::{Idx, IndexVec}; @@ -65,6 +64,7 @@ use rustc_session::Session; use rustc_span::source_map::MultiSpan; use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::Span; +use rustc_target::abi::{Layout, TargetDataLayout, VariantIdx}; use rustc_target::spec::abi; use smallvec::SmallVec; @@ -1203,7 +1203,7 @@ impl<'tcx> TyCtxt<'tcx> { } /// Obtain all lang items of this crate and all dependencies (recursively) - pub fn lang_items(self) -> &'tcx middle::lang_items::LanguageItems { + pub fn lang_items(self) -> &'tcx rustc_hir::lang_items::LanguageItems { self.get_lang_items(LOCAL_CRATE) } diff --git a/src/librustc_middle/ty/instance.rs b/src/librustc_middle/ty/instance.rs index fcfee0fea85af..5d47a6e13f488 100644 --- a/src/librustc_middle/ty/instance.rs +++ b/src/librustc_middle/ty/instance.rs @@ -1,10 +1,10 @@ use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags; -use crate::middle::lang_items::DropInPlaceFnLangItem; use crate::ty::print::{FmtPrinter, Printer}; use crate::ty::{self, SubstsRef, Ty, TyCtxt, TypeFoldable}; use rustc_data_structures::AtomicRef; use rustc_hir::def::Namespace; use rustc_hir::def_id::{CrateNum, DefId}; +use rustc_hir::lang_items::DropInPlaceFnLangItem; use rustc_macros::HashStable; use std::fmt; diff --git a/src/librustc_middle/ty/layout.rs b/src/librustc_middle/ty/layout.rs index 54fde52ba3a77..a2c5bcf119ef6 100644 --- a/src/librustc_middle/ty/layout.rs +++ b/src/librustc_middle/ty/layout.rs @@ -14,7 +14,7 @@ use rustc_span::DUMMY_SP; use rustc_target::abi::call::{ ArgAbi, ArgAttribute, ArgAttributes, Conv, FnAbi, PassMode, Reg, RegKind, }; -pub use rustc_target::abi::*; +use rustc_target::abi::*; use rustc_target::spec::{abi::Abi as SpecAbi, HasTargetSpec}; use std::cmp; diff --git a/src/librustc_middle/ty/mod.rs b/src/librustc_middle/ty/mod.rs index 43982439d47c8..3d1893d3bd07b 100644 --- a/src/librustc_middle/ty/mod.rs +++ b/src/librustc_middle/ty/mod.rs @@ -11,14 +11,12 @@ use crate::hir::exports::ExportMap; use crate::ich::StableHashingContext; use crate::infer::canonical::Canonical; use crate::middle::cstore::CrateStoreDyn; -use crate::middle::lang_items::{FnMutTraitLangItem, FnOnceTraitLangItem, FnTraitLangItem}; use crate::middle::resolve_lifetime::ObjectLifetimeDefault; use crate::mir::interpret::ErrorHandled; use crate::mir::GeneratorLayout; use crate::mir::ReadOnlyBodyAndCache; use crate::traits::{self, Reveal}; use crate::ty; -use crate::ty::layout::VariantIdx; use crate::ty::subst::{InternalSubsts, Subst, SubstsRef}; use crate::ty::util::{Discr, IntTypeExt}; use crate::ty::walk::TypeWalker; @@ -35,6 +33,7 @@ use rustc_data_structures::sync::{self, par_iter, Lrc, ParallelIterator}; use rustc_hir as hir; use rustc_hir::def::{CtorKind, CtorOf, DefKind, Namespace, Res}; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX}; +use rustc_hir::lang_items::{FnMutTraitLangItem, FnOnceTraitLangItem, FnTraitLangItem}; use rustc_hir::{Constness, GlobMap, Node, TraitMap}; use rustc_index::vec::{Idx, IndexVec}; use rustc_macros::HashStable; @@ -43,7 +42,7 @@ use rustc_session::DataTypeKind; use rustc_span::hygiene::ExpnId; use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::Span; -use rustc_target::abi::Align; +use rustc_target::abi::{Align, VariantIdx}; use std::cell::RefCell; use std::cmp::{self, Ordering}; @@ -2078,7 +2077,7 @@ pub struct AdtDef { /// The `DefId` of the struct, enum or union item. pub did: DefId, /// Variants of the ADT. If this is a struct or union, then there will be a single variant. - pub variants: IndexVec, + pub variants: IndexVec, /// Flags of the ADT (e.g., is this a struct? is this non-exhaustive?). flags: AdtFlags, /// Repr options provided by the user. diff --git a/src/librustc_middle/ty/print/pretty.rs b/src/librustc_middle/ty/print/pretty.rs index 5c365a57cd12d..a8b7b6a4b97a4 100644 --- a/src/librustc_middle/ty/print/pretty.rs +++ b/src/librustc_middle/ty/print/pretty.rs @@ -1,7 +1,7 @@ use crate::middle::cstore::{ExternCrate, ExternCrateSource}; use crate::middle::region; use crate::mir::interpret::{sign_extend, truncate, AllocId, ConstValue, Pointer, Scalar}; -use crate::ty::layout::{Integer, IntegerExt, Size}; +use crate::ty::layout::IntegerExt; use crate::ty::subst::{GenericArg, GenericArgKind, Subst}; use crate::ty::{self, DefIdTree, ParamConst, Ty, TyCtxt, TypeFoldable}; use rustc_apfloat::ieee::{Double, Single}; @@ -13,6 +13,7 @@ use rustc_hir::def::{DefKind, Namespace}; use rustc_hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE}; use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData}; use rustc_span::symbol::{kw, Symbol}; +use rustc_target::abi::{Integer, Size}; use rustc_target::spec::abi::Abi; use std::cell::Cell; diff --git a/src/librustc_middle/ty/query/mod.rs b/src/librustc_middle/ty/query/mod.rs index 744237520fbfd..9986eb88dc326 100644 --- a/src/librustc_middle/ty/query/mod.rs +++ b/src/librustc_middle/ty/query/mod.rs @@ -7,7 +7,6 @@ use crate::middle::codegen_fn_attrs::CodegenFnAttrs; use crate::middle::cstore::{CrateSource, DepKind, NativeLibraryKind}; use crate::middle::cstore::{ExternCrate, ForeignModule, LinkagePreference, NativeLibrary}; use crate::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel}; -use crate::middle::lang_items::{LangItem, LanguageItems}; use crate::middle::lib_features::LibFeatures; use crate::middle::privacy::AccessLevels; use crate::middle::region; @@ -34,16 +33,17 @@ use crate::ty::steal::Steal; use crate::ty::subst::{GenericArg, SubstsRef}; use crate::ty::util::AlwaysRequiresDrop; use crate::ty::{self, AdtSizedConstraint, CrateInherentImpls, ParamEnvAnd, Ty, TyCtxt}; -use crate::util::common::ErrorReported; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap}; use rustc_data_structures::profiling::ProfileCategory::*; use rustc_data_structures::stable_hasher::StableVec; use rustc_data_structures::svh::Svh; use rustc_data_structures::sync::Lrc; +use rustc_errors::ErrorReported; use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIdSet, LocalDefId}; +use rustc_hir::lang_items::{LangItem, LanguageItems}; use rustc_hir::{Crate, HirIdSet, ItemLocalId, TraitCandidate}; use rustc_index::vec::IndexVec; use rustc_session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion}; diff --git a/src/librustc_middle/ty/structural_impls.rs b/src/librustc_middle/ty/structural_impls.rs index 429791d09a49c..0ac4466d34f5c 100644 --- a/src/librustc_middle/ty/structural_impls.rs +++ b/src/librustc_middle/ty/structural_impls.rs @@ -254,7 +254,7 @@ CloneTypeFoldableAndLiftImpls! { (), bool, usize, - crate::ty::layout::VariantIdx, + ::rustc_target::abi::VariantIdx, u64, String, crate::middle::region::Scope, diff --git a/src/librustc_middle/ty/sty.rs b/src/librustc_middle/ty/sty.rs index 57df50dc1a05d..99e3b88f5052c 100644 --- a/src/librustc_middle/ty/sty.rs +++ b/src/librustc_middle/ty/sty.rs @@ -10,7 +10,6 @@ use crate::middle::region; use crate::mir::interpret::ConstValue; use crate::mir::interpret::{LitToConstInput, Scalar}; use crate::mir::Promoted; -use crate::ty::layout::VariantIdx; use crate::ty::subst::{GenericArg, InternalSubsts, Subst, SubstsRef}; use crate::ty::{ self, AdtDef, DefIdTree, Discr, Ty, TyCtxt, TypeFlags, TypeFoldable, WithConstness, @@ -24,6 +23,7 @@ use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_index::vec::Idx; use rustc_macros::HashStable; use rustc_span::symbol::{kw, Symbol}; +use rustc_target::abi::{Size, VariantIdx}; use rustc_target::spec::abi; use smallvec::SmallVec; use std::borrow::Cow; @@ -2501,7 +2501,7 @@ impl<'tcx> ConstKind<'tcx> { } #[inline] - pub fn try_to_bits(&self, size: ty::layout::Size) -> Option { + pub fn try_to_bits(&self, size: Size) -> Option { if let ConstKind::Value(val) = self { val.try_to_bits(size) } else { None } } } diff --git a/src/librustc_middle/ty/util.rs b/src/librustc_middle/ty/util.rs index dab367a6639ed..86575b013335c 100644 --- a/src/librustc_middle/ty/util.rs +++ b/src/librustc_middle/ty/util.rs @@ -2,24 +2,24 @@ use crate::ich::NodeIdHashingMode; use crate::mir::interpret::{sign_extend, truncate}; -use crate::ty::layout::{Integer, IntegerExt, Size}; +use crate::ty::layout::IntegerExt; use crate::ty::query::TyCtxtAt; use crate::ty::subst::{GenericArgKind, InternalSubsts, Subst, SubstsRef}; use crate::ty::TyKind::*; use crate::ty::{self, DefIdTree, GenericParamDefKind, Ty, TyCtxt, TypeFoldable}; -use crate::util::common::ErrorReported; use rustc_apfloat::Float as _; use rustc_ast::ast; use rustc_attr::{self as attr, SignedInt, UnsignedInt}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; +use rustc_errors::ErrorReported; use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; use rustc_hir::definitions::DefPathData; use rustc_macros::HashStable; use rustc_span::Span; -use rustc_target::abi::TargetDataLayout; +use rustc_target::abi::{Integer, Size, TargetDataLayout}; use smallvec::SmallVec; use std::{cmp, fmt}; diff --git a/src/librustc_middle/util/common.rs b/src/librustc_middle/util/common.rs index 19b43bfd16241..1e09702bf27ca 100644 --- a/src/librustc_middle/util/common.rs +++ b/src/librustc_middle/util/common.rs @@ -8,8 +8,6 @@ use std::time::{Duration, Instant}; #[cfg(test)] mod tests; -pub use rustc_errors::ErrorReported; - pub fn to_readable_str(mut val: usize) -> String { let mut groups = vec![]; loop { diff --git a/src/librustc_mir/borrow_check/diagnostics/mod.rs b/src/librustc_mir/borrow_check/diagnostics/mod.rs index 2991f29949aa0..619ae0ff8faa1 100644 --- a/src/librustc_mir/borrow_check/diagnostics/mod.rs +++ b/src/librustc_mir/borrow_check/diagnostics/mod.rs @@ -9,10 +9,10 @@ use rustc_middle::mir::{ AggregateKind, Constant, Field, Local, LocalInfo, LocalKind, Location, Operand, Place, PlaceRef, ProjectionElem, Rvalue, Statement, StatementKind, Terminator, TerminatorKind, }; -use rustc_middle::ty::layout::VariantIdx; use rustc_middle::ty::print::Print; use rustc_middle::ty::{self, DefIdTree, Ty, TyCtxt}; use rustc_span::Span; +use rustc_target::abi::VariantIdx; use super::borrow_set::BorrowData; use super::MirBorrowckCtxt; diff --git a/src/librustc_mir/borrow_check/type_check/mod.rs b/src/librustc_mir/borrow_check/type_check/mod.rs index 1d66bd13c6fe6..cedae94ab89fe 100644 --- a/src/librustc_mir/borrow_check/type_check/mod.rs +++ b/src/librustc_mir/borrow_check/type_check/mod.rs @@ -24,13 +24,13 @@ use rustc_middle::mir::*; use rustc_middle::ty::adjustment::PointerCast; use rustc_middle::ty::cast::CastTy; use rustc_middle::ty::fold::TypeFoldable; -use rustc_middle::ty::layout::VariantIdx; use rustc_middle::ty::subst::{GenericArgKind, Subst, SubstsRef, UserSubsts}; use rustc_middle::ty::{ self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, RegionVid, ToPolyTraitRef, Ty, TyCtxt, UserType, UserTypeAnnotationIndex, }; use rustc_span::{Span, DUMMY_SP}; +use rustc_target::abi::VariantIdx; use rustc_trait_selection::infer::InferCtxtExt as _; use rustc_trait_selection::opaque_types::{GenerateMemberConstraints, InferCtxtExt}; use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _; diff --git a/src/librustc_mir/borrow_check/universal_regions.rs b/src/librustc_mir/borrow_check/universal_regions.rs index c31f5a57ebc22..4d67d7204ca6e 100644 --- a/src/librustc_mir/borrow_check/universal_regions.rs +++ b/src/librustc_mir/borrow_check/universal_regions.rs @@ -17,10 +17,10 @@ use rustc_data_structures::fx::FxHashMap; use rustc_errors::DiagnosticBuilder; use rustc_hir as hir; use rustc_hir::def_id::DefId; +use rustc_hir::lang_items; use rustc_hir::{BodyOwnerKind, HirId}; use rustc_index::vec::{Idx, IndexVec}; use rustc_infer::infer::{InferCtxt, NLLRegionVariableOrigin}; -use rustc_middle::middle::lang_items; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::subst::{InternalSubsts, Subst, SubstsRef}; use rustc_middle::ty::{self, RegionVid, Ty, TyCtxt}; diff --git a/src/librustc_mir/const_eval/eval_queries.rs b/src/librustc_mir/const_eval/eval_queries.rs index c30d41e6a9222..238a2dfdd8f49 100644 --- a/src/librustc_mir/const_eval/eval_queries.rs +++ b/src/librustc_mir/const_eval/eval_queries.rs @@ -9,8 +9,9 @@ use rustc_hir::def::DefKind; use rustc_middle::mir; use rustc_middle::mir::interpret::{ConstEvalErr, ErrorHandled}; use rustc_middle::traits::Reveal; -use rustc_middle::ty::{self, layout, layout::LayoutOf, subst::Subst, TyCtxt}; +use rustc_middle::ty::{self, subst::Subst, TyCtxt}; use rustc_span::source_map::Span; +use rustc_target::abi::{Abi, LayoutOf}; use std::convert::TryInto; pub fn note_on_undefined_behavior_error() -> &'static str { @@ -106,8 +107,8 @@ pub(super) fn op_to_const<'tcx>( // the usual cases of extracting e.g. a `usize`, without there being a real use case for the // `Undef` situation. let try_as_immediate = match op.layout.abi { - layout::Abi::Scalar(..) => true, - layout::Abi::ScalarPair(..) => match op.layout.ty.kind { + Abi::Scalar(..) => true, + Abi::ScalarPair(..) => match op.layout.ty.kind { ty::Ref(_, inner, _) => match inner.kind { ty::Slice(elem) => elem == ecx.tcx.types.u8, ty::Str => true, diff --git a/src/librustc_mir/const_eval/mod.rs b/src/librustc_mir/const_eval/mod.rs index 78d1e8989a2f5..e1146ef30d131 100644 --- a/src/librustc_mir/const_eval/mod.rs +++ b/src/librustc_mir/const_eval/mod.rs @@ -3,9 +3,9 @@ use std::convert::TryFrom; use rustc_middle::mir; -use rustc_middle::ty::layout::VariantIdx; use rustc_middle::ty::{self, TyCtxt}; use rustc_span::{source_map::DUMMY_SP, symbol::Symbol}; +use rustc_target::abi::VariantIdx; use crate::interpret::{intern_const_alloc_recursive, ConstValue, InternKind, InterpCx}; diff --git a/src/librustc_mir/dataflow/framework/mod.rs b/src/librustc_mir/dataflow/framework/mod.rs index 91c4b5ad634cb..d85e2c0761f19 100644 --- a/src/librustc_mir/dataflow/framework/mod.rs +++ b/src/librustc_mir/dataflow/framework/mod.rs @@ -36,8 +36,8 @@ use rustc_hir::def_id::DefId; use rustc_index::bit_set::{BitSet, HybridBitSet}; use rustc_index::vec::{Idx, IndexVec}; use rustc_middle::mir::{self, BasicBlock, Location}; -use rustc_middle::ty::layout::VariantIdx; use rustc_middle::ty::{self, TyCtxt}; +use rustc_target::abi::VariantIdx; mod cursor; mod engine; diff --git a/src/librustc_mir/dataflow/impls/mod.rs b/src/librustc_mir/dataflow/impls/mod.rs index 3ffa771cb05a1..65c9e29bd10ec 100644 --- a/src/librustc_mir/dataflow/impls/mod.rs +++ b/src/librustc_mir/dataflow/impls/mod.rs @@ -5,8 +5,8 @@ use rustc_index::bit_set::BitSet; use rustc_index::vec::Idx; use rustc_middle::mir::{self, Body, Location}; -use rustc_middle::ty::layout::VariantIdx; use rustc_middle::ty::{self, TyCtxt}; +use rustc_target::abi::VariantIdx; use super::MoveDataParamEnv; diff --git a/src/librustc_mir/interpret/cast.rs b/src/librustc_mir/interpret/cast.rs index 215c7bb747593..67696aa2da8b0 100644 --- a/src/librustc_mir/interpret/cast.rs +++ b/src/librustc_mir/interpret/cast.rs @@ -7,10 +7,10 @@ use rustc_ast::ast::FloatTy; use rustc_middle::mir::interpret::{InterpResult, PointerArithmetic, Scalar}; use rustc_middle::mir::CastKind; use rustc_middle::ty::adjustment::PointerCast; -use rustc_middle::ty::layout::{self, Size, TyAndLayout}; +use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::{self, Ty, TypeAndMut, TypeFoldable}; use rustc_span::symbol::sym; -use rustc_target::abi::LayoutOf; +use rustc_target::abi::{LayoutOf, Size, Variants}; impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { pub fn cast( @@ -132,7 +132,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // Handle cast from a univariant (ZST) enum. match src.layout.variants { - layout::Variants::Single { index } => { + Variants::Single { index } => { if let Some(discr) = src.layout.ty.discriminant_for_variant(*self.tcx, index) { assert!(src.layout.is_zst()); let discr_layout = self.layout_of(discr.ty)?; @@ -141,7 +141,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { .into()); } } - layout::Variants::Multiple { .. } => {} + Variants::Multiple { .. } => {} } // Handle casting the metadata away from a fat pointer. diff --git a/src/librustc_mir/interpret/eval_context.rs b/src/librustc_mir/interpret/eval_context.rs index d204be7f80674..0b1ffe62eaaf3 100644 --- a/src/librustc_mir/interpret/eval_context.rs +++ b/src/librustc_mir/interpret/eval_context.rs @@ -13,11 +13,12 @@ use rustc_middle::mir; use rustc_middle::mir::interpret::{ sign_extend, truncate, AllocId, FrameInfo, GlobalId, InterpResult, Pointer, Scalar, }; -use rustc_middle::ty::layout::{self, Align, HasDataLayout, LayoutOf, Size, TyAndLayout}; +use rustc_middle::ty::layout::{self, TyAndLayout}; use rustc_middle::ty::query::TyCtxtAt; use rustc_middle::ty::subst::SubstsRef; use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable}; use rustc_span::source_map::{self, Span, DUMMY_SP}; +use rustc_target::abi::{Align, HasDataLayout, LayoutOf, Size, TargetDataLayout}; use super::{ Immediate, MPlaceTy, Machine, MemPlace, MemPlaceMeta, Memory, OpTy, Operand, Place, PlaceTy, @@ -176,7 +177,7 @@ impl<'mir, 'tcx, Tag, Extra> Frame<'mir, 'tcx, Tag, Extra> { impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for InterpCx<'mir, 'tcx, M> { #[inline] - fn data_layout(&self) -> &layout::TargetDataLayout { + fn data_layout(&self) -> &TargetDataLayout { &self.tcx.data_layout } } diff --git a/src/librustc_mir/interpret/intrinsics.rs b/src/librustc_mir/interpret/intrinsics.rs index c5f7a94969b2d..5b65a49b47d76 100644 --- a/src/librustc_mir/interpret/intrinsics.rs +++ b/src/librustc_mir/interpret/intrinsics.rs @@ -11,11 +11,11 @@ use rustc_middle::mir::{ BinOp, }; use rustc_middle::ty; -use rustc_middle::ty::layout::{LayoutOf, Primitive, Size}; use rustc_middle::ty::subst::SubstsRef; use rustc_middle::ty::TyCtxt; use rustc_span::symbol::{sym, Symbol}; use rustc_span::Span; +use rustc_target::abi::{Abi, LayoutOf, Primitive, Size}; use super::{ImmTy, InterpCx, Machine, OpTy, PlaceTy}; @@ -136,7 +136,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let val = self.read_scalar(args[0])?.not_undef()?; let bits = self.force_bits(val, layout_of.size)?; let kind = match layout_of.abi { - ty::layout::Abi::Scalar(ref scalar) => scalar.value, + Abi::Scalar(ref scalar) => scalar.value, _ => bug!("{} called on invalid type {:?}", intrinsic_name, ty), }; let (nonzero, intrinsic_name) = match intrinsic_name { diff --git a/src/librustc_mir/interpret/intrinsics/caller_location.rs b/src/librustc_mir/interpret/intrinsics/caller_location.rs index 37b01d6db3b41..5fcee1f25bbc3 100644 --- a/src/librustc_mir/interpret/intrinsics/caller_location.rs +++ b/src/librustc_mir/interpret/intrinsics/caller_location.rs @@ -1,6 +1,6 @@ use std::convert::TryFrom; -use rustc_middle::middle::lang_items::PanicLocationLangItem; +use rustc_hir::lang_items::PanicLocationLangItem; use rustc_middle::ty::subst::Subst; use rustc_span::{Span, Symbol}; use rustc_target::abi::LayoutOf; diff --git a/src/librustc_mir/interpret/memory.rs b/src/librustc_mir/interpret/memory.rs index 9443ae116fcfd..04a927c69a687 100644 --- a/src/librustc_mir/interpret/memory.rs +++ b/src/librustc_mir/interpret/memory.rs @@ -11,11 +11,10 @@ use std::collections::VecDeque; use std::convert::TryFrom; use std::ptr; +use rustc_ast::ast::Mutability; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; -use rustc_middle::ty::layout::{Align, HasDataLayout, Size, TargetDataLayout}; use rustc_middle::ty::{self, query::TyCtxtAt, Instance, ParamEnv}; - -use rustc_ast::ast::Mutability; +use rustc_target::abi::{Align, HasDataLayout, Size, TargetDataLayout}; use super::{ AllocId, AllocMap, Allocation, AllocationExtra, CheckInAllocMsg, ErrorHandled, GlobalAlloc, diff --git a/src/librustc_mir/interpret/operand.rs b/src/librustc_mir/interpret/operand.rs index 24639fece46be..c91cbb7550bc2 100644 --- a/src/librustc_mir/interpret/operand.rs +++ b/src/librustc_mir/interpret/operand.rs @@ -10,12 +10,12 @@ pub use rustc_middle::mir::interpret::ScalarMaybeUndef; use rustc_middle::mir::interpret::{ sign_extend, truncate, AllocId, ConstValue, GlobalId, InterpResult, Pointer, Scalar, }; -use rustc_middle::ty::layout::{ - self, HasDataLayout, IntegerExt, LayoutOf, PrimitiveExt, Size, TyAndLayout, VariantIdx, -}; +use rustc_middle::ty::layout::{IntegerExt, PrimitiveExt, TyAndLayout}; use rustc_middle::ty::print::{FmtPrinter, PrettyPrinter, Printer}; use rustc_middle::ty::Ty; use rustc_middle::{mir, ty}; +use rustc_target::abi::{Abi, DiscriminantKind, HasDataLayout, Integer, LayoutOf, Size}; +use rustc_target::abi::{VariantIdx, Variants}; use std::fmt::Write; /// An `Immediate` represents a single immediate self-contained Rust value. @@ -266,7 +266,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { }; match mplace.layout.abi { - layout::Abi::Scalar(..) => { + Abi::Scalar(..) => { let scalar = self.memory.get_raw(ptr.alloc_id)?.read_scalar( self, ptr, @@ -274,7 +274,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { )?; Ok(Some(ImmTy { imm: scalar.into(), layout: mplace.layout })) } - layout::Abi::ScalarPair(ref a, ref b) => { + Abi::ScalarPair(ref a, ref b) => { // We checked `ptr_align` above, so all fields will have the alignment they need. // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`, // which `ptr.offset(b_offset)` cannot possibly fail to satisfy. @@ -587,7 +587,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { trace!("read_discriminant_value {:#?}", rval.layout); let (discr_layout, discr_kind, discr_index) = match rval.layout.variants { - layout::Variants::Single { index } => { + Variants::Single { index } => { let discr_val = rval .layout .ty @@ -595,12 +595,9 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { .map_or(u128::from(index.as_u32()), |discr| discr.val); return Ok((discr_val, index)); } - layout::Variants::Multiple { - discr: ref discr_layout, - ref discr_kind, - discr_index, - .. - } => (discr_layout, discr_kind, discr_index), + Variants::Multiple { discr: ref discr_layout, ref discr_kind, discr_index, .. } => { + (discr_layout, discr_kind, discr_index) + } }; // read raw discriminant value @@ -610,7 +607,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { trace!("discr value: {:?}", raw_discr); // post-process Ok(match *discr_kind { - layout::DiscriminantKind::Tag => { + DiscriminantKind::Tag => { let bits_discr = raw_discr .not_undef() .and_then(|raw_discr| self.force_bits(raw_discr, discr_val.layout.size)) @@ -627,7 +624,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { .expect("tagged layout corresponds to adt") .repr .discr_type(); - let size = layout::Integer::from_attr(self, discr_ty).size(); + let size = Integer::from_attr(self, discr_ty).size(); truncate(sexted, size) } else { bits_discr @@ -648,11 +645,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { .ok_or_else(|| err_ub!(InvalidDiscriminant(raw_discr.erase_tag())))?; (real_discr, index.0) } - layout::DiscriminantKind::Niche { - dataful_variant, - ref niche_variants, - niche_start, - } => { + DiscriminantKind::Niche { dataful_variant, ref niche_variants, niche_start } => { let variants_start = niche_variants.start().as_u32(); let variants_end = niche_variants.end().as_u32(); let raw_discr = raw_discr diff --git a/src/librustc_mir/interpret/operator.rs b/src/librustc_mir/interpret/operator.rs index e81cd8b3d00d7..0aa7e98f3edfa 100644 --- a/src/librustc_mir/interpret/operator.rs +++ b/src/librustc_mir/interpret/operator.rs @@ -4,11 +4,8 @@ use rustc_apfloat::Float; use rustc_ast::ast::FloatTy; use rustc_middle::mir; use rustc_middle::mir::interpret::{InterpResult, Scalar}; -use rustc_middle::ty::{ - self, - layout::{LayoutOf, TyAndLayout}, - Ty, -}; +use rustc_middle::ty::{self, layout::TyAndLayout, Ty}; +use rustc_target::abi::LayoutOf; use super::{ImmTy, Immediate, InterpCx, Machine, PlaceTy}; diff --git a/src/librustc_mir/interpret/place.rs b/src/librustc_mir/interpret/place.rs index f7c1a3cadb881..85d02abd64a1d 100644 --- a/src/librustc_mir/interpret/place.rs +++ b/src/librustc_mir/interpret/place.rs @@ -8,10 +8,10 @@ use std::hash::Hash; use rustc_macros::HashStable; use rustc_middle::mir; use rustc_middle::mir::interpret::truncate; -use rustc_middle::ty::layout::{ - self, Align, HasDataLayout, LayoutOf, PrimitiveExt, Size, TyAndLayout, VariantIdx, -}; +use rustc_middle::ty::layout::{PrimitiveExt, TyAndLayout}; use rustc_middle::ty::{self, Ty}; +use rustc_target::abi::{Abi, Align, DiscriminantKind, FieldPlacement}; +use rustc_target::abi::{HasDataLayout, LayoutOf, Size, VariantIdx, Variants}; use super::{ AllocId, AllocMap, Allocation, AllocationExtra, ImmTy, Immediate, InterpCx, InterpResult, @@ -219,7 +219,7 @@ impl<'tcx, Tag> MPlaceTy<'tcx, Tag> { // Go through the layout. There are lots of types that support a length, // e.g., SIMD types. match self.layout.fields { - layout::FieldPlacement::Array { count, .. } => Ok(count), + FieldPlacement::Array { count, .. } => Ok(count), _ => bug!("len not supported on sized type {:?}", self.layout.ty), } } @@ -437,7 +437,7 @@ where ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { // Not using the layout method because we want to compute on u64 match base.layout.fields { - layout::FieldPlacement::Array { stride, .. } => { + FieldPlacement::Array { stride, .. } => { let len = base.len(self)?; if index >= len { // This can only be reached in ConstProp and non-rustc-MIR. @@ -463,7 +463,7 @@ where { let len = base.len(self)?; // also asserts that we have a type where this makes sense let stride = match base.layout.fields { - layout::FieldPlacement::Array { stride, .. } => stride, + FieldPlacement::Array { stride, .. } => stride, _ => bug!("mplace_array_fields: expected an array layout"), }; let layout = base.layout.field(self, 0)?; @@ -493,7 +493,7 @@ where // Not using layout method because that works with usize, and does not work with slices // (that have count 0 in their layout). let from_offset = match base.layout.fields { - layout::FieldPlacement::Array { stride, .. } => stride * from, // `Size` multiplication is checked + FieldPlacement::Array { stride, .. } => stride * from, // `Size` multiplication is checked _ => bug!("Unexpected layout of index access: {:#?}", base.layout), }; @@ -802,7 +802,7 @@ where match value { Immediate::Scalar(scalar) => { match dest.layout.abi { - layout::Abi::Scalar(_) => {} // fine + Abi::Scalar(_) => {} // fine _ => { bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}", dest.layout) } @@ -819,7 +819,7 @@ where // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`, // which `ptr.offset(b_offset)` cannot possibly fail to satisfy. let (a, b) = match dest.layout.abi { - layout::Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value), + Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value), _ => bug!( "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}", dest.layout @@ -1067,11 +1067,11 @@ where } match dest.layout.variants { - layout::Variants::Single { index } => { + Variants::Single { index } => { assert_eq!(index, variant_index); } - layout::Variants::Multiple { - discr_kind: layout::DiscriminantKind::Tag, + Variants::Multiple { + discr_kind: DiscriminantKind::Tag, discr: ref discr_layout, discr_index, .. @@ -1091,9 +1091,9 @@ where let discr_dest = self.place_field(dest, discr_index)?; self.write_scalar(Scalar::from_uint(discr_val, size), discr_dest)?; } - layout::Variants::Multiple { + Variants::Multiple { discr_kind: - layout::DiscriminantKind::Niche { dataful_variant, ref niche_variants, niche_start }, + DiscriminantKind::Niche { dataful_variant, ref niche_variants, niche_start }, discr: ref discr_layout, discr_index, .. diff --git a/src/librustc_mir/interpret/step.rs b/src/librustc_mir/interpret/step.rs index 5fb0a081648e8..a00b1c8ba9ba7 100644 --- a/src/librustc_mir/interpret/step.rs +++ b/src/librustc_mir/interpret/step.rs @@ -4,7 +4,7 @@ use rustc_middle::mir; use rustc_middle::mir::interpret::{InterpResult, Scalar}; -use rustc_middle::ty::layout::LayoutOf; +use rustc_target::abi::LayoutOf; use super::{InterpCx, Machine}; diff --git a/src/librustc_mir/interpret/terminator.rs b/src/librustc_mir/interpret/terminator.rs index 8e7abcd09c233..f6f82633acae1 100644 --- a/src/librustc_mir/interpret/terminator.rs +++ b/src/librustc_mir/interpret/terminator.rs @@ -1,10 +1,11 @@ use std::borrow::Cow; use std::convert::TryFrom; -use rustc_middle::ty::layout::{self, LayoutOf, TyAndLayout}; +use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::Instance; use rustc_middle::{mir, ty}; use rustc_span::source_map::Span; +use rustc_target::abi::{self, LayoutOf}; use rustc_target::spec::abi::Abi; use super::{ @@ -150,12 +151,12 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // Different valid ranges are okay (once we enforce validity, // that will take care to make it UB to leave the range, just // like for transmute). - (layout::Abi::Scalar(ref caller), layout::Abi::Scalar(ref callee)) => { + (abi::Abi::Scalar(ref caller), abi::Abi::Scalar(ref callee)) => { caller.value == callee.value } ( - layout::Abi::ScalarPair(ref caller1, ref caller2), - layout::Abi::ScalarPair(ref callee1, ref callee2), + abi::Abi::ScalarPair(ref caller1, ref caller2), + abi::Abi::ScalarPair(ref callee1, ref callee2), ) => caller1.value == callee1.value && caller2.value == callee2.value, // Be conservative _ => false, diff --git a/src/librustc_mir/interpret/traits.rs b/src/librustc_mir/interpret/traits.rs index ed882e107411d..fb9401c7d8f28 100644 --- a/src/librustc_mir/interpret/traits.rs +++ b/src/librustc_mir/interpret/traits.rs @@ -1,8 +1,8 @@ use std::convert::TryFrom; use rustc_middle::mir::interpret::{InterpResult, Pointer, PointerArithmetic, Scalar}; -use rustc_middle::ty::layout::{Align, HasDataLayout, LayoutOf, Size}; use rustc_middle::ty::{self, Instance, Ty, TypeFoldable}; +use rustc_target::abi::{Align, HasDataLayout, LayoutOf, Size}; use super::{FnVal, InterpCx, Machine, MemoryKind}; diff --git a/src/librustc_mir/interpret/validity.rs b/src/librustc_mir/interpret/validity.rs index 0ca565d86787a..701e394415bbd 100644 --- a/src/librustc_mir/interpret/validity.rs +++ b/src/librustc_mir/interpret/validity.rs @@ -11,8 +11,9 @@ use std::ops::RangeInclusive; use rustc_data_structures::fx::FxHashSet; use rustc_hir as hir; use rustc_middle::ty; -use rustc_middle::ty::layout::{self, LayoutOf, TyAndLayout, VariantIdx}; +use rustc_middle::ty::layout::TyAndLayout; use rustc_span::symbol::{sym, Symbol}; +use rustc_target::abi::{Abi, LayoutOf, Scalar, VariantIdx, Variants}; use std::hash::Hash; @@ -180,7 +181,7 @@ impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M fn aggregate_field_path_elem(&mut self, layout: TyAndLayout<'tcx>, field: usize) -> PathElem { // First, check if we are projecting to a variant. match layout.variants { - layout::Variants::Multiple { discr_index, .. } => { + Variants::Multiple { discr_index, .. } => { if discr_index == field { return match layout.ty.kind { ty::Adt(def, ..) if def.is_enum() => PathElem::EnumTag, @@ -189,7 +190,7 @@ impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M }; } } - layout::Variants::Single { .. } => {} + Variants::Single { .. } => {} } // Now we know we are projecting to a field, so figure out which one. @@ -226,11 +227,11 @@ impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M ty::Adt(def, ..) if def.is_enum() => { // we might be projecting *to* a variant, or to a field *in* a variant. match layout.variants { - layout::Variants::Single { index } => { + Variants::Single { index } => { // Inside a variant PathElem::Field(def.variants[index].fields[field].ident.name) } - layout::Variants::Multiple { .. } => bug!("we handled variants above"), + Variants::Multiple { .. } => bug!("we handled variants above"), } } @@ -539,7 +540,7 @@ impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M fn visit_scalar( &mut self, op: OpTy<'tcx, M::PointerTag>, - scalar_layout: &layout::Scalar, + scalar_layout: &Scalar, ) -> InterpResult<'tcx> { let value = self.ecx.read_scalar(op)?; let valid_range = &scalar_layout.valid_range; @@ -685,22 +686,22 @@ impl<'rt, 'mir, 'tcx, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M> // scalars, we do the same check on every "level" (e.g., first we check // MyNewtype and then the scalar in there). match op.layout.abi { - layout::Abi::Uninhabited => { + Abi::Uninhabited => { throw_validation_failure!( format_args!("a value of uninhabited type {:?}", op.layout.ty), self.path ); } - layout::Abi::Scalar(ref scalar_layout) => { + Abi::Scalar(ref scalar_layout) => { self.visit_scalar(op, scalar_layout)?; } - layout::Abi::ScalarPair { .. } | layout::Abi::Vector { .. } => { + Abi::ScalarPair { .. } | Abi::Vector { .. } => { // These have fields that we already visited above, so we already checked // all their scalar-level restrictions. // There is also no equivalent to `rustc_layout_scalar_valid_range_start` // that would make skipping them here an issue. } - layout::Abi::Aggregate { .. } => { + Abi::Aggregate { .. } => { // Nothing to do. } } diff --git a/src/librustc_mir/interpret/visitor.rs b/src/librustc_mir/interpret/visitor.rs index 11170164cf35b..0207ee9a3e952 100644 --- a/src/librustc_mir/interpret/visitor.rs +++ b/src/librustc_mir/interpret/visitor.rs @@ -3,7 +3,8 @@ use rustc_middle::mir::interpret::InterpResult; use rustc_middle::ty; -use rustc_middle::ty::layout::{self, TyAndLayout, VariantIdx}; +use rustc_middle::ty::layout::TyAndLayout; +use rustc_target::abi::{FieldPlacement, VariantIdx, Variants}; use super::{InterpCx, MPlaceTy, Machine, OpTy}; @@ -207,10 +208,10 @@ macro_rules! make_value_visitor { // Visit the fields of this value. match v.layout().fields { - layout::FieldPlacement::Union(fields) => { + FieldPlacement::Union(fields) => { self.visit_union(v, fields)?; }, - layout::FieldPlacement::Arbitrary { ref offsets, .. } => { + FieldPlacement::Arbitrary { ref offsets, .. } => { // FIXME: We collect in a vec because otherwise there are lifetime // errors: Projecting to a field needs access to `ecx`. let fields: Vec> = @@ -220,7 +221,7 @@ macro_rules! make_value_visitor { .collect(); self.visit_aggregate(v, fields.into_iter())?; }, - layout::FieldPlacement::Array { .. } => { + FieldPlacement::Array { .. } => { // Let's get an mplace first. let mplace = v.to_op(self.ecx())?.assert_mem_place(self.ecx()); // Now we can go over all the fields. @@ -237,7 +238,7 @@ macro_rules! make_value_visitor { match v.layout().variants { // If this is a multi-variant layout, find the right variant and proceed // with *its* fields. - layout::Variants::Multiple { .. } => { + Variants::Multiple { .. } => { let op = v.to_op(self.ecx())?; let idx = self.ecx().read_discriminant(op)?.1; let inner = v.project_downcast(self.ecx(), idx)?; @@ -246,7 +247,7 @@ macro_rules! make_value_visitor { self.visit_variant(v, idx, inner) } // For single-variant layouts, we already did anything there is to do. - layout::Variants::Single { .. } => Ok(()) + Variants::Single { .. } => Ok(()) } } } diff --git a/src/librustc_mir/monomorphize/collector.rs b/src/librustc_mir/monomorphize/collector.rs index 1106eba104682..1032ff413af41 100644 --- a/src/librustc_mir/monomorphize/collector.rs +++ b/src/librustc_mir/monomorphize/collector.rs @@ -181,9 +181,9 @@ use rustc_data_structures::sync::{par_iter, MTLock, MTRef, ParallelIterator}; use rustc_hir as hir; use rustc_hir::def_id::{DefId, DefIdMap, LOCAL_CRATE}; use rustc_hir::itemlikevisit::ItemLikeVisitor; +use rustc_hir::lang_items::{ExchangeMallocFnLangItem, StartFnLangItem}; use rustc_index::bit_set::GrowableBitSet; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; -use rustc_middle::middle::lang_items::{ExchangeMallocFnLangItem, StartFnLangItem}; use rustc_middle::mir::interpret::{AllocId, ConstValue}; use rustc_middle::mir::interpret::{ErrorHandled, GlobalAlloc, Scalar}; use rustc_middle::mir::mono::{InstantiationMode, MonoItem}; diff --git a/src/librustc_mir/shim.rs b/src/librustc_mir/shim.rs index 98a95801f1b40..16aade9d1a61f 100644 --- a/src/librustc_mir/shim.rs +++ b/src/librustc_mir/shim.rs @@ -1,10 +1,10 @@ use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_middle::mir::*; -use rustc_middle::ty::layout::VariantIdx; use rustc_middle::ty::query::Providers; use rustc_middle::ty::subst::{InternalSubsts, Subst}; use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable}; +use rustc_target::abi::VariantIdx; use rustc_index::vec::{Idx, IndexVec}; diff --git a/src/librustc_mir/transform/check_consts/validation.rs b/src/librustc_mir/transform/check_consts/validation.rs index c8320a1561ae8..8d509c0d8b01c 100644 --- a/src/librustc_mir/transform/check_consts/validation.rs +++ b/src/librustc_mir/transform/check_consts/validation.rs @@ -1,10 +1,10 @@ //! The `Visitor` responsible for actually checking a `mir::Body` for invalid operations. use rustc_errors::struct_span_err; +use rustc_hir::lang_items; use rustc_hir::{def_id::DefId, HirId}; use rustc_index::bit_set::BitSet; use rustc_infer::infer::TyCtxtInferExt; -use rustc_middle::middle::lang_items; use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::*; use rustc_middle::ty::cast::CastTy; diff --git a/src/librustc_mir/transform/const_prop.rs b/src/librustc_mir/transform/const_prop.rs index f1ddf3c635f7a..8116ec7991546 100644 --- a/src/librustc_mir/transform/const_prop.rs +++ b/src/librustc_mir/transform/const_prop.rs @@ -19,13 +19,12 @@ use rustc_middle::mir::{ SourceInfo, SourceScope, SourceScopeData, Statement, StatementKind, Terminator, TerminatorKind, UnOp, RETURN_PLACE, }; -use rustc_middle::ty::layout::{ - HasDataLayout, HasTyCtxt, LayoutError, LayoutOf, Size, TargetDataLayout, TyAndLayout, -}; +use rustc_middle::ty::layout::{HasTyCtxt, LayoutError, TyAndLayout}; use rustc_middle::ty::subst::{InternalSubsts, Subst}; use rustc_middle::ty::{self, ConstKind, Instance, ParamEnv, Ty, TyCtxt, TypeFoldable}; use rustc_session::lint; use rustc_span::{def_id::DefId, Span}; +use rustc_target::abi::{HasDataLayout, LayoutOf, Size, TargetDataLayout}; use rustc_trait_selection::traits; use crate::const_eval::error_to_const_error; diff --git a/src/librustc_mir/transform/elaborate_drops.rs b/src/librustc_mir/transform/elaborate_drops.rs index fc382312aeb50..8a612c9c5da11 100644 --- a/src/librustc_mir/transform/elaborate_drops.rs +++ b/src/librustc_mir/transform/elaborate_drops.rs @@ -13,9 +13,9 @@ use rustc_data_structures::fx::FxHashMap; use rustc_hir as hir; use rustc_index::bit_set::BitSet; use rustc_middle::mir::*; -use rustc_middle::ty::layout::VariantIdx; use rustc_middle::ty::{self, TyCtxt}; use rustc_span::Span; +use rustc_target::abi::VariantIdx; use std::fmt; pub struct ElaborateDrops; diff --git a/src/librustc_mir/transform/generator.rs b/src/librustc_mir/transform/generator.rs index 230a835b910d2..4fadd99cbaff0 100644 --- a/src/librustc_mir/transform/generator.rs +++ b/src/librustc_mir/transform/generator.rs @@ -63,10 +63,10 @@ use rustc_index::bit_set::{BitMatrix, BitSet}; use rustc_index::vec::{Idx, IndexVec}; use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor}; use rustc_middle::mir::*; -use rustc_middle::ty::layout::VariantIdx; use rustc_middle::ty::subst::SubstsRef; use rustc_middle::ty::GeneratorSubsts; use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt}; +use rustc_target::abi::VariantIdx; use std::borrow::Cow; use std::iter; diff --git a/src/librustc_mir/transform/uninhabited_enum_branching.rs b/src/librustc_mir/transform/uninhabited_enum_branching.rs index 38a9194e5c55d..0a08c13b479aa 100644 --- a/src/librustc_mir/transform/uninhabited_enum_branching.rs +++ b/src/librustc_mir/transform/uninhabited_enum_branching.rs @@ -5,8 +5,9 @@ use rustc_middle::mir::{ BasicBlock, BasicBlockData, Body, BodyAndCache, Local, Operand, Rvalue, StatementKind, TerminatorKind, }; -use rustc_middle::ty::layout::{Abi, TyAndLayout, Variants}; +use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::{Ty, TyCtxt}; +use rustc_target::abi::{Abi, Variants}; pub struct UninhabitedEnumBranching; diff --git a/src/librustc_mir/util/aggregate.rs b/src/librustc_mir/util/aggregate.rs index b22dbf40b5019..e77d264b7ce5c 100644 --- a/src/librustc_mir/util/aggregate.rs +++ b/src/librustc_mir/util/aggregate.rs @@ -1,7 +1,7 @@ use rustc_index::vec::Idx; use rustc_middle::mir::*; -use rustc_middle::ty::layout::VariantIdx; use rustc_middle::ty::{Ty, TyCtxt}; +use rustc_target::abi::VariantIdx; use std::iter::TrustedLen; diff --git a/src/librustc_mir/util/elaborate_drops.rs b/src/librustc_mir/util/elaborate_drops.rs index 7063ed1edc822..1d1a5140aae24 100644 --- a/src/librustc_mir/util/elaborate_drops.rs +++ b/src/librustc_mir/util/elaborate_drops.rs @@ -1,13 +1,13 @@ use crate::util::patch::MirPatch; use rustc_hir as hir; +use rustc_hir::lang_items; use rustc_index::vec::Idx; -use rustc_middle::middle::lang_items; use rustc_middle::mir::*; use rustc_middle::traits::Reveal; -use rustc_middle::ty::layout::VariantIdx; use rustc_middle::ty::subst::SubstsRef; use rustc_middle::ty::util::IntTypeExt; use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_target::abi::VariantIdx; use std::fmt; use std::convert::TryInto; diff --git a/src/librustc_mir/util/pretty.rs b/src/librustc_mir/util/pretty.rs index bd7725c1b5af3..38989269c7c37 100644 --- a/src/librustc_mir/util/pretty.rs +++ b/src/librustc_mir/util/pretty.rs @@ -9,7 +9,8 @@ use rustc_middle::mir::interpret::{ }; use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::*; -use rustc_middle::ty::{self, layout::Size, TyCtxt, TypeFoldable, TypeVisitor}; +use rustc_middle::ty::{self, TyCtxt, TypeFoldable, TypeVisitor}; +use rustc_target::abi::Size; use std::collections::BTreeSet; use std::fmt::Display; use std::fmt::Write as _; diff --git a/src/librustc_mir_build/build/matches/mod.rs b/src/librustc_mir_build/build/matches/mod.rs index d205ce254d3b2..d353950c4367f 100644 --- a/src/librustc_mir_build/build/matches/mod.rs +++ b/src/librustc_mir_build/build/matches/mod.rs @@ -10,16 +10,16 @@ use crate::build::ForGuard::{self, OutsideGuard, RefWithinGuard}; use crate::build::{BlockAnd, BlockAndExtension, Builder}; use crate::build::{GuardFrame, GuardFrameLocal, LocalsForNode}; use crate::hair::{self, *}; -use rustc_middle::middle::region; -use rustc_middle::mir::*; -use rustc_middle::ty::layout::VariantIdx; -use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty}; +use rustc_ast::ast::Name; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir::HirId; use rustc_index::bit_set::BitSet; +use rustc_middle::middle::region; +use rustc_middle::mir::*; +use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty}; use rustc_span::Span; +use rustc_target::abi::VariantIdx; use smallvec::{smallvec, SmallVec}; -use rustc_ast::ast::Name; // helper functions, broken out by category: mod simplify; diff --git a/src/librustc_mir_build/build/matches/simplify.rs b/src/librustc_mir_build/build/matches/simplify.rs index 664f56ae5e456..d74d8b5c7f318 100644 --- a/src/librustc_mir_build/build/matches/simplify.rs +++ b/src/librustc_mir_build/build/matches/simplify.rs @@ -15,12 +15,13 @@ use crate::build::matches::{Ascription, Binding, Candidate, MatchPair}; use crate::build::Builder; use crate::hair::{self, *}; +use rustc_attr::{SignedInt, UnsignedInt}; +use rustc_hir::RangeEnd; use rustc_middle::mir::interpret::truncate; use rustc_middle::mir::Place; use rustc_middle::ty; -use rustc_middle::ty::layout::{Integer, IntegerExt, Size}; -use rustc_attr::{SignedInt, UnsignedInt}; -use rustc_hir::RangeEnd; +use rustc_middle::ty::layout::IntegerExt; +use rustc_target::abi::{Integer, Size}; use std::mem; diff --git a/src/librustc_mir_build/build/matches/test.rs b/src/librustc_mir_build/build/matches/test.rs index 01b3cfb7ba05b..42242d772a42a 100644 --- a/src/librustc_mir_build/build/matches/test.rs +++ b/src/librustc_mir_build/build/matches/test.rs @@ -9,14 +9,14 @@ use crate::build::matches::{Candidate, MatchPair, Test, TestKind}; use crate::build::Builder; use crate::hair::pattern::compare_const_vals; use crate::hair::*; -use rustc_middle::mir::*; -use rustc_middle::ty::layout::VariantIdx; -use rustc_middle::ty::util::IntTypeExt; -use rustc_middle::ty::{self, adjustment::PointerCast, Ty}; use rustc_data_structures::fx::FxHashMap; use rustc_hir::RangeEnd; use rustc_index::bit_set::BitSet; +use rustc_middle::mir::*; +use rustc_middle::ty::util::IntTypeExt; +use rustc_middle::ty::{self, adjustment::PointerCast, Ty}; use rustc_span::symbol::sym; +use rustc_target::abi::VariantIdx; use std::cmp::Ordering; @@ -362,7 +362,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { place: Place<'tcx>, mut ty: Ty<'tcx>, ) { - use rustc_middle::middle::lang_items::EqTraitLangItem; + use rustc_hir::lang_items::EqTraitLangItem; let mut expect = self.literal_operand(source_info.span, value); let mut val = Operand::Copy(place); diff --git a/src/librustc_mir_build/build/mod.rs b/src/librustc_mir_build/build/mod.rs index c4eb9803b425f..23ab00d536fe4 100644 --- a/src/librustc_mir_build/build/mod.rs +++ b/src/librustc_mir_build/build/mod.rs @@ -2,17 +2,17 @@ use crate::build; use crate::build::scope::DropKind; use crate::hair::cx::Cx; use crate::hair::{BindingMode, LintLevel, PatKind}; -use rustc_middle::middle::lang_items; -use rustc_middle::middle::region; -use rustc_middle::mir::*; -use rustc_middle::ty::subst::Subst; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable}; use rustc_attr::{self as attr, UnwindAttr}; use rustc_hir as hir; use rustc_hir::def_id::DefId; +use rustc_hir::lang_items; use rustc_hir::{GeneratorKind, HirIdMap, Node}; use rustc_index::vec::{Idx, IndexVec}; use rustc_infer::infer::TyCtxtInferExt; +use rustc_middle::middle::region; +use rustc_middle::mir::*; +use rustc_middle::ty::subst::Subst; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable}; use rustc_span::symbol::kw; use rustc_span::Span; use rustc_target::spec::abi::Abi; diff --git a/src/librustc_mir_build/hair/constant.rs b/src/librustc_mir_build/hair/constant.rs index 667f29337c2b6..e5af0b5bd6bed 100644 --- a/src/librustc_mir_build/hair/constant.rs +++ b/src/librustc_mir_build/hair/constant.rs @@ -2,8 +2,9 @@ use rustc_ast::ast; use rustc_middle::mir::interpret::{ truncate, Allocation, ConstValue, LitToConstError, LitToConstInput, Scalar, }; -use rustc_middle::ty::{self, layout::Size, ParamEnv, TyCtxt, TyS}; +use rustc_middle::ty::{self, ParamEnv, TyCtxt, TyS}; use rustc_span::symbol::Symbol; +use rustc_target::abi::Size; crate fn lit_to_const<'tcx>( tcx: TyCtxt<'tcx>, diff --git a/src/librustc_mir_build/hair/cx/mod.rs b/src/librustc_mir_build/hair/cx/mod.rs index 13a476775db02..503bd26d51fcc 100644 --- a/src/librustc_mir_build/hair/cx/mod.rs +++ b/src/librustc_mir_build/hair/cx/mod.rs @@ -14,11 +14,11 @@ use rustc_index::vec::Idx; use rustc_infer::infer::InferCtxt; use rustc_middle::middle::region; use rustc_middle::mir::interpret::{LitToConstError, LitToConstInput}; -use rustc_middle::ty::layout::VariantIdx; use rustc_middle::ty::subst::Subst; use rustc_middle::ty::subst::{GenericArg, InternalSubsts}; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_span::symbol::{sym, Symbol}; +use rustc_target::abi::VariantIdx; use rustc_trait_selection::infer::InferCtxtExt; #[derive(Clone)] diff --git a/src/librustc_mir_build/hair/mod.rs b/src/librustc_mir_build/hair/mod.rs index fadfc7660d4f9..601e4412512ab 100644 --- a/src/librustc_mir_build/hair/mod.rs +++ b/src/librustc_mir_build/hair/mod.rs @@ -11,10 +11,10 @@ use rustc_middle::infer::canonical::Canonical; use rustc_middle::middle::region; use rustc_middle::mir::{BinOp, BorrowKind, Field, UnOp}; use rustc_middle::ty::adjustment::PointerCast; -use rustc_middle::ty::layout::VariantIdx; use rustc_middle::ty::subst::SubstsRef; use rustc_middle::ty::{AdtDef, Const, Ty, UpvarSubsts, UserType}; use rustc_span::Span; +use rustc_target::abi::VariantIdx; crate mod constant; crate mod cx; diff --git a/src/librustc_mir_build/hair/pattern/_match.rs b/src/librustc_mir_build/hair/pattern/_match.rs index 03f668d562e78..8c0843124f4f1 100644 --- a/src/librustc_mir_build/hair/pattern/_match.rs +++ b/src/librustc_mir_build/hair/pattern/_match.rs @@ -236,15 +236,16 @@ use super::{compare_const_vals, PatternFoldable, PatternFolder}; use super::{FieldPat, Pat, PatKind, PatRange}; use rustc_attr::{SignedInt, UnsignedInt}; +use rustc_errors::ErrorReported; use rustc_hir::def_id::DefId; use rustc_hir::{HirId, RangeEnd}; use rustc_middle::mir::interpret::{truncate, AllocId, ConstValue, Pointer, Scalar}; use rustc_middle::mir::Field; -use rustc_middle::ty::layout::{Integer, IntegerExt, Size, VariantIdx}; +use rustc_middle::ty::layout::IntegerExt; use rustc_middle::ty::{self, Const, Ty, TyCtxt, TypeFoldable, VariantDef}; -use rustc_middle::util::common::ErrorReported; use rustc_session::lint; use rustc_span::{Span, DUMMY_SP}; +use rustc_target::abi::{Integer, Size, VariantIdx}; use arena::TypedArena; diff --git a/src/librustc_mir_build/hair/pattern/mod.rs b/src/librustc_mir_build/hair/pattern/mod.rs index f15d2fc5caa03..2b6d8e920f5ed 100644 --- a/src/librustc_mir_build/hair/pattern/mod.rs +++ b/src/librustc_mir_build/hair/pattern/mod.rs @@ -19,13 +19,13 @@ use rustc_middle::mir::interpret::{get_slice_bytes, sign_extend, ConstValue, Err use rustc_middle::mir::interpret::{LitToConstError, LitToConstInput}; use rustc_middle::mir::UserTypeProjection; use rustc_middle::mir::{BorrowKind, Field, Mutability}; -use rustc_middle::ty::layout::VariantIdx; use rustc_middle::ty::subst::{GenericArg, SubstsRef}; use rustc_middle::ty::{self, AdtDef, DefIdTree, Region, Ty, TyCtxt, UserType}; use rustc_middle::ty::{ CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, }; use rustc_span::{Span, DUMMY_SP}; +use rustc_target::abi::VariantIdx; use std::cmp::Ordering; use std::fmt; @@ -1047,8 +1047,8 @@ crate fn compare_const_vals<'tcx>( } ty::Int(ity) => { use rustc_attr::SignedInt; - use rustc_middle::ty::layout::{Integer, IntegerExt}; - let size = Integer::from_attr(&tcx, SignedInt(ity)).size(); + use rustc_middle::ty::layout::IntegerExt; + let size = rustc_target::abi::Integer::from_attr(&tcx, SignedInt(ity)).size(); let a = sign_extend(a, size); let b = sign_extend(b, size); Some((a as i128).cmp(&(b as i128))) diff --git a/src/librustc_parse/parser/expr.rs b/src/librustc_parse/parser/expr.rs index b205a4b322229..cbff99f8da612 100644 --- a/src/librustc_parse/parser/expr.rs +++ b/src/librustc_parse/parser/expr.rs @@ -638,6 +638,7 @@ impl<'a> Parser<'a> { ExprKind::MethodCall(_, _) => "a method call", ExprKind::Call(_, _) => "a function call", ExprKind::Await(_) => "`.await`", + ExprKind::Err => return Ok(with_postfix), _ => unreachable!("parse_dot_or_call_expr_with_ shouldn't produce this"), } ); diff --git a/src/librustc_passes/intrinsicck.rs b/src/librustc_passes/intrinsicck.rs index 11096c693e630..cc1af630cdd3c 100644 --- a/src/librustc_passes/intrinsicck.rs +++ b/src/librustc_passes/intrinsicck.rs @@ -4,10 +4,11 @@ use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor}; use rustc_index::vec::Idx; -use rustc_middle::ty::layout::{LayoutError, Pointer, SizeSkeleton, VariantIdx}; +use rustc_middle::ty::layout::{LayoutError, SizeSkeleton}; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_span::{sym, Span}; +use rustc_target::abi::{Pointer, VariantIdx}; use rustc_target::spec::abi::Abi::RustIntrinsic; fn check_mod_intrinsics(tcx: TyCtxt<'_>, module_def_id: DefId) { diff --git a/src/librustc_passes/layout_test.rs b/src/librustc_passes/layout_test.rs index 9fa3225851ba1..da8ab727ed3aa 100644 --- a/src/librustc_passes/layout_test.rs +++ b/src/librustc_passes/layout_test.rs @@ -3,16 +3,10 @@ use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::itemlikevisit::ItemLikeVisitor; use rustc_hir::ItemKind; -use rustc_middle::ty::layout::HasDataLayout; -use rustc_middle::ty::layout::HasParamEnv; -use rustc_middle::ty::layout::HasTyCtxt; -use rustc_middle::ty::layout::LayoutOf; -use rustc_middle::ty::layout::TargetDataLayout; -use rustc_middle::ty::layout::TyAndLayout; -use rustc_middle::ty::ParamEnv; -use rustc_middle::ty::Ty; -use rustc_middle::ty::TyCtxt; +use rustc_middle::ty::layout::{HasParamEnv, HasTyCtxt, TyAndLayout}; +use rustc_middle::ty::{ParamEnv, Ty, TyCtxt}; use rustc_span::symbol::sym; +use rustc_target::abi::{HasDataLayout, LayoutOf, TargetDataLayout}; pub fn test_layout(tcx: TyCtxt<'_>) { if tcx.features().rustc_attrs { diff --git a/src/librustc_passes/weak_lang_items.rs b/src/librustc_passes/weak_lang_items.rs index 8d11af15b56ff..8e56ef0da5237 100644 --- a/src/librustc_passes/weak_lang_items.rs +++ b/src/librustc_passes/weak_lang_items.rs @@ -4,8 +4,8 @@ use rustc_data_structures::fx::FxHashSet; use rustc_errors::struct_span_err; use rustc_hir as hir; use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor}; +use rustc_hir::lang_items; use rustc_hir::weak_lang_items::WEAK_ITEMS_REFS; -use rustc_middle::middle::lang_items; use rustc_middle::middle::lang_items::whitelisted; use rustc_middle::ty::TyCtxt; use rustc_session::config; diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 75c5dfb8d18b0..21f43b6fd4f64 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -2808,7 +2808,7 @@ impl<'a> Resolver<'a> { ast::Path { span, segments: iter::once(Ident::with_dummy_span(kw::PathRoot)) - .chain({ path_str.split("::").skip(1).map(Ident::from_str) }) + .chain(path_str.split("::").skip(1).map(Ident::from_str)) .map(|i| self.new_ast_path_segment(i)) .collect(), } diff --git a/src/librustc_target/spec/windows_base.rs b/src/librustc_target/spec/windows_base.rs index 188548b41fe75..5f59ca8a5a311 100644 --- a/src/librustc_target/spec/windows_base.rs +++ b/src/librustc_target/spec/windows_base.rs @@ -60,6 +60,8 @@ pub fn opts() -> TargetOptions { "-lgcc".to_string(), "-lgcc_eh".to_string(), "-lpthread".to_string(), + // libpthread depends on libmsvcrt, so we need to link it *again*. + "-lmsvcrt".to_string(), "-lkernel32".to_string(), ], ); diff --git a/src/librustc_trait_selection/infer.rs b/src/librustc_trait_selection/infer.rs index d7a2e720a6d0b..24eb22fbd00b1 100644 --- a/src/librustc_trait_selection/infer.rs +++ b/src/librustc_trait_selection/infer.rs @@ -2,11 +2,11 @@ use crate::traits::query::outlives_bounds::InferCtxtExt as _; use crate::traits::{self, TraitEngine, TraitEngineExt}; use rustc_hir as hir; +use rustc_hir::lang_items; use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::traits::ObligationCause; use rustc_middle::arena::ArenaAllocatable; use rustc_middle::infer::canonical::{Canonical, CanonicalizedQueryResponse, QueryResponse}; -use rustc_middle::middle::lang_items; use rustc_middle::traits::query::Fallible; use rustc_middle::ty::{self, Ty, TypeFoldable}; use rustc_span::{Span, DUMMY_SP}; diff --git a/src/librustc_trait_selection/traits/mod.rs b/src/librustc_trait_selection/traits/mod.rs index 3ef44a198417a..928554a6d418e 100644 --- a/src/librustc_trait_selection/traits/mod.rs +++ b/src/librustc_trait_selection/traits/mod.rs @@ -24,13 +24,13 @@ use crate::infer::outlives::env::OutlivesEnvironment; use crate::infer::{InferCtxt, RegionckMode, TyCtxtInferExt}; use crate::traits::error_reporting::InferCtxtExt as _; use crate::traits::query::evaluate_obligation::InferCtxtExt as _; +use rustc_errors::ErrorReported; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_middle::middle::region; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::subst::{InternalSubsts, SubstsRef}; use rustc_middle::ty::{self, GenericParamDefKind, ToPredicate, Ty, TyCtxt, WithConstness}; -use rustc_middle::util::common::ErrorReported; use rustc_span::{Span, DUMMY_SP}; use std::fmt::Debug; diff --git a/src/librustc_trait_selection/traits/object_safety.rs b/src/librustc_trait_selection/traits/object_safety.rs index 3877c7f8a8c8e..20b3fa908d201 100644 --- a/src/librustc_trait_selection/traits/object_safety.rs +++ b/src/librustc_trait_selection/traits/object_safety.rs @@ -420,7 +420,7 @@ fn virtual_call_violation_for_method<'tcx>( } else { // Do sanity check to make sure the receiver actually has the layout of a pointer. - use rustc_middle::ty::layout::Abi; + use rustc_target::abi::Abi; let param_env = tcx.param_env(method.def_id); diff --git a/src/librustc_trait_selection/traits/on_unimplemented.rs b/src/librustc_trait_selection/traits/on_unimplemented.rs index 23c3bd46d2d80..cf29c4249c019 100644 --- a/src/librustc_trait_selection/traits/on_unimplemented.rs +++ b/src/librustc_trait_selection/traits/on_unimplemented.rs @@ -1,13 +1,11 @@ use fmt_macros::{Parser, Piece, Position}; -use rustc_middle::ty::{self, GenericParamDefKind, TyCtxt}; -use rustc_middle::util::common::ErrorReported; - use rustc_ast::ast::{MetaItem, NestedMetaItem}; use rustc_attr as attr; use rustc_data_structures::fx::FxHashMap; -use rustc_errors::struct_span_err; +use rustc_errors::{struct_span_err, ErrorReported}; use rustc_hir::def_id::DefId; +use rustc_middle::ty::{self, GenericParamDefKind, TyCtxt}; use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::Span; diff --git a/src/librustc_trait_selection/traits/select.rs b/src/librustc_trait_selection/traits/select.rs index 1e5a1edd4d8ee..3d95824cdf00e 100644 --- a/src/librustc_trait_selection/traits/select.rs +++ b/src/librustc_trait_selection/traits/select.rs @@ -39,9 +39,9 @@ use rustc_ast::attr; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir as hir; use rustc_hir::def_id::DefId; +use rustc_hir::lang_items; use rustc_index::bit_set::GrowableBitSet; use rustc_middle::dep_graph::{DepKind, DepNodeIndex}; -use rustc_middle::middle::lang_items; use rustc_middle::ty::fast_reject; use rustc_middle::ty::relate::TypeRelation; use rustc_middle::ty::subst::{Subst, SubstsRef}; diff --git a/src/librustc_trait_selection/traits/wf.rs b/src/librustc_trait_selection/traits/wf.rs index 59b56d673fb00..1eb41e0b4d1ae 100644 --- a/src/librustc_trait_selection/traits/wf.rs +++ b/src/librustc_trait_selection/traits/wf.rs @@ -3,7 +3,7 @@ use crate::opaque_types::required_region_bounds; use crate::traits::{self, AssocTypeBoundData}; use rustc_hir as hir; use rustc_hir::def_id::DefId; -use rustc_middle::middle::lang_items; +use rustc_hir::lang_items; use rustc_middle::ty::subst::SubstsRef; use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness}; use rustc_span::symbol::{kw, Ident}; diff --git a/src/librustc_ty/common_traits.rs b/src/librustc_ty/common_traits.rs index 597bc8546045d..265b811571afe 100644 --- a/src/librustc_ty/common_traits.rs +++ b/src/librustc_ty/common_traits.rs @@ -1,7 +1,7 @@ //! Queries for checking whether a type implements one of a few common traits. +use rustc_hir::lang_items; use rustc_infer::infer::TyCtxtInferExt; -use rustc_middle::middle::lang_items; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_span::DUMMY_SP; use rustc_trait_selection::traits; diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 932032bb2b45f..c3ebcbfc832d1 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -6,18 +6,18 @@ // ignore-tidy-filelength use crate::collect::PlaceholderHirTyCollector; -use crate::middle::lang_items::SizedTraitLangItem; use crate::middle::resolve_lifetime as rl; use crate::require_c_abi_if_c_variadic; -use crate::util::common::ErrorReported; use rustc_ast::ast; use rustc_ast::util::lev_distance::find_best_match_for_name; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; +use rustc_errors::ErrorReported; use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId, FatalError}; use rustc_hir as hir; use rustc_hir::def::{CtorOf, DefKind, Namespace, Res}; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::{walk_generics, Visitor as _}; +use rustc_hir::lang_items::SizedTraitLangItem; use rustc_hir::{Constness, GenericArg, GenericArgs}; use rustc_middle::ty::subst::{self, InternalSubsts, Subst, SubstsRef}; use rustc_middle::ty::{ diff --git a/src/librustc_typeck/check/cast.rs b/src/librustc_typeck/check/cast.rs index 7f1631a620499..5de0184f2bba9 100644 --- a/src/librustc_typeck/check/cast.rs +++ b/src/librustc_typeck/check/cast.rs @@ -32,11 +32,10 @@ use super::FnCtxt; use crate::hir::def_id::DefId; use crate::type_error_struct; -use crate::util::common::ErrorReported; use rustc_ast::ast; -use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder}; +use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorReported}; use rustc_hir as hir; -use rustc_middle::middle::lang_items; +use rustc_hir::lang_items; use rustc_middle::ty::adjustment::AllowTwoPhase; use rustc_middle::ty::cast::{CastKind, CastTy}; use rustc_middle::ty::error::TypeError; diff --git a/src/librustc_typeck/check/closure.rs b/src/librustc_typeck/check/closure.rs index 415b5103104a1..922d9ca6485bb 100644 --- a/src/librustc_typeck/check/closure.rs +++ b/src/librustc_typeck/check/closure.rs @@ -3,9 +3,10 @@ use super::{check_fn, Expectation, FnCtxt, GeneratorTypes}; use crate::astconv::AstConv; -use crate::middle::{lang_items, region}; +use crate::middle::region; use rustc_hir as hir; use rustc_hir::def_id::DefId; +use rustc_hir::lang_items; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_infer::infer::LateBoundRegionConversionTime; use rustc_infer::infer::{InferOk, InferResult}; diff --git a/src/librustc_typeck/check/compare_method.rs b/src/librustc_typeck/check/compare_method.rs index 9e45793fcdc72..24db25a1f3456 100644 --- a/src/librustc_typeck/check/compare_method.rs +++ b/src/librustc_typeck/check/compare_method.rs @@ -1,4 +1,4 @@ -use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId}; +use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId, ErrorReported}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::intravisit; @@ -8,7 +8,6 @@ use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::subst::{InternalSubsts, Subst}; use rustc_middle::ty::util::ExplicitSelf; use rustc_middle::ty::{self, GenericParamDefKind, TyCtxt}; -use rustc_middle::util::common::ErrorReported; use rustc_span::Span; use rustc_trait_selection::traits::error_reporting::InferCtxtExt; use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode, Reveal}; diff --git a/src/librustc_typeck/check/dropck.rs b/src/librustc_typeck/check/dropck.rs index a44a607a70335..72220d93d929d 100644 --- a/src/librustc_typeck/check/dropck.rs +++ b/src/librustc_typeck/check/dropck.rs @@ -1,8 +1,7 @@ use crate::check::regionck::RegionCtxt; use crate::hir; use crate::hir::def_id::DefId; -use crate::util::common::ErrorReported; -use rustc_errors::struct_span_err; +use rustc_errors::{struct_span_err, ErrorReported}; use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::{InferOk, RegionckMode, TyCtxtInferExt}; use rustc_infer::traits::TraitEngineExt as _; diff --git a/src/librustc_typeck/check/expr.rs b/src/librustc_typeck/check/expr.rs index bfcb6fe35fe75..9c57ffaf055ac 100644 --- a/src/librustc_typeck/check/expr.rs +++ b/src/librustc_typeck/check/expr.rs @@ -15,19 +15,19 @@ use crate::check::FnCtxt; use crate::check::Needs; use crate::check::TupleArgumentsFlag::DontTupleArguments; use crate::type_error_struct; -use crate::util::common::ErrorReported; use rustc_ast::ast; use rustc_ast::util::lev_distance::find_best_match_for_name; use rustc_data_structures::fx::FxHashMap; +use rustc_errors::ErrorReported; use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, DiagnosticId}; use rustc_hir as hir; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::DefId; +use rustc_hir::lang_items; use rustc_hir::{ExprKind, QPath}; use rustc_infer::infer; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; -use rustc_middle::middle::lang_items; use rustc_middle::ty; use rustc_middle::ty::adjustment::{ Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, diff --git a/src/librustc_typeck/check/method/suggest.rs b/src/librustc_typeck/check/method/suggest.rs index c8632086771f9..add706b5fcc9a 100644 --- a/src/librustc_typeck/check/method/suggest.rs +++ b/src/librustc_typeck/check/method/suggest.rs @@ -2,7 +2,6 @@ //! found or is otherwise invalid. use crate::check::FnCtxt; -use crate::middle::lang_items::FnOnceTraitLangItem; use rustc_ast::ast; use rustc_ast::util::lev_distance; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; @@ -11,6 +10,7 @@ use rustc_hir as hir; use rustc_hir::def::{DefKind, Namespace, Res}; use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE}; use rustc_hir::intravisit; +use rustc_hir::lang_items::FnOnceTraitLangItem; use rustc_hir::{ExprKind, Node, QPath}; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_middle::hir::map as hir_map; diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 6249e1d49779e..c3a4c0c873354 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -88,18 +88,19 @@ mod wfcheck; pub mod writeback; use crate::astconv::{AstConv, GenericArgCountMismatch, PathSeg}; -use crate::middle::lang_items; use rustc_ast::ast; use rustc_ast::util::parser::ExprPrecedence; use rustc_attr as attr; use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; +use rustc_errors::ErrorReported; use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, DiagnosticId}; use rustc_hir as hir; use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIdSet, LocalDefId, LOCAL_CRATE}; use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor}; use rustc_hir::itemlikevisit::ItemLikeVisitor; +use rustc_hir::lang_items; use rustc_hir::{ExprKind, GenericArg, HirIdMap, Item, ItemKind, Node, PatKind, QPath}; use rustc_index::vec::Idx; use rustc_infer::infer::canonical::{Canonical, OriginalQueryValues, QueryResponse}; @@ -114,7 +115,6 @@ use rustc_middle::ty::adjustment::{ Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCast, }; use rustc_middle::ty::fold::{TypeFoldable, TypeFolder}; -use rustc_middle::ty::layout::VariantIdx; use rustc_middle::ty::query::Providers; use rustc_middle::ty::subst::{ GenericArgKind, InternalSubsts, Subst, SubstsRef, UserSelfTy, UserSubsts, @@ -132,6 +132,7 @@ use rustc_span::hygiene::DesugaringKind; use rustc_span::source_map::{original_sp, DUMMY_SP}; use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::{self, BytePos, MultiSpan, Span}; +use rustc_target::abi::VariantIdx; use rustc_target::spec::abi::Abi; use rustc_trait_selection::infer::InferCtxtExt as _; use rustc_trait_selection::opaque_types::{InferCtxtExt as _, OpaqueTypeDecl}; @@ -151,7 +152,7 @@ use std::ops::{self, Deref}; use std::slice; use crate::require_c_abi_if_c_variadic; -use crate::util::common::{indenter, ErrorReported}; +use crate::util::common::indenter; use crate::TypeAndSubsts; use self::autoderef::Autoderef; diff --git a/src/librustc_typeck/check/wfcheck.rs b/src/librustc_typeck/check/wfcheck.rs index 6419113219162..30a53cbc397e8 100644 --- a/src/librustc_typeck/check/wfcheck.rs +++ b/src/librustc_typeck/check/wfcheck.rs @@ -7,8 +7,8 @@ use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder}; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::itemlikevisit::ParItemLikeVisitor; +use rustc_hir::lang_items; use rustc_hir::ItemKind; -use rustc_middle::middle::lang_items; use rustc_middle::ty::subst::{InternalSubsts, Subst}; use rustc_middle::ty::trait_def::TraitSpecializationKind; use rustc_middle::ty::{ diff --git a/src/librustc_typeck/coherence/builtin.rs b/src/librustc_typeck/coherence/builtin.rs index 32963b6a1f085..384a22d010e56 100644 --- a/src/librustc_typeck/coherence/builtin.rs +++ b/src/librustc_typeck/coherence/builtin.rs @@ -4,11 +4,11 @@ use rustc_errors::struct_span_err; use rustc_hir as hir; use rustc_hir::def_id::DefId; +use rustc_hir::lang_items::UnsizeTraitLangItem; use rustc_hir::ItemKind; use rustc_infer::infer; use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::{RegionckMode, TyCtxtInferExt}; -use rustc_middle::middle::lang_items::UnsizeTraitLangItem; use rustc_middle::middle::region; use rustc_middle::ty::adjustment::CoerceUnsizedInfo; use rustc_middle::ty::TypeFoldable; diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 30887f840321b..13c6670f6b226 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -17,7 +17,6 @@ use crate::astconv::{AstConv, Bounds, SizedByDefault}; use crate::check::intrinsic::intrinsic_operation_unsafety; use crate::constrained_generic_params as cgp; -use crate::middle::lang_items; use crate::middle::resolve_lifetime as rl; use rustc_ast::ast; use rustc_ast::ast::{Ident, MetaItemKind}; @@ -29,6 +28,7 @@ use rustc_hir as hir; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::{DefId, LOCAL_CRATE}; use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor}; +use rustc_hir::weak_lang_items; use rustc_hir::{GenericParamKind, Node, Unsafety}; use rustc_middle::hir::map::blocks::FnLikeNode; use rustc_middle::hir::map::Map; @@ -2569,7 +2569,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, id: DefId) -> CodegenFnAttrs { if tcx.is_weak_lang_item(id) { codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL; } - if let Some(name) = lang_items::link_name(&attrs) { + if let Some(name) = weak_lang_items::link_name(&attrs) { codegen_fn_attrs.export_name = Some(name); codegen_fn_attrs.link_name = Some(name); } diff --git a/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs index 1927b9c99e175..7ea6c1c17869a 100644 --- a/src/librustc_typeck/lib.rs +++ b/src/librustc_typeck/lib.rs @@ -89,7 +89,7 @@ mod outlives; mod structured_errors; mod variance; -use rustc_errors::struct_span_err; +use rustc_errors::{struct_span_err, ErrorReported}; use rustc_hir as hir; use rustc_hir::def_id::{DefId, LOCAL_CRATE}; use rustc_hir::Node; @@ -100,7 +100,6 @@ use rustc_middle::ty::query::Providers; use rustc_middle::ty::subst::SubstsRef; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::util; -use rustc_middle::util::common::ErrorReported; use rustc_session::config::EntryFnType; use rustc_span::{Span, DUMMY_SP}; use rustc_target::spec::abi::Abi; diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index 9f327b0b743d8..73df844a91b80 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -1,5 +1,6 @@ use rustc_data_structures::fx::FxHashSet; use rustc_hir as hir; +use rustc_hir::lang_items; use rustc_middle::ty::{self, Region, RegionVid, TypeFoldable}; use rustc_trait_selection::traits::auto_trait::{self, AutoTraitResult}; diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index f8e44bc5a1ab7..e027db8b56c00 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -17,7 +17,6 @@ use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX}; use rustc_index::vec::{Idx, IndexVec}; use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData}; -use rustc_middle::middle::lang_items; use rustc_middle::middle::resolve_lifetime as rl; use rustc_middle::middle::stability; use rustc_middle::ty::fold::TypeFolder; diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 7b3fd82479ebb..2e5ecacee12df 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -15,15 +15,15 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir as hir; use rustc_hir::def::Res; use rustc_hir::def_id::{CrateNum, DefId}; +use rustc_hir::lang_items; use rustc_hir::Mutability; use rustc_index::vec::IndexVec; -use rustc_middle::middle::lang_items; use rustc_middle::middle::stability; -use rustc_middle::ty::layout::VariantIdx; use rustc_span::hygiene::MacroKind; use rustc_span::source_map::DUMMY_SP; use rustc_span::symbol::{sym, Symbol}; use rustc_span::{self, FileName}; +use rustc_target::abi::VariantIdx; use rustc_target::spec::abi::Abi; use crate::clean::cfg::Cfg; diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index f9e9a07914d69..7841d5eef58a8 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -1,12 +1,12 @@ use rustc_ast::ast; use rustc_ast::with_globals; use rustc_data_structures::sync::Lrc; +use rustc_errors::ErrorReported; use rustc_feature::UnstableFeatures; use rustc_hir as hir; use rustc_hir::intravisit; use rustc_interface::interface; use rustc_middle::hir::map::Map; -use rustc_middle::util::common::ErrorReported; use rustc_session::{self, config, DiagnosticOutput, Session}; use rustc_span::edition::Edition; use rustc_span::source_map::SourceMap; diff --git a/src/libstd/sys/windows/handle.rs b/src/libstd/sys/windows/handle.rs index f2ad057b6b624..d00381792e351 100644 --- a/src/libstd/sys/windows/handle.rs +++ b/src/libstd/sys/windows/handle.rs @@ -115,8 +115,7 @@ impl RawHandle { ) -> io::Result> { let len = cmp::min(buf.len(), ::max_value() as usize) as c::DWORD; let mut amt = 0; - let res = - cvt({ c::ReadFile(self.0, buf.as_ptr() as c::LPVOID, len, &mut amt, overlapped) }); + let res = cvt(c::ReadFile(self.0, buf.as_ptr() as c::LPVOID, len, &mut amt, overlapped)); match res { Ok(_) => Ok(Some(amt as usize)), Err(e) => { @@ -139,7 +138,7 @@ impl RawHandle { unsafe { let mut bytes = 0; let wait = if wait { c::TRUE } else { c::FALSE }; - let res = cvt({ c::GetOverlappedResult(self.raw(), overlapped, &mut bytes, wait) }); + let res = cvt(c::GetOverlappedResult(self.raw(), overlapped, &mut bytes, wait)); match res { Ok(_) => Ok(bytes as usize), Err(e) => { diff --git a/src/test/incremental/const-generics/issue-61516.rs b/src/test/incremental/const-generics/issue-61516.rs index a7465b77267a5..a193bf998dc73 100644 --- a/src/test/incremental/const-generics/issue-61516.rs +++ b/src/test/incremental/const-generics/issue-61516.rs @@ -4,7 +4,7 @@ struct FakeArray(T); -impl FakeArray { +impl FakeArray { fn len(&self) -> usize { N } diff --git a/src/test/ui-fulldeps/undef_mask.rs b/src/test/ui-fulldeps/undef_mask.rs index cbf1b63d22b0f..656d0b451bc2b 100644 --- a/src/test/ui-fulldeps/undef_mask.rs +++ b/src/test/ui-fulldeps/undef_mask.rs @@ -5,9 +5,10 @@ #![feature(rustc_private)] extern crate rustc_middle; +extern crate rustc_target; use rustc_middle::mir::interpret::UndefMask; -use rustc_middle::ty::layout::Size; +use rustc_target::abi::Size; fn main() { let mut mask = UndefMask::new(Size::from_bytes(500), false); diff --git a/src/test/ui/array-slice-vec/vec-fixed-length.rs b/src/test/ui/array-slice-vec/vec-fixed-length.rs index 5db02ee066bbe..908c39c7951c0 100644 --- a/src/test/ui/array-slice-vec/vec-fixed-length.rs +++ b/src/test/ui/array-slice-vec/vec-fixed-length.rs @@ -9,7 +9,7 @@ fn test_big_vec() {} #[cfg(target_pointer_width = "64")] fn test_big_vec() { - assert_eq!(size_of::<[u8; (1 << 32)]>(), (1 << 32)); + assert_eq!(size_of::<[u8; 1 << 32]>(), (1 << 32)); } fn main() { diff --git a/src/test/ui/block-fn-coerce.rs b/src/test/ui/block-fn-coerce.rs index fc5f51d46b255..d993ad9945974 100644 --- a/src/test/ui/block-fn-coerce.rs +++ b/src/test/ui/block-fn-coerce.rs @@ -1,4 +1,5 @@ // run-pass +#![allow(unused_braces)] fn force(f: F) -> isize where F: FnOnce() -> isize { return f(); } diff --git a/src/test/ui/cleanup-rvalue-scopes.rs b/src/test/ui/cleanup-rvalue-scopes.rs index f51f13abf792f..c5dd87c0f5a1f 100644 --- a/src/test/ui/cleanup-rvalue-scopes.rs +++ b/src/test/ui/cleanup-rvalue-scopes.rs @@ -1,5 +1,5 @@ // run-pass - +#![allow(unused_braces)] #![allow(non_snake_case)] #![allow(unused_variables)] // Test that destructors for rvalue temporaries run either at end of diff --git a/src/test/ui/coerce/coerce-expect-unsized.rs b/src/test/ui/coerce/coerce-expect-unsized.rs index b44aa6ab37760..d486fdf73aba8 100644 --- a/src/test/ui/coerce/coerce-expect-unsized.rs +++ b/src/test/ui/coerce/coerce-expect-unsized.rs @@ -1,4 +1,5 @@ // run-pass +#![allow(unused_braces)] #![feature(box_syntax)] use std::cell::RefCell; diff --git a/src/test/ui/coerce/coerce-overloaded-autoderef.rs b/src/test/ui/coerce/coerce-overloaded-autoderef.rs index 3fe18103ef8c3..d5484607c8b52 100644 --- a/src/test/ui/coerce/coerce-overloaded-autoderef.rs +++ b/src/test/ui/coerce/coerce-overloaded-autoderef.rs @@ -1,4 +1,5 @@ // run-pass +#![allow(unused_braces)] #![allow(dead_code)] // pretty-expanded FIXME #23616 diff --git a/src/test/ui/const-generics/issues/issue-62504.rs b/src/test/ui/const-generics/issues/issue-62504.rs index cd3cfaac3b95b..212e16253f6b8 100644 --- a/src/test/ui/const-generics/issues/issue-62504.rs +++ b/src/test/ui/const-generics/issues/issue-62504.rs @@ -7,13 +7,13 @@ trait HasSize { const SIZE: usize; } -impl HasSize for ArrayHolder<{ X }> { +impl HasSize for ArrayHolder { const SIZE: usize = X; } struct ArrayHolder([u32; X]); -impl ArrayHolder<{ X }> { +impl ArrayHolder { pub const fn new() -> Self { ArrayHolder([0; Self::SIZE]) //~^ ERROR: mismatched types diff --git a/src/test/ui/const-generics/issues/issue-70125-2.rs b/src/test/ui/const-generics/issues/issue-70125-2.rs index ea7a68c2f93d9..a3eca0dd7d965 100644 --- a/src/test/ui/const-generics/issues/issue-70125-2.rs +++ b/src/test/ui/const-generics/issues/issue-70125-2.rs @@ -13,4 +13,4 @@ trait Foo { } } -impl Foo<{3}> for () {} +impl Foo<3> for () {} diff --git a/src/test/ui/const-generics/unused_braces.rs b/src/test/ui/const-generics/unused_braces.rs new file mode 100644 index 0000000000000..05234faf71420 --- /dev/null +++ b/src/test/ui/const-generics/unused_braces.rs @@ -0,0 +1,13 @@ +// check-pass +#![warn(unused_braces)] + +#![feature(const_generics)] +//~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash + +struct A; + +fn main() { + let _: A<7>; // ok + let _: A<{ 7 }>; //~ WARN unnecessary braces + let _: A<{ 3 + 5 }>; // ok +} diff --git a/src/test/ui/const-generics/unused_braces.stderr b/src/test/ui/const-generics/unused_braces.stderr new file mode 100644 index 0000000000000..fc3da6096e7d4 --- /dev/null +++ b/src/test/ui/const-generics/unused_braces.stderr @@ -0,0 +1,20 @@ +warning: the feature `const_generics` is incomplete and may cause the compiler to crash + --> $DIR/unused_braces.rs:4:12 + | +LL | #![feature(const_generics)] + | ^^^^^^^^^^^^^^ + | + = note: `#[warn(incomplete_features)]` on by default + +warning: unnecessary braces around const expression + --> $DIR/unused_braces.rs:11:14 + | +LL | let _: A<{ 7 }>; + | ^^^^^ help: remove these braces + | +note: the lint level is defined here + --> $DIR/unused_braces.rs:2:9 + | +LL | #![warn(unused_braces)] + | ^^^^^^^^^^^^^ + diff --git a/src/test/ui/consts/const-block.rs b/src/test/ui/consts/const-block.rs index 7172a34c8cfeb..ec99c70f6e0b9 100644 --- a/src/test/ui/consts/const-block.rs +++ b/src/test/ui/consts/const-block.rs @@ -1,5 +1,5 @@ // run-pass - +#![allow(unused_braces)] #![allow(dead_code)] #![allow(unused_unsafe)] diff --git a/src/test/ui/expr-block-generic-unique1.rs b/src/test/ui/expr-block-generic-unique1.rs index c14191f2ffcb5..d081cb2be7ee3 100644 --- a/src/test/ui/expr-block-generic-unique1.rs +++ b/src/test/ui/expr-block-generic-unique1.rs @@ -1,5 +1,5 @@ // run-pass - +#![allow(unused_braces)] #![feature(box_syntax)] fn test_generic(expected: Box, eq: F) where T: Clone, F: FnOnce(Box, Box) -> bool { diff --git a/src/test/ui/expr-block-generic-unique2.rs b/src/test/ui/expr-block-generic-unique2.rs index 90ebc02931ad1..9362eb86fc309 100644 --- a/src/test/ui/expr-block-generic-unique2.rs +++ b/src/test/ui/expr-block-generic-unique2.rs @@ -1,5 +1,5 @@ // run-pass - +#![allow(unused_braces)] #![feature(box_syntax)] fn test_generic(expected: T, eq: F) where T: Clone, F: FnOnce(T, T) -> bool { diff --git a/src/test/ui/expr-block-generic.rs b/src/test/ui/expr-block-generic.rs index ec93f59722d0c..29c7c42219c73 100644 --- a/src/test/ui/expr-block-generic.rs +++ b/src/test/ui/expr-block-generic.rs @@ -1,4 +1,5 @@ // run-pass +#![allow(unused_braces)] fn test_generic(expected: T, eq: F) where F: FnOnce(T, T) -> bool { let actual: T = { expected.clone() }; diff --git a/src/test/ui/expr-block-unique.rs b/src/test/ui/expr-block-unique.rs index fe1a7d9f1fb31..eff3fd3a15152 100644 --- a/src/test/ui/expr-block-unique.rs +++ b/src/test/ui/expr-block-unique.rs @@ -1,5 +1,5 @@ // run-pass - +#![allow(unused_braces)] #![feature(box_syntax)] pub fn main() { let x: Box<_> = { box 100 }; assert_eq!(*x, 100); } diff --git a/src/test/ui/expr-block.rs b/src/test/ui/expr-block.rs index 549ccf9774f43..ff87595c934e9 100644 --- a/src/test/ui/expr-block.rs +++ b/src/test/ui/expr-block.rs @@ -1,10 +1,7 @@ // run-pass - +#![allow(unused_braces)] #![allow(dead_code)] - - - // Tests for standalone blocks as expressions fn test_basic() { let rs: bool = { true }; assert!((rs)); } diff --git a/src/test/ui/expr-fn.rs b/src/test/ui/expr-fn.rs index af809f563fc04..253cbfd5d38fa 100644 --- a/src/test/ui/expr-fn.rs +++ b/src/test/ui/expr-fn.rs @@ -1,4 +1,5 @@ // run-pass +#![allow(unused_braces)] fn test_int() { fn f() -> isize { 10 } diff --git a/src/test/ui/functions-closures/closure-inference.rs b/src/test/ui/functions-closures/closure-inference.rs index 96878445245bc..1877414f09942 100644 --- a/src/test/ui/functions-closures/closure-inference.rs +++ b/src/test/ui/functions-closures/closure-inference.rs @@ -1,5 +1,5 @@ // run-pass - +#![allow(unused_braces)] fn foo(i: isize) -> isize { i + 1 } diff --git a/src/test/ui/functions-closures/closure-inference2.rs b/src/test/ui/functions-closures/closure-inference2.rs index f2dfa5888aac5..4ce132e86caa4 100644 --- a/src/test/ui/functions-closures/closure-inference2.rs +++ b/src/test/ui/functions-closures/closure-inference2.rs @@ -1,6 +1,6 @@ // run-pass // Test a rather underspecified example: - +#![allow(unused_braces)] pub fn main() { let f = {|i| i}; diff --git a/src/test/ui/intrinsics/intrinsic-move-val-cleanups.rs b/src/test/ui/intrinsics/intrinsic-move-val-cleanups.rs index a2068429af5ea..9804c421db081 100644 --- a/src/test/ui/intrinsics/intrinsic-move-val-cleanups.rs +++ b/src/test/ui/intrinsics/intrinsic-move-val-cleanups.rs @@ -1,4 +1,5 @@ // run-pass +#![allow(unused_braces)] #![allow(unused_unsafe)] #![allow(unreachable_code)] // ignore-emscripten no threads support diff --git a/src/test/ui/issues/issue-23898.rs b/src/test/ui/issues/issue-23898.rs index a8787f279b71b..3de365675ad22 100644 --- a/src/test/ui/issues/issue-23898.rs +++ b/src/test/ui/issues/issue-23898.rs @@ -1,4 +1,5 @@ // run-pass +#![allow(unused_parens)] #![allow(non_camel_case_types)] // Note: This test was used to demonstrate #5873 (now #23898). diff --git a/src/test/ui/issues/issue-28777.rs b/src/test/ui/issues/issue-28777.rs index 74de00adadbda..1f426b7185e8f 100644 --- a/src/test/ui/issues/issue-28777.rs +++ b/src/test/ui/issues/issue-28777.rs @@ -1,4 +1,5 @@ // run-pass +#![allow(unused_braces)] fn main() { let v1 = { 1 + {2} * {3} }; let v2 = 1 + {2} * {3} ; diff --git a/src/test/ui/lint/lint-unnecessary-parens.rs b/src/test/ui/lint/lint-unnecessary-parens.rs index 5ce1f57608132..623cd04d9bce3 100644 --- a/src/test/ui/lint/lint-unnecessary-parens.rs +++ b/src/test/ui/lint/lint-unnecessary-parens.rs @@ -48,11 +48,11 @@ fn main() { if (true) {} //~ ERROR unnecessary parentheses around `if` condition while (true) {} //~ ERROR unnecessary parentheses around `while` condition //~^ WARN denote infinite loops with - match (true) { //~ ERROR unnecessary parentheses around `match` head expression + match (true) { //~ ERROR unnecessary parentheses around `match` scrutinee expression _ => {} } - if let 1 = (1) {} //~ ERROR unnecessary parentheses around `let` head expression - while let 1 = (2) {} //~ ERROR unnecessary parentheses around `let` head expression + if let 1 = (1) {} //~ ERROR unnecessary parentheses around `let` scrutinee expression + while let 1 = (2) {} //~ ERROR unnecessary parentheses around `let` scrutinee expression let v = X { y: false }; // struct lits needs parens, so these shouldn't warn. if (v == X { y: true }) {} diff --git a/src/test/ui/lint/lint-unnecessary-parens.stderr b/src/test/ui/lint/lint-unnecessary-parens.stderr index 8858c95327322..15184ba36ae85 100644 --- a/src/test/ui/lint/lint-unnecessary-parens.stderr +++ b/src/test/ui/lint/lint-unnecessary-parens.stderr @@ -72,19 +72,19 @@ LL | while (true) {} | = note: `#[warn(while_true)]` on by default -error: unnecessary parentheses around `match` head expression +error: unnecessary parentheses around `match` scrutinee expression --> $DIR/lint-unnecessary-parens.rs:51:11 | LL | match (true) { | ^^^^^^ help: remove these parentheses -error: unnecessary parentheses around `let` head expression +error: unnecessary parentheses around `let` scrutinee expression --> $DIR/lint-unnecessary-parens.rs:54:16 | LL | if let 1 = (1) {} | ^^^ help: remove these parentheses -error: unnecessary parentheses around `let` head expression +error: unnecessary parentheses around `let` scrutinee expression --> $DIR/lint-unnecessary-parens.rs:55:19 | LL | while let 1 = (2) {} diff --git a/src/test/ui/lint/unused_braces.rs b/src/test/ui/lint/unused_braces.rs new file mode 100644 index 0000000000000..de456ee6c230c --- /dev/null +++ b/src/test/ui/lint/unused_braces.rs @@ -0,0 +1,31 @@ +// check-pass +#![warn(unused_braces, unused_parens)] + +fn main() { + let _ = (7); + //~^WARN unnecessary parentheses + + let _ = { 7 }; + //~^ WARN unnecessary braces + + if let 7 = { 7 } { + //~^ WARN unnecessary braces + } + + let _: [u8; { 3 }]; + //~^ WARN unnecessary braces + + // do not emit error for multiline blocks. + let _ = { + 7 + }; + + // do not emit error for unsafe blocks. + let _ = unsafe { 7 }; + + // do not emit error, as the `{` would then + // be parsed as part of the `return`. + if { return } { + + } +} diff --git a/src/test/ui/lint/unused_braces.stderr b/src/test/ui/lint/unused_braces.stderr new file mode 100644 index 0000000000000..72f425ffc3e01 --- /dev/null +++ b/src/test/ui/lint/unused_braces.stderr @@ -0,0 +1,36 @@ +warning: unnecessary parentheses around assigned value + --> $DIR/unused_braces.rs:5:13 + | +LL | let _ = (7); + | ^^^ help: remove these parentheses + | +note: the lint level is defined here + --> $DIR/unused_braces.rs:2:24 + | +LL | #![warn(unused_braces, unused_parens)] + | ^^^^^^^^^^^^^ + +warning: unnecessary braces around assigned value + --> $DIR/unused_braces.rs:8:13 + | +LL | let _ = { 7 }; + | ^^^^^ help: remove these braces + | +note: the lint level is defined here + --> $DIR/unused_braces.rs:2:9 + | +LL | #![warn(unused_braces, unused_parens)] + | ^^^^^^^^^^^^^ + +warning: unnecessary braces around `let` scrutinee expression + --> $DIR/unused_braces.rs:11:16 + | +LL | if let 7 = { 7 } { + | ^^^^^ help: remove these braces + +warning: unnecessary braces around const expression + --> $DIR/unused_braces.rs:15:17 + | +LL | let _: [u8; { 3 }]; + | ^^^^^ help: remove these braces + diff --git a/src/test/ui/lint/unused_parens_borrow.rs b/src/test/ui/lint/unused_parens_borrow.rs new file mode 100644 index 0000000000000..98dbbecfedde6 --- /dev/null +++ b/src/test/ui/lint/unused_parens_borrow.rs @@ -0,0 +1,22 @@ +// check-pass +#![warn(unused_braces)] + +// changing `&{ expr }` to `&expr` changes the semantic of the program +// so we should not warn this case + +#[repr(packed)] +struct A { + a: u8, + b: u32, +} + +fn main() { + let a = A { + a: 42, + b: 1729, + }; + + let _ = &{ a.b }; + let _ = { a.b }; + //~^ WARN unnecessary braces +} diff --git a/src/test/ui/lint/unused_parens_borrow.stderr b/src/test/ui/lint/unused_parens_borrow.stderr new file mode 100644 index 0000000000000..7e3839ae4e014 --- /dev/null +++ b/src/test/ui/lint/unused_parens_borrow.stderr @@ -0,0 +1,12 @@ +warning: unnecessary braces around assigned value + --> $DIR/unused_parens_borrow.rs:20:13 + | +LL | let _ = { a.b }; + | ^^^^^^^ help: remove these braces + | +note: the lint level is defined here + --> $DIR/unused_parens_borrow.rs:2:9 + | +LL | #![warn(unused_braces)] + | ^^^^^^^^^^^^^ + diff --git a/src/test/ui/lint/unused_parens_remove_json_suggestion.stderr b/src/test/ui/lint/unused_parens_remove_json_suggestion.stderr index c3bf77a3a6f2d..5fb67fd7c95a3 100644 --- a/src/test/ui/lint/unused_parens_remove_json_suggestion.stderr +++ b/src/test/ui/lint/unused_parens_remove_json_suggestion.stderr @@ -46,14 +46,14 @@ LL | while(true && false) { | ^^^^^^^^^^^^^^^ help: remove these parentheses "} -{"message":"unnecessary parentheses around `for` head expression","code":{"code":"unused_parens","explanation":null},"level":"error","spans":[{"file_name":"$DIR/unused_parens_remove_json_suggestion.rs","byte_start":987,"byte_end":995,"line_start":44,"line_end":44,"column_start":18,"column_end":26,"is_primary":true,"text":[{"text":" for _ in (0 .. 3){ +{"message":"unnecessary parentheses around `for` iterator expression","code":{"code":"unused_parens","explanation":null},"level":"error","spans":[{"file_name":"$DIR/unused_parens_remove_json_suggestion.rs","byte_start":987,"byte_end":995,"line_start":44,"line_end":44,"column_start":18,"column_end":26,"is_primary":true,"text":[{"text":" for _ in (0 .. 3){ --> $DIR/unused_parens_remove_json_suggestion.rs:44:18 | LL | for _ in (0 .. 3){ | ^^^^^^^^ help: remove these parentheses "} -{"message":"unnecessary parentheses around `for` head expression","code":{"code":"unused_parens","explanation":null},"level":"error","spans":[{"file_name":"$DIR/unused_parens_remove_json_suggestion.rs","byte_start":1088,"byte_end":1096,"line_start":49,"line_end":49,"column_start":14,"column_end":22,"is_primary":true,"text":[{"text":" for _ in (0 .. 3) { +{"message":"unnecessary parentheses around `for` iterator expression","code":{"code":"unused_parens","explanation":null},"level":"error","spans":[{"file_name":"$DIR/unused_parens_remove_json_suggestion.rs","byte_start":1088,"byte_end":1096,"line_start":49,"line_end":49,"column_start":14,"column_end":22,"is_primary":true,"text":[{"text":" for _ in (0 .. 3) { --> $DIR/unused_parens_remove_json_suggestion.rs:49:14 | LL | for _ in (0 .. 3) { diff --git a/src/test/ui/parser/issue-70552-ascription-in-parens-after-call.rs b/src/test/ui/parser/issue-70552-ascription-in-parens-after-call.rs new file mode 100644 index 0000000000000..9b6dd7db4beb3 --- /dev/null +++ b/src/test/ui/parser/issue-70552-ascription-in-parens-after-call.rs @@ -0,0 +1,3 @@ +fn main() { + expr as fun()(:); //~ ERROR expected expression +} diff --git a/src/test/ui/parser/issue-70552-ascription-in-parens-after-call.stderr b/src/test/ui/parser/issue-70552-ascription-in-parens-after-call.stderr new file mode 100644 index 0000000000000..f03c92e1b1f17 --- /dev/null +++ b/src/test/ui/parser/issue-70552-ascription-in-parens-after-call.stderr @@ -0,0 +1,8 @@ +error: expected expression, found `:` + --> $DIR/issue-70552-ascription-in-parens-after-call.rs:2:19 + | +LL | expr as fun()(:); + | ^ expected expression + +error: aborting due to previous error + diff --git a/src/test/ui/range.rs b/src/test/ui/range.rs index 82983e37ea18e..f3f7508d12434 100644 --- a/src/test/ui/range.rs +++ b/src/test/ui/range.rs @@ -1,5 +1,5 @@ // run-pass - +#![allow(unused_braces)] #![allow(unused_comparisons)] #![allow(dead_code)] #![allow(unused_mut)] diff --git a/src/test/ui/range_inclusive.rs b/src/test/ui/range_inclusive.rs index 68d9bf7d26b69..540b35e0392de 100644 --- a/src/test/ui/range_inclusive.rs +++ b/src/test/ui/range_inclusive.rs @@ -1,7 +1,7 @@ // run-pass // Test inclusive range syntax. - #![feature(range_is_empty)] +#![allow(unused_braces)] #![allow(unused_comparisons)] use std::ops::RangeToInclusive; diff --git a/src/test/ui/structs-enums/empty-tag.rs b/src/test/ui/structs-enums/empty-tag.rs index 56a438200c00b..271ab72c74fc1 100644 --- a/src/test/ui/structs-enums/empty-tag.rs +++ b/src/test/ui/structs-enums/empty-tag.rs @@ -1,4 +1,5 @@ // run-pass +#![allow(unused_braces)] #![allow(non_camel_case_types)] #[derive(Copy, Clone, Debug)] diff --git a/src/test/ui/type-alias-impl-trait/assoc-type-const.rs b/src/test/ui/type-alias-impl-trait/assoc-type-const.rs index 2907c21c6203c..7f3f86e4df009 100644 --- a/src/test/ui/type-alias-impl-trait/assoc-type-const.rs +++ b/src/test/ui/type-alias-impl-trait/assoc-type-const.rs @@ -18,16 +18,16 @@ trait MyTrait<'a, const C: usize> { const MY_CONST: usize; } -impl<'a, const C: usize> MyTrait<'a, { C }> for MyStruct<{ C }> { +impl<'a, const C: usize> MyTrait<'a, C> for MyStruct { type MyItem = u8; const MY_CONST: usize = C; } -impl<'a, I, const C: usize> UnwrapItemsExt<'a, { C }> for I { - type Iter = impl MyTrait<'a, { C }>; +impl<'a, I, const C: usize> UnwrapItemsExt<'a, C> for I { + type Iter = impl MyTrait<'a, C>; fn unwrap_items(self) -> Self::Iter { - MyStruct::<{ C }> {} + MyStruct:: {} } } diff --git a/src/test/ui/unsized-locals/unsized-exprs-rpass.rs b/src/test/ui/unsized-locals/unsized-exprs-rpass.rs index bc64fcdec2e39..24c2758a0a255 100644 --- a/src/test/ui/unsized-locals/unsized-exprs-rpass.rs +++ b/src/test/ui/unsized-locals/unsized-exprs-rpass.rs @@ -1,5 +1,5 @@ // run-pass - +#![allow(unused_braces, unused_parens)] #![feature(unsized_tuple_coercion, unsized_locals)] struct A(X); @@ -30,7 +30,6 @@ fn main() { *foo() }); udrop::<[u8]>({*foo()}); - #[allow(unused_parens)] udrop::<[u8]>((*foo())); udrop::<[u8]>((*tfoo()).1); *afoo() + 42; diff --git a/src/test/ui/weird-exprs.rs b/src/test/ui/weird-exprs.rs index ca68a5af0ddca..d812bbd011e0e 100644 --- a/src/test/ui/weird-exprs.rs +++ b/src/test/ui/weird-exprs.rs @@ -5,7 +5,7 @@ #![allow(non_camel_case_types)] #![allow(dead_code)] #![allow(unreachable_code)] -#![allow(unused_parens)] +#![allow(unused_braces, unused_parens)] #![recursion_limit = "256"] diff --git a/src/test/ui/zero-sized/zero-sized-tuple-struct.rs b/src/test/ui/zero-sized/zero-sized-tuple-struct.rs index 6c438720e5d86..2208590f7d61b 100644 --- a/src/test/ui/zero-sized/zero-sized-tuple-struct.rs +++ b/src/test/ui/zero-sized/zero-sized-tuple-struct.rs @@ -1,4 +1,5 @@ // run-pass +#![allow(unused_braces)] #![allow(unused_assignments)] // Make sure that the constructor args are codegened for zero-sized tuple structs