Skip to content

[experiment] use unreachable_unchecked() everywhere #53307

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/liballoc/borrow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ impl<'a, B: ?Sized> Cow<'a, B>
Borrowed(borrowed) => {
*self = Owned(borrowed.to_owned());
match *self {
Borrowed(..) => unreachable!(),
Borrowed(..) => unsafe { ::core::hint::unreachable_unchecked() },
Owned(ref mut owned) => owned,
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/liballoc/collections/btree/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> {
{
let mut out_node = match out_tree.root.as_mut().force() {
Leaf(leaf) => leaf,
Internal(_) => unreachable!(),
Internal(_) => unsafe { ::core::hint::unreachable_unchecked() },
};

let mut in_edge = leaf.first_edge();
Expand Down Expand Up @@ -979,7 +979,7 @@ impl<K: Ord, V> BTreeMap<K, V> {
// We need to steal.
let mut last_kv = match last_edge.left_kv() {
Ok(left) => left,
Err(_) => unreachable!(),
Err(_) => unsafe { ::core::hint::unreachable_unchecked() },
};
last_kv.bulk_steal_left(node::MIN_LEN - right_child_len);
last_edge = last_kv.right_edge();
Expand Down Expand Up @@ -1057,7 +1057,7 @@ impl<K: Ord, V> BTreeMap<K, V> {
break;
}
_ => {
unreachable!();
unsafe { ::core::hint::unreachable_unchecked() };
}
}
}
Expand Down Expand Up @@ -2508,7 +2508,7 @@ impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> {
while cur_node.len() < node::CAPACITY / 2 {
match handle_underfull_node(cur_node) {
AtRoot => break,
EmptyParent(_) => unreachable!(),
EmptyParent(_) => unsafe { ::core::hint::unreachable_unchecked() },
Merged(parent) => {
if parent.len() == 0 {
// We must be at the root
Expand Down
6 changes: 3 additions & 3 deletions src/liballoc/collections/btree/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1425,7 +1425,7 @@ impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::
move_edges(left, new_left_len + 1, right, 0, count);
},
(ForceResult::Leaf(_), ForceResult::Leaf(_)) => { }
_ => { unreachable!(); }
_ => { ::core::hint::unreachable_unchecked(); }
}
}
}
Expand Down Expand Up @@ -1486,7 +1486,7 @@ impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::
right.correct_childrens_parent_links(0, new_right_len + 1);
},
(ForceResult::Leaf(_), ForceResult::Leaf(_)) => { }
_ => { unreachable!(); }
_ => { ::core::hint::unreachable_unchecked(); }
}
}
}
Expand Down Expand Up @@ -1571,7 +1571,7 @@ impl<'a, K, V> Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, ma
move_edges(left, left_new_len + 1, right, 1, right_new_len);
},
(ForceResult::Leaf(_), ForceResult::Leaf(_)) => { }
_ => { unreachable!(); }
_ => { ::core::hint::unreachable_unchecked(); }
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/liballoc/raw_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,7 @@ impl<T, A: Alloc> RawVec<T, A> {
pub fn reserve_exact(&mut self, used_cap: usize, needed_extra_cap: usize) {
match self.reserve_internal(used_cap, needed_extra_cap, Infallible, Exact) {
Err(CapacityOverflow) => capacity_overflow(),
Err(AllocErr) => unreachable!(),
Err(AllocErr) => unsafe { ::core::hint::unreachable_unchecked() },
Ok(()) => { /* yay */ }
}
}
Expand Down Expand Up @@ -501,7 +501,7 @@ impl<T, A: Alloc> RawVec<T, A> {
pub fn reserve(&mut self, used_cap: usize, needed_extra_cap: usize) {
match self.reserve_internal(used_cap, needed_extra_cap, Infallible, Amortized) {
Err(CapacityOverflow) => capacity_overflow(),
Err(AllocErr) => unreachable!(),
Err(AllocErr) => unsafe { ::core::hint::unreachable_unchecked() },
Ok(()) => { /* yay */ }
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/liballoc/tests/btree/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ fn test_entry() {

// Existing key (insert)
match map.entry(1) {
Vacant(_) => unreachable!(),
Vacant(_) => unsafe { ::core::hint::unreachable_unchecked() },
Occupied(mut view) => {
assert_eq!(view.get(), &10);
assert_eq!(view.insert(100), 10);
Expand All @@ -380,7 +380,7 @@ fn test_entry() {

// Existing key (update)
match map.entry(2) {
Vacant(_) => unreachable!(),
Vacant(_) => unsafe { ::core::hint::unreachable_unchecked() },
Occupied(mut view) => {
let v = view.get_mut();
*v *= 10;
Expand All @@ -391,7 +391,7 @@ fn test_entry() {

// Existing key (take)
match map.entry(3) {
Vacant(_) => unreachable!(),
Vacant(_) => unsafe { ::core::hint::unreachable_unchecked() },
Occupied(view) => {
assert_eq!(view.remove(), 30);
}
Expand All @@ -402,7 +402,7 @@ fn test_entry() {

// Inexistent key (insert)
match map.entry(10) {
Occupied(_) => unreachable!(),
Occupied(_) => unsafe { ::core::hint::unreachable_unchecked() },
Vacant(view) => {
assert_eq!(*view.insert(1000), 1000);
}
Expand Down
5 changes: 3 additions & 2 deletions src/libcore/iter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,7 @@ use ops::{self, Try};
use usize;
use intrinsics;
use mem;
use super::hint;

#[stable(feature = "rust1", since = "1.0.0")]
pub use self::iterator::Iterator;
Expand Down Expand Up @@ -1177,7 +1178,7 @@ impl<A, B> ZipImpl<A, B> for Zip<A, B>
match (self.a.next_back(), self.b.next_back()) {
(Some(x), Some(y)) => Some((x, y)),
(None, None) => None,
_ => unreachable!(),
_ => unsafe { hint::unreachable_unchecked() },
}
}

Expand Down Expand Up @@ -2035,7 +2036,7 @@ impl<I: Iterator> Peekable<I> {
match self.peeked {
Some(Some(ref value)) => Some(value),
Some(None) => None,
_ => unreachable!(),
_ => unsafe { hint::unreachable_unchecked() },
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/libcore/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,7 @@ macro_rules! writeln {
/// if 3*i < i { panic!("u32 overflow"); }
/// if x < 3*i { return i-1; }
/// }
/// unreachable!();
/// unreachable!()
/// }
/// ```
#[macro_export]
Expand Down
7 changes: 5 additions & 2 deletions src/libcore/num/dec2flt/rawfp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ use num::FpCategory::{Infinite, Zero, Subnormal, Normal, Nan};
use num::FpCategory;
use num::dec2flt::num::{self, Big};
use num::dec2flt::table;
use super::super::super::hint;

#[derive(Copy, Clone, Debug)]
pub struct Unpacked {
Expand Down Expand Up @@ -298,14 +299,16 @@ pub fn encode_normal<T: RawFloat>(x: Unpacked) -> T {
"encode_normal: exponent out of range");
// Leave sign bit at 0 ("+"), our numbers are all positive
let bits = (k_enc as u64) << T::EXPLICIT_SIG_BITS | sig_enc;
T::from_bits(bits.try_into().unwrap_or_else(|_| unreachable!()))
T::from_bits(bits.try_into().unwrap_or_else(|_|
unsafe { hint::unreachable_unchecked() }))
}

/// Construct a subnormal. A mantissa of 0 is allowed and constructs zero.
pub fn encode_subnormal<T: RawFloat>(significand: u64) -> T {
assert!(significand < T::MIN_SIG, "encode_subnormal: not actually subnormal");
// Encoded exponent is 0, the sign bit is 0, so we just have to reinterpret the bits.
T::from_bits(significand.try_into().unwrap_or_else(|_| unreachable!()))
T::from_bits(significand.try_into().unwrap_or_else(|_|
unsafe { hint::unreachable_unchecked() }))
}

/// Approximate a bignum with an Fp. Rounds within 0.5 ULP with half-to-even.
Expand Down
4 changes: 2 additions & 2 deletions src/libcore/tests/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -399,7 +399,7 @@ fn test_iter_ref_consistency() {
let v : &[T] = &[x, x, x];
let v_ptrs : [*const T; 3] = match v {
[ref v1, ref v2, ref v3] => [v1 as *const _, v2 as *const _, v3 as *const _],
_ => unreachable!()
_ => unsafe { ::core::hint::unreachable_unchecked() }
};
let len = v.len();

Expand Down Expand Up @@ -455,7 +455,7 @@ fn test_iter_ref_consistency() {
let v_ptrs : [*mut T; 3] = match v {
[ref v1, ref v2, ref v3] =>
[v1 as *const _ as *mut _, v2 as *const _ as *mut _, v3 as *const _ as *mut _],
_ => unreachable!()
_ => unsafe { ::core::hint::unreachable_unchecked() }
};
let len = v.len();

Expand Down
2 changes: 1 addition & 1 deletion src/libpanic_unwind/emcc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ pub unsafe fn panic(data: Box<dyn Any + Send>) -> u32 {
ptr::write(exception, data);
__cxa_throw(exception as *mut _, ptr::null_mut(), ptr::null_mut());

unreachable!()
unsafe { ::core::hint::unreachable_unchecked() }
}

#[lang = "eh_personality"]
Expand Down
2 changes: 1 addition & 1 deletion src/libproc_macro/quote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ pub fn quote(stream: TokenStream) -> TokenStream {
lit.set_span((@ quote_span(tt.span())));
lit
} else {
unreachable!()
unsafe { ::std::hint::unreachable_unchecked() }
}
}))
})),))
Expand Down
8 changes: 5 additions & 3 deletions src/libproc_macro/rustc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,10 @@ impl TokenTree {
}),

DotEq => op!('.', '='),
OpenDelim(..) | CloseDelim(..) => unreachable!(),
Whitespace | Comment | Shebang(..) | Eof => unreachable!(),
OpenDelim(..) | CloseDelim(..) => unsafe { ::std::hint::unreachable_unchecked() },
Whitespace | Comment | Shebang(..) | Eof => unsafe {
::std::hint::unreachable_unchecked()
},
}
}

Expand Down Expand Up @@ -260,7 +262,7 @@ impl TokenTree {
'$' => Dollar,
'?' => Question,
'\'' => SingleQuote,
_ => unreachable!(),
_ => unsafe { ::std::hint::unreachable_unchecked() },
};

let tree = TokenTree::Token(span.0, token);
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/hir/def_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ impl DefIndex {
match self.0 & 1 {
0 => DefIndexAddressSpace::Low,
1 => DefIndexAddressSpace::High,
_ => unreachable!()
_ => unsafe { ::core::hint::unreachable_unchecked() }
}
}

Expand Down
4 changes: 3 additions & 1 deletion src/librustc/hir/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3786,7 +3786,9 @@ impl<'a> LoweringContext<'a> {
(&None, &Some(..), HalfOpen) => "RangeTo",
(&Some(..), &Some(..), HalfOpen) => "Range",
(&None, &Some(..), Closed) => "RangeToInclusive",
(&Some(..), &Some(..), Closed) => unreachable!(),
(&Some(..), &Some(..), Closed) => unsafe {
::core::hint::unreachable_unchecked()
},
(_, &None, Closed) => self.diagnostic()
.span_fatal(e.span, "inclusive range with no end")
.raise(),
Expand Down
4 changes: 2 additions & 2 deletions src/librustc/hir/print.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2057,7 +2057,7 @@ impl<'a> State<'a> {
self.print_type(&ty)?;
self.maybe_print_comment(ty.span.lo())
}
hir::DefaultReturn(..) => unreachable!(),
hir::DefaultReturn(..) => unsafe { ::core::hint::unreachable_unchecked() },
}
}

Expand Down Expand Up @@ -2224,7 +2224,7 @@ impl<'a> State<'a> {
self.ibox(indent_unit)?;
self.word_space("->")?;
match decl.output {
hir::DefaultReturn(..) => unreachable!(),
hir::DefaultReturn(..) => unsafe { ::core::hint::unreachable_unchecked() },
hir::Return(ref ty) => self.print_type(&ty)?,
}
self.end()?;
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/infer/error_reporting/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
Some(hir_map::NodeItem(it)) => Self::item_scope_tag(&it),
Some(hir_map::NodeTraitItem(it)) => Self::trait_item_scope_tag(&it),
Some(hir_map::NodeImplItem(it)) => Self::impl_item_scope_tag(&it),
_ => unreachable!()
_ => unsafe { ::core::hint::unreachable_unchecked() }
};
let (prefix, span) = match *region {
ty::ReEarlyBound(ref br) => {
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/lint/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ impl LintStore {
CheckLintNameResult::NoLint => {
Some(struct_err!(sess, E0602, "unknown lint: `{}`", lint_name))
}
CheckLintNameResult::Tool(_) => unreachable!(),
CheckLintNameResult::Tool(_) => unsafe { ::core::hint::unreachable_unchecked() },
};

if let Some(mut db) = db {
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/middle/reachable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,7 @@ impl<'a, 'tcx: 'a> ItemLikeVisitor<'tcx> for CollectPrivateImplItemsVisitor<'a,

let trait_def_id = match trait_ref.path.def {
Def::Trait(def_id) => def_id,
_ => unreachable!()
_ => unsafe { ::core::hint::unreachable_unchecked() }
};

if !trait_def_id.is_local() {
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/mir/tcx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ impl BinOp {
BinOp::Gt => hir::BinOpKind::Gt,
BinOp::Le => hir::BinOpKind::Le,
BinOp::Ge => hir::BinOpKind::Ge,
BinOp::Offset => unreachable!()
BinOp::Offset => unsafe { ::core::hint::unreachable_unchecked() }
}
}
}
2 changes: 1 addition & 1 deletion src/librustc/traits/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ impl<'tcx> ProjectionTyCandidateSet<'tcx> {
match (current, candidate) {
(ParamEnv(..), ParamEnv(..)) => convert_to_ambiguous = (),
(ParamEnv(..), _) => return false,
(_, ParamEnv(..)) => { unreachable!(); }
(_, ParamEnv(..)) => { unsafe { ::core::hint::unreachable_unchecked() }; }
(_, _) => convert_to_ambiguous = (),
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/librustc/ty/query/on_disk_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -658,7 +658,7 @@ impl<'a, 'tcx, 'x> SpecializedDecoder<Span> for CacheDecoder<'a, 'tcx, 'x> {
}
}
_ => {
unreachable!()
unsafe { ::core::hint::unreachable_unchecked() }
}
};

Expand Down Expand Up @@ -751,7 +751,7 @@ for CacheDecoder<'a, 'tcx, 'x> {
Ok(mir::ClearCrossCrate::Set(val))
}
_ => {
unreachable!()
unsafe { ::core::hint::unreachable_unchecked() }
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/ty/query/plumbing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -650,7 +650,7 @@ macro_rules! handle_cycle_error {
}};
([fatal_cycle$(, $modifiers:ident)*][$this:expr]) => {{
$this.sess.abort_if_errors();
unreachable!();
unsafe { ::core::hint::unreachable_unchecked() };
}};
([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => {
handle_cycle_error!([$($modifiers),*][$($args)*])
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/util/bug.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,5 +47,5 @@ fn opt_span_bug_fmt<S: Into<MultiSpan>>(
(None, _) => panic!(msg),
}
});
unreachable!();
unsafe { ::core::hint::unreachable_unchecked() };
}
2 changes: 1 addition & 1 deletion src/librustc_apfloat/ieee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1756,7 +1756,7 @@ impl<S: Semantics> IeeeFloat<S> {
1..=7 => Loss::LessThanHalf,
8 => Loss::ExactlyHalf,
9..=15 => Loss::MoreThanHalf,
_ => unreachable!(),
_ => unsafe { ::std::hint::unreachable_unchecked() },
});
}
}
Expand Down
1 change: 0 additions & 1 deletion src/librustc_apfloat/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/")]
#![forbid(unsafe_code)]

#![cfg_attr(not(stage0), feature(nll))]
#![feature(try_from)]
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_borrowck/borrowck/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -728,7 +728,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
});
let (move_span, move_note) = match the_move.kind {
move_data::Declared => {
unreachable!();
unsafe { ::std::hint::unreachable_unchecked() };
}

move_data::MoveExpr |
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_codegen_llvm/back/lto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ pub(crate) fn run(cgcx: &CodegenContext,
}
thin_lto(&diag_handler, modules, upstream_modules, &arr, timeline)
}
Lto::No => unreachable!(),
Lto::No => unsafe { ::std::hint::unreachable_unchecked() },
}
}

Expand Down
Loading