Skip to content

Commit

Permalink
Auto merge of #88611 - m-ou-se:array-into-iter-new-deprecate, r=josht…
Browse files Browse the repository at this point in the history
…riplett

Deprecate array::IntoIter::new.
  • Loading branch information
bors committed Dec 5, 2021
2 parents cafc458 + 27d3935 commit 1597728
Show file tree
Hide file tree
Showing 25 changed files with 69 additions and 99 deletions.
7 changes: 3 additions & 4 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,9 @@ use smallvec::SmallVec;
use tracing::{debug, trace};

macro_rules! arena_vec {
($this:expr; $($x:expr),*) => ({
let a = [$($x),*];
$this.arena.alloc_from_iter(std::array::IntoIter::new(a))
});
($this:expr; $($x:expr),*) => (
$this.arena.alloc_from_iter([$($x),*])
);
}

mod asm;
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_codegen_cranelift/scripts/cargo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ fn main() {
"RUSTFLAGS",
env::var("RUSTFLAGS").unwrap_or(String::new()) + " -Cprefer-dynamic",
);
std::array::IntoIter::new(["rustc".to_string()])
IntoIterator::into_iter(["rustc".to_string()])
.chain(env::args().skip(2))
.chain([
"--".to_string(),
Expand All @@ -56,7 +56,7 @@ fn main() {
"RUSTFLAGS",
env::var("RUSTFLAGS").unwrap_or(String::new()) + " -Cprefer-dynamic",
);
std::array::IntoIter::new(["rustc".to_string()])
IntoIterator::into_iter(["rustc".to_string()])
.chain(env::args().skip(2))
.chain([
"--".to_string(),
Expand Down
5 changes: 2 additions & 3 deletions compiler/rustc_expand/src/proc_macro_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -466,13 +466,12 @@ impl server::TokenStream for Rustc<'_, '_> {
ast::ExprKind::Unary(ast::UnOp::Neg, e) => match &e.kind {
ast::ExprKind::Lit(l) => match l.token {
token::Lit { kind: token::Integer | token::Float, .. } => {
Ok(std::array::IntoIter::new([
Ok(Self::TokenStream::from_iter([
// FIXME: The span of the `-` token is lost when
// parsing, so we cannot faithfully recover it here.
tokenstream::TokenTree::token(token::BinOp(token::Minus), e.span),
tokenstream::TokenTree::token(token::Literal(l.token), l.span),
])
.collect())
]))
}
_ => Err(()),
},
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_hir/src/def.rs
Original file line number Diff line number Diff line change
Expand Up @@ -443,11 +443,11 @@ impl<T> PerNS<T> {
}

pub fn into_iter(self) -> IntoIter<T, 3> {
IntoIter::new([self.value_ns, self.type_ns, self.macro_ns])
[self.value_ns, self.type_ns, self.macro_ns].into_iter()
}

pub fn iter(&self) -> IntoIter<&T, 3> {
IntoIter::new([&self.value_ns, &self.type_ns, &self.macro_ns])
[&self.value_ns, &self.type_ns, &self.macro_ns].into_iter()
}
}

Expand Down Expand Up @@ -481,7 +481,7 @@ impl<T> PerNS<Option<T>> {

/// Returns an iterator over the items which are `Some`.
pub fn present_items(self) -> impl Iterator<Item = T> {
IntoIter::new([self.type_ns, self.value_ns, self.macro_ns]).flatten()
[self.type_ns, self.value_ns, self.macro_ns].into_iter().flatten()
}
}

Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_session/src/filesearch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pub use self::FileMatch::*;

use std::env;
use std::fs;
use std::iter::FromIterator;
use std::path::{Path, PathBuf};

use crate::search_paths::{PathKind, SearchPath, SearchPathFile};
Expand Down Expand Up @@ -91,8 +92,7 @@ impl<'a> FileSearch<'a> {

pub fn make_target_lib_path(sysroot: &Path, target_triple: &str) -> PathBuf {
let rustlib_path = rustc_target::target_rustlib_path(sysroot, target_triple);
std::array::IntoIter::new([sysroot, Path::new(&rustlib_path), Path::new("lib")])
.collect::<PathBuf>()
PathBuf::from_iter([sysroot, Path::new(&rustlib_path), Path::new("lib")])
}

/// This function checks if sysroot is found using env::args().next(), and if it
Expand Down
5 changes: 2 additions & 3 deletions compiler/rustc_session/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -792,12 +792,11 @@ impl Session {
/// Returns a list of directories where target-specific tool binaries are located.
pub fn get_tools_search_paths(&self, self_contained: bool) -> Vec<PathBuf> {
let rustlib_path = rustc_target::target_rustlib_path(&self.sysroot, &config::host_triple());
let p = std::array::IntoIter::new([
let p = PathBuf::from_iter([
Path::new(&self.sysroot),
Path::new(&rustlib_path),
Path::new("bin"),
])
.collect::<PathBuf>();
]);
if self_contained { vec![p.clone(), p.join("self-contained")] } else { vec![p] }
}

Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_target/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#![feature(min_specialization)]
#![feature(step_trait)]

use std::iter::FromIterator;
use std::path::{Path, PathBuf};

#[macro_use]
Expand Down Expand Up @@ -47,12 +48,11 @@ const RUST_LIB_DIR: &str = "rustlib";
/// `"lib*/rustlib/x86_64-unknown-linux-gnu"`.
pub fn target_rustlib_path(sysroot: &Path, target_triple: &str) -> PathBuf {
let libdir = find_libdir(sysroot);
std::array::IntoIter::new([
PathBuf::from_iter([
Path::new(libdir.as_ref()),
Path::new(RUST_LIB_DIR),
Path::new(target_triple),
])
.collect::<PathBuf>()
}

/// The name of the directory rustc expects libraries to be located.
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_target/src/spec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ use rustc_serialize::json::{Json, ToJson};
use rustc_span::symbol::{sym, Symbol};
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::iter::FromIterator;
use std::ops::{Deref, DerefMut};
use std::path::{Path, PathBuf};
use std::str::FromStr;
Expand Down Expand Up @@ -2173,12 +2174,11 @@ impl Target {
// Additionally look in the sysroot under `lib/rustlib/<triple>/target.json`
// as a fallback.
let rustlib_path = crate::target_rustlib_path(&sysroot, &target_triple);
let p = std::array::IntoIter::new([
let p = PathBuf::from_iter([
Path::new(sysroot),
Path::new(&rustlib_path),
Path::new("target.json"),
])
.collect::<PathBuf>();
]);
if p.is_file() {
return load_file(&p);
}
Expand Down
8 changes: 2 additions & 6 deletions compiler/rustc_trait_selection/src/traits/object_safety.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ use rustc_span::symbol::Symbol;
use rustc_span::{MultiSpan, Span};
use smallvec::SmallVec;

use std::array;
use std::iter;
use std::ops::ControlFlow;

Expand Down Expand Up @@ -692,11 +691,8 @@ fn receiver_is_dispatchable<'tcx>(
.to_predicate(tcx)
};

let caller_bounds: Vec<Predicate<'tcx>> = param_env
.caller_bounds()
.iter()
.chain(array::IntoIter::new([unsize_predicate, trait_predicate]))
.collect();
let caller_bounds: Vec<Predicate<'tcx>> =
param_env.caller_bounds().iter().chain([unsize_predicate, trait_predicate]).collect();

ty::ParamEnv::new(tcx.intern_predicates(&caller_bounds), param_env.reveal())
};
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_typeck/src/astconv/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ use rustc_trait_selection::traits::error_reporting::report_object_safety_error;
use rustc_trait_selection::traits::wf::object_region_bounds;

use smallvec::SmallVec;
use std::array;
use std::collections::BTreeSet;
use std::slice;

Expand Down Expand Up @@ -1635,7 +1634,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);

let is_equality = is_equality();
let bounds = array::IntoIter::new([bound, bound2]).chain(matching_candidates);
let bounds = IntoIterator::into_iter([bound, bound2]).chain(matching_candidates);
let mut err = if is_equality.is_some() {
// More specific Error Index entry.
struct_span_err!(
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_typeck/src/check/wfcheck.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1822,7 +1822,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// Inherent impl: take implied bounds from the `self` type.
let self_ty = self.tcx.type_of(impl_def_id);
let self_ty = self.normalize_associated_types_in(span, self_ty);
std::array::IntoIter::new([self_ty]).collect()
FxHashSet::from_iter([self_ty])
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion library/alloc/src/collections/binary_heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1500,7 +1500,7 @@ impl<T: Ord, const N: usize> From<[T; N]> for BinaryHeap<T> {
/// }
/// ```
fn from(arr: [T; N]) -> Self {
core::array::IntoIter::new(arr).collect()
Self::from_iter(arr)
}
}

Expand Down
8 changes: 4 additions & 4 deletions library/alloc/src/collections/btree/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1305,11 +1305,11 @@ impl<K, V> BTreeMap<K, V> {
pub(crate) fn bulk_build_from_sorted_iter<I>(iter: I) -> Self
where
K: Ord,
I: Iterator<Item = (K, V)>,
I: IntoIterator<Item = (K, V)>,
{
let mut root = Root::new();
let mut length = 0;
root.bulk_push(DedupSortedIter::new(iter), &mut length);
root.bulk_push(DedupSortedIter::new(iter.into_iter()), &mut length);
BTreeMap { root: Some(root), length }
}
}
Expand Down Expand Up @@ -1944,7 +1944,7 @@ impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {

// use stable sort to preserve the insertion order.
inputs.sort_by(|a, b| a.0.cmp(&b.0));
BTreeMap::bulk_build_from_sorted_iter(inputs.into_iter())
BTreeMap::bulk_build_from_sorted_iter(inputs)
}
}

Expand Down Expand Up @@ -2061,7 +2061,7 @@ impl<K: Ord, V, const N: usize> From<[(K, V); N]> for BTreeMap<K, V> {

// use stable sort to preserve the insertion order.
arr.sort_by(|a, b| a.0.cmp(&b.0));
BTreeMap::bulk_build_from_sorted_iter(core::array::IntoIter::new(arr))
BTreeMap::bulk_build_from_sorted_iter(arr)
}
}

Expand Down
2 changes: 1 addition & 1 deletion library/alloc/src/collections/btree/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1106,7 +1106,7 @@ impl<T: Ord, const N: usize> From<[T; N]> for BTreeSet<T> {

// use stable sort to preserve the insertion order.
arr.sort();
let iter = core::array::IntoIter::new(arr).map(|k| (k, ()));
let iter = IntoIterator::into_iter(arr).map(|k| (k, ()));
let map = BTreeMap::bulk_build_from_sorted_iter(iter);
BTreeSet { map }
}
Expand Down
2 changes: 1 addition & 1 deletion library/alloc/src/collections/linked_list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1961,7 +1961,7 @@ impl<T, const N: usize> From<[T; N]> for LinkedList<T> {
/// assert_eq!(list1, list2);
/// ```
fn from(arr: [T; N]) -> Self {
core::array::IntoIter::new(arr).collect()
Self::from_iter(arr)
}
}

Expand Down
50 changes: 26 additions & 24 deletions library/core/src/array/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,30 +34,23 @@ pub struct IntoIter<T, const N: usize> {
alive: Range<usize>,
}

impl<T, const N: usize> IntoIter<T, N> {
/// Creates a new iterator over the given `array`.
///
/// *Note*: this method might be deprecated in the future,
/// since [`IntoIterator`] is now implemented for arrays.
///
/// # Examples
///
/// ```
/// use std::array;
// Note: the `#[rustc_skip_array_during_method_dispatch]` on `trait IntoIterator`
// hides this implementation from explicit `.into_iter()` calls on editions < 2021,
// so those calls will still resolve to the slice implementation, by reference.
#[stable(feature = "array_into_iter_impl", since = "1.53.0")]
impl<T, const N: usize> IntoIterator for [T; N] {
type Item = T;
type IntoIter = IntoIter<T, N>;

/// Creates a consuming iterator, that is, one that moves each value out of
/// the array (from start to end). The array cannot be used after calling
/// this unless `T` implements `Copy`, so the whole array is copied.
///
/// for value in array::IntoIter::new([1, 2, 3, 4, 5]) {
/// // The type of `value` is an `i32` here, instead of `&i32`
/// let _: i32 = value;
/// }
/// Arrays have special behavior when calling `.into_iter()` prior to the
/// 2021 edition -- see the [array] Editions section for more information.
///
/// // Since Rust 1.53, arrays implement IntoIterator directly:
/// for value in [1, 2, 3, 4, 5] {
/// // The type of `value` is an `i32` here, instead of `&i32`
/// let _: i32 = value;
/// }
/// ```
#[stable(feature = "array_value_iter", since = "1.51.0")]
pub fn new(array: [T; N]) -> Self {
/// [array]: prim@array
fn into_iter(self) -> Self::IntoIter {
// SAFETY: The transmute here is actually safe. The docs of `MaybeUninit`
// promise:
//
Expand All @@ -76,11 +69,20 @@ impl<T, const N: usize> IntoIter<T, N> {
// Until then, we can use `mem::transmute_copy` to create a bitwise copy
// as a different type, then forget `array` so that it is not dropped.
unsafe {
let iter = Self { data: mem::transmute_copy(&array), alive: 0..N };
mem::forget(array);
let iter = IntoIter { data: mem::transmute_copy(&self), alive: 0..N };
mem::forget(self);
iter
}
}
}

impl<T, const N: usize> IntoIter<T, N> {
/// Creates a new iterator over the given `array`.
#[stable(feature = "array_value_iter", since = "1.51.0")]
#[rustc_deprecated(since = "1.59.0", reason = "use `IntoIterator::into_iter` instead")]
pub fn new(array: [T; N]) -> Self {
IntoIterator::into_iter(array)
}

/// Returns an immutable slice of all elements that have not been yielded
/// yet.
Expand Down
21 changes: 0 additions & 21 deletions library/core/src/array/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,27 +243,6 @@ impl<T: fmt::Debug, const N: usize> fmt::Debug for [T; N] {
}
}

// Note: the `#[rustc_skip_array_during_method_dispatch]` on `trait IntoIterator`
// hides this implementation from explicit `.into_iter()` calls on editions < 2021,
// so those calls will still resolve to the slice implementation, by reference.
#[stable(feature = "array_into_iter_impl", since = "1.53.0")]
impl<T, const N: usize> IntoIterator for [T; N] {
type Item = T;
type IntoIter = IntoIter<T, N>;

/// Creates a consuming iterator, that is, one that moves each value out of
/// the array (from start to end). The array cannot be used after calling
/// this unless `T` implements `Copy`, so the whole array is copied.
///
/// Arrays have special behavior when calling `.into_iter()` prior to the
/// 2021 edition -- see the [array] Editions section for more information.
///
/// [array]: prim@array
fn into_iter(self) -> Self::IntoIter {
IntoIter::new(self)
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T, const N: usize> IntoIterator for &'a [T; N] {
type Item = &'a T;
Expand Down
3 changes: 1 addition & 2 deletions library/core/src/primitive_docs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -606,8 +606,7 @@ mod prim_pointer {}
/// println!("array[{}] = {}", i, x);
/// }
///
/// // You can explicitly iterate an array by value using
/// // `IntoIterator::into_iter` or `std::array::IntoIter::new`:
/// // You can explicitly iterate an array by value using `IntoIterator::into_iter`
/// for item in IntoIterator::into_iter(array).enumerate() {
/// let (i, x): (usize, i32) = item;
/// println!("array[{}] = {}", i, x);
Expand Down
Loading

0 comments on commit 1597728

Please sign in to comment.