Skip to content

Commit 76e755c

Browse files
committed
Auto merge of #88066 - LeSeulArtichaut:patterns-cleanups, r=nagisa
Use if-let guards in the codebase and various other pattern cleanups Dogfooding if-let guards as experimentation for the feature. Tracking issue #51114. Conflicts with #87937.
2 parents c4be230 + 2b0c8ff commit 76e755c

File tree

35 files changed

+288
-321
lines changed

35 files changed

+288
-321
lines changed

compiler/rustc_ast/src/attr/mod.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -564,11 +564,11 @@ impl NestedMetaItem {
564564
I: Iterator<Item = TokenTree>,
565565
{
566566
match tokens.peek() {
567-
Some(TokenTree::Token(token)) => {
568-
if let Ok(lit) = Lit::from_token(token) {
569-
tokens.next();
570-
return Some(NestedMetaItem::Literal(lit));
571-
}
567+
Some(TokenTree::Token(token))
568+
if let Ok(lit) = Lit::from_token(token) =>
569+
{
570+
tokens.next();
571+
return Some(NestedMetaItem::Literal(lit));
572572
}
573573
Some(TokenTree::Delimited(_, token::NoDelim, inner_tokens)) => {
574574
let inner_tokens = inner_tokens.clone();

compiler/rustc_ast/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,12 @@
1111
#![feature(box_patterns)]
1212
#![cfg_attr(bootstrap, feature(const_fn_transmute))]
1313
#![feature(crate_visibility_modifier)]
14+
#![feature(if_let_guard)]
1415
#![feature(iter_zip)]
1516
#![feature(label_break_value)]
1617
#![feature(nll)]
1718
#![feature(min_specialization)]
19+
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard
1820
#![recursion_limit = "256"]
1921

2022
#[macro_use]

compiler/rustc_ast/src/mut_visit.rs

+2-5
Original file line numberDiff line numberDiff line change
@@ -1179,13 +1179,10 @@ fn noop_visit_inline_asm<T: MutVisitor>(asm: &mut InlineAsm, vis: &mut T) {
11791179
for (op, _) in &mut asm.operands {
11801180
match op {
11811181
InlineAsmOperand::In { expr, .. }
1182+
| InlineAsmOperand::Out { expr: Some(expr), .. }
11821183
| InlineAsmOperand::InOut { expr, .. }
11831184
| InlineAsmOperand::Sym { expr, .. } => vis.visit_expr(expr),
1184-
InlineAsmOperand::Out { expr, .. } => {
1185-
if let Some(expr) = expr {
1186-
vis.visit_expr(expr);
1187-
}
1188-
}
1185+
InlineAsmOperand::Out { expr: None, .. } => {}
11891186
InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
11901187
vis.visit_expr(in_expr);
11911188
if let Some(out_expr) = out_expr {

compiler/rustc_ast/src/visit.rs

+2-5
Original file line numberDiff line numberDiff line change
@@ -714,13 +714,10 @@ fn walk_inline_asm<'a, V: Visitor<'a>>(visitor: &mut V, asm: &'a InlineAsm) {
714714
for (op, _) in &asm.operands {
715715
match op {
716716
InlineAsmOperand::In { expr, .. }
717+
| InlineAsmOperand::Out { expr: Some(expr), .. }
717718
| InlineAsmOperand::InOut { expr, .. }
718719
| InlineAsmOperand::Sym { expr, .. } => visitor.visit_expr(expr),
719-
InlineAsmOperand::Out { expr, .. } => {
720-
if let Some(expr) = expr {
721-
visitor.visit_expr(expr);
722-
}
723-
}
720+
InlineAsmOperand::Out { expr: None, .. } => {}
724721
InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
725722
visitor.visit_expr(in_expr);
726723
if let Some(out_expr) = out_expr {

compiler/rustc_errors/src/lib.rs

+9-7
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@
55
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
66
#![feature(crate_visibility_modifier)]
77
#![feature(backtrace)]
8+
#![feature(if_let_guard)]
89
#![feature(format_args_capture)]
910
#![feature(iter_zip)]
1011
#![feature(nll)]
12+
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard
1113

1214
#[macro_use]
1315
extern crate rustc_macros;
@@ -1027,15 +1029,15 @@ impl HandlerInner {
10271029
let mut error_codes = self
10281030
.emitted_diagnostic_codes
10291031
.iter()
1030-
.filter_map(|x| match &x {
1031-
DiagnosticId::Error(s) => {
1032-
if let Ok(Some(_explanation)) = registry.try_find_description(s) {
1033-
Some(s.clone())
1034-
} else {
1035-
None
1036-
}
1032+
.filter_map(|x| {
1033+
match &x {
1034+
DiagnosticId::Error(s)
1035+
if let Ok(Some(_explanation)) = registry.try_find_description(s) =>
1036+
{
1037+
Some(s.clone())
10371038
}
10381039
_ => None,
1040+
}
10391041
})
10401042
.collect::<Vec<_>>();
10411043
if !error_codes.is_empty() {

compiler/rustc_expand/src/config.rs

+7-8
Original file line numberDiff line numberDiff line change
@@ -305,15 +305,14 @@ impl<'a> StripUnconfigured<'a> {
305305
Some((AttrAnnotatedTokenTree::Delimited(sp, delim, inner), *spacing))
306306
.into_iter()
307307
}
308+
AttrAnnotatedTokenTree::Token(ref token) if let TokenKind::Interpolated(ref nt) = token.kind => {
309+
panic!(
310+
"Nonterminal should have been flattened at {:?}: {:?}",
311+
token.span, nt
312+
);
313+
}
308314
AttrAnnotatedTokenTree::Token(token) => {
309-
if let TokenKind::Interpolated(nt) = token.kind {
310-
panic!(
311-
"Nonterminal should have been flattened at {:?}: {:?}",
312-
token.span, nt
313-
);
314-
} else {
315-
Some((AttrAnnotatedTokenTree::Token(token), *spacing)).into_iter()
316-
}
315+
Some((AttrAnnotatedTokenTree::Token(token), *spacing)).into_iter()
317316
}
318317
})
319318
.collect();

compiler/rustc_expand/src/lib.rs

+3
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
1+
#![cfg_attr(bootstrap, feature(bindings_after_at))]
12
#![feature(crate_visibility_modifier)]
23
#![feature(decl_macro)]
34
#![feature(destructuring_assignment)]
45
#![feature(format_args_capture)]
6+
#![feature(if_let_guard)]
57
#![feature(iter_zip)]
68
#![feature(proc_macro_diagnostic)]
79
#![feature(proc_macro_internals)]
810
#![feature(proc_macro_span)]
911
#![feature(try_blocks)]
12+
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard
1013

1114
#[macro_use]
1215
extern crate rustc_macros;

compiler/rustc_expand/src/module.rs

+5-6
Original file line numberDiff line numberDiff line change
@@ -86,13 +86,12 @@ crate fn mod_dir_path(
8686
inline: Inline,
8787
) -> (PathBuf, DirOwnership) {
8888
match inline {
89+
Inline::Yes if let Some(file_path) = mod_file_path_from_attr(sess, attrs, &module.dir_path) => {
90+
// For inline modules file path from `#[path]` is actually the directory path
91+
// for historical reasons, so we don't pop the last segment here.
92+
(file_path, DirOwnership::Owned { relative: None })
93+
}
8994
Inline::Yes => {
90-
if let Some(file_path) = mod_file_path_from_attr(sess, attrs, &module.dir_path) {
91-
// For inline modules file path from `#[path]` is actually the directory path
92-
// for historical reasons, so we don't pop the last segment here.
93-
return (file_path, DirOwnership::Owned { relative: None });
94-
}
95-
9695
// We have to push on the current module name in the case of relative
9796
// paths in order to ensure that any additional module paths from inline
9897
// `mod x { ... }` come after the relative extension.

compiler/rustc_expand/src/proc_macro_server.rs

+12-11
Original file line numberDiff line numberDiff line change
@@ -178,18 +178,19 @@ impl FromInternal<(TreeAndSpacing, &'_ mut Vec<Self>, &mut Rustc<'_>)>
178178
tt!(Punct::new('#', false))
179179
}
180180

181+
Interpolated(nt)
182+
if let Some((name, is_raw)) = ident_name_compatibility_hack(&nt, span, rustc) =>
183+
{
184+
TokenTree::Ident(Ident::new(rustc.sess, name.name, is_raw, name.span))
185+
}
181186
Interpolated(nt) => {
182-
if let Some((name, is_raw)) = ident_name_compatibility_hack(&nt, span, rustc) {
183-
TokenTree::Ident(Ident::new(rustc.sess, name.name, is_raw, name.span))
184-
} else {
185-
let stream = nt_to_tokenstream(&nt, rustc.sess, CanSynthesizeMissingTokens::No);
186-
TokenTree::Group(Group {
187-
delimiter: Delimiter::None,
188-
stream,
189-
span: DelimSpan::from_single(span),
190-
flatten: crate::base::pretty_printing_compatibility_hack(&nt, rustc.sess),
191-
})
192-
}
187+
let stream = nt_to_tokenstream(&nt, rustc.sess, CanSynthesizeMissingTokens::No);
188+
TokenTree::Group(Group {
189+
delimiter: Delimiter::None,
190+
stream,
191+
span: DelimSpan::from_single(span),
192+
flatten: crate::base::pretty_printing_compatibility_hack(&nt, rustc.sess),
193+
})
193194
}
194195

195196
OpenDelim(..) | CloseDelim(..) => unreachable!(),

compiler/rustc_middle/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
#![feature(box_patterns)]
3232
#![feature(core_intrinsics)]
3333
#![feature(discriminant_kind)]
34+
#![feature(if_let_guard)]
3435
#![feature(never_type)]
3536
#![feature(extern_types)]
3637
#![feature(new_uninit)]
@@ -52,6 +53,7 @@
5253
#![feature(try_reserve)]
5354
#![feature(try_reserve_kind)]
5455
#![feature(nonzero_ops)]
56+
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard
5557
#![recursion_limit = "512"]
5658

5759
#[macro_use]

compiler/rustc_middle/src/mir/mod.rs

+3-6
Original file line numberDiff line numberDiff line change
@@ -1664,13 +1664,10 @@ impl Debug for Statement<'_> {
16641664
AscribeUserType(box (ref place, ref c_ty), ref variance) => {
16651665
write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
16661666
}
1667-
Coverage(box ref coverage) => {
1668-
if let Some(rgn) = &coverage.code_region {
1669-
write!(fmt, "Coverage::{:?} for {:?}", coverage.kind, rgn)
1670-
} else {
1671-
write!(fmt, "Coverage::{:?}", coverage.kind)
1672-
}
1667+
Coverage(box self::Coverage { ref kind, code_region: Some(ref rgn) }) => {
1668+
write!(fmt, "Coverage::{:?} for {:?}", kind, rgn)
16731669
}
1670+
Coverage(box ref coverage) => write!(fmt, "Coverage::{:?}", coverage.kind),
16741671
CopyNonOverlapping(box crate::mir::CopyNonOverlapping {
16751672
ref src,
16761673
ref dst,

compiler/rustc_middle/src/mir/visit.rs

+8-9
Original file line numberDiff line numberDiff line change
@@ -587,14 +587,12 @@ macro_rules! make_mir_visitor {
587587
InlineAsmOperand::In { value, .. } => {
588588
self.visit_operand(value, location);
589589
}
590-
InlineAsmOperand::Out { place, .. } => {
591-
if let Some(place) = place {
592-
self.visit_place(
593-
place,
594-
PlaceContext::MutatingUse(MutatingUseContext::Store),
595-
location,
596-
);
597-
}
590+
InlineAsmOperand::Out { place: Some(place), .. } => {
591+
self.visit_place(
592+
place,
593+
PlaceContext::MutatingUse(MutatingUseContext::Store),
594+
location,
595+
);
598596
}
599597
InlineAsmOperand::InOut { in_value, out_place, .. } => {
600598
self.visit_operand(in_value, location);
@@ -610,7 +608,8 @@ macro_rules! make_mir_visitor {
610608
| InlineAsmOperand::SymFn { value } => {
611609
self.visit_constant(value, location);
612610
}
613-
InlineAsmOperand::SymStatic { def_id: _ } => {}
611+
InlineAsmOperand::Out { place: None, .. }
612+
| InlineAsmOperand::SymStatic { def_id: _ } => {}
614613
}
615614
}
616615
}

compiler/rustc_middle/src/thir.rs

+4-12
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use rustc_hir::def::CtorKind;
1414
use rustc_hir::def_id::DefId;
1515
use rustc_hir::RangeEnd;
1616
use rustc_index::newtype_index;
17-
use rustc_index::vec::{Idx, IndexVec};
17+
use rustc_index::vec::IndexVec;
1818
use rustc_middle::infer::canonical::Canonical;
1919
use rustc_middle::middle::region;
2020
use rustc_middle::mir::{
@@ -716,17 +716,9 @@ impl<'tcx> fmt::Display for Pat<'tcx> {
716716
PatKind::Variant { adt_def, variant_index, .. } => {
717717
Some(&adt_def.variants[variant_index])
718718
}
719-
_ => {
720-
if let ty::Adt(adt, _) = self.ty.kind() {
721-
if !adt.is_enum() {
722-
Some(&adt.variants[VariantIdx::new(0)])
723-
} else {
724-
None
725-
}
726-
} else {
727-
None
728-
}
729-
}
719+
_ => self.ty.ty_adt_def().and_then(|adt| {
720+
if !adt.is_enum() { Some(adt.non_enum_variant()) } else { None }
721+
}),
730722
};
731723

732724
if let Some(variant) = variant {

compiler/rustc_middle/src/ty/error.rs

+13-17
Original file line numberDiff line numberDiff line change
@@ -279,13 +279,10 @@ impl<'tcx> ty::TyS<'tcx> {
279279
}
280280
ty::FnDef(..) => "fn item".into(),
281281
ty::FnPtr(_) => "fn pointer".into(),
282-
ty::Dynamic(ref inner, ..) => {
283-
if let Some(principal) = inner.principal() {
284-
format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
285-
} else {
286-
"trait object".into()
287-
}
282+
ty::Dynamic(ref inner, ..) if let Some(principal) = inner.principal() => {
283+
format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
288284
}
285+
ty::Dynamic(..) => "trait object".into(),
289286
ty::Closure(..) => "closure".into(),
290287
ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
291288
ty::GeneratorWitness(..) => "generator witness".into(),
@@ -365,20 +362,19 @@ impl<'tcx> TyCtxt<'tcx> {
365362
// Issue #63167
366363
db.note("distinct uses of `impl Trait` result in different opaque types");
367364
}
368-
(ty::Float(_), ty::Infer(ty::IntVar(_))) => {
365+
(ty::Float(_), ty::Infer(ty::IntVar(_)))
369366
if let Ok(
370367
// Issue #53280
371368
snippet,
372-
) = self.sess.source_map().span_to_snippet(sp)
373-
{
374-
if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
375-
db.span_suggestion(
376-
sp,
377-
"use a float literal",
378-
format!("{}.0", snippet),
379-
MachineApplicable,
380-
);
381-
}
369+
) = self.sess.source_map().span_to_snippet(sp) =>
370+
{
371+
if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
372+
db.span_suggestion(
373+
sp,
374+
"use a float literal",
375+
format!("{}.0", snippet),
376+
MachineApplicable,
377+
);
382378
}
383379
}
384380
(ty::Param(expected), ty::Param(found)) => {

compiler/rustc_middle/src/ty/print/pretty.rs

+20-18
Original file line numberDiff line numberDiff line change
@@ -927,27 +927,29 @@ pub trait PrettyPrinter<'tcx>:
927927
}
928928

929929
match ct.val {
930-
ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted }) => {
931-
if let Some(promoted) = promoted {
932-
p!(print_value_path(def.did, substs));
933-
p!(write("::{:?}", promoted));
934-
} else {
935-
match self.tcx().def_kind(def.did) {
936-
DefKind::Static | DefKind::Const | DefKind::AssocConst => {
937-
p!(print_value_path(def.did, substs))
938-
}
939-
_ => {
940-
if def.is_local() {
941-
let span = self.tcx().def_span(def.did);
942-
if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span)
943-
{
944-
p!(write("{}", snip))
945-
} else {
946-
print_underscore!()
947-
}
930+
ty::ConstKind::Unevaluated(ty::Unevaluated {
931+
def,
932+
substs,
933+
promoted: Some(promoted),
934+
}) => {
935+
p!(print_value_path(def.did, substs));
936+
p!(write("::{:?}", promoted));
937+
}
938+
ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted: None }) => {
939+
match self.tcx().def_kind(def.did) {
940+
DefKind::Static | DefKind::Const | DefKind::AssocConst => {
941+
p!(print_value_path(def.did, substs))
942+
}
943+
_ => {
944+
if def.is_local() {
945+
let span = self.tcx().def_span(def.did);
946+
if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) {
947+
p!(write("{}", snip))
948948
} else {
949949
print_underscore!()
950950
}
951+
} else {
952+
print_underscore!()
951953
}
952954
}
953955
}

compiler/rustc_middle/src/ty/util.rs

+4-6
Original file line numberDiff line numberDiff line change
@@ -225,14 +225,12 @@ impl<'tcx> TyCtxt<'tcx> {
225225
}
226226
}
227227

228-
ty::Tuple(tys) => {
229-
if let Some((&last_ty, _)) = tys.split_last() {
230-
ty = last_ty.expect_ty();
231-
} else {
232-
break;
233-
}
228+
ty::Tuple(tys) if let Some((&last_ty, _)) = tys.split_last() => {
229+
ty = last_ty.expect_ty();
234230
}
235231

232+
ty::Tuple(_) => break,
233+
236234
ty::Projection(_) | ty::Opaque(..) => {
237235
let normalized = normalize(ty);
238236
if ty == normalized {

0 commit comments

Comments
 (0)