Use if-let guards in the codebase

This commit is contained in:
Léo Lanteri Thauvin 2021-08-16 17:29:49 +02:00
parent a992a11913
commit fde1b76b4b
27 changed files with 242 additions and 254 deletions

View file

@ -564,12 +564,12 @@ impl NestedMetaItem {
I: Iterator<Item = TokenTree>,
{
match tokens.peek() {
Some(TokenTree::Token(token)) => {
if let Ok(lit) = Lit::from_token(token) {
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();
tokens.next();

View file

@ -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]

View file

@ -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;
@ -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) {
.filter_map(|x| {
match &x {
DiagnosticId::Error(s)
if let Ok(Some(_explanation)) = registry.try_find_description(s) =>
{
Some(s.clone())
} else {
None
}
}
_ => None,
}
})
.collect::<Vec<_>>();
if !error_codes.is_empty() {

View file

@ -305,15 +305,14 @@ impl<'a> StripUnconfigured<'a> {
Some((AttrAnnotatedTokenTree::Delimited(sp, delim, inner), *spacing))
.into_iter()
}
AttrAnnotatedTokenTree::Token(token) => {
if let TokenKind::Interpolated(nt) = token.kind {
AttrAnnotatedTokenTree::Token(ref token) if let TokenKind::Interpolated(ref nt) = token.kind => {
panic!(
"Nonterminal should have been flattened at {:?}: {:?}",
token.span, nt
);
} else {
Some((AttrAnnotatedTokenTree::Token(token), *spacing)).into_iter()
}
AttrAnnotatedTokenTree::Token(token) => {
Some((AttrAnnotatedTokenTree::Token(token), *spacing)).into_iter()
}
})
.collect();

View file

@ -2,11 +2,13 @@
#![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;

View file

@ -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) {
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 });
(file_path, DirOwnership::Owned { relative: None })
}
Inline::Yes => {
// 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.

View file

@ -178,10 +178,12 @@ 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) {
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 {
}
Interpolated(nt) => {
let stream = nt_to_tokenstream(&nt, rustc.sess, CanSynthesizeMissingTokens::No);
TokenTree::Group(Group {
delimiter: Delimiter::None,
@ -190,7 +192,6 @@ impl FromInternal<(TreeAndSpacing, &'_ mut Vec<Self>, &mut Rustc<'_>)>
flatten: crate::base::pretty_printing_compatibility_hack(&nt, rustc.sess),
})
}
}
OpenDelim(..) | CloseDelim(..) => unreachable!(),
Eof => unreachable!(),

View file

@ -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)]
@ -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]

View file

@ -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() {
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(..) => "trait object".into(),
ty::Closure(..) => "closure".into(),
ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
ty::GeneratorWitness(..) => "generator witness".into(),
@ -365,11 +362,11 @@ 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)
) = self.sess.source_map().span_to_snippet(sp) =>
{
if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
db.span_suggestion(
@ -380,7 +377,6 @@ impl<'tcx> TyCtxt<'tcx> {
);
}
}
}
(ty::Param(expected), ty::Param(found)) => {
let generics = self.generics_of(body_owner_def_id);
let e_span = self.def_span(generics.type_param(expected, self).def_id);

View file

@ -225,14 +225,12 @@ impl<'tcx> TyCtxt<'tcx> {
}
}
ty::Tuple(tys) => {
if let Some((&last_ty, _)) = tys.split_last() {
ty::Tuple(tys) if let Some((&last_ty, _)) = tys.split_last() => {
ty = last_ty.expect_ty();
} else {
break;
}
}
ty::Tuple(_) => break,
ty::Projection(_) | ty::Opaque(..) => {
let normalized = normalize(ty);
if ty == normalized {

View file

@ -2,8 +2,10 @@
#![feature(array_windows)]
#![feature(crate_visibility_modifier)]
#![feature(if_let_guard)]
#![cfg_attr(bootstrap, feature(bindings_after_at))]
#![feature(box_patterns)]
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard
#![recursion_limit = "256"]
use rustc_ast as ast;
@ -262,8 +264,7 @@ pub fn nt_to_tokenstream(
let tokens = match *nt {
Nonterminal::NtItem(ref item) => prepend_attrs(&item.attrs, item.tokens.as_ref()),
Nonterminal::NtBlock(ref block) => convert_tokens(block.tokens.as_ref()),
Nonterminal::NtStmt(ref stmt) => {
if let ast::StmtKind::Empty = stmt.kind {
Nonterminal::NtStmt(ref stmt) if let ast::StmtKind::Empty = stmt.kind => {
let tokens = AttrAnnotatedTokenStream::new(vec![(
tokenstream::AttrAnnotatedTokenTree::Token(Token::new(
TokenKind::Semi,
@ -272,10 +273,8 @@ pub fn nt_to_tokenstream(
Spacing::Alone,
)]);
prepend_attrs(&stmt.attrs(), Some(&LazyTokenStream::new(tokens)))
} else {
prepend_attrs(&stmt.attrs(), stmt.tokens())
}
}
Nonterminal::NtStmt(ref stmt) => prepend_attrs(&stmt.attrs(), stmt.tokens()),
Nonterminal::NtPat(ref pat) => convert_tokens(pat.tokens.as_ref()),
Nonterminal::NtTy(ref ty) => convert_tokens(ty.tokens.as_ref()),
Nonterminal::NtIdent(ident, is_raw) => {

View file

@ -143,16 +143,17 @@ impl<'a> Parser<'a> {
token::NtTy(self.collect_tokens_no_attrs(|this| this.parse_ty())?)
}
// this could be handled like a token, since it is one
NonterminalKind::Ident => {
if let Some((ident, is_raw)) = get_macro_ident(&self.token) {
NonterminalKind::Ident
if let Some((ident, is_raw)) = get_macro_ident(&self.token) =>
{
self.bump();
token::NtIdent(ident, is_raw)
} else {
}
NonterminalKind::Ident => {
let token_str = pprust::token_to_string(&self.token);
let msg = &format!("expected ident, found {}", &token_str);
return Err(self.struct_span_err(self.token.span, msg));
}
}
NonterminalKind::Path => token::NtPath(
self.collect_tokens_no_attrs(|this| this.parse_path(PathStyle::Type))?,
),

View file

@ -493,8 +493,7 @@ impl<'a> Parser<'a> {
}
}
StmtKind::Expr(_) | StmtKind::MacCall(_) => {}
StmtKind::Local(ref mut local) => {
if let Err(e) = self.expect_semi() {
StmtKind::Local(ref mut local) if let Err(e) = self.expect_semi() => {
// We might be at the `,` in `let x = foo<bar, baz>;`. Try to recover.
match &mut local.init {
Some(ref mut expr) => {
@ -504,10 +503,9 @@ impl<'a> Parser<'a> {
}
None => return Err(e),
}
}
eat_semi = false;
}
StmtKind::Empty | StmtKind::Item(_) | StmtKind::Semi(_) => eat_semi = false,
StmtKind::Empty | StmtKind::Item(_) | StmtKind::Local(_) | StmtKind::Semi(_) => eat_semi = false,
}
if eat_semi && self.eat(&token::Semi) {

View file

@ -24,8 +24,7 @@ pub fn check_meta(sess: &ParseSess, attr: &Attribute) {
Some((name, _, template, _)) if name != sym::rustc_dummy => {
check_builtin_attribute(sess, attr, name, template)
}
_ => {
if let MacArgs::Eq(..) = attr.get_normal_item().args {
_ if let MacArgs::Eq(..) = attr.get_normal_item().args => {
// All key-value attributes are restricted to meta-item syntax.
parse_meta(sess, attr)
.map_err(|mut err| {
@ -33,7 +32,7 @@ pub fn check_meta(sess: &ParseSess, attr: &Attribute) {
})
.ok();
}
}
_ => {}
}
}

View file

@ -1,5 +1,7 @@
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![feature(if_let_guard)]
#![feature(nll)]
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard
#![recursion_limit = "256"]
mod dump_visitor;
@ -326,8 +328,9 @@ impl<'tcx> SaveContext<'tcx> {
attributes: lower_attributes(attrs.to_vec(), self),
}))
}
hir::ItemKind::Impl(hir::Impl { ref of_trait, ref self_ty, ref items, .. }) => {
if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = self_ty.kind {
hir::ItemKind::Impl(hir::Impl { ref of_trait, ref self_ty, ref items, .. })
if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = self_ty.kind =>
{
// Common case impl for a struct or something basic.
if generated_code(path.span) {
return None;
@ -370,10 +373,8 @@ impl<'tcx> SaveContext<'tcx> {
},
)
})
} else {
None
}
}
hir::ItemKind::Impl(_) => None,
_ => {
// FIXME
bug!();

View file

@ -16,10 +16,12 @@
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![feature(array_windows)]
#![feature(crate_visibility_modifier)]
#![feature(if_let_guard)]
#![feature(negative_impls)]
#![feature(nll)]
#![feature(min_specialization)]
#![feature(thread_local_const_init)]
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard
#[macro_use]
extern crate rustc_macros;

View file

@ -982,15 +982,13 @@ impl SourceMap {
None
}
pub fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool {
source_file.add_external_src(|| match source_file.name {
FileName::Real(ref name) => {
if let Some(local_path) = name.local_path() {
source_file.add_external_src(|| {
match source_file.name {
FileName::Real(ref name) if let Some(local_path) = name.local_path() => {
self.file_loader.read_file(local_path).ok()
} else {
None
}
}
_ => None,
}
})
}
@ -1033,8 +1031,7 @@ impl FilePathMapping {
fn map_filename_prefix(&self, file: &FileName) -> (FileName, bool) {
match file {
FileName::Real(realfile) => {
if let RealFileName::LocalPath(local_path) = realfile {
FileName::Real(realfile) if let RealFileName::LocalPath(local_path) = realfile => {
let (mapped_path, mapped) = self.map_prefix(local_path.to_path_buf());
let realfile = if mapped {
RealFileName::Remapped {
@ -1045,10 +1042,8 @@ impl FilePathMapping {
realfile.clone()
};
(FileName::Real(realfile), mapped)
} else {
unreachable!("attempted to remap an already remapped filename");
}
}
FileName::Real(_) => unreachable!("attempted to remap an already remapped filename"),
other => (other.clone(), false),
}
}

View file

@ -2380,12 +2380,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
// Our own parameters are the resolved lifetimes.
match param.kind {
GenericParamDefKind::Lifetime => {
if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
GenericParamDefKind::Lifetime
if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] =>
{
self.ast_region_to_region(lifetime, None).into()
} else {
bug!()
}
}
_ => bug!(),
}

View file

@ -1178,13 +1178,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let mut user_self_ty = None;
let mut is_alias_variant_ctor = false;
match res {
Res::Def(DefKind::Ctor(CtorOf::Variant, _), _) => {
if let Some(self_ty) = self_ty {
Res::Def(DefKind::Ctor(CtorOf::Variant, _), _)
if let Some(self_ty) = self_ty =>
{
let adt_def = self_ty.ty_adt_def().unwrap();
user_self_ty = Some(UserSelfTy { impl_def_id: adt_def.did, self_ty });
is_alias_variant_ctor = true;
}
}
Res::Def(DefKind::AssocFn | DefKind::AssocConst, def_id) => {
let container = tcx.associated_item(def_id).container;
debug!("instantiate_value_path: def_id={:?} container={:?}", def_id, container);

View file

@ -616,8 +616,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
let lang_items = self.tcx.lang_items();
match *self_ty.value.value.kind() {
ty::Dynamic(ref data, ..) => {
if let Some(p) = data.principal() {
ty::Dynamic(ref data, ..) if let Some(p) = data.principal() => {
// Subtle: we can't use `instantiate_query_response` here: using it will
// commit to all of the type equalities assumed by inference going through
// autoderef (see the `method-probe-no-guessing` test).
@ -642,7 +641,6 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
self.assemble_inherent_candidates_from_object(generalized_self_ty);
self.assemble_inherent_impl_candidates_for_type(p.def_id());
}
}
ty::Adt(def, _) => {
self.assemble_inherent_impl_candidates_for_type(def.did);
}

View file

@ -627,8 +627,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let binding_parent = tcx.hir().get(binding_parent_id);
debug!("inner {:?} pat {:?} parent {:?}", inner, pat, binding_parent);
match binding_parent {
hir::Node::Param(hir::Param { span, .. }) => {
if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(inner.span) {
hir::Node::Param(hir::Param { span, .. })
if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(inner.span) =>
{
err.span_suggestion(
*span,
&format!("did you mean `{}`", snippet),
@ -636,7 +637,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
Applicability::MachineApplicable,
);
}
}
hir::Node::Arm(_) | hir::Node::Pat(_) => {
// rely on match ergonomics or it might be nested `&&pat`
if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(inner.span) {
@ -1293,13 +1293,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
(Some(mut err), None) => {
err.emit();
}
(None, None) => {
if let Some(mut err) =
self.error_tuple_variant_index_shorthand(variant, pat, fields)
(None, None) if let Some(mut err) =
self.error_tuple_variant_index_shorthand(variant, pat, fields) =>
{
err.emit();
}
}
(None, None) => {}
}
no_field_errors
}

View file

@ -1049,8 +1049,7 @@ fn check_opaque_types<'fcx, 'tcx>(
let arg_is_param = match arg.unpack() {
GenericArgKind::Type(ty) => matches!(ty.kind(), ty::Param(_)),
GenericArgKind::Lifetime(region) => {
if let ty::ReStatic = region {
GenericArgKind::Lifetime(region) if let ty::ReStatic = region => {
tcx.sess
.struct_span_err(
span,
@ -1066,8 +1065,7 @@ fn check_opaque_types<'fcx, 'tcx>(
continue;
}
true
}
GenericArgKind::Lifetime(_) => true,
GenericArgKind::Const(ct) => matches!(ct.val, ty::ConstKind::Param(_)),
};

View file

@ -175,11 +175,11 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
}
}
}
hir::ExprKind::AssignOp(..) => {
if let Some(a) = typeck_results.adjustments_mut().get_mut(lhs.hir_id) {
hir::ExprKind::AssignOp(..)
if let Some(a) = typeck_results.adjustments_mut().get_mut(lhs.hir_id) =>
{
a.pop();
}
}
_ => {}
}
}

View file

@ -446,13 +446,13 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
}
}
Node::AnonConst(_) => {
if let Some(param) = tcx.opt_const_param_of(def_id) {
Node::AnonConst(_) if let Some(param) = tcx.opt_const_param_of(def_id) => {
// We defer to `type_of` of the corresponding parameter
// for generic arguments.
return tcx.type_of(param);
tcx.type_of(param)
}
Node::AnonConst(_) => {
let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
match parent_node {
Node::Ty(&Ty { kind: TyKind::Array(_, ref constant), .. })

View file

@ -60,6 +60,7 @@ This API is completely unstable and subject to change.
#![feature(bool_to_option)]
#![feature(crate_visibility_modifier)]
#![feature(format_args_capture)]
#![feature(if_let_guard)]
#![feature(in_band_lifetimes)]
#![feature(is_sorted)]
#![feature(iter_zip)]
@ -68,6 +69,7 @@ This API is completely unstable and subject to change.
#![feature(never_type)]
#![feature(slice_partition_dedup)]
#![feature(control_flow_enum)]
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard
#![recursion_limit = "256"]
#[macro_use]

View file

@ -69,6 +69,7 @@
#![warn(missing_debug_implementations)]
#![warn(missing_docs)]
#![allow(explicit_outlives_requirements)]
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard
//
// Library features for const fns:
#![feature(const_align_of_val)]
@ -134,6 +135,7 @@
#![feature(exhaustive_patterns)]
#![feature(extern_types)]
#![feature(fundamental)]
#![feature(if_let_guard)]
#![feature(intra_doc_pointers)]
#![feature(intrinsics)]
#![feature(lang_items)]

View file

@ -236,13 +236,8 @@ pub fn dec2flt<F: RawFloat>(s: &str) -> Result<F, ParseFloatError> {
let num = match parse_number(s, negative) {
Some(r) => r,
None => {
if let Some(value) = parse_inf_nan(s, negative) {
return Ok(value);
} else {
return Err(pfe_invalid());
}
}
None if let Some(value) = parse_inf_nan(s, negative) => return Ok(value),
None => return Err(pfe_invalid()),
};
if let Some(value) = num.try_fast_path::<F>() {
return Ok(value);