Skip to content

Commit

Permalink
Adopt let_else across the compiler
Browse files Browse the repository at this point in the history
This performs a substitution of code following the pattern:

let <id> = if let <pat> = ... { identity } else { ... : ! };

To simplify it to:

let <pat> = ... { identity } else { ... : ! };

By adopting the let_else feature.
  • Loading branch information
est31 committed Oct 16, 2021
1 parent c102653 commit 1418df5
Show file tree
Hide file tree
Showing 51 changed files with 69 additions and 137 deletions.
4 changes: 1 addition & 3 deletions compiler/rustc_borrowck/src/borrow_set.rs
Expand Up @@ -315,9 +315,7 @@ impl<'a, 'tcx> GatherBorrows<'a, 'tcx> {
// TEMP = &foo
//
// so extract `temp`.
let temp = if let Some(temp) = assigned_place.as_local() {
temp
} else {
let Some(temp) = assigned_place.as_local() else {
span_bug!(
self.body.source_info(start_location).span,
"expected 2-phase borrow to assign to a local, not `{:?}`",
Expand Down
Expand Up @@ -90,9 +90,7 @@ impl OutlivesSuggestionBuilder {
let mut unified_already = FxHashSet::default();

for (fr, outlived) in &self.constraints_to_add {
let fr_name = if let Some(fr_name) = self.region_vid_to_name(mbcx, *fr) {
fr_name
} else {
let Some(fr_name) = self.region_vid_to_name(mbcx, *fr) else {
continue;
};

Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_borrowck/src/lib.rs
Expand Up @@ -7,6 +7,7 @@
#![feature(format_args_capture)]
#![feature(in_band_lifetimes)]
#![feature(iter_zip)]
#![feature(let_else)]
#![feature(min_specialization)]
#![feature(stmt_expr_attributes)]
#![feature(trusted_step)]
Expand Down
5 changes: 2 additions & 3 deletions compiler/rustc_codegen_ssa/src/back/link.rs
Expand Up @@ -174,9 +174,8 @@ pub fn each_linked_rlib(
_ => {}
}
}
let fmts = match fmts {
Some(f) => f,
None => return Err("could not find formats for rlibs".to_string()),
let Some(fmts) = fmts else {
return Err("could not find formats for rlibs".to_string());
};
for &cnum in crates {
match fmts.get(cnum.as_usize() - 1) {
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_codegen_ssa/src/lib.rs
Expand Up @@ -3,6 +3,7 @@
#![feature(box_patterns)]
#![feature(try_blocks)]
#![feature(in_band_lifetimes)]
#![feature(let_else)]
#![feature(once_cell)]
#![feature(nll)]
#![feature(associated_type_bounds)]
Expand Down
4 changes: 1 addition & 3 deletions compiler/rustc_codegen_ssa/src/mir/operand.rs
Expand Up @@ -343,9 +343,7 @@ impl<'a, 'tcx, V: CodegenObject> OperandValue<V> {
.unwrap_or_else(|| bug!("indirect_dest has non-pointer type: {:?}", indirect_dest))
.ty;

let (llptr, llextra) = if let OperandValue::Ref(llptr, Some(llextra), _) = self {
(llptr, llextra)
} else {
let OperandValue::Ref(llptr, Some(llextra), _) = self else {
bug!("store_unsized called with a sized value")
};

Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_const_eval/src/lib.rs
Expand Up @@ -13,6 +13,7 @@ Rust MIR: a lowered representation of Rust.
#![feature(exact_size_is_empty)]
#![feature(in_band_lifetimes)]
#![feature(iter_zip)]
#![feature(let_else)]
#![feature(map_try_insert)]
#![feature(min_specialization)]
#![feature(slice_ptr_get)]
Expand Down
Expand Up @@ -122,9 +122,7 @@ impl Qualif for NeedsNonConstDrop {
Ok([..]) => {}
}

let drop_trait = if let Some(did) = cx.tcx.lang_items().drop_trait() {
did
} else {
let Some(drop_trait) = cx.tcx.lang_items().drop_trait() else {
// there is no way to define a type that needs non-const drop
// without having the lang item present.
return false;
Expand Down
6 changes: 1 addition & 5 deletions compiler/rustc_errors/src/emitter.rs
Expand Up @@ -449,11 +449,7 @@ pub trait Emitter {
span: &mut MultiSpan,
children: &mut Vec<SubDiagnostic>,
) {
let source_map = if let Some(ref sm) = source_map {
sm
} else {
return;
};
let Some(source_map) = source_map else { return };
debug!("fix_multispans_in_extern_macros: before: span={:?} children={:?}", span, children);
self.fix_multispan_in_extern_macros(source_map, span);
for child in children.iter_mut() {
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_errors/src/lib.rs
Expand Up @@ -8,6 +8,7 @@
#![feature(if_let_guard)]
#![feature(format_args_capture)]
#![feature(iter_zip)]
#![feature(let_else)]
#![feature(nll)]

#[macro_use]
Expand Down
4 changes: 1 addition & 3 deletions compiler/rustc_expand/src/expand.rs
Expand Up @@ -447,9 +447,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
let mut undetermined_invocations = Vec::new();
let (mut progress, mut force) = (false, !self.monotonic);
loop {
let (invoc, ext) = if let Some(invoc) = invocations.pop() {
invoc
} else {
let Some((invoc, ext)) = invocations.pop() else {
self.resolve_imports();
if undetermined_invocations.is_empty() {
break;
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_expand/src/lib.rs
Expand Up @@ -4,6 +4,7 @@
#![feature(format_args_capture)]
#![feature(if_let_guard)]
#![feature(iter_zip)]
#![feature(let_else)]
#![feature(proc_macro_diagnostic)]
#![feature(proc_macro_internals)]
#![feature(proc_macro_span)]
Expand Down
10 changes: 3 additions & 7 deletions compiler/rustc_expand/src/mbe/transcribe.rs
Expand Up @@ -116,10 +116,8 @@ pub(super) fn transcribe<'a>(

loop {
// Look at the last frame on the stack.
let tree = if let Some(tree) = stack.last_mut().unwrap().next() {
// If it still has a TokenTree we have not looked at yet, use that tree.
tree
} else {
// If it still has a TokenTree we have not looked at yet, use that tree.
let Some(tree) = stack.last_mut().unwrap().next() else {
// This else-case never produces a value for `tree` (it `continue`s or `return`s).

// Otherwise, if we have just reached the end of a sequence and we can keep repeating,
Expand Down Expand Up @@ -190,9 +188,7 @@ pub(super) fn transcribe<'a>(
LockstepIterSize::Constraint(len, _) => {
// We do this to avoid an extra clone above. We know that this is a
// sequence already.
let (sp, seq) = if let mbe::TokenTree::Sequence(sp, seq) = seq {
(sp, seq)
} else {
let mbe::TokenTree::Sequence(sp, seq) = seq else {
unreachable!()
};

Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_incremental/src/lib.rs
Expand Up @@ -2,6 +2,7 @@

#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![feature(in_band_lifetimes)]
#![feature(let_else)]
#![feature(nll)]
#![recursion_limit = "256"]

Expand Down
13 changes: 5 additions & 8 deletions compiler/rustc_incremental/src/persist/fs.rs
Expand Up @@ -241,9 +241,7 @@ pub fn prepare_session_directory(
// have already tried before.
let source_directory = find_source_directory(&crate_dir, &source_directories_already_tried);

let source_directory = if let Some(dir) = source_directory {
dir
} else {
let Some(source_directory) = source_directory else {
// There's nowhere to copy from, we're done
debug!(
"no source directory found. Continuing with empty session \
Expand Down Expand Up @@ -397,15 +395,14 @@ fn copy_files(sess: &Session, target_dir: &Path, source_dir: &Path) -> Result<bo
// We acquire a shared lock on the lock file of the directory, so that
// nobody deletes it out from under us while we are reading from it.
let lock_file_path = lock_file_path(source_dir);
let _lock = if let Ok(lock) = flock::Lock::new(

// not exclusive
let Ok(_lock) = flock::Lock::new(
&lock_file_path,
false, // don't wait,
false, // don't create
false,
) {
// not exclusive
lock
} else {
) else {
// Could not acquire the lock, don't try to copy from here
return Err(());
};
Expand Down
Expand Up @@ -263,9 +263,7 @@ pub fn suggest_new_region_bound(
match fn_return.kind {
TyKind::OpaqueDef(item_id, _) => {
let item = tcx.hir().item(item_id);
let opaque = if let ItemKind::OpaqueTy(opaque) = &item.kind {
opaque
} else {
let ItemKind::OpaqueTy(opaque) = &item.kind else {
return;
};

Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_infer/src/lib.rs
Expand Up @@ -17,6 +17,7 @@
#![feature(box_patterns)]
#![feature(extend_one)]
#![feature(iter_zip)]
#![feature(let_else)]
#![feature(never_type)]
#![feature(in_band_lifetimes)]
#![feature(control_flow_enum)]
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_metadata/src/lib.rs
Expand Up @@ -2,6 +2,7 @@
#![feature(crate_visibility_modifier)]
#![feature(drain_filter)]
#![feature(in_band_lifetimes)]
#![feature(let_else)]
#![feature(nll)]
#![feature(once_cell)]
#![feature(proc_macro_internals)]
Expand Down
4 changes: 1 addition & 3 deletions compiler/rustc_metadata/src/rmeta/decoder.rs
Expand Up @@ -472,9 +472,7 @@ impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for Span {
let len = BytePos::decode(decoder)?;
let hi = lo + len;

let sess = if let Some(sess) = decoder.sess {
sess
} else {
let Some(sess) = decoder.sess else {
bug!("Cannot decode Span without Session.")
};

Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_middle/src/lib.rs
Expand Up @@ -39,6 +39,7 @@
#![feature(new_uninit)]
#![feature(nll)]
#![feature(once_cell)]
#![feature(let_else)]
#![feature(min_specialization)]
#![feature(trusted_len)]
#![feature(in_band_lifetimes)]
Expand Down
4 changes: 1 addition & 3 deletions compiler/rustc_middle/src/ty/diagnostics.rs
Expand Up @@ -221,9 +221,7 @@ pub fn suggest_constraining_type_param(
) -> bool {
let param = generics.params.iter().find(|p| p.name.ident().as_str() == param_name);

let param = if let Some(param) = param {
param
} else {
let Some(param) = param else {
return false;
};

Expand Down
13 changes: 4 additions & 9 deletions compiler/rustc_middle/src/ty/layout.rs
Expand Up @@ -755,17 +755,14 @@ impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> {
}

// Extract the number of elements from the layout of the array field:
let len = if let Ok(TyAndLayout {
let Ok(TyAndLayout {
layout: Layout { fields: FieldsShape::Array { count, .. }, .. },
..
}) = self.layout_of(f0_ty)
{
count
} else {
}) = self.layout_of(f0_ty) else {
return Err(LayoutError::Unknown(ty));
};

(*e_ty, *len, true)
(*e_ty, *count, true)
} else {
// First ADT field is not an array:
(f0_ty, def.non_enum_variant().fields.len() as _, false)
Expand All @@ -787,9 +784,7 @@ impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> {

// Compute the ABI of the element type:
let e_ly = self.layout_of(e_ty)?;
let e_abi = if let Abi::Scalar(scalar) = e_ly.abi {
scalar
} else {
let Abi::Scalar(e_abi) = e_ly.abi else {
// This error isn't caught in typeck, e.g., if
// the element type of the vector is generic.
tcx.sess.fatal(&format!(
Expand Down
6 changes: 2 additions & 4 deletions compiler/rustc_mir_build/src/build/expr/as_place.rs
Expand Up @@ -221,15 +221,13 @@ fn to_upvars_resolved_place_builder<'a, 'tcx>(
let closure_hir_id = tcx.hir().local_def_id_to_hir_id(closure_def_id.expect_local());
let closure_span = tcx.hir().span(closure_hir_id);

let (capture_index, capture) = if let Some(capture_details) =
let Some((capture_index, capture)) =
find_capture_matching_projections(
typeck_results,
var_hir_id,
closure_def_id,
&from_builder.projection,
) {
capture_details
} else {
) else {
if !enable_precise_capture(tcx, closure_span) {
bug!(
"No associated capture found for {:?}[{:#?}] even though \
Expand Down
6 changes: 1 addition & 5 deletions compiler/rustc_mir_build/src/build/scope.rs
Expand Up @@ -362,11 +362,7 @@ impl DropTree {
blocks: &IndexVec<DropIdx, Option<BasicBlock>>,
) {
for (drop_idx, drop_data) in self.drops.iter_enumerated().rev() {
let block = if let Some(block) = blocks[drop_idx] {
block
} else {
continue;
};
let Some(block) = blocks[drop_idx] else { continue };
match drop_data.0.kind {
DropKind::Value => {
let terminator = TerminatorKind::Drop {
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_mir_build/src/lib.rs
Expand Up @@ -6,6 +6,7 @@
#![feature(crate_visibility_modifier)]
#![feature(bool_to_option)]
#![feature(iter_zip)]
#![feature(let_else)]
#![feature(once_cell)]
#![feature(min_specialization)]
#![recursion_limit = "256"]
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_mir_dataflow/src/lib.rs
Expand Up @@ -6,6 +6,7 @@
#![feature(exact_size_is_empty)]
#![feature(in_band_lifetimes)]
#![feature(iter_zip)]
#![feature(let_else)]
#![feature(min_specialization)]
#![feature(once_cell)]
#![feature(stmt_expr_attributes)]
Expand Down
8 changes: 2 additions & 6 deletions compiler/rustc_mir_dataflow/src/rustc_peek.rs
Expand Up @@ -290,9 +290,7 @@ impl<'tcx> RustcPeekAt<'tcx> for MaybeMutBorrowedLocals<'_, 'tcx> {
call: PeekCall,
) {
info!(?place, "peek_at");
let local = if let Some(l) = place.as_local() {
l
} else {
let Some(local) = place.as_local() else {
tcx.sess.span_err(call.span, "rustc_peek: argument was not a local");
return;
};
Expand All @@ -312,9 +310,7 @@ impl<'tcx> RustcPeekAt<'tcx> for MaybeLiveLocals {
call: PeekCall,
) {
info!(?place, "peek_at");
let local = if let Some(l) = place.as_local() {
l
} else {
let Some(local) = place.as_local() else {
tcx.sess.span_err(call.span, "rustc_peek: argument was not a local");
return;
};
Expand Down
4 changes: 1 addition & 3 deletions compiler/rustc_mir_transform/src/inline.rs
Expand Up @@ -673,9 +673,7 @@ impl Inliner<'tcx> {
assert!(args.next().is_none());

let tuple = Place::from(tuple);
let tuple_tys = if let ty::Tuple(s) = tuple.ty(caller_body, tcx).ty.kind() {
s
} else {
let ty::Tuple(tuple_tys) = tuple.ty(caller_body, tcx).ty.kind() else {
bug!("Closure arguments are not passed as a tuple");
};

Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_mir_transform/src/lib.rs
Expand Up @@ -4,6 +4,7 @@
#![cfg_attr(bootstrap, feature(const_panic))]
#![feature(in_band_lifetimes)]
#![feature(iter_zip)]
#![feature(let_else)]
#![feature(map_try_insert)]
#![feature(min_specialization)]
#![feature(option_get_or_insert_default)]
Expand Down
4 changes: 1 addition & 3 deletions compiler/rustc_mir_transform/src/lower_slice_len.rs
Expand Up @@ -17,9 +17,7 @@ impl<'tcx> MirPass<'tcx> for LowerSliceLenCalls {

pub fn lower_slice_len_calls<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
let language_items = tcx.lang_items();
let slice_len_fn_item_def_id = if let Some(slice_len_fn_item) = language_items.slice_len_fn() {
slice_len_fn_item
} else {
let Some(slice_len_fn_item_def_id) = language_items.slice_len_fn() else {
// there is no language item to compare to :)
return;
};
Expand Down
6 changes: 2 additions & 4 deletions compiler/rustc_mir_transform/src/normalize_array_len.rs
Expand Up @@ -208,7 +208,7 @@ fn normalize_array_len_call<'tcx>(
operand,
cast_ty,
) => {
let local = if let Some(local) = place.as_local() { local } else { return };
let Some(local) = place.as_local() else { return };
match operand {
Operand::Copy(place) | Operand::Move(place) => {
let operand_local =
Expand Down Expand Up @@ -255,9 +255,7 @@ fn normalize_array_len_call<'tcx>(
}
}
Rvalue::Len(place) => {
let local = if let Some(local) = place.local_or_deref_local() {
local
} else {
let Some(local) = place.local_or_deref_local() else {
return;
};
if let Some(cast_statement_idx) = state.get(&local).copied() {
Expand Down

0 comments on commit 1418df5

Please sign in to comment.