]> git.lizzy.rs Git - rust.git/commitdiff
Auto merge of #76912 - RalfJung:rollup-q9ur56h, r=RalfJung
authorbors <bors@rust-lang.org>
Sat, 19 Sep 2020 11:29:00 +0000 (11:29 +0000)
committerbors <bors@rust-lang.org>
Sat, 19 Sep 2020 11:29:00 +0000 (11:29 +0000)
Rollup of 14 pull requests

Successful merges:

 - #73963 (deny(unsafe_op_in_unsafe_fn) in libstd/path.rs)
 - #75099 (lint/ty: move fns to avoid abstraction violation)
 - #75502 (Use implicit (not explicit) rules for promotability by default in `const fn`)
 - #75580 (Add test for checking duplicated branch or-patterns)
 - #76310 (Add `[T; N]: TryFrom<Vec<T>>` (insta-stable))
 - #76400 (Clean up vec benches bench_in_place style)
 - #76434 (do not inline black_box when building for Miri)
 - #76492 (Add associated constant `BITS` to all integer types)
 - #76525 (Add as_str() to string::Drain.)
 - #76636 (assert ScalarMaybeUninit size)
 - #76749 (give *even better* suggestion when matching a const range)
 - #76757 (don't convert types to the same type with try_into (clippy::useless_conversion))
 - #76796 (Give a better error message when x.py uses the wrong stage for CI)
 - #76798 (Build fixes for RISC-V 32-bit Linux support)

Failed merges:

r? `@ghost`

46 files changed:
compiler/rustc_data_structures/src/lib.rs
compiler/rustc_data_structures/src/tagged_ptr/copy.rs
compiler/rustc_lint/src/builtin.rs
compiler/rustc_lint/src/types.rs
compiler/rustc_middle/src/mir/interpret/value.rs
compiler/rustc_middle/src/ty/mod.rs
compiler/rustc_middle/src/ty/sty.rs
compiler/rustc_mir/src/dataflow/move_paths/builder.rs
compiler/rustc_mir/src/interpret/place.rs
compiler/rustc_mir/src/transform/promote_consts.rs
compiler/rustc_mir_build/src/build/matches/util.rs
compiler/rustc_typeck/src/check/pat.rs
library/alloc/benches/vec.rs
library/alloc/src/collections/binary_heap.rs
library/alloc/src/lib.rs
library/alloc/src/raw_vec.rs
library/alloc/src/string.rs
library/alloc/src/vec.rs
library/alloc/tests/lib.rs
library/alloc/tests/string.rs
library/alloc/tests/vec.rs
library/core/src/fmt/mod.rs
library/core/src/hint.rs
library/core/src/num/bignum.rs
library/core/src/num/mod.rs
library/core/src/slice/sort.rs
library/core/tests/iter.rs
library/core/tests/lib.rs
library/core/tests/num/int_macros.rs
library/core/tests/num/uint_macros.rs
library/panic_unwind/src/dwarf/mod.rs
library/panic_unwind/src/gcc.rs
library/panic_unwind/src/lib.rs
library/std/src/os/linux/raw.rs
library/std/src/os/raw/mod.rs
library/std/src/path.rs
library/std/src/sys_common/alloc.rs
library/unwind/src/libunwind.rs
src/bootstrap/config.rs
src/test/mir-opt/issues/issue-75439.rs [new file with mode: 0644]
src/test/mir-opt/issues/issue_75439.foo.MatchBranchSimplification.diff [new file with mode: 0644]
src/test/ui/consts/cast-discriminant-zst-enum.rs
src/test/ui/consts/const_discriminant.rs
src/test/ui/issues/issue-76191.rs
src/test/ui/issues/issue-76191.stderr
src/tools/build-manifest/src/main.rs

index 88c160e93b66a618eed378141e8314f18aaa7ee7..06718cc9803127f2e9e50a4011963c2eaf0db16a 100644 (file)
@@ -14,6 +14,7 @@
 #![feature(generators)]
 #![feature(generator_trait)]
 #![feature(fn_traits)]
+#![feature(int_bits_const)]
 #![feature(min_specialization)]
 #![feature(optin_builtin_traits)]
 #![feature(nll)]
index d39d146db318f230f11e8ff1ae909c14e2e47175..d63bcdb3c2b0425d4993010dccc6fb0aee679cab 100644 (file)
@@ -48,7 +48,7 @@ impl<P, T, const COMPARE_PACKED: bool> CopyTaggedPtr<P, T, COMPARE_PACKED>
     P: Pointer,
     T: Tag,
 {
-    const TAG_BIT_SHIFT: usize = (8 * std::mem::size_of::<usize>()) - T::BITS;
+    const TAG_BIT_SHIFT: usize = usize::BITS as usize - T::BITS;
     const ASSERTION: () = {
         assert!(T::BITS <= P::BITS);
         // Used for the transmute_copy's below
index 5b5dbcf192ca16caf6fb17405e658de0df370372..8c8487dc8a17f327640cd426367017a4e7c9aae0 100644 (file)
@@ -21,7 +21,8 @@
 //! `late_lint_methods!` invocation in `lib.rs`.
 
 use crate::{
-    types::CItemKind, EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext,
+    types::{transparent_newtype_field, CItemKind},
+    EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext,
 };
 use rustc_ast::attr::{self, HasAttrs};
 use rustc_ast::tokenstream::{TokenStream, TokenTree};
@@ -2688,8 +2689,7 @@ fn structurally_same_type_impl<'tcx>(
                         if is_transparent && !is_non_null {
                             debug_assert!(def.variants.len() == 1);
                             let v = &def.variants[VariantIdx::new(0)];
-                            ty = v
-                                .transparent_newtype_field(tcx)
+                            ty = transparent_newtype_field(tcx, v)
                                 .expect(
                                     "single-variant transparent structure with zero-sized field",
                                 )
index a202efa6edadd927f370bc1a6a90c40d8b439f37..ccbe9f80e25b73a3b086644c696727b2d76779b5 100644 (file)
@@ -639,6 +639,26 @@ enum FfiResult<'tcx> {
         .any(|a| tcx.sess.check_name(a, sym::rustc_nonnull_optimization_guaranteed))
 }
 
+/// `repr(transparent)` structs can have a single non-ZST field, this function returns that
+/// field.
+pub fn transparent_newtype_field<'a, 'tcx>(
+    tcx: TyCtxt<'tcx>,
+    variant: &'a ty::VariantDef,
+) -> Option<&'a ty::FieldDef> {
+    let param_env = tcx.param_env(variant.def_id);
+    for field in &variant.fields {
+        let field_ty = tcx.type_of(field.did);
+        let is_zst =
+            tcx.layout_of(param_env.and(field_ty)).map(|layout| layout.is_zst()).unwrap_or(false);
+
+        if !is_zst {
+            return Some(field);
+        }
+    }
+
+    None
+}
+
 /// Is type known to be non-null?
 crate fn ty_is_known_nonnull<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, mode: CItemKind) -> bool {
     let tcx = cx.tcx;
@@ -654,7 +674,7 @@ enum FfiResult<'tcx> {
             }
 
             for variant in &def.variants {
-                if let Some(field) = variant.transparent_newtype_field(tcx) {
+                if let Some(field) = transparent_newtype_field(cx.tcx, variant) {
                     if ty_is_known_nonnull(cx, field.ty(tcx, substs), mode) {
                         return true;
                     }
@@ -675,7 +695,7 @@ fn get_nullable_type<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'t
         ty::Adt(field_def, field_substs) => {
             let inner_field_ty = {
                 let first_non_zst_ty =
-                    field_def.variants.iter().filter_map(|v| v.transparent_newtype_field(tcx));
+                    field_def.variants.iter().filter_map(|v| transparent_newtype_field(cx.tcx, v));
                 debug_assert_eq!(
                     first_non_zst_ty.clone().count(),
                     1,
@@ -816,7 +836,7 @@ fn check_variant_for_ffi(
         if def.repr.transparent() {
             // Can assume that only one field is not a ZST, so only check
             // that field's type for FFI-safety.
-            if let Some(field) = variant.transparent_newtype_field(self.cx.tcx) {
+            if let Some(field) = transparent_newtype_field(self.cx.tcx, variant) {
                 self.check_field_type_for_ffi(cache, field, substs)
             } else {
                 bug!("malformed transparent type");
index 7d6ff3eb5c1ccb25c7732403b2e7b7bfffe6025a..7741c76ff3e4517bfe23deba370d05727d619d69 100644 (file)
@@ -578,6 +578,9 @@ pub enum ScalarMaybeUninit<Tag = ()> {
     Uninit,
 }
 
+#[cfg(target_arch = "x86_64")]
+static_assert_size!(ScalarMaybeUninit, 24);
+
 impl<Tag> From<Scalar<Tag>> for ScalarMaybeUninit<Tag> {
     #[inline(always)]
     fn from(s: Scalar<Tag>) -> Self {
index 8283deb3ecc24ffaae4b71cb526fb3a733721ce2..f23d666cfcfdd4f63c0aa2e138224385499f8639 100644 (file)
@@ -1999,7 +1999,7 @@ pub struct VariantDef {
     flags: VariantFlags,
 }
 
-impl<'tcx> VariantDef {
+impl VariantDef {
     /// Creates a new `VariantDef`.
     ///
     /// `variant_did` is the `DefId` that identifies the enum variant (if this `VariantDef`
@@ -2065,19 +2065,6 @@ pub fn is_field_list_non_exhaustive(&self) -> bool {
     pub fn is_recovered(&self) -> bool {
         self.flags.intersects(VariantFlags::IS_RECOVERED)
     }
-
-    /// `repr(transparent)` structs can have a single non-ZST field, this function returns that
-    /// field.
-    pub fn transparent_newtype_field(&self, tcx: TyCtxt<'tcx>) -> Option<&FieldDef> {
-        for field in &self.fields {
-            let field_ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, self.def_id));
-            if !field_ty.is_zst(tcx, self.def_id) {
-                return Some(field);
-            }
-        }
-
-        None
-    }
 }
 
 #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
index d4c8ba082751e89a13abeb1a95c9fc7e0ce6239e..724ec101b23b71a388f914dcdf9f7bdb0da1dd43 100644 (file)
@@ -2322,9 +2322,4 @@ pub fn is_trivially_sized(&self, tcx: TyCtxt<'tcx>) -> bool {
             }
         }
     }
-
-    /// Is this a zero-sized type?
-    pub fn is_zst(&'tcx self, tcx: TyCtxt<'tcx>, did: DefId) -> bool {
-        tcx.layout_of(tcx.param_env(did).and(self)).map(|layout| layout.is_zst()).unwrap_or(false)
-    }
 }
index b083044a9c6d9a4e6f955137b85def97de4270b3..5c3e3538401801993de42ebe832fdd8423fba66b 100644 (file)
@@ -4,7 +4,6 @@
 use rustc_middle::ty::{self, TyCtxt};
 use smallvec::{smallvec, SmallVec};
 
-use std::convert::TryInto;
 use std::mem;
 
 use super::abs_domain::Lift;
@@ -481,12 +480,7 @@ fn gather_move(&mut self, place: Place<'tcx>) {
             };
             let base_ty = base_place.ty(self.builder.body, self.builder.tcx).ty;
             let len: u64 = match base_ty.kind() {
-                ty::Array(_, size) => {
-                    let length = size.eval_usize(self.builder.tcx, self.builder.param_env);
-                    length
-                        .try_into()
-                        .expect("slice pattern of array with more than u32::MAX elements")
-                }
+                ty::Array(_, size) => size.eval_usize(self.builder.tcx, self.builder.param_env),
                 _ => bug!("from_end: false slice pattern of non-array type"),
             };
             for offset in from..to {
index 9e16063bd21af2a0ca6bd656d273404914e58e7f..3b22eb5d98719c18097843ca627414834061416f 100644 (file)
@@ -551,7 +551,7 @@ pub(super) fn mplace_projection(
                 let n = base.len(self)?;
                 if n < min_length {
                     // This can only be reached in ConstProp and non-rustc-MIR.
-                    throw_ub!(BoundsCheckFailed { len: min_length.into(), index: n });
+                    throw_ub!(BoundsCheckFailed { len: min_length, index: n });
                 }
 
                 let index = if from_end {
@@ -565,9 +565,7 @@ pub(super) fn mplace_projection(
                 self.mplace_index(base, index)?
             }
 
-            Subslice { from, to, from_end } => {
-                self.mplace_subslice(base, u64::from(from), u64::from(to), from_end)?
-            }
+            Subslice { from, to, from_end } => self.mplace_subslice(base, from, to, from_end)?,
         })
     }
 
index 1d2295a37dddf10bfadfef0740136e396b5c343a..b6124049579fd92b65ce4c1a47644c7d45c28b3f 100644 (file)
@@ -734,7 +734,14 @@ fn validate_call(
     ) -> Result<(), Unpromotable> {
         let fn_ty = callee.ty(self.body, self.tcx);
 
-        if !self.explicit && self.const_kind.is_none() {
+        // `const` and `static` use the explicit rules for promotion regardless of the `Candidate`,
+        // meaning calls to `const fn` can be promoted.
+        let context_uses_explicit_promotion_rules = matches!(
+            self.const_kind,
+            Some(hir::ConstContext::Static(_) | hir::ConstContext::Const)
+        );
+
+        if !self.explicit && !context_uses_explicit_promotion_rules {
             if let ty::FnDef(def_id, _) = *fn_ty.kind() {
                 // Never promote runtime `const fn` calls of
                 // functions without `#[rustc_promotable]`.
index d6e828c966a95de5b28eb875b8d1f50c4d067eb1..4ef88c25cadf3393663ba6a6b90b236a7d2b2857 100644 (file)
@@ -33,7 +33,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
         let tcx = self.hir.tcx();
         let (min_length, exact_size) = match place.ty(&self.local_decls, tcx).ty.kind() {
             ty::Array(_, length) => {
-                (length.eval_usize(tcx, self.hir.param_env).try_into().unwrap(), true)
+                (length.eval_usize(tcx, self.hir.param_env), true)
             }
             _ => ((prefix.len() + suffix.len()).try_into().unwrap(), false),
         };
index 54b0671fab5a7f1f9b927ce3b441dbb283a527b2..321472b8fe8d36332fbf7f29305c95d38e6e1704 100644 (file)
@@ -1,5 +1,6 @@
 use crate::check::FnCtxt;
 use rustc_ast as ast;
+
 use rustc_ast::util::lev_distance::find_best_match_for_name;
 use rustc_data_structures::fx::FxHashMap;
 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder};
@@ -740,6 +741,40 @@ fn check_pat_path(
         pat_ty
     }
 
+    fn maybe_suggest_range_literal(
+        &self,
+        e: &mut DiagnosticBuilder<'_>,
+        opt_def_id: Option<hir::def_id::DefId>,
+        ident: Ident,
+    ) -> bool {
+        match opt_def_id {
+            Some(def_id) => match self.tcx.hir().get_if_local(def_id) {
+                Some(hir::Node::Item(hir::Item {
+                    kind: hir::ItemKind::Const(_, body_id), ..
+                })) => match self.tcx.hir().get(body_id.hir_id) {
+                    hir::Node::Expr(expr) => {
+                        if hir::is_range_literal(expr) {
+                            let span = self.tcx.hir().span(body_id.hir_id);
+                            if let Ok(snip) = self.tcx.sess.source_map().span_to_snippet(span) {
+                                e.span_suggestion_verbose(
+                                    ident.span,
+                                    "you may want to move the range into the match block",
+                                    snip,
+                                    Applicability::MachineApplicable,
+                                );
+                                return true;
+                            }
+                        }
+                    }
+                    _ => (),
+                },
+                _ => (),
+            },
+            _ => (),
+        }
+        false
+    }
+
     fn emit_bad_pat_path(
         &self,
         mut e: DiagnosticBuilder<'_>,
@@ -772,12 +807,12 @@ fn emit_bad_pat_path(
                         );
                     }
                     _ => {
-                        let const_def_id = match pat_ty.kind() {
+                        let (type_def_id, item_def_id) = match pat_ty.kind() {
                             Adt(def, _) => match res {
-                                Res::Def(DefKind::Const, _) => Some(def.did),
-                                _ => None,
+                                Res::Def(DefKind::Const, def_id) => (Some(def.did), Some(def_id)),
+                                _ => (None, None),
                             },
-                            _ => None,
+                            _ => (None, None),
                         };
 
                         let ranges = &[
@@ -788,11 +823,13 @@ fn emit_bad_pat_path(
                             self.tcx.lang_items().range_inclusive_struct(),
                             self.tcx.lang_items().range_to_inclusive_struct(),
                         ];
-                        if const_def_id != None && ranges.contains(&const_def_id) {
-                            let msg = "constants only support matching by type, \
-                                if you meant to match against a range of values, \
-                                consider using a range pattern like `min ..= max` in the match block";
-                            e.note(msg);
+                        if type_def_id != None && ranges.contains(&type_def_id) {
+                            if !self.maybe_suggest_range_literal(&mut e, item_def_id, *ident) {
+                                let msg = "constants only support matching by type, \
+                                    if you meant to match against a range of values, \
+                                    consider using a range pattern like `min ..= max` in the match block";
+                                e.note(msg);
+                            }
                         } else {
                             let msg = "introduce a new binding instead";
                             let sugg = format!("other_{}", ident.as_str().to_lowercase());
index 5ba3e0e00572c052f509c3e155e42dd1ca63a48f..6703a99b15155683008ef24d88474ea40b00befe 100644 (file)
@@ -457,9 +457,7 @@ fn bench_clone_from_10_1000_0100(b: &mut Bencher) {
 }
 
 macro_rules! bench_in_place {
-    (
-        $($fname:ident, $type:ty , $count:expr, $init: expr);*
-    ) => {
+    ($($fname:ident, $type:ty, $count:expr, $init:expr);*) => {
         $(
             #[bench]
             fn $fname(b: &mut Bencher) {
@@ -467,7 +465,8 @@ fn $fname(b: &mut Bencher) {
                     let src: Vec<$type> = black_box(vec![$init; $count]);
                     let mut sink = src.into_iter()
                         .enumerate()
-                        .map(|(idx, e)| { (idx as $type) ^ e }).collect::<Vec<$type>>();
+                        .map(|(idx, e)| idx as $type ^ e)
+                        .collect::<Vec<$type>>();
                     black_box(sink.as_mut_ptr())
                 });
             }
@@ -476,24 +475,24 @@ fn $fname(b: &mut Bencher) {
 }
 
 bench_in_place![
-    bench_in_place_xxu8_i0_0010,     u8,     10, 0;
-    bench_in_place_xxu8_i0_0100,     u8,    100, 0;
-    bench_in_place_xxu8_i0_1000,     u8,   1000, 0;
-    bench_in_place_xxu8_i1_0010,     u8,     10, 1;
-    bench_in_place_xxu8_i1_0100,     u8,    100, 1;
-    bench_in_place_xxu8_i1_1000,     u8,   1000, 1;
-    bench_in_place_xu32_i0_0010,    u32,     10, 0;
-    bench_in_place_xu32_i0_0100,    u32,    100, 0;
-    bench_in_place_xu32_i0_1000,    u32,   1000, 0;
-    bench_in_place_xu32_i1_0010,    u32,     10, 1;
-    bench_in_place_xu32_i1_0100,    u32,    100, 1;
-    bench_in_place_xu32_i1_1000,    u32,   1000, 1;
-    bench_in_place_u128_i0_0010,   u128,     10, 0;
-    bench_in_place_u128_i0_0100,   u128,    100, 0;
-    bench_in_place_u128_i0_1000,   u128,   1000, 0;
-    bench_in_place_u128_i1_0010,   u128,     10, 1;
-    bench_in_place_u128_i1_0100,   u128,    100, 1;
-    bench_in_place_u128_i1_1000,   u128,   1000, 1
+    bench_in_place_xxu8_0010_i0,   u8,   10, 0;
+    bench_in_place_xxu8_0100_i0,   u8,  100, 0;
+    bench_in_place_xxu8_1000_i0,   u8, 1000, 0;
+    bench_in_place_xxu8_0010_i1,   u8,   10, 1;
+    bench_in_place_xxu8_0100_i1,   u8,  100, 1;
+    bench_in_place_xxu8_1000_i1,   u8, 1000, 1;
+    bench_in_place_xu32_0010_i0,  u32,   10, 0;
+    bench_in_place_xu32_0100_i0,  u32,  100, 0;
+    bench_in_place_xu32_1000_i0,  u32, 1000, 0;
+    bench_in_place_xu32_0010_i1,  u32,   10, 1;
+    bench_in_place_xu32_0100_i1,  u32,  100, 1;
+    bench_in_place_xu32_1000_i1,  u32, 1000, 1;
+    bench_in_place_u128_0010_i0, u128,   10, 0;
+    bench_in_place_u128_0100_i0, u128,  100, 0;
+    bench_in_place_u128_1000_i0, u128, 1000, 0;
+    bench_in_place_u128_0010_i1, u128,   10, 1;
+    bench_in_place_u128_0100_i1, u128,  100, 1;
+    bench_in_place_u128_1000_i1, u128, 1000, 1
 ];
 
 #[bench]
index 24d17fdd880ba8bc9585f93ce7c4e08dbaf7b59e..8a7dd9d4249a8b66a802cdb2e30db6abee59213e 100644 (file)
 
 use core::fmt;
 use core::iter::{FromIterator, FusedIterator, InPlaceIterable, SourceIter, TrustedLen};
-use core::mem::{self, size_of, swap, ManuallyDrop};
+use core::mem::{self, swap, ManuallyDrop};
 use core::ops::{Deref, DerefMut};
 use core::ptr;
 
@@ -617,7 +617,7 @@ pub fn append(&mut self, other: &mut Self) {
 
         #[inline(always)]
         fn log2_fast(x: usize) -> usize {
-            8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
+            (usize::BITS - x.leading_zeros() - 1) as usize
         }
 
         // `rebuild` takes O(len1 + len2) operations
index 7881c101f9f60f496f1b6f62b525c7cb330a2a2b..f3c1eee47c7216ac1d1036e8b4d858326738e2e8 100644 (file)
 #![feature(fn_traits)]
 #![feature(fundamental)]
 #![feature(inplace_iteration)]
+#![feature(int_bits_const)]
 #![feature(lang_items)]
 #![feature(layout_for_ptr)]
 #![feature(libc)]
index 05382d0b5594edfece3d193fb5d1698b8fdcdab0..62675665f037f39da3c680db2e7338f6fdc83071 100644 (file)
@@ -528,7 +528,7 @@ fn drop(&mut self) {
 
 #[inline]
 fn alloc_guard(alloc_size: usize) -> Result<(), TryReserveError> {
-    if mem::size_of::<usize>() < 8 && alloc_size > isize::MAX as usize {
+    if usize::BITS < 64 && alloc_size > isize::MAX as usize {
         Err(CapacityOverflow)
     } else {
         Ok(())
index 2b0ce5ede56308b1a907def495bc12d5215b0d27..d3598ccfce81f341e319dc7ccb61489de0b7c8a8 100644 (file)
@@ -2440,7 +2440,7 @@ pub struct Drain<'a> {
 #[stable(feature = "collection_debug", since = "1.17.0")]
 impl fmt::Debug for Drain<'_> {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        f.pad("Drain { .. }")
+        f.debug_tuple("Drain").field(&self.as_str()).finish()
     }
 }
 
@@ -2463,6 +2463,40 @@ fn drop(&mut self) {
     }
 }
 
+impl<'a> Drain<'a> {
+    /// Returns the remaining (sub)string of this iterator as a slice.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// #![feature(string_drain_as_str)]
+    /// let mut s = String::from("abc");
+    /// let mut drain = s.drain(..);
+    /// assert_eq!(drain.as_str(), "abc");
+    /// let _ = drain.next().unwrap();
+    /// assert_eq!(drain.as_str(), "bc");
+    /// ```
+    #[unstable(feature = "string_drain_as_str", issue = "76905")] // Note: uncomment AsRef impls below when stabilizing.
+    pub fn as_str(&self) -> &str {
+        self.iter.as_str()
+    }
+}
+
+// Uncomment when stabilizing `string_drain_as_str`.
+// #[unstable(feature = "string_drain_as_str", issue = "76905")]
+// impl<'a> AsRef<str> for Drain<'a> {
+//     fn as_ref(&self) -> &str {
+//         self.as_str()
+//     }
+// }
+//
+// #[unstable(feature = "string_drain_as_str", issue = "76905")]
+// impl<'a> AsRef<[u8]> for Drain<'a> {
+//     fn as_ref(&self) -> &[u8] {
+//         self.as_str().as_bytes()
+//     }
+// }
+
 #[stable(feature = "drain", since = "1.6.0")]
 impl Iterator for Drain<'_> {
     type Item = char;
index 9dbea0dc9e68b9296d8d2dbdaebdb48635cb07d4..8c0b6af54829b4cbfc1a224bbd51b94cfd03fc20 100644 (file)
@@ -55,6 +55,7 @@
 #![stable(feature = "rust1", since = "1.0.0")]
 
 use core::cmp::{self, Ordering};
+use core::convert::TryFrom;
 use core::fmt;
 use core::hash::{Hash, Hasher};
 use core::intrinsics::{arith_offset, assume};
@@ -2754,6 +2755,57 @@ fn from(s: &str) -> Vec<u8> {
     }
 }
 
+#[stable(feature = "array_try_from_vec", since = "1.48.0")]
+impl<T, const N: usize> TryFrom<Vec<T>> for [T; N] {
+    type Error = Vec<T>;
+
+    /// Gets the entire contents of the `Vec<T>` as an array,
+    /// if its size exactly matches that of the requested array.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::convert::TryInto;
+    /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
+    /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
+    /// ```
+    ///
+    /// If the length doesn't match, the input comes back in `Err`:
+    /// ```
+    /// use std::convert::TryInto;
+    /// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
+    /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
+    /// ```
+    ///
+    /// If you're fine with just getting a prefix of the `Vec<T>`,
+    /// you can call [`.truncate(N)`](Vec::truncate) first.
+    /// ```
+    /// use std::convert::TryInto;
+    /// let mut v = String::from("hello world").into_bytes();
+    /// v.sort();
+    /// v.truncate(2);
+    /// let [a, b]: [_; 2] = v.try_into().unwrap();
+    /// assert_eq!(a, b' ');
+    /// assert_eq!(b, b'd');
+    /// ```
+    fn try_from(mut vec: Vec<T>) -> Result<[T; N], Vec<T>> {
+        if vec.len() != N {
+            return Err(vec);
+        }
+
+        // SAFETY: `.set_len(0)` is always sound.
+        unsafe { vec.set_len(0) };
+
+        // SAFETY: A `Vec`'s pointer is always aligned properly, and
+        // the alignment the array needs is the same as the items.
+        // We checked earlier that we have sufficient items.
+        // The items will not double-drop as the `set_len`
+        // tells the `Vec` not to also drop them.
+        let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) };
+        Ok(array)
+    }
+}
+
 ////////////////////////////////////////////////////////////////////////////////
 // Clone-on-write
 ////////////////////////////////////////////////////////////////////////////////
index 03737e1ef1f4dcd4d8be3439edffbd365ea8741f..3ee0cfbe74759862a6da591141abb1b85a931808 100644 (file)
@@ -18,6 +18,7 @@
 #![feature(deque_range)]
 #![feature(inplace_iteration)]
 #![feature(iter_map_while)]
+#![feature(int_bits_const)]
 
 use std::collections::hash_map::DefaultHasher;
 use std::hash::{Hash, Hasher};
index 4e6043541226f77310e96628c9b23a7a5026354e..a6e41b21b618c8d841d510c73fcba95e24028993 100644 (file)
@@ -1,6 +1,5 @@
 use std::borrow::Cow;
 use std::collections::TryReserveError::*;
-use std::mem::size_of;
 use std::ops::Bound::*;
 
 pub trait IntoCow<'a, B: ?Sized>
@@ -605,7 +604,7 @@ fn test_try_reserve() {
     // on 64-bit, we assume the OS will give an OOM for such a ridiculous size.
     // Any platform that succeeds for these requests is technically broken with
     // ptr::offset because LLVM is the worst.
-    let guards_against_isize = size_of::<usize>() < 8;
+    let guards_against_isize = usize::BITS < 64;
 
     {
         // Note: basic stuff is checked by test_reserve
@@ -686,7 +685,7 @@ fn test_try_reserve_exact() {
     const MAX_CAP: usize = isize::MAX as usize;
     const MAX_USIZE: usize = usize::MAX;
 
-    let guards_against_isize = size_of::<usize>() < 8;
+    let guards_against_isize = usize::BITS < 64;
 
     {
         let mut empty_string: String = String::new();
index 368ca4c543219a50d0d8e8a601185eeea7d4c5da..a49ca7c256a75697ff19c6c7aad7738e730a7cfa 100644 (file)
@@ -1341,7 +1341,7 @@ fn test_try_reserve() {
     // on 64-bit, we assume the OS will give an OOM for such a ridiculous size.
     // Any platform that succeeds for these requests is technically broken with
     // ptr::offset because LLVM is the worst.
-    let guards_against_isize = size_of::<usize>() < 8;
+    let guards_against_isize = usize::BITS < 64;
 
     {
         // Note: basic stuff is checked by test_reserve
index 48b7f2739eeb29b9ac47958bdb14d13bf3acf06d..8558cb5a5e8a32ebadc1f8c3becb89f78f73f3c5 100644 (file)
@@ -2086,7 +2086,7 @@ fn fmt(&self, f: &mut Formatter<'_>) -> Result {
             f.flags |= 1 << (FlagV1::SignAwareZeroPad as u32);
 
             if f.width.is_none() {
-                f.width = Some(((mem::size_of::<usize>() * 8) / 4) + 2);
+                f.width = Some((usize::BITS / 4) as usize + 2);
             }
         }
         f.flags |= 1 << (FlagV1::Alternate as u32);
index 1192b9e164a1450efb5ec71bf4bf59798f5649dd..e53682ece1d7f55d47704bc6e638097fc985f07e 100644 (file)
@@ -108,7 +108,8 @@ pub fn spin_loop() {
 /// Note however, that `black_box` is only (and can only be) provided on a "best-effort" basis. The
 /// extent to which it can block optimisations may vary depending upon the platform and code-gen
 /// backend used. Programs cannot rely on `black_box` for *correctness* in any way.
-#[inline]
+#[cfg_attr(not(miri), inline)]
+#[cfg_attr(miri, inline(never))]
 #[unstable(feature = "test", issue = "50297")]
 #[allow(unreachable_code)] // this makes #[cfg] a bit easier below.
 pub fn black_box<T>(mut dummy: T) -> T {
index 6f16b93d0488aa6278a24591f6a5c952e828f86d..6a1a1e1976160077f340cf17664a8a8f4434cf85 100644 (file)
@@ -20,7 +20,6 @@
 #![macro_use]
 
 use crate::intrinsics;
-use crate::mem;
 
 /// Arithmetic operations required by bignums.
 pub trait FullOps: Sized {
@@ -58,25 +57,22 @@ fn full_mul(self, other: $ty, carry: $ty) -> ($ty, $ty) {
                     // This cannot overflow;
                     // the output is between `0` and `2^nbits * (2^nbits - 1)`.
                     // FIXME: will LLVM optimize this into ADC or similar?
-                    let nbits = mem::size_of::<$ty>() * 8;
                     let v = (self as $bigty) * (other as $bigty) + (carry as $bigty);
-                    ((v >> nbits) as $ty, v as $ty)
+                    ((v >> <$ty>::BITS) as $ty, v as $ty)
                 }
 
                 fn full_mul_add(self, other: $ty, other2: $ty, carry: $ty) -> ($ty, $ty) {
                     // This cannot overflow;
                     // the output is between `0` and `2^nbits * (2^nbits - 1)`.
-                    let nbits = mem::size_of::<$ty>() * 8;
                     let v = (self as $bigty) * (other as $bigty) + (other2 as $bigty) +
                             (carry as $bigty);
-                    ((v >> nbits) as $ty, v as $ty)
+                    ((v >> <$ty>::BITS) as $ty, v as $ty)
                 }
 
                 fn full_div_rem(self, other: $ty, borrow: $ty) -> ($ty, $ty) {
                     debug_assert!(borrow < other);
                     // This cannot overflow; the output is between `0` and `other * (2^nbits - 1)`.
-                    let nbits = mem::size_of::<$ty>() * 8;
-                    let lhs = ((borrow as $bigty) << nbits) | (self as $bigty);
+                    let lhs = ((borrow as $bigty) << <$ty>::BITS) | (self as $bigty);
                     let rhs = other as $bigty;
                     ((lhs / rhs) as $ty, (lhs % rhs) as $ty)
                 }
@@ -128,13 +124,11 @@ pub fn from_small(v: $ty) -> $name {
 
             /// Makes a bignum from `u64` value.
             pub fn from_u64(mut v: u64) -> $name {
-                use crate::mem;
-
                 let mut base = [0; $n];
                 let mut sz = 0;
                 while v > 0 {
                     base[sz] = v as $ty;
-                    v >>= mem::size_of::<$ty>() * 8;
+                    v >>= <$ty>::BITS;
                     sz += 1;
                 }
                 $name { size: sz, base: base }
@@ -150,9 +144,7 @@ pub fn digits(&self) -> &[$ty] {
             /// Returns the `i`-th bit where bit 0 is the least significant one.
             /// In other words, the bit with weight `2^i`.
             pub fn get_bit(&self, i: usize) -> u8 {
-                use crate::mem;
-
-                let digitbits = mem::size_of::<$ty>() * 8;
+                let digitbits = <$ty>::BITS as usize;
                 let d = i / digitbits;
                 let b = i % digitbits;
                 ((self.base[d] >> b) & 1) as u8
@@ -166,8 +158,6 @@ pub fn is_zero(&self) -> bool {
             /// Returns the number of bits necessary to represent this value. Note that zero
             /// is considered to need 0 bits.
             pub fn bit_length(&self) -> usize {
-                use crate::mem;
-
                 // Skip over the most significant digits which are zero.
                 let digits = self.digits();
                 let zeros = digits.iter().rev().take_while(|&&x| x == 0).count();
@@ -180,7 +170,7 @@ pub fn bit_length(&self) -> usize {
                 }
                 // This could be optimized with leading_zeros() and bit shifts, but that's
                 // probably not worth the hassle.
-                let digitbits = mem::size_of::<$ty>() * 8;
+                let digitbits = <$ty>::BITS as usize;
                 let mut i = nonzero.len() * digitbits - 1;
                 while self.get_bit(i) == 0 {
                     i -= 1;
@@ -265,9 +255,7 @@ pub fn mul_small(&mut self, other: $ty) -> &mut $name {
 
             /// Multiplies itself by `2^bits` and returns its own mutable reference.
             pub fn mul_pow2(&mut self, bits: usize) -> &mut $name {
-                use crate::mem;
-
-                let digitbits = mem::size_of::<$ty>() * 8;
+                let digitbits = <$ty>::BITS as usize;
                 let digits = bits / digitbits;
                 let bits = bits % digitbits;
 
@@ -393,13 +381,11 @@ pub fn div_rem_small(&mut self, other: $ty) -> (&mut $name, $ty) {
             /// Divide self by another bignum, overwriting `q` with the quotient and `r` with the
             /// remainder.
             pub fn div_rem(&self, d: &$name, q: &mut $name, r: &mut $name) {
-                use crate::mem;
-
                 // Stupid slow base-2 long division taken from
                 // https://en.wikipedia.org/wiki/Division_algorithm
                 // FIXME use a greater base ($ty) for the long division.
                 assert!(!d.is_zero());
-                let digitbits = mem::size_of::<$ty>() * 8;
+                let digitbits = <$ty>::BITS as usize;
                 for digit in &mut q.base[..] {
                     *digit = 0;
                 }
@@ -462,10 +448,8 @@ fn clone(&self) -> Self {
 
         impl crate::fmt::Debug for $name {
             fn fmt(&self, f: &mut crate::fmt::Formatter<'_>) -> crate::fmt::Result {
-                use crate::mem;
-
                 let sz = if self.size < 1 { 1 } else { self.size };
-                let digitlen = mem::size_of::<$ty>() * 2;
+                let digitlen = <$ty>::BITS as usize / 4;
 
                 write!(f, "{:#x}", self.base[sz - 1])?;
                 for &v in self.base[..sz - 1].iter().rev() {
index 050c187e55576b5009becf286bd3c3576b780322..eec149cc3e8014276661f328046d3b9c1e6b1bf7 100644 (file)
@@ -348,6 +348,20 @@ macro_rules! int_impl {
             pub const MAX: Self = !Self::MIN;
         }
 
+        doc_comment! {
+            concat!("The size of this integer type in bits.
+
+# Examples
+
+```
+", $Feature, "#![feature(int_bits_const)]
+assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");",
+$EndFeature, "
+```"),
+            #[unstable(feature = "int_bits_const", issue = "76904")]
+            pub const BITS: u32 = $BITS;
+        }
+
         doc_comment! {
             concat!("Converts a string slice in a given base to an integer.
 
@@ -2601,6 +2615,20 @@ macro_rules! uint_impl {
             pub const MAX: Self = !0;
         }
 
+        doc_comment! {
+            concat!("The size of this integer type in bits.
+
+# Examples
+
+```
+", $Feature, "#![feature(int_bits_const)]
+assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");",
+$EndFeature, "
+```"),
+            #[unstable(feature = "int_bits_const", issue = "76904")]
+            pub const BITS: u32 = $BITS;
+        }
+
         doc_comment! {
             concat!("Converts a string slice in a given base to an integer.
 
index 8c14651bd826cd4881f545a8d16d9446bf234037..71d2c2c9b2f4c2f3be43c3f9754ceec87f56c8dc 100644 (file)
@@ -565,7 +565,7 @@ fn break_patterns<T>(v: &mut [T]) {
             random
         };
         let mut gen_usize = || {
-            if mem::size_of::<usize>() <= 4 {
+            if usize::BITS <= 32 {
                 gen_u32() as usize
             } else {
                 (((gen_u32() as u64) << 32) | (gen_u32() as u64)) as usize
@@ -667,7 +667,7 @@ fn choose_pivot<T, F>(v: &mut [T], is_less: &mut F) -> (usize, bool)
 ///
 /// `limit` is the number of allowed imbalanced partitions before switching to `heapsort`. If zero,
 /// this function will immediately switch to heapsort.
-fn recurse<'a, T, F>(mut v: &'a mut [T], is_less: &mut F, mut pred: Option<&'a T>, mut limit: usize)
+fn recurse<'a, T, F>(mut v: &'a mut [T], is_less: &mut F, mut pred: Option<&'a T>, mut limit: u32)
 where
     F: FnMut(&T, &T) -> bool,
 {
@@ -763,7 +763,7 @@ pub fn quicksort<T, F>(v: &mut [T], mut is_less: F)
     }
 
     // Limit the number of imbalanced partitions to `floor(log2(len)) + 1`.
-    let limit = mem::size_of::<usize>() * 8 - v.len().leading_zeros() as usize;
+    let limit = usize::BITS - v.len().leading_zeros();
 
     recurse(v, &mut is_less, None, limit);
 }
index 00e3972c42f9d41fe0e14eb356615e2c851f5fca..0eb9af3f454e986adb2eb73e2161a447eab939f8 100644 (file)
@@ -474,7 +474,7 @@ fn nth(&mut self, n: usize) -> Option<Self::Item> {
     }
 
     let mut it = Test(0);
-    let root = usize::MAX >> (::std::mem::size_of::<usize>() * 8 / 2);
+    let root = usize::MAX >> (usize::BITS / 2);
     let n = root + 20;
     (&mut it).step_by(n).nth(n);
     assert_eq!(it.0, n as Bigger * n as Bigger);
index a5b1b51e06c64ebea26e19a3d3b54a486d7579ac..4db391f3e567eb69c962c40b7c53264320c5057e 100644 (file)
@@ -52,6 +52,7 @@
 #![feature(partition_point)]
 #![feature(once_cell)]
 #![feature(unsafe_block_in_unsafe_fn)]
+#![feature(int_bits_const)]
 #![deny(unsafe_op_in_unsafe_fn)]
 
 extern crate test;
index 58a585669122ca3b7859cf19b9bef7525354d705..27e6760e7cbb9175e667dc50941b4828dec8ec0f 100644 (file)
@@ -2,7 +2,6 @@ macro_rules! int_module {
     ($T:ident, $T_i:ident) => {
         #[cfg(test)]
         mod tests {
-            use core::mem;
             use core::ops::{BitAnd, BitOr, BitXor, Not, Shl, Shr};
             use core::$T_i::*;
 
@@ -82,30 +81,27 @@ fn test_count_ones() {
 
             #[test]
             fn test_count_zeros() {
-                let bits = mem::size_of::<$T>() * 8;
-                assert_eq!(A.count_zeros(), bits as u32 - 3);
-                assert_eq!(B.count_zeros(), bits as u32 - 2);
-                assert_eq!(C.count_zeros(), bits as u32 - 5);
+                assert_eq!(A.count_zeros(), $T::BITS - 3);
+                assert_eq!(B.count_zeros(), $T::BITS - 2);
+                assert_eq!(C.count_zeros(), $T::BITS - 5);
             }
 
             #[test]
             fn test_leading_trailing_ones() {
-                let bits = (mem::size_of::<$T>() * 8) as u32;
-
                 let a: $T = 0b0101_1111;
                 assert_eq!(a.trailing_ones(), 5);
-                assert_eq!((!a).leading_ones(), bits - 7);
+                assert_eq!((!a).leading_ones(), $T::BITS - 7);
 
                 assert_eq!(a.reverse_bits().leading_ones(), 5);
 
-                assert_eq!(_1.leading_ones(), bits);
-                assert_eq!(_1.trailing_ones(), bits);
+                assert_eq!(_1.leading_ones(), $T::BITS);
+                assert_eq!(_1.trailing_ones(), $T::BITS);
 
                 assert_eq!((_1 << 1).trailing_ones(), 0);
                 assert_eq!(MAX.leading_ones(), 0);
 
-                assert_eq!((_1 << 1).leading_ones(), bits - 1);
-                assert_eq!(MAX.trailing_ones(), bits - 1);
+                assert_eq!((_1 << 1).leading_ones(), $T::BITS - 1);
+                assert_eq!(MAX.trailing_ones(), $T::BITS - 1);
 
                 assert_eq!(_0.leading_ones(), 0);
                 assert_eq!(_0.trailing_ones(), 0);
index b84a8a7d9f88ba3aee84214cc61ac21f764e9a56..952ec188dc1385f9911e4665c237db2935feb2f4 100644 (file)
@@ -4,7 +4,6 @@ macro_rules! uint_module {
         mod tests {
             use core::ops::{BitAnd, BitOr, BitXor, Not, Shl, Shr};
             use core::$T_i::*;
-            use std::mem;
             use std::str::FromStr;
 
             use crate::num;
@@ -47,30 +46,27 @@ fn test_count_ones() {
 
             #[test]
             fn test_count_zeros() {
-                let bits = mem::size_of::<$T>() * 8;
-                assert!(A.count_zeros() == bits as u32 - 3);
-                assert!(B.count_zeros() == bits as u32 - 2);
-                assert!(C.count_zeros() == bits as u32 - 5);
+                assert!(A.count_zeros() == $T::BITS - 3);
+                assert!(B.count_zeros() == $T::BITS - 2);
+                assert!(C.count_zeros() == $T::BITS - 5);
             }
 
             #[test]
             fn test_leading_trailing_ones() {
-                let bits = (mem::size_of::<$T>() * 8) as u32;
-
                 let a: $T = 0b0101_1111;
                 assert_eq!(a.trailing_ones(), 5);
-                assert_eq!((!a).leading_ones(), bits - 7);
+                assert_eq!((!a).leading_ones(), $T::BITS - 7);
 
                 assert_eq!(a.reverse_bits().leading_ones(), 5);
 
-                assert_eq!(_1.leading_ones(), bits);
-                assert_eq!(_1.trailing_ones(), bits);
+                assert_eq!(_1.leading_ones(), $T::BITS);
+                assert_eq!(_1.trailing_ones(), $T::BITS);
 
                 assert_eq!((_1 << 1).trailing_ones(), 0);
                 assert_eq!((_1 >> 1).leading_ones(), 0);
 
-                assert_eq!((_1 << 1).leading_ones(), bits - 1);
-                assert_eq!((_1 >> 1).trailing_ones(), bits - 1);
+                assert_eq!((_1 << 1).leading_ones(), $T::BITS - 1);
+                assert_eq!((_1 >> 1).trailing_ones(), $T::BITS - 1);
 
                 assert_eq!(_0.leading_ones(), 0);
                 assert_eq!(_0.trailing_ones(), 0);
index 649bbce52a364ccc6a329816c2a2ca462562cb0c..652fbe95a14d195f39281a727d056b5f78aede60 100644 (file)
@@ -53,7 +53,7 @@ pub unsafe fn read_uleb128(&mut self) -> u64 {
     }
 
     pub unsafe fn read_sleb128(&mut self) -> i64 {
-        let mut shift: usize = 0;
+        let mut shift: u32 = 0;
         let mut result: u64 = 0;
         let mut byte: u8;
         loop {
@@ -65,7 +65,7 @@ pub unsafe fn read_sleb128(&mut self) -> i64 {
             }
         }
         // sign-extend
-        if shift < 8 * mem::size_of::<u64>() && (byte & 0x40) != 0 {
+        if shift < u64::BITS && (byte & 0x40) != 0 {
             result |= (!0 as u64) << shift;
         }
         result as i64
index 85a2a18947db211345d438824dac13e254f7b2fc..1cfd527b5841aed3339bcc2534ca0663586ed5cc 100644 (file)
@@ -120,7 +120,7 @@ fn rust_exception_class() -> uw::_Unwind_Exception_Class {
 #[cfg(target_arch = "hexagon")]
 const UNWIND_DATA_REG: (i32, i32) = (0, 1); // R0, R1
 
-#[cfg(target_arch = "riscv64")]
+#[cfg(any(target_arch = "riscv64", target_arch = "riscv32"))]
 const UNWIND_DATA_REG: (i32, i32) = (10, 11); // x10, x11
 
 // The following code is based on GCC's C and C++ personality routines.  For reference, see:
index 6f31e6dcae70d7b40f406b2c863034ffbd77a8a2..162f0386b6692c757e845c91f55e70babad28995 100644 (file)
@@ -18,6 +18,7 @@
     issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/"
 )]
 #![feature(core_intrinsics)]
+#![feature(int_bits_const)]
 #![feature(lang_items)]
 #![feature(libc)]
 #![feature(nll)]
index a007fd2b6be04c4b879756b7c9f4b49f2ade3f32..4ff3a6e578984cc0bb36da0d4f6e7b3c36648200 100644 (file)
@@ -234,7 +234,8 @@ pub struct stat {
     target_arch = "mips64",
     target_arch = "s390x",
     target_arch = "sparc64",
-    target_arch = "riscv64"
+    target_arch = "riscv64",
+    target_arch = "riscv32"
 ))]
 mod arch {
     pub use libc::{blkcnt_t, blksize_t, ino_t, nlink_t, off_t, stat, time_t};
index 83e8853fe79230a74ab94410c29251b7f83d32c4..16272aa05712f7bab6a717e74ea078d24f9061b3 100644 (file)
@@ -22,7 +22,8 @@
             target_arch = "powerpc",
             target_arch = "powerpc64",
             target_arch = "s390x",
-            target_arch = "riscv64"
+            target_arch = "riscv64",
+            target_arch = "riscv32"
         )
     ),
     all(target_os = "android", any(target_arch = "aarch64", target_arch = "arm")),
@@ -65,7 +66,8 @@
             target_arch = "powerpc",
             target_arch = "powerpc64",
             target_arch = "s390x",
-            target_arch = "riscv64"
+            target_arch = "riscv64",
+            target_arch = "riscv32"
         )
     ),
     all(target_os = "android", any(target_arch = "aarch64", target_arch = "arm")),
index d71e89d0eee682f7d7ab15d61eef35840d80fa34..b83c1e9628dc646f482366862ebbc4a4ebe86f4e 100644 (file)
@@ -58,6 +58,7 @@
 //! [`push`]: PathBuf::push
 
 #![stable(feature = "rust1", since = "1.0.0")]
+#![deny(unsafe_op_in_unsafe_fn)]
 
 #[cfg(test)]
 mod tests;
@@ -294,7 +295,8 @@ fn os_str_as_u8_slice(s: &OsStr) -> &[u8] {
     unsafe { &*(s as *const OsStr as *const [u8]) }
 }
 unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
-    &*(s as *const [u8] as *const OsStr)
+    // SAFETY: see the comment of `os_str_as_u8_slice`
+    unsafe { &*(s as *const [u8] as *const OsStr) }
 }
 
 // Detect scheme on Redox
@@ -314,24 +316,21 @@ fn has_physical_root(s: &[u8], prefix: Option<Prefix<'_>>) -> bool {
 
 // basic workhorse for splitting stem and extension
 fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
-    unsafe {
-        if os_str_as_u8_slice(file) == b".." {
-            return (Some(file), None);
-        }
-
-        // The unsafety here stems from converting between &OsStr and &[u8]
-        // and back. This is safe to do because (1) we only look at ASCII
-        // contents of the encoding and (2) new &OsStr values are produced
-        // only from ASCII-bounded slices of existing &OsStr values.
+    if os_str_as_u8_slice(file) == b".." {
+        return (Some(file), None);
+    }
 
-        let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
-        let after = iter.next();
-        let before = iter.next();
-        if before == Some(b"") {
-            (Some(file), None)
-        } else {
-            (before.map(|s| u8_slice_as_os_str(s)), after.map(|s| u8_slice_as_os_str(s)))
-        }
+    // The unsafety here stems from converting between &OsStr and &[u8]
+    // and back. This is safe to do because (1) we only look at ASCII
+    // contents of the encoding and (2) new &OsStr values are produced
+    // only from ASCII-bounded slices of existing &OsStr values.
+    let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.');
+    let after = iter.next();
+    let before = iter.next();
+    if before == Some(b"") {
+        (Some(file), None)
+    } else {
+        unsafe { (before.map(|s| u8_slice_as_os_str(s)), after.map(|s| u8_slice_as_os_str(s))) }
     }
 }
 
@@ -1702,7 +1701,7 @@ impl Path {
     // The following (private!) function allows construction of a path from a u8
     // slice, which is only safe when it is known to follow the OsStr encoding.
     unsafe fn from_u8_slice(s: &[u8]) -> &Path {
-        Path::new(u8_slice_as_os_str(s))
+        unsafe { Path::new(u8_slice_as_os_str(s)) }
     }
     // The following (private!) function reveals the byte encoding used for OsStr.
     fn as_u8_slice(&self) -> &[u8] {
index c669410078592ca952035430ff178486b494cb34..f22476be325603039fcecd71728d7569acd545dc 100644 (file)
@@ -14,7 +14,8 @@
     target_arch = "powerpc64",
     target_arch = "asmjs",
     target_arch = "wasm32",
-    target_arch = "hexagon"
+    target_arch = "hexagon",
+    target_arch = "riscv32"
 )))]
 pub const MIN_ALIGN: usize = 8;
 #[cfg(all(any(
index 0c57861f70a82ca7eadd7c62c754ce07525717c0..dcf4fcd4e5aabeb6105b66c2d10c6ab8b35ec8b9 100644 (file)
@@ -54,7 +54,7 @@ pub enum _Unwind_Reason_Code {
 #[cfg(target_arch = "sparc64")]
 pub const unwinder_private_data_size: usize = 2;
 
-#[cfg(target_arch = "riscv64")]
+#[cfg(any(target_arch = "riscv64", target_arch = "riscv32"))]
 pub const unwinder_private_data_size: usize = 2;
 
 #[cfg(target_os = "emscripten")]
index 7e2cb7721865e512034a64f6fc6725a62639e391..6de4388495bafd29e9f5cc7c268d292d3d7c3fcd 100644 (file)
@@ -617,7 +617,13 @@ pub fn parse(args: &[String]) -> Config {
                 | Subcommand::Build { .. }
                 | Subcommand::Bench { .. }
                 | Subcommand::Dist { .. }
-                | Subcommand::Install { .. } => assert_eq!(config.stage, 2),
+                | Subcommand::Install { .. } => {
+                    assert_eq!(
+                        config.stage, 2,
+                        "x.py should be run with `--stage 2` on CI, but was run with `--stage {}`",
+                        config.stage,
+                    );
+                }
                 Subcommand::Clean { .. }
                 | Subcommand::Check { .. }
                 | Subcommand::Clippy { .. }
diff --git a/src/test/mir-opt/issues/issue-75439.rs b/src/test/mir-opt/issues/issue-75439.rs
new file mode 100644 (file)
index 0000000..44d6bc6
--- /dev/null
@@ -0,0 +1,21 @@
+// EMIT_MIR issue_75439.foo.MatchBranchSimplification.diff
+
+#![feature(const_fn_transmute)]
+#![feature(or_patterns)]
+
+use std::mem::transmute;
+
+pub fn foo(bytes: [u8; 16]) -> Option<[u8; 4]> {
+    // big endian `u32`s
+    let dwords: [u32; 4] = unsafe { transmute(bytes) };
+    const FF: u32 = 0x0000_ffff_u32.to_be();
+    if let [0, 0, 0 | FF, ip] = dwords {
+        Some(unsafe { transmute(ip) })
+    } else {
+        None
+    }
+}
+
+fn main() {
+  let _ = foo([0; 16]);
+}
diff --git a/src/test/mir-opt/issues/issue_75439.foo.MatchBranchSimplification.diff b/src/test/mir-opt/issues/issue_75439.foo.MatchBranchSimplification.diff
new file mode 100644 (file)
index 0000000..43422b3
--- /dev/null
@@ -0,0 +1,87 @@
+- // MIR for `foo` before MatchBranchSimplification
++ // MIR for `foo` after MatchBranchSimplification
+  
+  fn foo(_1: [u8; 16]) -> Option<[u8; 4]> {
+      debug bytes => _1;                   // in scope 0 at $DIR/issue-75439.rs:8:12: 8:17
+      let mut _0: std::option::Option<[u8; 4]>; // return place in scope 0 at $DIR/issue-75439.rs:8:32: 8:47
+      let _2: [u32; 4];                    // in scope 0 at $DIR/issue-75439.rs:10:9: 10:15
+      let mut _3: [u8; 16];                // in scope 0 at $DIR/issue-75439.rs:10:47: 10:52
+      let mut _5: [u8; 4];                 // in scope 0 at $DIR/issue-75439.rs:13:14: 13:38
+      let mut _6: u32;                     // in scope 0 at $DIR/issue-75439.rs:13:33: 13:35
+      scope 1 {
+          debug dwords => _2;              // in scope 1 at $DIR/issue-75439.rs:10:9: 10:15
+          let _4: u32;                     // in scope 1 at $DIR/issue-75439.rs:12:27: 12:29
+          scope 3 {
+              debug ip => _4;              // in scope 3 at $DIR/issue-75439.rs:12:27: 12:29
+              scope 4 {
+              }
+          }
+      }
+      scope 2 {
+      }
+  
+      bb0: {
+          StorageLive(_2);                 // scope 0 at $DIR/issue-75439.rs:10:9: 10:15
+          StorageLive(_3);                 // scope 2 at $DIR/issue-75439.rs:10:47: 10:52
+          _3 = _1;                         // scope 2 at $DIR/issue-75439.rs:10:47: 10:52
+          _2 = transmute::<[u8; 16], [u32; 4]>(move _3) -> bb1; // scope 2 at $DIR/issue-75439.rs:10:37: 10:53
+                                           // mir::Constant
+                                           // + span: $DIR/issue-75439.rs:10:37: 10:46
+                                           // + literal: Const { ty: unsafe extern "rust-intrinsic" fn([u8; 16]) -> [u32; 4] {std::intrinsics::transmute::<[u8; 16], [u32; 4]>}, val: Value(Scalar(<ZST>)) }
+      }
+  
+      bb1: {
+          StorageDead(_3);                 // scope 2 at $DIR/issue-75439.rs:10:52: 10:53
+          switchInt(_2[0 of 4]) -> [0_u32: bb2, otherwise: bb4]; // scope 1 at $DIR/issue-75439.rs:12:13: 12:14
+      }
+  
+      bb2: {
+          switchInt(_2[1 of 4]) -> [0_u32: bb3, otherwise: bb4]; // scope 1 at $DIR/issue-75439.rs:12:16: 12:17
+      }
+  
+      bb3: {
+          switchInt(_2[2 of 4]) -> [0_u32: bb6, 4294901760_u32: bb7, otherwise: bb4]; // scope 1 at $DIR/issue-75439.rs:12:19: 12:20
+      }
+  
+      bb4: {
+          discriminant(_0) = 0;            // scope 1 at $DIR/issue-75439.rs:15:9: 15:13
+          goto -> bb9;                     // scope 1 at $DIR/issue-75439.rs:12:5: 16:6
+      }
+  
+      bb5: {
+          StorageLive(_5);                 // scope 3 at $DIR/issue-75439.rs:13:14: 13:38
+          StorageLive(_6);                 // scope 4 at $DIR/issue-75439.rs:13:33: 13:35
+          _6 = _4;                         // scope 4 at $DIR/issue-75439.rs:13:33: 13:35
+          _5 = transmute::<u32, [u8; 4]>(move _6) -> bb8; // scope 4 at $DIR/issue-75439.rs:13:23: 13:36
+                                           // mir::Constant
+                                           // + span: $DIR/issue-75439.rs:13:23: 13:32
+                                           // + literal: Const { ty: unsafe extern "rust-intrinsic" fn(u32) -> [u8; 4] {std::intrinsics::transmute::<u32, [u8; 4]>}, val: Value(Scalar(<ZST>)) }
+      }
+  
+      bb6: {
+          StorageLive(_4);                 // scope 1 at $DIR/issue-75439.rs:12:27: 12:29
+          _4 = _2[3 of 4];                 // scope 1 at $DIR/issue-75439.rs:12:27: 12:29
+          goto -> bb5;                     // scope 1 at $DIR/issue-75439.rs:12:5: 16:6
+      }
+  
+      bb7: {
+          StorageLive(_4);                 // scope 1 at $DIR/issue-75439.rs:12:27: 12:29
+          _4 = _2[3 of 4];                 // scope 1 at $DIR/issue-75439.rs:12:27: 12:29
+          goto -> bb5;                     // scope 1 at $DIR/issue-75439.rs:12:5: 16:6
+      }
+  
+      bb8: {
+          StorageDead(_6);                 // scope 4 at $DIR/issue-75439.rs:13:35: 13:36
+          ((_0 as Some).0: [u8; 4]) = move _5; // scope 3 at $DIR/issue-75439.rs:13:9: 13:39
+          discriminant(_0) = 1;            // scope 3 at $DIR/issue-75439.rs:13:9: 13:39
+          StorageDead(_5);                 // scope 3 at $DIR/issue-75439.rs:13:38: 13:39
+          StorageDead(_4);                 // scope 1 at $DIR/issue-75439.rs:14:5: 14:6
+          goto -> bb9;                     // scope 1 at $DIR/issue-75439.rs:12:5: 16:6
+      }
+  
+      bb9: {
+          StorageDead(_2);                 // scope 0 at $DIR/issue-75439.rs:17:1: 17:2
+          return;                          // scope 0 at $DIR/issue-75439.rs:17:2: 17:2
+      }
+  }
+  
index a77258120111e70d668e6e87694f83a1a0dbfe88..9c02d232e134b1a9ea5afeff0fd2f526b5f32c36 100644 (file)
@@ -1,5 +1,7 @@
 // run-pass
 // Test a ZST enum whose dicriminant is ~0i128. This caused an ICE when casting to a i32.
+#![feature(test)]
+use std::hint::black_box;
 
 #[derive(Copy, Clone)]
 enum Nums {
@@ -12,9 +14,6 @@ enum Nums {
 const NEG_ONE_I64: i64 = Nums::NegOne as i64;
 const NEG_ONE_I128: i128 = Nums::NegOne as i128;
 
-#[inline(never)]
-fn identity<T>(t: T) -> T { t }
-
 fn test_as_arg(n: Nums) {
     assert_eq!(-1i8, n as i8);
     assert_eq!(-1i16, n as i16);
@@ -31,11 +30,11 @@ fn main() {
     assert_eq!(-1i64, kind as i64);
     assert_eq!(-1i128, kind as i128);
 
-    assert_eq!(-1i8, identity(kind) as i8);
-    assert_eq!(-1i16, identity(kind) as i16);
-    assert_eq!(-1i32, identity(kind) as i32);
-    assert_eq!(-1i64, identity(kind) as i64);
-    assert_eq!(-1i128, identity(kind) as i128);
+    assert_eq!(-1i8, black_box(kind) as i8);
+    assert_eq!(-1i16, black_box(kind) as i16);
+    assert_eq!(-1i32, black_box(kind) as i32);
+    assert_eq!(-1i64, black_box(kind) as i64);
+    assert_eq!(-1i128, black_box(kind) as i128);
 
     test_as_arg(Nums::NegOne);
 
index 1ad5134e71c522d2e801a7fd5aead1905ab607cb..d016d236dbf81a5e24127f33099d13585c1078cf 100644 (file)
@@ -1,14 +1,10 @@
 // run-pass
 #![feature(const_discriminant)]
+#![feature(test)]
 #![allow(dead_code)]
 
 use std::mem::{discriminant, Discriminant};
-
-// `discriminant(const_expr)` may get const-propagated.
-// As we want to check that const-eval is equal to ordinary exection,
-// we wrap `const_expr` with a function which is not const to prevent this.
-#[inline(never)]
-fn identity<T>(x: T) -> T { x }
+use std::hint::black_box;
 
 enum Test {
     A(u8),
@@ -31,10 +27,10 @@ enum SingleVariant {
 
 fn main() {
     assert_eq!(TEST_A, TEST_A_OTHER);
-    assert_eq!(TEST_A, discriminant(identity(&Test::A(17))));
-    assert_eq!(TEST_B, discriminant(identity(&Test::B)));
+    assert_eq!(TEST_A, discriminant(black_box(&Test::A(17))));
+    assert_eq!(TEST_B, discriminant(black_box(&Test::B)));
     assert_ne!(TEST_A, TEST_B);
-    assert_ne!(TEST_B, discriminant(identity(&Test::C { a: 42, b: 7 })));
+    assert_ne!(TEST_B, discriminant(black_box(&Test::C { a: 42, b: 7 })));
 
-    assert_eq!(TEST_V, discriminant(identity(&SingleVariant::V)));
+    assert_eq!(TEST_V, discriminant(black_box(&SingleVariant::V)));
 }
index bc327123c6fe92192500064c74effcc3aa7bcc67..d9790d2b56e2895fed4a1ec169ed63fd8bfa07f1 100644 (file)
@@ -2,13 +2,18 @@
 #![allow(non_snake_case)]
 
 use std::ops::RangeInclusive;
+
 const RANGE: RangeInclusive<i32> = 0..=255;
 
+const RANGE2: RangeInclusive<i32> = panic!();
+
 fn main() {
     let n: i32 = 1;
     match n {
         RANGE => {}
         //~^ ERROR mismatched types
+        RANGE2 => {}
+        //~^ ERROR mismatched types
         _ => {}
     }
 }
index a5544d9e9da405be0f4b6af4a3851bb41e773834..bdcd2fe1adc5a727636cea40fc055b4a0687ad3d 100644 (file)
@@ -1,5 +1,5 @@
 error[E0308]: mismatched types
-  --> $DIR/issue-76191.rs:10:9
+  --> $DIR/issue-76191.rs:13:9
    |
 LL | const RANGE: RangeInclusive<i32> = 0..=255;
    | ------------------------------------------- constant defined here
@@ -14,8 +14,30 @@ LL |         RANGE => {}
    |
    = note: expected type `i32`
             found struct `RangeInclusive<i32>`
+help: you may want to move the range into the match block
+   |
+LL |         0..=255 => {}
+   |         ^^^^^^^
+
+error[E0308]: mismatched types
+  --> $DIR/issue-76191.rs:15:9
+   |
+LL | const RANGE2: RangeInclusive<i32> = panic!();
+   | --------------------------------------------- constant defined here
+...
+LL |     match n {
+   |           - this expression has type `i32`
+...
+LL |         RANGE2 => {}
+   |         ^^^^^^
+   |         |
+   |         expected `i32`, found struct `RangeInclusive`
+   |         `RANGE2` is interpreted as a constant, not a new binding
+   |
+   = note: expected type `i32`
+            found struct `RangeInclusive<i32>`
    = note: constants only support matching by type, if you meant to match against a range of values, consider using a range pattern like `min ..= max` in the match block
 
-error: aborting due to previous error
+error: aborting due to 2 previous errors
 
 For more information about this error, try `rustc --explain E0308`.
index ff9ee67763ba5dbb3f701414b029fca828163127..125f2d1f76cce75649fd990d02bf3d24a38d3e75 100644 (file)
     "riscv32i-unknown-none-elf",
     "riscv32imc-unknown-none-elf",
     "riscv32imac-unknown-none-elf",
+    "riscv32gc-unknown-linux-gnu",
     "riscv64imac-unknown-none-elf",
     "riscv64gc-unknown-none-elf",
     "riscv64gc-unknown-linux-gnu",