From bfecb18771aa0249efe05dd7c35fa232f180bb70 Mon Sep 17 00:00:00 2001 From: Joshua Nelson Date: Mon, 26 Oct 2020 20:02:06 -0400 Subject: [PATCH 1/3] Fix some more clippy warnings --- compiler/rustc_ast_lowering/src/lib.rs | 5 +-- compiler/rustc_ast_lowering/src/path.rs | 6 +-- compiler/rustc_expand/src/mbe.rs | 5 +-- compiler/rustc_expand/src/mbe/macro_check.rs | 5 +-- compiler/rustc_expand/src/mbe/macro_rules.rs | 9 ++--- compiler/rustc_expand/src/placeholders.rs | 8 ++-- compiler/rustc_lint/src/builtin.rs | 16 ++++---- compiler/rustc_lint/src/nonstandard_style.rs | 2 +- compiler/rustc_lint/src/types.rs | 29 ++++++-------- compiler/rustc_lint/src/unused.rs | 7 +--- compiler/rustc_metadata/src/creader.rs | 5 +-- compiler/rustc_metadata/src/locator.rs | 8 ++-- .../src/rmeta/decoder/cstore_impl.rs | 13 +++--- compiler/rustc_privacy/src/lib.rs | 8 ++-- compiler/rustc_traits/src/chalk/db.rs | 40 +++++++++---------- .../src/implied_outlives_bounds.rs | 2 +- 16 files changed, 71 insertions(+), 97 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 269811053a084..599599f415f1c 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -490,10 +490,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let count = generics .params .iter() - .filter(|param| match param.kind { - ast::GenericParamKind::Lifetime { .. } => true, - _ => false, - }) + .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. })) .count(); self.lctx.type_def_lifetime_params.insert(def_id.to_def_id(), count); } diff --git a/compiler/rustc_ast_lowering/src/path.rs b/compiler/rustc_ast_lowering/src/path.rs index cf68dfb9ae1a1..e1eed168b31bb 100644 --- a/compiler/rustc_ast_lowering/src/path.rs +++ b/compiler/rustc_ast_lowering/src/path.rs @@ -262,10 +262,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx) }; - let has_lifetimes = generic_args.args.iter().any(|arg| match arg { - GenericArg::Lifetime(_) => true, - _ => false, - }); + let has_lifetimes = + generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_))); let first_generic_span = generic_args .args .iter() diff --git a/compiler/rustc_expand/src/mbe.rs b/compiler/rustc_expand/src/mbe.rs index 9aed307ec93ae..eb4aab116f00f 100644 --- a/compiler/rustc_expand/src/mbe.rs +++ b/compiler/rustc_expand/src/mbe.rs @@ -102,10 +102,7 @@ impl TokenTree { /// Returns `true` if the given token tree is delimited. fn is_delimited(&self) -> bool { - match *self { - TokenTree::Delimited(..) => true, - _ => false, - } + matches!(*self, TokenTree::Delimited(..)) } /// Returns `true` if the given token tree is a token of the given kind. diff --git a/compiler/rustc_expand/src/mbe/macro_check.rs b/compiler/rustc_expand/src/mbe/macro_check.rs index 6b419dae3f6e2..91add4f921844 100644 --- a/compiler/rustc_expand/src/mbe/macro_check.rs +++ b/compiler/rustc_expand/src/mbe/macro_check.rs @@ -134,10 +134,7 @@ enum Stack<'a, T> { impl<'a, T> Stack<'a, T> { /// Returns whether a stack is empty. fn is_empty(&self) -> bool { - match *self { - Stack::Empty => true, - _ => false, - } + matches!(*self, Stack::Empty) } /// Returns a new stack with an element of top. diff --git a/compiler/rustc_expand/src/mbe/macro_rules.rs b/compiler/rustc_expand/src/mbe/macro_rules.rs index 791d2686cb5eb..a074af0189a28 100644 --- a/compiler/rustc_expand/src/mbe/macro_rules.rs +++ b/compiler/rustc_expand/src/mbe/macro_rules.rs @@ -1036,17 +1036,16 @@ fn token_can_be_followed_by_any(tok: &mbe::TokenTree) -> bool { /// a fragment specifier (indeed, these fragments can be followed by /// ANYTHING without fear of future compatibility hazards). fn frag_can_be_followed_by_any(kind: NonterminalKind) -> bool { - match kind { + matches!( + kind, NonterminalKind::Item // always terminated by `}` or `;` | NonterminalKind::Block // exactly one token tree | NonterminalKind::Ident // exactly one token tree | NonterminalKind::Literal // exactly one token tree | NonterminalKind::Meta // exactly one token tree | NonterminalKind::Lifetime // exactly one token tree - | NonterminalKind::TT => true, // exactly one token tree - - _ => false, - } + | NonterminalKind::TT // exactly one token tree + ) } enum IsInFollow { diff --git a/compiler/rustc_expand/src/placeholders.rs b/compiler/rustc_expand/src/placeholders.rs index 4c9271a58df58..1bc14ae41bf29 100644 --- a/compiler/rustc_expand/src/placeholders.rs +++ b/compiler/rustc_expand/src/placeholders.rs @@ -345,10 +345,10 @@ impl<'a, 'b> MutVisitor for PlaceholderExpander<'a, 'b> { fn visit_mod(&mut self, module: &mut ast::Mod) { noop_visit_mod(module, self); - module.items.retain(|item| match item.kind { - ast::ItemKind::MacCall(_) if !self.cx.ecfg.keep_macs => false, // remove macro definitions - _ => true, - }); + // remove macro definitions + module.items.retain( + |item| !matches!(item.kind, ast::ItemKind::MacCall(_) if !self.cx.ecfg.keep_macs), + ); } fn visit_mac(&mut self, _mac: &mut ast::MacCall) { diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index e5f66611d0f9b..7e029aa7a1928 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -1369,10 +1369,9 @@ impl TypeAliasBounds { hir::QPath::TypeRelative(ref ty, _) => { // If this is a type variable, we found a `T::Assoc`. match ty.kind { - hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => match path.res { - Res::Def(DefKind::TyParam, _) => true, - _ => false, - }, + hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => { + matches!(path.res, Res::Def(DefKind::TyParam, _)) + } _ => false, } } @@ -2381,10 +2380,9 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { return Some(InitKind::Zeroed); } else if cx.tcx.is_diagnostic_item(sym::mem_uninitialized, def_id) { return Some(InitKind::Uninit); - } else if cx.tcx.is_diagnostic_item(sym::transmute, def_id) { - if is_zero(&args[0]) { - return Some(InitKind::Zeroed); - } + } else if cx.tcx.is_diagnostic_item(sym::transmute, def_id) && is_zero(&args[0]) + { + return Some(InitKind::Zeroed); } } } else if let hir::ExprKind::MethodCall(_, _, ref args, _) = expr.kind { @@ -2880,7 +2878,7 @@ impl<'tcx> LateLintPass<'tcx> for ClashingExternDeclarations { fn check_foreign_item(&mut self, cx: &LateContext<'tcx>, this_fi: &hir::ForeignItem<'_>) { trace!("ClashingExternDeclarations: check_foreign_item: {:?}", this_fi); if let ForeignItemKind::Fn(..) = this_fi.kind { - let tcx = *&cx.tcx; + let tcx = cx.tcx; if let Some(existing_hid) = self.insert(tcx, this_fi) { let existing_decl_ty = tcx.type_of(tcx.hir().local_def_id(existing_hid)); let this_decl_ty = tcx.type_of(tcx.hir().local_def_id(this_fi.hir_id)); diff --git a/compiler/rustc_lint/src/nonstandard_style.rs b/compiler/rustc_lint/src/nonstandard_style.rs index b3125f55d4d6e..f117ce1f80544 100644 --- a/compiler/rustc_lint/src/nonstandard_style.rs +++ b/compiler/rustc_lint/src/nonstandard_style.rs @@ -320,7 +320,7 @@ impl<'tcx> LateLintPass<'tcx> for NonSnakeCase { .with_hi(lit.span.hi() - BytePos(right as u32)), ) }) - .unwrap_or_else(|| lit.span); + .unwrap_or(lit.span); Some(Ident::new(name, sp)) } else { diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index bd0250305671e..32611fef1faf0 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -544,15 +544,15 @@ impl<'tcx> LateLintPass<'tcx> for TypeLimits { } fn is_comparison(binop: hir::BinOp) -> bool { - match binop.node { + matches!( + binop.node, hir::BinOpKind::Eq - | hir::BinOpKind::Lt - | hir::BinOpKind::Le - | hir::BinOpKind::Ne - | hir::BinOpKind::Ge - | hir::BinOpKind::Gt => true, - _ => false, - } + | hir::BinOpKind::Lt + | hir::BinOpKind::Le + | hir::BinOpKind::Ne + | hir::BinOpKind::Ge + | hir::BinOpKind::Gt + ) } } } @@ -1233,15 +1233,10 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { } fn is_internal_abi(&self, abi: SpecAbi) -> bool { - if let SpecAbi::Rust - | SpecAbi::RustCall - | SpecAbi::RustIntrinsic - | SpecAbi::PlatformIntrinsic = abi - { - true - } else { - false - } + matches!( + abi, + SpecAbi::Rust | SpecAbi::RustCall | SpecAbi::RustIntrinsic | SpecAbi::PlatformIntrinsic + ) } } diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index 17f0d5632e657..4bbc180b226a5 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -752,14 +752,11 @@ impl UnusedDelimLint for UnusedParens { && value.attrs.is_empty() && !value.span.from_expansion() && (ctx != UnusedDelimsCtx::LetScrutineeExpr - || match inner.kind { - ast::ExprKind::Binary( + || !matches!(inner.kind, ast::ExprKind::Binary( rustc_span::source_map::Spanned { node, .. }, _, _, - ) if node.lazy() => false, - _ => true, - }) + ) if node.lazy())) { self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos) } diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index 7562da6d78261..33cbf0fb2345e 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -752,10 +752,7 @@ impl<'a> CrateLoader<'a> { // At this point we've determined that we need an allocator. Let's see // if our compilation session actually needs an allocator based on what // we're emitting. - let all_rlib = self.sess.crate_types().iter().all(|ct| match *ct { - CrateType::Rlib => true, - _ => false, - }); + let all_rlib = self.sess.crate_types().iter().all(|ct| matches!(*ct, CrateType::Rlib)); if all_rlib { return; } diff --git a/compiler/rustc_metadata/src/locator.rs b/compiler/rustc_metadata/src/locator.rs index f225f8acc89ff..d16985b9c2b3f 100644 --- a/compiler/rustc_metadata/src/locator.rs +++ b/compiler/rustc_metadata/src/locator.rs @@ -633,11 +633,9 @@ impl<'a> CrateLocator<'a> { } } - if self.exact_paths.is_empty() { - if self.crate_name != root.name() { - info!("Rejecting via crate name"); - return None; - } + if self.exact_paths.is_empty() && self.crate_name != root.name() { + info!("Rejecting via crate name"); + return None; } if root.triple() != &self.triple { diff --git a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs index 68faf9c7a629d..b5fb850e92e6d 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs @@ -220,10 +220,7 @@ provide! { <'tcx> tcx, def_id, other, cdata, missing_lang_items => { cdata.get_missing_lang_items(tcx) } missing_extern_crate_item => { - let r = match *cdata.extern_crate.borrow() { - Some(extern_crate) if !extern_crate.is_direct() => true, - _ => false, - }; + let r = matches!(*cdata.extern_crate.borrow(), Some(extern_crate) if !extern_crate.is_direct()); r } @@ -254,9 +251,11 @@ pub fn provide(providers: &mut Providers) { } _ => false, }, - is_statically_included_foreign_item: |tcx, id| match tcx.native_library_kind(id) { - Some(NativeLibKind::StaticBundle | NativeLibKind::StaticNoBundle) => true, - _ => false, + is_statically_included_foreign_item: |tcx, id| { + matches!( + tcx.native_library_kind(id), + Some(NativeLibKind::StaticBundle | NativeLibKind::StaticNoBundle) + ) }, native_library_kind: |tcx, id| { tcx.native_libraries(id.krate) diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 851e0dfbe0d45..fb0b50d1c248a 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -1219,9 +1219,11 @@ impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> { .maybe_typeck_results .and_then(|typeck_results| typeck_results.type_dependent_def(id)), }; - let def = def.filter(|(kind, _)| match kind { - DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Static => true, - _ => false, + let def = def.filter(|(kind, _)| { + matches!( + kind, + DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Static + ) }); if let Some((kind, def_id)) = def { let is_local_static = diff --git a/compiler/rustc_traits/src/chalk/db.rs b/compiler/rustc_traits/src/chalk/db.rs index 3368c5b769902..e5ae899a2f356 100644 --- a/compiler/rustc_traits/src/chalk/db.rs +++ b/compiler/rustc_traits/src/chalk/db.rs @@ -342,29 +342,29 @@ impl<'tcx> chalk_solve::RustIrDatabase> for RustIrDatabase<'t } (ty::Bool, Scalar(Bool)) => true, (ty::Char, Scalar(Char)) => true, - (ty::Int(ty1), Scalar(Int(ty2))) => match (ty1, ty2) { + (ty::Int(ty1), Scalar(Int(ty2))) => matches!( + (ty1, ty2), (ast::IntTy::Isize, chalk_ir::IntTy::Isize) - | (ast::IntTy::I8, chalk_ir::IntTy::I8) - | (ast::IntTy::I16, chalk_ir::IntTy::I16) - | (ast::IntTy::I32, chalk_ir::IntTy::I32) - | (ast::IntTy::I64, chalk_ir::IntTy::I64) - | (ast::IntTy::I128, chalk_ir::IntTy::I128) => true, - _ => false, - }, - (ty::Uint(ty1), Scalar(Uint(ty2))) => match (ty1, ty2) { + | (ast::IntTy::I8, chalk_ir::IntTy::I8) + | (ast::IntTy::I16, chalk_ir::IntTy::I16) + | (ast::IntTy::I32, chalk_ir::IntTy::I32) + | (ast::IntTy::I64, chalk_ir::IntTy::I64) + | (ast::IntTy::I128, chalk_ir::IntTy::I128) + ), + (ty::Uint(ty1), Scalar(Uint(ty2))) => matches!( + (ty1, ty2), (ast::UintTy::Usize, chalk_ir::UintTy::Usize) - | (ast::UintTy::U8, chalk_ir::UintTy::U8) - | (ast::UintTy::U16, chalk_ir::UintTy::U16) - | (ast::UintTy::U32, chalk_ir::UintTy::U32) - | (ast::UintTy::U64, chalk_ir::UintTy::U64) - | (ast::UintTy::U128, chalk_ir::UintTy::U128) => true, - _ => false, - }, - (ty::Float(ty1), Scalar(Float(ty2))) => match (ty1, ty2) { + | (ast::UintTy::U8, chalk_ir::UintTy::U8) + | (ast::UintTy::U16, chalk_ir::UintTy::U16) + | (ast::UintTy::U32, chalk_ir::UintTy::U32) + | (ast::UintTy::U64, chalk_ir::UintTy::U64) + | (ast::UintTy::U128, chalk_ir::UintTy::U128) + ), + (ty::Float(ty1), Scalar(Float(ty2))) => matches!( + (ty1, ty2), (ast::FloatTy::F32, chalk_ir::FloatTy::F32) - | (ast::FloatTy::F64, chalk_ir::FloatTy::F64) => true, - _ => false, - }, + | (ast::FloatTy::F64, chalk_ir::FloatTy::F64) + ), (&ty::Tuple(..), Tuple(..)) => true, (&ty::Array(..), Array) => true, (&ty::Slice(..), Slice) => true, diff --git a/compiler/rustc_traits/src/implied_outlives_bounds.rs b/compiler/rustc_traits/src/implied_outlives_bounds.rs index bc5c07fce045c..c44fd1d58593f 100644 --- a/compiler/rustc_traits/src/implied_outlives_bounds.rs +++ b/compiler/rustc_traits/src/implied_outlives_bounds.rs @@ -62,7 +62,7 @@ fn compute_implied_outlives_bounds<'tcx>( // unresolved inference variables here anyway, but there might be // during typeck under some circumstances.) let obligations = wf::obligations(infcx, param_env, hir::CRATE_HIR_ID, 0, arg, DUMMY_SP) - .unwrap_or(vec![]); + .unwrap_or_default(); // N.B., all of these predicates *ought* to be easily proven // true. In fact, their correctness is (mostly) implied by From 57c6ed0c07aaea9c89a192e54b3274464ebe6fbf Mon Sep 17 00:00:00 2001 From: Joshua Nelson Date: Mon, 26 Oct 2020 21:02:48 -0400 Subject: [PATCH 2/3] Fix even more clippy warnings --- compiler/rustc_arena/src/lib.rs | 10 +-- compiler/rustc_ast_pretty/src/pprust/state.rs | 12 ++- compiler/rustc_attr/src/builtin.rs | 58 +++++++------- compiler/rustc_codegen_llvm/src/allocator.rs | 2 +- compiler/rustc_codegen_llvm/src/asm.rs | 10 +-- compiler/rustc_codegen_llvm/src/back/lto.rs | 2 +- compiler/rustc_codegen_llvm/src/builder.rs | 5 +- compiler/rustc_codegen_llvm/src/consts.rs | 6 +- compiler/rustc_codegen_llvm/src/context.rs | 10 +-- .../rustc_codegen_llvm/src/debuginfo/mod.rs | 2 +- .../src/graph/scc/mod.rs | 5 +- compiler/rustc_data_structures/src/sso/map.rs | 6 +- compiler/rustc_driver/src/lib.rs | 2 +- compiler/rustc_errors/src/json.rs | 5 +- compiler/rustc_errors/src/lib.rs | 10 +-- compiler/rustc_errors/src/snippet.rs | 5 +- compiler/rustc_feature/src/builtin_attrs.rs | 5 +- compiler/rustc_hir/src/hir.rs | 47 +++-------- compiler/rustc_hir/src/pat_util.rs | 5 +- compiler/rustc_hir_pretty/src/lib.rs | 27 ++----- compiler/rustc_lexer/src/lib.rs | 10 +-- .../src/build/expr/as_place.rs | 5 +- .../src/build/expr/as_rvalue.rs | 5 +- .../rustc_mir_build/src/build/expr/into.rs | 5 +- .../rustc_mir_build/src/build/matches/test.rs | 14 ++-- compiler/rustc_mir_build/src/build/scope.rs | 16 ++-- compiler/rustc_mir_build/src/thir/cx/expr.rs | 16 ++-- .../src/thir/pattern/_match.rs | 15 +--- .../rustc_mir_build/src/thir/pattern/mod.rs | 5 +- compiler/rustc_parse/src/lib.rs | 4 +- .../rustc_parse/src/parser/diagnostics.rs | 6 +- compiler/rustc_parse/src/parser/item.rs | 31 +++---- .../rustc_parse/src/parser/nonterminal.rs | 22 ++--- compiler/rustc_parse/src/parser/pat.rs | 17 ++-- compiler/rustc_parse/src/parser/path.rs | 14 ++-- .../rustc_query_system/src/dep_graph/graph.rs | 6 +- .../rustc_query_system/src/query/plumbing.rs | 6 +- .../rustc_resolve/src/build_reduced_graph.rs | 8 +- compiler/rustc_resolve/src/diagnostics.rs | 25 ++---- compiler/rustc_resolve/src/imports.rs | 36 +++------ compiler/rustc_resolve/src/late.rs | 57 ++++--------- .../rustc_resolve/src/late/diagnostics.rs | 12 +-- compiler/rustc_resolve/src/late/lifetimes.rs | 42 ++++------ compiler/rustc_resolve/src/lib.rs | 80 +++++++------------ compiler/rustc_session/src/config.rs | 5 +- compiler/rustc_session/src/output.rs | 6 +- compiler/rustc_symbol_mangling/src/legacy.rs | 6 +- compiler/rustc_symbol_mangling/src/lib.rs | 25 +++--- compiler/rustc_target/src/abi/call/mod.rs | 20 +---- compiler/rustc_target/src/abi/call/riscv.rs | 6 +- compiler/rustc_target/src/abi/call/wasm32.rs | 12 +-- compiler/rustc_target/src/abi/mod.rs | 20 +---- compiler/rustc_target/src/asm/mod.rs | 5 +- 53 files changed, 276 insertions(+), 520 deletions(-) diff --git a/compiler/rustc_arena/src/lib.rs b/compiler/rustc_arena/src/lib.rs index a852254766699..b76e1e7ce65e0 100644 --- a/compiler/rustc_arena/src/lib.rs +++ b/compiler/rustc_arena/src/lib.rs @@ -228,7 +228,7 @@ impl TypedArena { // bytes, then this chunk will be least double the previous // chunk's size. new_cap = last_chunk.storage.len().min(HUGE_PAGE / elem_size / 2); - new_cap = new_cap * 2; + new_cap *= 2; } else { new_cap = PAGE / elem_size; } @@ -346,7 +346,7 @@ impl DroplessArena { // bytes, then this chunk will be least double the previous // chunk's size. new_cap = last_chunk.storage.len().min(HUGE_PAGE / 2); - new_cap = new_cap * 2; + new_cap *= 2; } else { new_cap = PAGE; } @@ -562,10 +562,8 @@ impl DropArena { // Record the destructors after doing the allocation as that may panic // and would cause `object`'s destructor to run twice if it was recorded before for i in 0..len { - destructors.push(DropType { - drop_fn: drop_for_type::, - obj: start_ptr.offset(i as isize) as *mut u8, - }); + destructors + .push(DropType { drop_fn: drop_for_type::, obj: start_ptr.add(i) as *mut u8 }); } slice::from_raw_parts_mut(start_ptr, len) diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index 8be344140dee6..9fcba90244330 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -639,13 +639,11 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere fn break_offset_if_not_bol(&mut self, n: usize, off: isize) { if !self.is_beginning_of_line() { self.break_offset(n, off) - } else { - if off != 0 && self.last_token().is_hardbreak_tok() { - // We do something pretty sketchy here: tuck the nonzero - // offset-adjustment we were going to deposit along with the - // break into the previous hardbreak. - self.replace_last_token(pp::Printer::hardbreak_tok_offset(off)); - } + } else if off != 0 && self.last_token().is_hardbreak_tok() { + // We do something pretty sketchy here: tuck the nonzero + // offset-adjustment we were going to deposit along with the + // break into the previous hardbreak. + self.replace_last_token(pp::Printer::hardbreak_tok_offset(off)); } } diff --git a/compiler/rustc_attr/src/builtin.rs b/compiler/rustc_attr/src/builtin.rs index 218a9b229e0df..48238c8bbf571 100644 --- a/compiler/rustc_attr/src/builtin.rs +++ b/compiler/rustc_attr/src/builtin.rs @@ -901,38 +901,36 @@ pub fn find_repr_attrs(sess: &Session, attr: &Attribute) -> Vec { ) .emit(); } - } else { - if let Some(meta_item) = item.meta_item() { - if meta_item.has_name(sym::align) { - if let MetaItemKind::NameValue(ref value) = meta_item.kind { - recognised = true; - let mut err = struct_span_err!( - diagnostic, - item.span(), - E0693, - "incorrect `repr(align)` attribute format" - ); - match value.kind { - ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => { - err.span_suggestion( - item.span(), - "use parentheses instead", - format!("align({})", int), - Applicability::MachineApplicable, - ); - } - ast::LitKind::Str(s, _) => { - err.span_suggestion( - item.span(), - "use parentheses instead", - format!("align({})", s), - Applicability::MachineApplicable, - ); - } - _ => {} + } else if let Some(meta_item) = item.meta_item() { + if meta_item.has_name(sym::align) { + if let MetaItemKind::NameValue(ref value) = meta_item.kind { + recognised = true; + let mut err = struct_span_err!( + diagnostic, + item.span(), + E0693, + "incorrect `repr(align)` attribute format" + ); + match value.kind { + ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => { + err.span_suggestion( + item.span(), + "use parentheses instead", + format!("align({})", int), + Applicability::MachineApplicable, + ); + } + ast::LitKind::Str(s, _) => { + err.span_suggestion( + item.span(), + "use parentheses instead", + format!("align({})", s), + Applicability::MachineApplicable, + ); } - err.emit(); + _ => {} } + err.emit(); } } } diff --git a/compiler/rustc_codegen_llvm/src/allocator.rs b/compiler/rustc_codegen_llvm/src/allocator.rs index d02bc41f4af3b..f7d82ff78fa38 100644 --- a/compiler/rustc_codegen_llvm/src/allocator.rs +++ b/compiler/rustc_codegen_llvm/src/allocator.rs @@ -93,7 +93,7 @@ pub(crate) unsafe fn codegen( let args = [usize, usize]; // size, align let ty = llvm::LLVMFunctionType(void, args.as_ptr(), args.len() as c_uint, False); - let name = format!("__rust_alloc_error_handler"); + let name = "__rust_alloc_error_handler".to_string(); let llfn = llvm::LLVMRustGetOrInsertFunction(llmod, name.as_ptr().cast(), name.len(), ty); // -> ! DIFlagNoReturn llvm::Attribute::NoReturn.apply_llfn(llvm::AttributePlace::Function, llfn); diff --git a/compiler/rustc_codegen_llvm/src/asm.rs b/compiler/rustc_codegen_llvm/src/asm.rs index b096664bc74c6..d856280158f2d 100644 --- a/compiler/rustc_codegen_llvm/src/asm.rs +++ b/compiler/rustc_codegen_llvm/src/asm.rs @@ -302,13 +302,11 @@ impl AsmBuilderMethods<'tcx> for Builder<'a, 'll, 'tcx> { } else if options.contains(InlineAsmOptions::READONLY) { llvm::Attribute::ReadOnly.apply_callsite(llvm::AttributePlace::Function, result); } + } else if options.contains(InlineAsmOptions::NOMEM) { + llvm::Attribute::InaccessibleMemOnly + .apply_callsite(llvm::AttributePlace::Function, result); } else { - if options.contains(InlineAsmOptions::NOMEM) { - llvm::Attribute::InaccessibleMemOnly - .apply_callsite(llvm::AttributePlace::Function, result); - } else { - // LLVM doesn't have an attribute to represent ReadOnly + SideEffect - } + // LLVM doesn't have an attribute to represent ReadOnly + SideEffect } // Write results to outputs diff --git a/compiler/rustc_codegen_llvm/src/back/lto.rs b/compiler/rustc_codegen_llvm/src/back/lto.rs index ff312bade2521..64fd1d09cc24f 100644 --- a/compiler/rustc_codegen_llvm/src/back/lto.rs +++ b/compiler/rustc_codegen_llvm/src/back/lto.rs @@ -900,7 +900,7 @@ impl ThinLTOKeysMap { let file = File::open(path)?; for line in io::BufReader::new(file).lines() { let line = line?; - let mut split = line.split(" "); + let mut split = line.split(' '); let module = split.next().unwrap(); let key = split.next().unwrap(); assert_eq!(split.next(), None, "Expected two space-separated values, found {:?}", line); diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index 978ad37c0f390..f122fa14e70be 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -732,10 +732,7 @@ impl BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { let src_ty = self.cx.val_ty(val); let float_width = self.cx.float_width(src_ty); let int_width = self.cx.int_width(dest_ty); - match (int_width, float_width) { - (32, 32) | (32, 64) | (64, 32) | (64, 64) => true, - _ => false, - } + matches!((int_width, float_width), (32, 32) | (32, 64) | (64, 32) | (64, 64)) } fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value { diff --git a/compiler/rustc_codegen_llvm/src/consts.rs b/compiler/rustc_codegen_llvm/src/consts.rs index b57a23328b663..1672601d36f7a 100644 --- a/compiler/rustc_codegen_llvm/src/consts.rs +++ b/compiler/rustc_codegen_llvm/src/consts.rs @@ -397,10 +397,8 @@ impl StaticMethods for CodegenCx<'ll, 'tcx> { // As an optimization, all shared statics which do not have interior // mutability are placed into read-only memory. - if !is_mutable { - if self.type_is_freeze(ty) { - llvm::LLVMSetGlobalConstant(g, llvm::True); - } + if !is_mutable && self.type_is_freeze(ty) { + llvm::LLVMSetGlobalConstant(g, llvm::True); } debuginfo::create_global_var_metadata(&self, def_id, g); diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index 56ff580b43b59..253e02bd08248 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -122,10 +122,10 @@ pub unsafe fn create_module( if llvm_util::get_major_version() < 9 { target_data_layout = strip_function_ptr_alignment(target_data_layout); } - if llvm_util::get_major_version() < 10 { - if sess.target.arch == "x86" || sess.target.arch == "x86_64" { - target_data_layout = strip_x86_address_spaces(target_data_layout); - } + if llvm_util::get_major_version() < 10 + && (sess.target.arch == "x86" || sess.target.arch == "x86_64") + { + target_data_layout = strip_x86_address_spaces(target_data_layout); } // Ensure the data-layout values hardcoded remain the defaults. @@ -864,7 +864,7 @@ impl<'b, 'tcx> CodegenCx<'b, 'tcx> { // user defined names let mut name = String::with_capacity(prefix.len() + 6); name.push_str(prefix); - name.push_str("."); + name.push('.'); base_n::push_str(idx as u128, base_n::ALPHANUMERIC_ONLY, &mut name); name } diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs index beaea49874e6e..6bb93857d71aa 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs @@ -435,7 +435,7 @@ impl DebugInfoMethods<'tcx> for CodegenCx<'ll, 'tcx> { name_to_append_suffix_to.push('<'); for (i, actual_type) in substs.types().enumerate() { if i != 0 { - name_to_append_suffix_to.push_str(","); + name_to_append_suffix_to.push(','); } let actual_type = diff --git a/compiler/rustc_data_structures/src/graph/scc/mod.rs b/compiler/rustc_data_structures/src/graph/scc/mod.rs index 2db8e466e1144..486a9ba77b75f 100644 --- a/compiler/rustc_data_structures/src/graph/scc/mod.rs +++ b/compiler/rustc_data_structures/src/graph/scc/mod.rs @@ -307,10 +307,7 @@ where fn walk_unvisited_node(&mut self, depth: usize, node: G::Node) -> WalkReturn { debug!("walk_unvisited_node(depth = {:?}, node = {:?})", depth, node); - debug_assert!(match self.node_states[node] { - NodeState::NotVisited => true, - _ => false, - }); + debug_assert!(matches!(self.node_states[node], NodeState::NotVisited)); // Push `node` onto the stack. self.node_states[node] = NodeState::BeingVisited { depth }; diff --git a/compiler/rustc_data_structures/src/sso/map.rs b/compiler/rustc_data_structures/src/sso/map.rs index fa510e58314af..fe8ae7abf982b 100644 --- a/compiler/rustc_data_structures/src/sso/map.rs +++ b/compiler/rustc_data_structures/src/sso/map.rs @@ -395,7 +395,7 @@ where V: Copy, { fn extend>(&mut self, iter: T) { - self.extend(iter.into_iter().map(|(k, v)| (k.clone(), v.clone()))) + self.extend(iter.into_iter().map(|(k, v)| (*k, *v))) } #[inline] @@ -451,7 +451,7 @@ impl<'a, K, V> IntoIterator for &'a SsoHashMap { fn into_iter(self) -> Self::IntoIter { match self { SsoHashMap::Array(array) => EitherIter::Left(array.into_iter().map(adapt_array_ref_it)), - SsoHashMap::Map(map) => EitherIter::Right(map.into_iter()), + SsoHashMap::Map(map) => EitherIter::Right(map.iter()), } } } @@ -469,7 +469,7 @@ impl<'a, K, V> IntoIterator for &'a mut SsoHashMap { fn into_iter(self) -> Self::IntoIter { match self { SsoHashMap::Array(array) => EitherIter::Left(array.into_iter().map(adapt_array_mut_it)), - SsoHashMap::Map(map) => EitherIter::Right(map.into_iter()), + SsoHashMap::Map(map) => EitherIter::Right(map.iter_mut()), } } } diff --git a/compiler/rustc_driver/src/lib.rs b/compiler/rustc_driver/src/lib.rs index 29771bee9aeb5..f434673c39e10 100644 --- a/compiler/rustc_driver/src/lib.rs +++ b/compiler/rustc_driver/src/lib.rs @@ -716,7 +716,7 @@ impl RustcDefaultCalls { TargetList => { let mut targets = rustc_target::spec::TARGETS.iter().copied().collect::>(); - targets.sort(); + targets.sort_unstable(); println!("{}", targets.join("\n")); } Sysroot => println!("{}", sess.sysroot.display()), diff --git a/compiler/rustc_errors/src/json.rs b/compiler/rustc_errors/src/json.rs index 750d36d3d891a..fbe3588280ad1 100644 --- a/compiler/rustc_errors/src/json.rs +++ b/compiler/rustc_errors/src/json.rs @@ -136,10 +136,7 @@ impl Emitter for JsonEmitter { } fn should_show_explain(&self) -> bool { - match self.json_rendered { - HumanReadableErrorType::Short(_) => false, - _ => true, - } + !matches!(self.json_rendered, HumanReadableErrorType::Short(_)) } } diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 2e8a4ef327ac4..2ebc4a7e9d923 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -91,10 +91,7 @@ pub enum SuggestionStyle { impl SuggestionStyle { fn hide_inline(&self) -> bool { - match *self { - SuggestionStyle::ShowCode => false, - _ => true, - } + !matches!(*self, SuggestionStyle::ShowCode) } } @@ -1038,10 +1035,7 @@ impl Level { } pub fn is_failure_note(&self) -> bool { - match *self { - FailureNote => true, - _ => false, - } + matches!(*self, FailureNote) } } diff --git a/compiler/rustc_errors/src/snippet.rs b/compiler/rustc_errors/src/snippet.rs index fae5b94b3a81e..dbb2523f28691 100644 --- a/compiler/rustc_errors/src/snippet.rs +++ b/compiler/rustc_errors/src/snippet.rs @@ -158,10 +158,7 @@ impl Annotation { pub fn takes_space(&self) -> bool { // Multiline annotations always have to keep vertical space. - match self.annotation_type { - AnnotationType::MultilineStart(_) | AnnotationType::MultilineEnd(_) => true, - _ => false, - } + matches!(self.annotation_type, AnnotationType::MultilineStart(_) | AnnotationType::MultilineEnd(_)) } } diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index f73363cbccc25..57ae534590ddf 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -83,10 +83,7 @@ impl std::fmt::Debug for AttributeGate { impl AttributeGate { fn is_deprecated(&self) -> bool { - match *self { - Self::Gated(Stability::Deprecated(_, _), ..) => true, - _ => false, - } + matches!(*self, Self::Gated(Stability::Deprecated(_, _), ..)) } } diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index fc15bb324c1d8..b9ec18688c5f2 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -272,10 +272,7 @@ impl GenericArg<'_> { } pub fn is_const(&self) -> bool { - match self { - GenericArg::Const(_) => true, - _ => false, - } + matches!(self, GenericArg::Const(_)) } pub fn descr(&self) -> &'static str { @@ -980,17 +977,11 @@ impl BinOpKind { } pub fn is_lazy(self) -> bool { - match self { - BinOpKind::And | BinOpKind::Or => true, - _ => false, - } + matches!(self, BinOpKind::And | BinOpKind::Or) } pub fn is_shift(self) -> bool { - match self { - BinOpKind::Shl | BinOpKind::Shr => true, - _ => false, - } + matches!(self, BinOpKind::Shl | BinOpKind::Shr) } pub fn is_comparison(self) -> bool { @@ -1070,10 +1061,7 @@ impl UnOp { /// Returns `true` if the unary operator takes its argument by value. pub fn is_by_value(self) -> bool { - match self { - Self::UnNeg | Self::UnNot => true, - _ => false, - } + matches!(self, Self::UnNeg | Self::UnNot) } } @@ -1409,10 +1397,9 @@ impl Expr<'_> { /// on the given expression should be considered a place expression. pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool { match self.kind { - ExprKind::Path(QPath::Resolved(_, ref path)) => match path.res { - Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err => true, - _ => false, - }, + ExprKind::Path(QPath::Resolved(_, ref path)) => { + matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err) + } // Type ascription inherits its place expression kind from its // operand. See: @@ -2204,10 +2191,7 @@ pub enum ImplicitSelfKind { impl ImplicitSelfKind { /// Does this represent an implicit self? pub fn has_implicit_self(&self) -> bool { - match *self { - ImplicitSelfKind::None => false, - _ => true, - } + !matches!(*self, ImplicitSelfKind::None) } } @@ -2237,10 +2221,7 @@ impl Defaultness { } pub fn is_default(&self) -> bool { - match *self { - Defaultness::Default { .. } => true, - _ => false, - } + matches!(*self, Defaultness::Default { .. }) } } @@ -2371,10 +2352,7 @@ pub enum VisibilityKind<'hir> { impl VisibilityKind<'_> { pub fn is_pub(&self) -> bool { - match *self { - VisibilityKind::Public => true, - _ => false, - } + matches!(*self, VisibilityKind::Public) } pub fn is_pub_restricted(&self) -> bool { @@ -2502,10 +2480,7 @@ pub struct FnHeader { impl FnHeader { pub fn is_const(&self) -> bool { - match &self.constness { - Constness::Const => true, - _ => false, - } + matches!(&self.constness, Constness::Const) } } diff --git a/compiler/rustc_hir/src/pat_util.rs b/compiler/rustc_hir/src/pat_util.rs index c05d3e44423cf..9e0a6aae24272 100644 --- a/compiler/rustc_hir/src/pat_util.rs +++ b/compiler/rustc_hir/src/pat_util.rs @@ -92,10 +92,7 @@ impl hir::Pat<'_> { /// Checks if the pattern contains any patterns that bind something to /// an ident, e.g., `foo`, or `Foo(foo)` or `foo @ Bar(..)`. pub fn contains_bindings(&self) -> bool { - self.satisfies(|p| match p.kind { - PatKind::Binding(..) => true, - _ => false, - }) + self.satisfies(|p| matches!(p.kind, PatKind::Binding(..))) } /// Checks if the pattern satisfies the given predicate on some sub-pattern. diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index 1cd4ddad5783a..f7018ae62aa19 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -299,13 +299,11 @@ impl<'a> State<'a> { pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) { if !self.s.is_beginning_of_line() { self.s.break_offset(n, off) - } else { - if off != 0 && self.s.last_token().is_hardbreak_tok() { - // We do something pretty sketchy here: tuck the nonzero - // offset-adjustment we were going to deposit along with the - // break into the previous hardbreak. - self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off)); - } + } else if off != 0 && self.s.last_token().is_hardbreak_tok() { + // We do something pretty sketchy here: tuck the nonzero + // offset-adjustment we were going to deposit along with the + // break into the previous hardbreak. + self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off)); } } @@ -1921,10 +1919,7 @@ impl<'a> State<'a> { self.pclose(); } PatKind::Box(ref inner) => { - let is_range_inner = match inner.kind { - PatKind::Range(..) => true, - _ => false, - }; + let is_range_inner = matches!(inner.kind, PatKind::Range(..)); self.s.word("box "); if is_range_inner { self.popen(); @@ -1935,10 +1930,7 @@ impl<'a> State<'a> { } } PatKind::Ref(ref inner, mutbl) => { - let is_range_inner = match inner.kind { - PatKind::Range(..) => true, - _ => false, - }; + let is_range_inner = matches!(inner.kind, PatKind::Range(..)); self.s.word("&"); self.s.word(mutbl.prefix_str()); if is_range_inner { @@ -2435,10 +2427,7 @@ impl<'a> State<'a> { // // Duplicated from `parse::classify`, but adapted for the HIR. fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool { - match e.kind { - hir::ExprKind::Match(..) | hir::ExprKind::Block(..) | hir::ExprKind::Loop(..) => false, - _ => true, - } + !matches!(e.kind, hir::ExprKind::Match(..) | hir::ExprKind::Block(..) | hir::ExprKind::Loop(..)) } /// This statement requires a semicolon after it. diff --git a/compiler/rustc_lexer/src/lib.rs b/compiler/rustc_lexer/src/lib.rs index c5b59a041abf6..84ae2e9dd7133 100644 --- a/compiler/rustc_lexer/src/lib.rs +++ b/compiler/rustc_lexer/src/lib.rs @@ -238,9 +238,9 @@ pub fn is_whitespace(c: char) -> bool { // Note that this set is stable (ie, it doesn't change with different // Unicode versions), so it's ok to just hard-code the values. - match c { - // Usual ASCII suspects - | '\u{0009}' // \t + matches!( + c, + '\u{0009}' // \t | '\u{000A}' // \n | '\u{000B}' // vertical tab | '\u{000C}' // form feed @@ -257,9 +257,7 @@ pub fn is_whitespace(c: char) -> bool { // Dedicated whitespace characters from Unicode | '\u{2028}' // LINE SEPARATOR | '\u{2029}' // PARAGRAPH SEPARATOR - => true, - _ => false, - } + ) } /// True if `c` is valid as a first character of an identifier. diff --git a/compiler/rustc_mir_build/src/build/expr/as_place.rs b/compiler/rustc_mir_build/src/build/expr/as_place.rs index 443025c4f8458..b94346fa43911 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_place.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_place.rs @@ -262,10 +262,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { | ExprKind::ThreadLocalRef(_) | ExprKind::Call { .. } => { // these are not places, so we need to make a temporary. - debug_assert!(match Category::of(&expr.kind) { - Some(Category::Place) => false, - _ => true, - }); + debug_assert!(!matches!(Category::of(&expr.kind), Some(Category::Place))); let temp = unpack!(block = this.as_temp(block, expr.temp_lifetime, expr, mutability)); block.and(PlaceBuilder::from(temp)) diff --git a/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs b/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs index 4033cc6cf46c4..2853bf887faaf 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs @@ -260,10 +260,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { | ExprKind::ValueTypeAscription { .. } => { // these do not have corresponding `Rvalue` variants, // so make an operand and then return that - debug_assert!(match Category::of(&expr.kind) { - Some(Category::Rvalue(RvalueFunc::AsRvalue)) => false, - _ => true, - }); + debug_assert!(!matches!(Category::of(&expr.kind), Some(Category::Rvalue(RvalueFunc::AsRvalue)))); let operand = unpack!(block = this.as_operand(block, scope, expr)); block.and(Rvalue::Use(operand)) } diff --git a/compiler/rustc_mir_build/src/build/expr/into.rs b/compiler/rustc_mir_build/src/build/expr/into.rs index a268b0b46ff51..9dc596a345fe1 100644 --- a/compiler/rustc_mir_build/src/build/expr/into.rs +++ b/compiler/rustc_mir_build/src/build/expr/into.rs @@ -58,10 +58,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } ExprKind::NeverToAny { source } => { let source = this.hir.mirror(source); - let is_call = match source.kind { - ExprKind::Call { .. } | ExprKind::InlineAsm { .. } => true, - _ => false, - }; + let is_call = matches!(source.kind, ExprKind::Call { .. } | ExprKind::InlineAsm { .. }); // (#66975) Source could be a const of type `!`, so has to // exist in the generated MIR. diff --git a/compiler/rustc_mir_build/src/build/matches/test.rs b/compiler/rustc_mir_build/src/build/matches/test.rs index c41919001477e..7bea8220ada74 100644 --- a/compiler/rustc_mir_build/src/build/matches/test.rs +++ b/compiler/rustc_mir_build/src/build/matches/test.rs @@ -250,15 +250,13 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { place, ty, ); + } else if let [success, fail] = *make_target_blocks(self) { + assert_eq!(value.ty, ty); + let expect = self.literal_operand(test.span, value); + let val = Operand::Copy(place); + self.compare(block, success, fail, source_info, BinOp::Eq, expect, val); } else { - if let [success, fail] = *make_target_blocks(self) { - assert_eq!(value.ty, ty); - let expect = self.literal_operand(test.span, value); - let val = Operand::Copy(place); - self.compare(block, success, fail, source_info, BinOp::Eq, expect, val); - } else { - bug!("`TestKind::Eq` should have two target blocks"); - } + bug!("`TestKind::Eq` should have two target blocks"); } } diff --git a/compiler/rustc_mir_build/src/build/scope.rs b/compiler/rustc_mir_build/src/build/scope.rs index b6321c3bf6702..e91227d8357de 100644 --- a/compiler/rustc_mir_build/src/build/scope.rs +++ b/compiler/rustc_mir_build/src/build/scope.rs @@ -331,13 +331,11 @@ impl DropTree { } if let DropKind::Value = drop_data.0.kind { needs_block[drop_data.1] = Block::Own; - } else { - if drop_idx != ROOT_NODE { - match &mut needs_block[drop_data.1] { - pred @ Block::None => *pred = Block::Shares(drop_idx), - pred @ Block::Shares(_) => *pred = Block::Own, - Block::Own => (), - } + } else if drop_idx != ROOT_NODE { + match &mut needs_block[drop_data.1] { + pred @ Block::None => *pred = Block::Shares(drop_idx), + pred @ Block::Shares(_) => *pred = Block::Own, + Block::Own => (), } } } @@ -461,9 +459,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let breakable_scope = self.scopes.breakable_scopes.pop().unwrap(); assert!(breakable_scope.region_scope == region_scope); let break_block = self.build_exit_tree(breakable_scope.break_drops, None); - breakable_scope.continue_drops.map(|drops| { - self.build_exit_tree(drops, loop_block); - }); + if let Some(drops) = breakable_scope.continue_drops { self.build_exit_tree(drops, loop_block); } match (normal_exit_block, break_block) { (Some(block), None) | (None, Some(block)) => block, (None, None) => self.cfg.start_new_block().unit(), diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index 731bd954246ce..6ed7ed575fcb5 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -316,16 +316,14 @@ fn make_mirror_unadjusted<'a, 'tcx>( hir::ExprKind::Unary(hir::UnOp::UnNeg, ref arg) => { if cx.typeck_results().is_method_call(expr) { overloaded_operator(cx, expr, vec![arg.to_ref()]) - } else { - if let hir::ExprKind::Lit(ref lit) = arg.kind { - ExprKind::Literal { - literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, true), - user_ty: None, - const_id: None, - } - } else { - ExprKind::Unary { op: UnOp::Neg, arg: arg.to_ref() } + } else if let hir::ExprKind::Lit(ref lit) = arg.kind { + ExprKind::Literal { + literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, true), + user_ty: None, + const_id: None, } + } else { + ExprKind::Unary { op: UnOp::Neg, arg: arg.to_ref() } } } diff --git a/compiler/rustc_mir_build/src/thir/pattern/_match.rs b/compiler/rustc_mir_build/src/thir/pattern/_match.rs index 843a6c0e461f9..2da5ae574bbea 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/_match.rs @@ -337,10 +337,7 @@ impl<'tcx> PatternFolder<'tcx> for LiteralExpander { impl<'tcx> Pat<'tcx> { pub(super) fn is_wildcard(&self) -> bool { - match *self.kind { - PatKind::Binding { subpattern: None, .. } | PatKind::Wild => true, - _ => false, - } + matches!(*self.kind, PatKind::Binding { subpattern: None, .. } | PatKind::Wild) } } @@ -1358,10 +1355,7 @@ impl<'tcx> Usefulness<'tcx> { } fn is_useful(&self) -> bool { - match *self { - NotUseful => false, - _ => true, - } + !matches!(*self, NotUseful) } fn apply_constructor<'p>( @@ -1623,10 +1617,7 @@ struct IntRange<'tcx> { impl<'tcx> IntRange<'tcx> { #[inline] fn is_integral(ty: Ty<'_>) -> bool { - match ty.kind() { - ty::Char | ty::Int(_) | ty::Uint(_) | ty::Bool => true, - _ => false, - } + matches!(ty.kind(), ty::Char | ty::Int(_) | ty::Uint(_) | ty::Bool) } fn is_singleton(&self) -> bool { diff --git a/compiler/rustc_mir_build/src/thir/pattern/mod.rs b/compiler/rustc_mir_build/src/thir/pattern/mod.rs index 25e187243416d..3c746ac515393 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/mod.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/mod.rs @@ -223,10 +223,7 @@ impl<'tcx> fmt::Display for Pat<'tcx> { BindingMode::ByValue => mutability == Mutability::Mut, BindingMode::ByRef(bk) => { write!(f, "ref ")?; - match bk { - BorrowKind::Mut { .. } => true, - _ => false, - } + matches!(bk, BorrowKind::Mut { .. }) } }; if is_mut { diff --git a/compiler/rustc_parse/src/lib.rs b/compiler/rustc_parse/src/lib.rs index ba416be6b38d3..5c404161004a4 100644 --- a/compiler/rustc_parse/src/lib.rs +++ b/compiler/rustc_parse/src/lib.rs @@ -606,7 +606,7 @@ fn prepend_attrs( ) -> Option { let tokens = tokens?.clone().into_token_stream(); if attrs.is_empty() { - return Some(tokens.clone()); + return Some(tokens); } let mut builder = tokenstream::TokenStreamBuilder::new(); for attr in attrs { @@ -622,6 +622,6 @@ fn prepend_attrs( .into_token_stream(), ); } - builder.push(tokens.clone()); + builder.push(tokens); Some(builder.build()) } diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index f13a4329d3b6f..cd3b8db2303b3 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -1359,11 +1359,7 @@ impl<'a> Parser<'a> { (self.token == token::Lt && // `foo: true, - _ => false, - } && + matches!(node, ast::ExprKind::Path(..) | ast::ExprKind::Field(..)) && !self.token.is_reserved_ident() && // v `foo:bar(baz)` self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren)) || self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) // `foo:bar {` diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index 26492d92a77e9..48a635844fe70 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -376,21 +376,19 @@ impl<'a> Parser<'a> { format!(" {} ", kw), Applicability::MachineApplicable, ); + } else if let Ok(snippet) = self.span_to_snippet(ident_sp) { + err.span_suggestion( + full_sp, + "if you meant to call a macro, try", + format!("{}!", snippet), + // this is the `ambiguous` conditional branch + Applicability::MaybeIncorrect, + ); } else { - if let Ok(snippet) = self.span_to_snippet(ident_sp) { - err.span_suggestion( - full_sp, - "if you meant to call a macro, try", - format!("{}!", snippet), - // this is the `ambiguous` conditional branch - Applicability::MaybeIncorrect, - ); - } else { - err.help( - "if you meant to call a macro, remove the `pub` \ - and add a trailing `!` after the identifier", - ); - } + err.help( + "if you meant to call a macro, remove the `pub` \ + and add a trailing `!` after the identifier", + ); } Err(err) } else if self.look_ahead(1, |t| *t == token::Lt) { @@ -982,10 +980,7 @@ impl<'a> Parser<'a> { if token.is_keyword(kw::Move) { return true; } - match token.kind { - token::BinOp(token::Or) | token::OrOr => true, - _ => false, - } + matches!(token.kind, token::BinOp(token::Or) | token::OrOr) }) } else { false diff --git a/compiler/rustc_parse/src/parser/nonterminal.rs b/compiler/rustc_parse/src/parser/nonterminal.rs index 98fb1c8292510..ab88362dad954 100644 --- a/compiler/rustc_parse/src/parser/nonterminal.rs +++ b/compiler/rustc_parse/src/parser/nonterminal.rs @@ -38,16 +38,13 @@ impl<'a> Parser<'a> { }, NonterminalKind::Block => match token.kind { token::OpenDelim(token::Brace) => true, - token::Interpolated(ref nt) => match **nt { - token::NtItem(_) + token::Interpolated(ref nt) => !matches!(**nt, token::NtItem(_) | token::NtPat(_) | token::NtTy(_) | token::NtIdent(..) | token::NtMeta(_) | token::NtPath(_) - | token::NtVis(_) => false, // none of these may start with '{'. - _ => true, - }, + | token::NtVis(_)), _ => false, }, NonterminalKind::Path | NonterminalKind::Meta => match token.kind { @@ -76,17 +73,14 @@ impl<'a> Parser<'a> { }, NonterminalKind::Lifetime => match token.kind { token::Lifetime(_) => true, - token::Interpolated(ref nt) => match **nt { - token::NtLifetime(_) | token::NtTT(_) => true, - _ => false, - }, + token::Interpolated(ref nt) => { + matches!(**nt, token::NtLifetime(_) | token::NtTT(_)) + } _ => false, }, - NonterminalKind::TT | NonterminalKind::Item | NonterminalKind::Stmt => match token.kind - { - token::CloseDelim(_) => false, - _ => true, - }, + NonterminalKind::TT | NonterminalKind::Item | NonterminalKind::Stmt => { + !matches!(token.kind, token::CloseDelim(_)) + } } } diff --git a/compiler/rustc_parse/src/parser/pat.rs b/compiler/rustc_parse/src/parser/pat.rs index 27fe75a23b6a8..93a23e3a91aa0 100644 --- a/compiler/rustc_parse/src/parser/pat.rs +++ b/compiler/rustc_parse/src/parser/pat.rs @@ -149,8 +149,10 @@ impl<'a> Parser<'a> { /// Note that there are more tokens such as `@` for which we know that the `|` /// is an illegal parse. However, the user's intent is less clear in that case. fn recover_trailing_vert(&mut self, lo: Option) -> bool { - let is_end_ahead = self.look_ahead(1, |token| match &token.uninterpolate().kind { - token::FatArrow // e.g. `a | => 0,`. + let is_end_ahead = self.look_ahead(1, |token| { + matches!( + &token.uninterpolate().kind, + token::FatArrow // e.g. `a | => 0,`. | token::Ident(kw::If, false) // e.g. `a | if expr`. | token::Eq // e.g. `let a | = 0`. | token::Semi // e.g. `let a |;`. @@ -158,8 +160,8 @@ impl<'a> Parser<'a> { | token::Comma // e.g. `let (a |,)`. | token::CloseDelim(token::Bracket) // e.g. `let [a | ]`. | token::CloseDelim(token::Paren) // e.g. `let (a | )`. - | token::CloseDelim(token::Brace) => true, // e.g. `let A { f: a | }`. - _ => false, + | token::CloseDelim(token::Brace) + ) }); match (is_end_ahead, &self.token.kind) { (true, token::BinOp(token::Or) | token::OrOr) => { @@ -766,14 +768,11 @@ impl<'a> Parser<'a> { && !self.token.is_path_segment_keyword() // Avoid e.g. `Self` as it is a path. // Avoid `in`. Due to recovery in the list parser this messes with `for ( $pat in $expr )`. && !self.token.is_keyword(kw::In) - && self.look_ahead(1, |t| match t.kind { // Try to do something more complex? - token::OpenDelim(token::Paren) // A tuple struct pattern. + && self.look_ahead(1, |t| !matches!(t.kind, token::OpenDelim(token::Paren) // A tuple struct pattern. | token::OpenDelim(token::Brace) // A struct pattern. | token::DotDotDot | token::DotDotEq | token::DotDot // A range pattern. | token::ModSep // A tuple / struct variant pattern. - | token::Not => false, // A macro expanding to a pattern. - _ => true, - }) + | token::Not)) } /// Parses `ident` or `ident @ pat`. diff --git a/compiler/rustc_parse/src/parser/path.rs b/compiler/rustc_parse/src/parser/path.rs index 06760547eba0c..79e737490386c 100644 --- a/compiler/rustc_parse/src/parser/path.rs +++ b/compiler/rustc_parse/src/parser/path.rs @@ -187,12 +187,14 @@ impl<'a> Parser<'a> { pub(super) fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> { let ident = self.parse_path_segment_ident()?; - let is_args_start = |token: &Token| match token.kind { - token::Lt - | token::BinOp(token::Shl) - | token::OpenDelim(token::Paren) - | token::LArrow => true, - _ => false, + let is_args_start = |token: &Token| { + matches!( + token.kind, + token::Lt + | token::BinOp(token::Shl) + | token::OpenDelim(token::Paren) + | token::LArrow + ) }; let check_args_start = |this: &mut Self| { this.expected_tokens.extend_from_slice(&[ diff --git a/compiler/rustc_query_system/src/dep_graph/graph.rs b/compiler/rustc_query_system/src/dep_graph/graph.rs index 85335f0ba50c2..d9b687c48af01 100644 --- a/compiler/rustc_query_system/src/dep_graph/graph.rs +++ b/compiler/rustc_query_system/src/dep_graph/graph.rs @@ -292,10 +292,8 @@ impl DepGraph { ); data.colors.insert(prev_index, color); - } else { - if print_status { - eprintln!("[task::new] {:?}", key); - } + } else if print_status { + eprintln!("[task::new] {:?}", key); } (result, dep_node_index) diff --git a/compiler/rustc_query_system/src/query/plumbing.rs b/compiler/rustc_query_system/src/query/plumbing.rs index 50f443716f44b..426f5bb41d6f2 100644 --- a/compiler/rustc_query_system/src/query/plumbing.rs +++ b/compiler/rustc_query_system/src/query/plumbing.rs @@ -612,10 +612,8 @@ where prof_timer.finish_with_query_invocation_id(dep_node_index.into()); - if unlikely!(!diagnostics.is_empty()) { - if dep_node.kind != DepKind::NULL { - tcx.store_diagnostics(dep_node_index, diagnostics); - } + if unlikely!(!diagnostics.is_empty()) && dep_node.kind != DepKind::NULL { + tcx.store_diagnostics(dep_node_index, diagnostics); } let result = job.complete(result, dep_node_index); diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index feeea726f4c1b..d2d2a79374e22 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -344,10 +344,10 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { fn block_needs_anonymous_module(&mut self, block: &Block) -> bool { // If any statements are items, we need to create an anonymous module - block.stmts.iter().any(|statement| match statement.kind { - StmtKind::Item(_) | StmtKind::MacCall(_) => true, - _ => false, - }) + block + .stmts + .iter() + .any(|statement| matches!(statement.kind, StmtKind::Item(_) | StmtKind::MacCall(_))) } // Add an import to the current module. diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 33ab09a8f4280..6a915727ef178 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -922,15 +922,10 @@ impl<'a> Resolver<'a> { ); self.add_typo_suggestion(err, suggestion, ident.span); - let import_suggestions = self.lookup_import_candidates( - ident, - Namespace::MacroNS, - parent_scope, - |res| match res { - Res::Def(DefKind::Macro(MacroKind::Bang), _) => true, - _ => false, - }, - ); + let import_suggestions = + self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, |res| { + matches!(res, Res::Def(DefKind::Macro(MacroKind::Bang), _)) + }); show_candidates(err, None, &import_suggestions, false, true); if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) { @@ -1010,11 +1005,8 @@ impl<'a> Resolver<'a> { fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String { let res = b.res(); if b.span.is_dummy() { - let add_built_in = match b.res() { - // These already contain the "built-in" prefix or look bad with it. - Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod => false, - _ => true, - }; + let add_built_in = + !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod); let (built_in, from) = if from_prelude { ("", " from prelude") } else if b.is_extern_crate() @@ -1610,10 +1602,7 @@ fn find_span_immediately_after_crate_name( if *c == ':' { num_colons += 1; } - match c { - ':' if num_colons == 2 => false, - _ => true, - } + !matches!(c, ':' if num_colons == 2) }); // Find everything after the second colon.. `foo::{baz, makro};` let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1)); diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs index adff4542b0ff8..269d25be0a569 100644 --- a/compiler/rustc_resolve/src/imports.rs +++ b/compiler/rustc_resolve/src/imports.rs @@ -114,10 +114,7 @@ crate struct Import<'a> { impl<'a> Import<'a> { pub fn is_glob(&self) -> bool { - match self.kind { - ImportKind::Glob { .. } => true, - _ => false, - } + matches!(self.kind, ImportKind::Glob { .. }) } pub fn is_nested(&self) -> bool { @@ -898,12 +895,10 @@ impl<'a, 'b> ImportResolver<'a, 'b> { let msg = "inconsistent resolution for an import"; self.r.session.span_err(import.span, msg); } - } else { - if self.r.privacy_errors.is_empty() { - let msg = "cannot determine resolution for the import"; - let msg_note = "import resolution is stuck, try simplifying other imports"; - self.r.session.struct_span_err(import.span, msg).note(msg_note).emit(); - } + } else if self.r.privacy_errors.is_empty() { + let msg = "cannot determine resolution for the import"; + let msg_note = "import resolution is stuck, try simplifying other imports"; + self.r.session.struct_span_err(import.span, msg).note(msg_note).emit(); } module @@ -1044,19 +1039,14 @@ impl<'a, 'b> ImportResolver<'a, 'b> { if res != initial_res && this.ambiguity_errors.is_empty() { span_bug!(import.span, "inconsistent resolution for an import"); } - } else { - if res != Res::Err - && this.ambiguity_errors.is_empty() - && this.privacy_errors.is_empty() - { - let msg = "cannot determine resolution for the import"; - let msg_note = - "import resolution is stuck, try simplifying other imports"; - this.session - .struct_span_err(import.span, msg) - .note(msg_note) - .emit(); - } + } else if res != Res::Err + && this.ambiguity_errors.is_empty() + && this.privacy_errors.is_empty() + { + let msg = "cannot determine resolution for the import"; + let msg_note = + "import resolution is stuck, try simplifying other imports"; + this.session.struct_span_err(import.span, msg).note(msg_note).emit(); } } Err(..) => { diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index d323aebe59798..8d99d8f2455b8 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -257,16 +257,12 @@ impl<'a> PathSource<'a> { } fn is_call(self) -> bool { - match self { - PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })) => true, - _ => false, - } + matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. }))) } crate fn is_expected(self, res: Res) -> bool { match self { - PathSource::Type => match res { - Res::Def( + PathSource::Type => matches!(res, Res::Def( DefKind::Struct | DefKind::Union | DefKind::Enum @@ -280,19 +276,12 @@ impl<'a> PathSource<'a> { _, ) | Res::PrimTy(..) - | Res::SelfTy(..) => true, - _ => false, - }, - PathSource::Trait(AliasPossibility::No) => match res { - Res::Def(DefKind::Trait, _) => true, - _ => false, - }, - PathSource::Trait(AliasPossibility::Maybe) => match res { - Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => true, - _ => false, - }, - PathSource::Expr(..) => match res { - Res::Def( + | Res::SelfTy(..)), + PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)), + PathSource::Trait(AliasPossibility::Maybe) => { + matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) + } + PathSource::Expr(..) => matches!(res, Res::Def( DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn) | DefKind::Const | DefKind::Static @@ -303,23 +292,16 @@ impl<'a> PathSource<'a> { _, ) | Res::Local(..) - | Res::SelfCtor(..) => true, - _ => false, - }, - PathSource::Pat => match res { - Res::Def( + | Res::SelfCtor(..)), + PathSource::Pat => matches!(res, Res::Def( DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst, _, ) - | Res::SelfCtor(..) => true, - _ => false, - }, - PathSource::TupleStruct(..) => match res { - Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..) => true, - _ => false, - }, - PathSource::Struct => match res { - Res::Def( + | Res::SelfCtor(..)), + PathSource::TupleStruct(..) => { + matches!(res, Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..)) + } + PathSource::Struct => matches!(res, Res::Def( DefKind::Struct | DefKind::Union | DefKind::Variant @@ -327,9 +309,7 @@ impl<'a> PathSource<'a> { | DefKind::AssocTy, _, ) - | Res::SelfTy(..) => true, - _ => false, - }, + | Res::SelfTy(..)), PathSource::TraitItem(ns) => match res { Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true, Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true, @@ -1450,10 +1430,7 @@ impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> { } fn is_base_res_local(&self, nid: NodeId) -> bool { - match self.r.partial_res_map.get(&nid).map(|res| res.base_res()) { - Some(Res::Local(..)) => true, - _ => false, - } + matches!(self.r.partial_res_map.get(&nid).map(|res| res.base_res()), Some(Res::Local(..))) } /// Checks that all of the arms in an or-pattern have exactly the diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index cafceff4f29ed..7b355f7238f0e 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -702,10 +702,7 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> { _ => break, } } - let followed_by_brace = match sm.span_to_snippet(sp) { - Ok(ref snippet) if snippet == "{" => true, - _ => false, - }; + let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{"); // In case this could be a struct literal that needs to be surrounded // by parentheses, find the appropriate span. let mut i = 0; @@ -1788,12 +1785,11 @@ impl<'tcx> LifetimeContext<'_, 'tcx> { } msg = "consider introducing a named lifetime parameter".to_string(); should_break = true; - if let Some(param) = generics.params.iter().find(|p| match p.kind { - hir::GenericParamKind::Type { + if let Some(param) = generics.params.iter().find(|p| { + !matches!(p.kind, hir::GenericParamKind::Type { synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), .. - } => false, - _ => true, + }) }) { (param.span.shrink_to_lo(), "'a, ".to_string()) } else { diff --git a/compiler/rustc_resolve/src/late/lifetimes.rs b/compiler/rustc_resolve/src/late/lifetimes.rs index 072fb509b192a..c79d670737edd 100644 --- a/compiler/rustc_resolve/src/late/lifetimes.rs +++ b/compiler/rustc_resolve/src/late/lifetimes.rs @@ -351,10 +351,7 @@ fn krate(tcx: TyCtxt<'_>) -> NamedRegionMap { /// We have to account for this when computing the index of the other generic parameters. /// This function returns whether there is such an implicit parameter defined on the given item. fn sub_items_have_self_param(node: &hir::ItemKind<'_>) -> bool { - match *node { - hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => true, - _ => false, - } + matches!(*node, hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..)) } impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { @@ -417,10 +414,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { // Impls permit `'_` to be used and it is equivalent to "some fresh lifetime name". // This is not true for other kinds of items.x - let track_lifetime_uses = match item.kind { - hir::ItemKind::Impl { .. } => true, - _ => false, - }; + let track_lifetime_uses = matches!(item.kind, hir::ItemKind::Impl { .. }); // These kinds of items have only early-bound lifetime parameters. let mut index = if sub_items_have_self_param(&item.kind) { 1 // Self comes before lifetimes @@ -970,10 +964,10 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let trait_ref_hack = take(&mut self.trait_ref_hack); if !trait_ref_hack - || trait_ref.bound_generic_params.iter().any(|param| match param.kind { - GenericParamKind::Lifetime { .. } => true, - _ => false, - }) + || trait_ref + .bound_generic_params + .iter() + .any(|param| matches!(param.kind, GenericParamKind::Lifetime { .. })) { if trait_ref_hack { struct_span_err!( @@ -1384,18 +1378,16 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } if in_band { Some(param.span) + } else if generics.params.len() == 1 { + // if sole lifetime, remove the entire `<>` brackets + Some(generics.span) } else { - if generics.params.len() == 1 { - // if sole lifetime, remove the entire `<>` brackets - Some(generics.span) + // if removing within `<>` brackets, we also want to + // delete a leading or trailing comma as appropriate + if i >= generics.params.len() - 1 { + Some(generics.params[i - 1].span.shrink_to_hi().to(param.span)) } else { - // if removing within `<>` brackets, we also want to - // delete a leading or trailing comma as appropriate - if i >= generics.params.len() - 1 { - Some(generics.params[i - 1].span.shrink_to_hi().to(param.span)) - } else { - Some(param.span.to(generics.params[i + 1].span.shrink_to_lo())) - } + Some(param.span.to(generics.params[i + 1].span.shrink_to_lo())) } } } else { @@ -2047,10 +2039,8 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { // // This is intended to leave room for us to implement the // correct behavior in the future. - let has_lifetime_parameter = generic_args.args.iter().any(|arg| match arg { - GenericArg::Lifetime(_) => true, - _ => false, - }); + let has_lifetime_parameter = + generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_))); // Resolve lifetimes found in the type `XX` from `Item = XX` bindings. for b in generic_args.bindings { diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 902ee5f4d0936..30cd9944b1a2a 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -313,17 +313,17 @@ impl<'tcx> Visitor<'tcx> for UsePlacementFinder { ItemKind::ExternCrate(_) => {} // but place them before the first other item _ => { - if self.span.map_or(true, |span| item.span < span) { - if !item.span.from_expansion() { - // don't insert between attributes and an item - if item.attrs.is_empty() { - self.span = Some(item.span.shrink_to_lo()); - } else { - // find the first attribute on the item - for attr in &item.attrs { - if self.span.map_or(true, |span| attr.span < span) { - self.span = Some(attr.span.shrink_to_lo()); - } + if self.span.map_or(true, |span| item.span < span) + && !item.span.from_expansion() + { + // don't insert between attributes and an item + if item.attrs.is_empty() { + self.span = Some(item.span.shrink_to_lo()); + } else { + // find the first attribute on the item + for attr in &item.attrs { + if self.span.map_or(true, |span| attr.span < span) { + self.span = Some(attr.span.shrink_to_lo()); } } } @@ -558,17 +558,11 @@ impl<'a> ModuleData<'a> { // `self` resolves to the first module ancestor that `is_normal`. fn is_normal(&self) -> bool { - match self.kind { - ModuleKind::Def(DefKind::Mod, _, _) => true, - _ => false, - } + matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _)) } fn is_trait(&self) -> bool { - match self.kind { - ModuleKind::Def(DefKind::Trait, _, _) => true, - _ => false, - } + matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _)) } fn nearest_item_scope(&'a self) -> Module<'a> { @@ -628,10 +622,7 @@ enum NameBindingKind<'a> { impl<'a> NameBindingKind<'a> { /// Is this a name binding of a import? fn is_import(&self) -> bool { - match *self { - NameBindingKind::Import { .. } => true, - _ => false, - } + matches!(*self, NameBindingKind::Import { .. }) } } @@ -750,13 +741,10 @@ impl<'a> NameBinding<'a> { } fn is_variant(&self) -> bool { - match self.kind { - NameBindingKind::Res( + matches!(self.kind, NameBindingKind::Res( Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _), _, - ) => true, - _ => false, - } + )) } fn is_extern_crate(&self) -> bool { @@ -774,10 +762,7 @@ impl<'a> NameBinding<'a> { } fn is_import(&self) -> bool { - match self.kind { - NameBindingKind::Import { .. } => true, - _ => false, - } + matches!(self.kind, NameBindingKind::Import { .. }) } fn is_glob_import(&self) -> bool { @@ -788,17 +773,14 @@ impl<'a> NameBinding<'a> { } fn is_importable(&self) -> bool { - match self.res() { - Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _) => false, - _ => true, - } + !matches!( + self.res(), + Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _) + ) } fn is_macro_def(&self) -> bool { - match self.kind { - NameBindingKind::Res(Res::Def(DefKind::Macro(..), _), _) => true, - _ => false, - } + matches!(self.kind, NameBindingKind::Res(Res::Def(DefKind::Macro(..), _), _)) } fn macro_kind(&self) -> Option { @@ -1380,7 +1362,7 @@ impl<'a> Resolver<'a> { let maybe_unused_extern_crates = self.maybe_unused_extern_crates; let glob_map = self.glob_map; ResolverOutputs { - definitions: definitions, + definitions, cstore: Box::new(self.crate_loader.into_cstore()), visibilities, extern_crate_map, @@ -1992,11 +1974,12 @@ impl<'a> Resolver<'a> { // The macro is a proc macro derive if let Some(def_id) = module.expansion.expn_data().macro_def_id { if let Some(ext) = self.get_macro_by_def_id(def_id) { - if !ext.is_builtin && ext.macro_kind() == MacroKind::Derive { - if parent.expansion.outer_expn_is_descendant_of(span.ctxt()) { - *poisoned = Some(node_id); - return module.parent; - } + if !ext.is_builtin + && ext.macro_kind() == MacroKind::Derive + && parent.expansion.outer_expn_is_descendant_of(span.ctxt()) + { + *poisoned = Some(node_id); + return module.parent; } } } @@ -2390,10 +2373,7 @@ impl<'a> Resolver<'a> { _ => None, }; let (label, suggestion) = if module_res == self.graph_root.res() { - let is_mod = |res| match res { - Res::Def(DefKind::Mod, _) => true, - _ => false, - }; + let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _)); // Don't look up import candidates if this is a speculative resolve let mut candidates = if record_used { self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod) diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index f33bebf99d6e1..b632bfbed301c 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -2057,10 +2057,7 @@ impl PpMode { pub fn needs_analysis(&self) -> bool { use PpMode::*; - match *self { - PpmMir | PpmMirCFG => true, - _ => false, - } + matches!(*self, PpmMir | PpmMirCFG) } } diff --git a/compiler/rustc_session/src/output.rs b/compiler/rustc_session/src/output.rs index 0766c55da7431..130c3a061228b 100644 --- a/compiler/rustc_session/src/output.rs +++ b/compiler/rustc_session/src/output.rs @@ -199,10 +199,8 @@ pub fn invalid_output_for_target(sess: &Session, crate_type: CrateType) -> bool _ => {} } } - if !sess.target.options.executables { - if crate_type == CrateType::Executable { - return true; - } + if !sess.target.options.executables && crate_type == CrateType::Executable { + return true; } false diff --git a/compiler/rustc_symbol_mangling/src/legacy.rs b/compiler/rustc_symbol_mangling/src/legacy.rs index 2c9caf73b8e42..e8d470297ea6c 100644 --- a/compiler/rustc_symbol_mangling/src/legacy.rs +++ b/compiler/rustc_symbol_mangling/src/legacy.rs @@ -326,10 +326,8 @@ impl Printer<'tcx> for SymbolPrinter<'tcx> { ) -> Result { self = print_prefix(self)?; - let args = args.iter().cloned().filter(|arg| match arg.unpack() { - GenericArgKind::Lifetime(_) => false, - _ => true, - }); + let args = + args.iter().cloned().filter(|arg| !matches!(arg.unpack(), GenericArgKind::Lifetime(_))); if args.clone().next().is_some() { self.generic_delimiters(|cx| cx.comma_sep(args)) diff --git a/compiler/rustc_symbol_mangling/src/lib.rs b/compiler/rustc_symbol_mangling/src/lib.rs index 28b4a78929e59..10245d21b63a5 100644 --- a/compiler/rustc_symbol_mangling/src/lib.rs +++ b/compiler/rustc_symbol_mangling/src/lib.rs @@ -174,10 +174,7 @@ fn compute_symbol_name( return tcx.sess.generate_proc_macro_decls_symbol(disambiguator); } let hir_id = tcx.hir().local_def_id_to_hir_id(def_id); - match tcx.hir().get(hir_id) { - Node::ForeignItem(_) => true, - _ => false, - } + matches!(tcx.hir().get(hir_id), Node::ForeignItem(_)) } else { tcx.is_foreign_item(def_id) }; @@ -200,15 +197,14 @@ fn compute_symbol_name( // show up in the `wasm-import-name` custom attribute in LLVM IR. // // [1]: https://bugs.llvm.org/show_bug.cgi?id=44316 - if is_foreign { - if tcx.sess.target.arch != "wasm32" - || !tcx.wasm_import_module_map(def_id.krate).contains_key(&def_id) - { - if let Some(name) = attrs.link_name { - return name.to_string(); - } - return tcx.item_name(def_id).to_string(); + if is_foreign + && (tcx.sess.target.arch != "wasm32" + || !tcx.wasm_import_module_map(def_id.krate).contains_key(&def_id)) + { + if let Some(name) = attrs.link_name { + return name.to_string(); } + return tcx.item_name(def_id).to_string(); } if let Some(name) = attrs.export_name { @@ -234,10 +230,7 @@ fn compute_symbol_name( // codegen units) then this symbol may become an exported (but hidden // visibility) symbol. This means that multiple crates may do the same // and we want to be sure to avoid any symbol conflicts here. - match MonoItem::Fn(instance).instantiation_mode(tcx) { - InstantiationMode::GloballyShared { may_conflict: true } => true, - _ => false, - }; + matches!(MonoItem::Fn(instance).instantiation_mode(tcx), InstantiationMode::GloballyShared { may_conflict: true }); let instantiating_crate = if avoid_cross_crate_conflicts { Some(compute_instantiating_crate()) } else { None }; diff --git a/compiler/rustc_target/src/abi/call/mod.rs b/compiler/rustc_target/src/abi/call/mod.rs index 8f7e2bba5aa6d..507ae10877b85 100644 --- a/compiler/rustc_target/src/abi/call/mod.rs +++ b/compiler/rustc_target/src/abi/call/mod.rs @@ -474,31 +474,19 @@ impl<'a, Ty> ArgAbi<'a, Ty> { } pub fn is_indirect(&self) -> bool { - match self.mode { - PassMode::Indirect(..) => true, - _ => false, - } + matches!(self.mode, PassMode::Indirect(..)) } pub fn is_sized_indirect(&self) -> bool { - match self.mode { - PassMode::Indirect(_, None) => true, - _ => false, - } + matches!(self.mode, PassMode::Indirect(_, None)) } pub fn is_unsized_indirect(&self) -> bool { - match self.mode { - PassMode::Indirect(_, Some(_)) => true, - _ => false, - } + matches!(self.mode, PassMode::Indirect(_, Some(_))) } pub fn is_ignore(&self) -> bool { - match self.mode { - PassMode::Ignore => true, - _ => false, - } + matches!(self.mode, PassMode::Ignore) } } diff --git a/compiler/rustc_target/src/abi/call/riscv.rs b/compiler/rustc_target/src/abi/call/riscv.rs index 2e10bed3bd451..47530eeacd0cd 100644 --- a/compiler/rustc_target/src/abi/call/riscv.rs +++ b/compiler/rustc_target/src/abi/call/riscv.rs @@ -333,10 +333,8 @@ where let mut avail_gprs = 8; let mut avail_fprs = 8; - if !fn_abi.ret.is_ignore() { - if classify_ret(cx, &mut fn_abi.ret, xlen, flen) { - avail_gprs -= 1; - } + if !fn_abi.ret.is_ignore() && classify_ret(cx, &mut fn_abi.ret, xlen, flen) { + avail_gprs -= 1; } for (i, arg) in fn_abi.args.iter_mut().enumerate() { diff --git a/compiler/rustc_target/src/abi/call/wasm32.rs b/compiler/rustc_target/src/abi/call/wasm32.rs index 510f671a501e1..ff2c0e9bb6fcc 100644 --- a/compiler/rustc_target/src/abi/call/wasm32.rs +++ b/compiler/rustc_target/src/abi/call/wasm32.rs @@ -24,10 +24,8 @@ where C: LayoutOf> + HasDataLayout, { ret.extend_integer_width_to(32); - if ret.layout.is_aggregate() { - if !unwrap_trivial_aggregate(cx, ret) { - ret.make_indirect(); - } + if ret.layout.is_aggregate() && !unwrap_trivial_aggregate(cx, ret) { + ret.make_indirect(); } } @@ -37,10 +35,8 @@ where C: LayoutOf> + HasDataLayout, { arg.extend_integer_width_to(32); - if arg.layout.is_aggregate() { - if !unwrap_trivial_aggregate(cx, arg) { - arg.make_indirect_byval(); - } + if arg.layout.is_aggregate() && !unwrap_trivial_aggregate(cx, arg) { + arg.make_indirect_byval(); } } diff --git a/compiler/rustc_target/src/abi/mod.rs b/compiler/rustc_target/src/abi/mod.rs index 047b8cf5cdbe8..5c87a8f6b3d26 100644 --- a/compiler/rustc_target/src/abi/mod.rs +++ b/compiler/rustc_target/src/abi/mod.rs @@ -557,17 +557,11 @@ impl Primitive { } pub fn is_float(self) -> bool { - match self { - F32 | F64 => true, - _ => false, - } + matches!(self, F32 | F64) } pub fn is_int(self) -> bool { - match self { - Int(..) => true, - _ => false, - } + matches!(self, Int(..)) } } @@ -794,18 +788,12 @@ impl Abi { /// Returns `true` if this is an uninhabited type pub fn is_uninhabited(&self) -> bool { - match *self { - Abi::Uninhabited => true, - _ => false, - } + matches!(*self, Abi::Uninhabited) } /// Returns `true` is this is a scalar type pub fn is_scalar(&self) -> bool { - match *self { - Abi::Scalar(_) => true, - _ => false, - } + matches!(*self, Abi::Scalar(_)) } } diff --git a/compiler/rustc_target/src/asm/mod.rs b/compiler/rustc_target/src/asm/mod.rs index 0d691dc441eb1..8e60085262afd 100644 --- a/compiler/rustc_target/src/asm/mod.rs +++ b/compiler/rustc_target/src/asm/mod.rs @@ -478,10 +478,7 @@ pub enum InlineAsmType { impl InlineAsmType { pub fn is_integer(self) -> bool { - match self { - Self::I8 | Self::I16 | Self::I32 | Self::I64 | Self::I128 => true, - _ => false, - } + matches!(self, Self::I8 | Self::I16 | Self::I32 | Self::I64 | Self::I128) } pub fn size(self) -> Size { From 5339bd1ebeb76ea7304ff07dcf8e6c317ba0ced8 Mon Sep 17 00:00:00 2001 From: Joshua Nelson Date: Tue, 27 Oct 2020 10:55:26 -0400 Subject: [PATCH 3/3] Add back missing comments --- compiler/rustc_lexer/src/lib.rs | 1 + compiler/rustc_parse/src/parser/pat.rs | 5 +++-- compiler/rustc_resolve/src/diagnostics.rs | 1 + 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_lexer/src/lib.rs b/compiler/rustc_lexer/src/lib.rs index 84ae2e9dd7133..6539419aefb27 100644 --- a/compiler/rustc_lexer/src/lib.rs +++ b/compiler/rustc_lexer/src/lib.rs @@ -240,6 +240,7 @@ pub fn is_whitespace(c: char) -> bool { matches!( c, + // Usual ASCII suspects '\u{0009}' // \t | '\u{000A}' // \n | '\u{000B}' // vertical tab diff --git a/compiler/rustc_parse/src/parser/pat.rs b/compiler/rustc_parse/src/parser/pat.rs index 93a23e3a91aa0..196790a0ab323 100644 --- a/compiler/rustc_parse/src/parser/pat.rs +++ b/compiler/rustc_parse/src/parser/pat.rs @@ -160,7 +160,7 @@ impl<'a> Parser<'a> { | token::Comma // e.g. `let (a |,)`. | token::CloseDelim(token::Bracket) // e.g. `let [a | ]`. | token::CloseDelim(token::Paren) // e.g. `let (a | )`. - | token::CloseDelim(token::Brace) + | token::CloseDelim(token::Brace) // e.g. `let A { f: a | }`. ) }); match (is_end_ahead, &self.token.kind) { @@ -768,11 +768,12 @@ impl<'a> Parser<'a> { && !self.token.is_path_segment_keyword() // Avoid e.g. `Self` as it is a path. // Avoid `in`. Due to recovery in the list parser this messes with `for ( $pat in $expr )`. && !self.token.is_keyword(kw::In) + // Try to do something more complex? && self.look_ahead(1, |t| !matches!(t.kind, token::OpenDelim(token::Paren) // A tuple struct pattern. | token::OpenDelim(token::Brace) // A struct pattern. | token::DotDotDot | token::DotDotEq | token::DotDot // A range pattern. | token::ModSep // A tuple / struct variant pattern. - | token::Not)) + | token::Not)) // A macro expanding to a pattern. } /// Parses `ident` or `ident @ pat`. diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 6a915727ef178..4e115c62c9ef8 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -1005,6 +1005,7 @@ impl<'a> Resolver<'a> { fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String { let res = b.res(); if b.span.is_dummy() { + // These already contain the "built-in" prefix or look bad with it. let add_built_in = !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod); let (built_in, from) = if from_prelude {