Skip to content
/ rust Public
forked from rust-lang/rust

Commit

Permalink
Auto merge of rust-lang#88066 - LeSeulArtichaut:patterns-cleanups, r=…
Browse files Browse the repository at this point in the history
…nagisa

Use if-let guards in the codebase and various other pattern cleanups

Dogfooding if-let guards as experimentation for the feature.

Tracking issue rust-lang#51114. Conflicts with rust-lang#87937.
  • Loading branch information
bors committed Aug 26, 2021
2 parents c4be230 + 2b0c8ff commit 76e755c
Show file tree
Hide file tree
Showing 35 changed files with 288 additions and 321 deletions.
10 changes: 5 additions & 5 deletions compiler/rustc_ast/src/attr/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -564,11 +564,11 @@ impl NestedMetaItem {
I: Iterator<Item = TokenTree>,
{
match tokens.peek() {
Some(TokenTree::Token(token)) => {
if let Ok(lit) = Lit::from_token(token) {
tokens.next();
return Some(NestedMetaItem::Literal(lit));
}
Some(TokenTree::Token(token))
if let Ok(lit) = Lit::from_token(token) =>
{
tokens.next();
return Some(NestedMetaItem::Literal(lit));
}
Some(TokenTree::Delimited(_, token::NoDelim, inner_tokens)) => {
let inner_tokens = inner_tokens.clone();
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_ast/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@
#![feature(box_patterns)]
#![cfg_attr(bootstrap, feature(const_fn_transmute))]
#![feature(crate_visibility_modifier)]
#![feature(if_let_guard)]
#![feature(iter_zip)]
#![feature(label_break_value)]
#![feature(nll)]
#![feature(min_specialization)]
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard
#![recursion_limit = "256"]

#[macro_use]
Expand Down
7 changes: 2 additions & 5 deletions compiler/rustc_ast/src/mut_visit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1179,13 +1179,10 @@ fn noop_visit_inline_asm<T: MutVisitor>(asm: &mut InlineAsm, vis: &mut T) {
for (op, _) in &mut asm.operands {
match op {
InlineAsmOperand::In { expr, .. }
| InlineAsmOperand::Out { expr: Some(expr), .. }
| InlineAsmOperand::InOut { expr, .. }
| InlineAsmOperand::Sym { expr, .. } => vis.visit_expr(expr),
InlineAsmOperand::Out { expr, .. } => {
if let Some(expr) = expr {
vis.visit_expr(expr);
}
}
InlineAsmOperand::Out { expr: None, .. } => {}
InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
vis.visit_expr(in_expr);
if let Some(out_expr) = out_expr {
Expand Down
7 changes: 2 additions & 5 deletions compiler/rustc_ast/src/visit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -714,13 +714,10 @@ fn walk_inline_asm<'a, V: Visitor<'a>>(visitor: &mut V, asm: &'a InlineAsm) {
for (op, _) in &asm.operands {
match op {
InlineAsmOperand::In { expr, .. }
| InlineAsmOperand::Out { expr: Some(expr), .. }
| InlineAsmOperand::InOut { expr, .. }
| InlineAsmOperand::Sym { expr, .. } => visitor.visit_expr(expr),
InlineAsmOperand::Out { expr, .. } => {
if let Some(expr) = expr {
visitor.visit_expr(expr);
}
}
InlineAsmOperand::Out { expr: None, .. } => {}
InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
visitor.visit_expr(in_expr);
if let Some(out_expr) = out_expr {
Expand Down
16 changes: 9 additions & 7 deletions compiler/rustc_errors/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![feature(crate_visibility_modifier)]
#![feature(backtrace)]
#![feature(if_let_guard)]
#![feature(format_args_capture)]
#![feature(iter_zip)]
#![feature(nll)]
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard

#[macro_use]
extern crate rustc_macros;
Expand Down Expand Up @@ -1027,15 +1029,15 @@ impl HandlerInner {
let mut error_codes = self
.emitted_diagnostic_codes
.iter()
.filter_map(|x| match &x {
DiagnosticId::Error(s) => {
if let Ok(Some(_explanation)) = registry.try_find_description(s) {
Some(s.clone())
} else {
None
}
.filter_map(|x| {
match &x {
DiagnosticId::Error(s)
if let Ok(Some(_explanation)) = registry.try_find_description(s) =>
{
Some(s.clone())
}
_ => None,
}
})
.collect::<Vec<_>>();
if !error_codes.is_empty() {
Expand Down
15 changes: 7 additions & 8 deletions compiler/rustc_expand/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -305,15 +305,14 @@ impl<'a> StripUnconfigured<'a> {
Some((AttrAnnotatedTokenTree::Delimited(sp, delim, inner), *spacing))
.into_iter()
}
AttrAnnotatedTokenTree::Token(ref token) if let TokenKind::Interpolated(ref nt) = token.kind => {
panic!(
"Nonterminal should have been flattened at {:?}: {:?}",
token.span, nt
);
}
AttrAnnotatedTokenTree::Token(token) => {
if let TokenKind::Interpolated(nt) = token.kind {
panic!(
"Nonterminal should have been flattened at {:?}: {:?}",
token.span, nt
);
} else {
Some((AttrAnnotatedTokenTree::Token(token), *spacing)).into_iter()
}
Some((AttrAnnotatedTokenTree::Token(token), *spacing)).into_iter()
}
})
.collect();
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_expand/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
#![cfg_attr(bootstrap, feature(bindings_after_at))]
#![feature(crate_visibility_modifier)]
#![feature(decl_macro)]
#![feature(destructuring_assignment)]
#![feature(format_args_capture)]
#![feature(if_let_guard)]
#![feature(iter_zip)]
#![feature(proc_macro_diagnostic)]
#![feature(proc_macro_internals)]
#![feature(proc_macro_span)]
#![feature(try_blocks)]
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard

#[macro_use]
extern crate rustc_macros;
Expand Down
11 changes: 5 additions & 6 deletions compiler/rustc_expand/src/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,12 @@ crate fn mod_dir_path(
inline: Inline,
) -> (PathBuf, DirOwnership) {
match inline {
Inline::Yes if let Some(file_path) = mod_file_path_from_attr(sess, attrs, &module.dir_path) => {
// For inline modules file path from `#[path]` is actually the directory path
// for historical reasons, so we don't pop the last segment here.
(file_path, DirOwnership::Owned { relative: None })
}
Inline::Yes => {
if let Some(file_path) = mod_file_path_from_attr(sess, attrs, &module.dir_path) {
// For inline modules file path from `#[path]` is actually the directory path
// for historical reasons, so we don't pop the last segment here.
return (file_path, DirOwnership::Owned { relative: None });
}

// We have to push on the current module name in the case of relative
// paths in order to ensure that any additional module paths from inline
// `mod x { ... }` come after the relative extension.
Expand Down
23 changes: 12 additions & 11 deletions compiler/rustc_expand/src/proc_macro_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,18 +178,19 @@ impl FromInternal<(TreeAndSpacing, &'_ mut Vec<Self>, &mut Rustc<'_>)>
tt!(Punct::new('#', false))
}

Interpolated(nt)
if let Some((name, is_raw)) = ident_name_compatibility_hack(&nt, span, rustc) =>
{
TokenTree::Ident(Ident::new(rustc.sess, name.name, is_raw, name.span))
}
Interpolated(nt) => {
if let Some((name, is_raw)) = ident_name_compatibility_hack(&nt, span, rustc) {
TokenTree::Ident(Ident::new(rustc.sess, name.name, is_raw, name.span))
} else {
let stream = nt_to_tokenstream(&nt, rustc.sess, CanSynthesizeMissingTokens::No);
TokenTree::Group(Group {
delimiter: Delimiter::None,
stream,
span: DelimSpan::from_single(span),
flatten: crate::base::pretty_printing_compatibility_hack(&nt, rustc.sess),
})
}
let stream = nt_to_tokenstream(&nt, rustc.sess, CanSynthesizeMissingTokens::No);
TokenTree::Group(Group {
delimiter: Delimiter::None,
stream,
span: DelimSpan::from_single(span),
flatten: crate::base::pretty_printing_compatibility_hack(&nt, rustc.sess),
})
}

OpenDelim(..) | CloseDelim(..) => unreachable!(),
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_middle/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
#![feature(box_patterns)]
#![feature(core_intrinsics)]
#![feature(discriminant_kind)]
#![feature(if_let_guard)]
#![feature(never_type)]
#![feature(extern_types)]
#![feature(new_uninit)]
Expand All @@ -52,6 +53,7 @@
#![feature(try_reserve)]
#![feature(try_reserve_kind)]
#![feature(nonzero_ops)]
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard
#![recursion_limit = "512"]

#[macro_use]
Expand Down
9 changes: 3 additions & 6 deletions compiler/rustc_middle/src/mir/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1664,13 +1664,10 @@ impl Debug for Statement<'_> {
AscribeUserType(box (ref place, ref c_ty), ref variance) => {
write!(fmt, "AscribeUserType({:?}, {:?}, {:?})", place, variance, c_ty)
}
Coverage(box ref coverage) => {
if let Some(rgn) = &coverage.code_region {
write!(fmt, "Coverage::{:?} for {:?}", coverage.kind, rgn)
} else {
write!(fmt, "Coverage::{:?}", coverage.kind)
}
Coverage(box self::Coverage { ref kind, code_region: Some(ref rgn) }) => {
write!(fmt, "Coverage::{:?} for {:?}", kind, rgn)
}
Coverage(box ref coverage) => write!(fmt, "Coverage::{:?}", coverage.kind),
CopyNonOverlapping(box crate::mir::CopyNonOverlapping {
ref src,
ref dst,
Expand Down
17 changes: 8 additions & 9 deletions compiler/rustc_middle/src/mir/visit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -587,14 +587,12 @@ macro_rules! make_mir_visitor {
InlineAsmOperand::In { value, .. } => {
self.visit_operand(value, location);
}
InlineAsmOperand::Out { place, .. } => {
if let Some(place) = place {
self.visit_place(
place,
PlaceContext::MutatingUse(MutatingUseContext::Store),
location,
);
}
InlineAsmOperand::Out { place: Some(place), .. } => {
self.visit_place(
place,
PlaceContext::MutatingUse(MutatingUseContext::Store),
location,
);
}
InlineAsmOperand::InOut { in_value, out_place, .. } => {
self.visit_operand(in_value, location);
Expand All @@ -610,7 +608,8 @@ macro_rules! make_mir_visitor {
| InlineAsmOperand::SymFn { value } => {
self.visit_constant(value, location);
}
InlineAsmOperand::SymStatic { def_id: _ } => {}
InlineAsmOperand::Out { place: None, .. }
| InlineAsmOperand::SymStatic { def_id: _ } => {}
}
}
}
Expand Down
16 changes: 4 additions & 12 deletions compiler/rustc_middle/src/thir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use rustc_hir::def::CtorKind;
use rustc_hir::def_id::DefId;
use rustc_hir::RangeEnd;
use rustc_index::newtype_index;
use rustc_index::vec::{Idx, IndexVec};
use rustc_index::vec::IndexVec;
use rustc_middle::infer::canonical::Canonical;
use rustc_middle::middle::region;
use rustc_middle::mir::{
Expand Down Expand Up @@ -716,17 +716,9 @@ impl<'tcx> fmt::Display for Pat<'tcx> {
PatKind::Variant { adt_def, variant_index, .. } => {
Some(&adt_def.variants[variant_index])
}
_ => {
if let ty::Adt(adt, _) = self.ty.kind() {
if !adt.is_enum() {
Some(&adt.variants[VariantIdx::new(0)])
} else {
None
}
} else {
None
}
}
_ => self.ty.ty_adt_def().and_then(|adt| {
if !adt.is_enum() { Some(adt.non_enum_variant()) } else { None }
}),
};

if let Some(variant) = variant {
Expand Down
30 changes: 13 additions & 17 deletions compiler/rustc_middle/src/ty/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,13 +279,10 @@ impl<'tcx> ty::TyS<'tcx> {
}
ty::FnDef(..) => "fn item".into(),
ty::FnPtr(_) => "fn pointer".into(),
ty::Dynamic(ref inner, ..) => {
if let Some(principal) = inner.principal() {
format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
} else {
"trait object".into()
}
ty::Dynamic(ref inner, ..) if let Some(principal) = inner.principal() => {
format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
}
ty::Dynamic(..) => "trait object".into(),
ty::Closure(..) => "closure".into(),
ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
ty::GeneratorWitness(..) => "generator witness".into(),
Expand Down Expand Up @@ -365,20 +362,19 @@ impl<'tcx> TyCtxt<'tcx> {
// Issue #63167
db.note("distinct uses of `impl Trait` result in different opaque types");
}
(ty::Float(_), ty::Infer(ty::IntVar(_))) => {
(ty::Float(_), ty::Infer(ty::IntVar(_)))
if let Ok(
// Issue #53280
snippet,
) = self.sess.source_map().span_to_snippet(sp)
{
if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
db.span_suggestion(
sp,
"use a float literal",
format!("{}.0", snippet),
MachineApplicable,
);
}
) = self.sess.source_map().span_to_snippet(sp) =>
{
if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
db.span_suggestion(
sp,
"use a float literal",
format!("{}.0", snippet),
MachineApplicable,
);
}
}
(ty::Param(expected), ty::Param(found)) => {
Expand Down
38 changes: 20 additions & 18 deletions compiler/rustc_middle/src/ty/print/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -927,27 +927,29 @@ pub trait PrettyPrinter<'tcx>:
}

match ct.val {
ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted }) => {
if let Some(promoted) = promoted {
p!(print_value_path(def.did, substs));
p!(write("::{:?}", promoted));
} else {
match self.tcx().def_kind(def.did) {
DefKind::Static | DefKind::Const | DefKind::AssocConst => {
p!(print_value_path(def.did, substs))
}
_ => {
if def.is_local() {
let span = self.tcx().def_span(def.did);
if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span)
{
p!(write("{}", snip))
} else {
print_underscore!()
}
ty::ConstKind::Unevaluated(ty::Unevaluated {
def,
substs,
promoted: Some(promoted),
}) => {
p!(print_value_path(def.did, substs));
p!(write("::{:?}", promoted));
}
ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted: None }) => {
match self.tcx().def_kind(def.did) {
DefKind::Static | DefKind::Const | DefKind::AssocConst => {
p!(print_value_path(def.did, substs))
}
_ => {
if def.is_local() {
let span = self.tcx().def_span(def.did);
if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) {
p!(write("{}", snip))
} else {
print_underscore!()
}
} else {
print_underscore!()
}
}
}
Expand Down
10 changes: 4 additions & 6 deletions compiler/rustc_middle/src/ty/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,14 +225,12 @@ impl<'tcx> TyCtxt<'tcx> {
}
}

ty::Tuple(tys) => {
if let Some((&last_ty, _)) = tys.split_last() {
ty = last_ty.expect_ty();
} else {
break;
}
ty::Tuple(tys) if let Some((&last_ty, _)) = tys.split_last() => {
ty = last_ty.expect_ty();
}

ty::Tuple(_) => break,

ty::Projection(_) | ty::Opaque(..) => {
let normalized = normalize(ty);
if ty == normalized {
Expand Down
Loading

0 comments on commit 76e755c

Please sign in to comment.