From 9bba047c2e425fce03b039bcb8ccd60ddcbc80a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sun, 22 Mar 2020 13:36:56 +0100 Subject: [PATCH] Use if let instead of match when only matching a single variant (clippy::single_match) Makes code more compact and reduces nestig. --- src/librustc_ast_lowering/item.rs | 17 +- src/librustc_ast_passes/feature_gate.rs | 14 +- src/librustc_ast_pretty/pprust.rs | 31 ++-- src/librustc_builtin_macros/format_foreign.rs | 12 +- .../debuginfo/metadata.rs | 18 +- src/librustc_driver/pretty.rs | 30 ++-- src/librustc_errors/emitter.rs | 38 ++-- src/librustc_expand/mbe/macro_rules.rs | 25 ++- src/librustc_hir_pretty/lib.rs | 25 +-- .../infer/error_reporting/mod.rs | 162 +++++++++--------- .../trait_impl_difference.rs | 35 ++-- src/librustc_lint/builtin.rs | 68 ++++---- src/librustc_lint/context.rs | 5 +- src/librustc_lint/internal.rs | 17 +- src/librustc_lint/unused.rs | 9 +- src/librustc_metadata/rmeta/encoder.rs | 9 +- .../mir/interpret/allocation.rs | 16 +- src/librustc_middle/ty/layout.rs | 7 +- src/librustc_middle/ty/print/pretty.rs | 31 ++-- .../diagnostics/conflict_errors.rs | 13 +- .../diagnostics/explain_borrow.rs | 37 ++-- .../diagnostics/mutability_errors.rs | 102 ++++++----- src/librustc_mir/borrow_check/used_muts.rs | 15 +- .../dataflow/framework/graphviz.rs | 36 ++-- src/librustc_mir/dataflow/impls/mod.rs | 21 +-- .../dataflow/move_paths/builder.rs | 9 +- .../interpret/intrinsics/type_name.rs | 5 +- src/librustc_mir/interpret/operator.rs | 9 +- src/librustc_mir/monomorphize/collector.rs | 9 +- src/librustc_mir/transform/check_unsafety.rs | 60 ++++--- src/librustc_mir/transform/generator.rs | 7 +- src/librustc_mir/transform/promote_consts.rs | 26 ++- .../transform/remove_noop_landing_pads.rs | 15 +- src/librustc_mir/util/pretty.rs | 8 +- src/librustc_mir_build/hair/pattern/_match.rs | 20 +-- src/librustc_mir_build/hair/pattern/mod.rs | 19 +- src/librustc_passes/dead.rs | 9 +- src/librustc_privacy/lib.rs | 68 ++++---- src/librustc_save_analysis/dump_visitor.rs | 7 +- src/librustc_symbol_mangling/legacy.rs | 5 +- src/librustc_target/abi/call/riscv.rs | 21 +-- .../traits/auto_trait.rs | 155 ++++++++--------- .../error_reporting/on_unimplemented.rs | 7 +- src/librustc_trait_selection/traits/wf.rs | 15 +- src/librustc_typeck/astconv.rs | 8 +- src/librustc_typeck/check/method/confirm.rs | 11 +- src/librustc_typeck/check/method/suggest.rs | 33 ++-- src/librustc_typeck/check/writeback.rs | 23 ++- 48 files changed, 591 insertions(+), 751 deletions(-) diff --git a/src/librustc_ast_lowering/item.rs b/src/librustc_ast_lowering/item.rs index 740f62b41a584..b319ee76c819f 100644 --- a/src/librustc_ast_lowering/item.rs +++ b/src/librustc_ast_lowering/item.rs @@ -1332,17 +1332,14 @@ impl<'hir> LoweringContext<'_, 'hir> { self.resolver.definitions().as_local_node_id(def_id) { for param in &generics.params { - match param.kind { - GenericParamKind::Type { .. } => { - if node_id == param.id { - add_bounds - .entry(param.id) - .or_default() - .push(bound.clone()); - continue 'next_bound; - } + if let GenericParamKind::Type { .. } = param.kind { + if node_id == param.id { + add_bounds + .entry(param.id) + .or_default() + .push(bound.clone()); + continue 'next_bound; } - _ => {} } } } diff --git a/src/librustc_ast_passes/feature_gate.rs b/src/librustc_ast_passes/feature_gate.rs index a0d7b064d0ccf..76c790f80b86b 100644 --- a/src/librustc_ast_passes/feature_gate.rs +++ b/src/librustc_ast_passes/feature_gate.rs @@ -516,27 +516,25 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { } fn visit_generic_param(&mut self, param: &'a GenericParam) { - match param.kind { - GenericParamKind::Const { .. } => gate_feature_post!( + if let GenericParamKind::Const { .. } = param.kind { + gate_feature_post!( &self, const_generics, param.ident.span, "const generics are unstable" - ), - _ => {} + ) } visit::walk_generic_param(self, param) } fn visit_assoc_ty_constraint(&mut self, constraint: &'a AssocTyConstraint) { - match constraint.kind { - AssocTyConstraintKind::Bound { .. } => gate_feature_post!( + if let AssocTyConstraintKind::Bound { .. } = constraint.kind { + gate_feature_post!( &self, associated_type_bounds, constraint.span, "associated type bounds are unstable" - ), - _ => {} + ) } visit::walk_assoc_ty_constraint(self, constraint) } diff --git a/src/librustc_ast_pretty/pprust.rs b/src/librustc_ast_pretty/pprust.rs index 4aabbe7efbef4..6541ac156b487 100644 --- a/src/librustc_ast_pretty/pprust.rs +++ b/src/librustc_ast_pretty/pprust.rs @@ -637,9 +637,8 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere match tt { TokenTree::Token(ref token) => { self.word(token_to_string_ext(&token, convert_dollar_crate)); - match token.kind { - token::DocComment(..) => self.hardbreak(), - _ => {} + if let token::DocComment(..) = token.kind { + self.hardbreak() } } TokenTree::Delimited(dspan, delim, tts) => { @@ -1390,13 +1389,10 @@ impl<'a> State<'a> { self.print_visibility(&v.vis); let generics = ast::Generics::default(); self.print_struct(&v.data, &generics, v.ident, v.span, false); - match v.disr_expr { - Some(ref d) => { - self.s.space(); - self.word_space("="); - self.print_expr(&d.value) - } - _ => {} + if let Some(ref d) = v.disr_expr { + self.s.space(); + self.word_space("="); + self.print_expr(&d.value) } } @@ -2082,12 +2078,10 @@ impl<'a> State<'a> { } ast::ExprKind::Yield(ref e) => { self.s.word("yield"); - match *e { - Some(ref expr) => { - self.s.space(); - self.print_expr_maybe_paren(expr, parser::PREC_JUMP); - } - _ => (), + + if let Some(ref expr) = *e { + self.s.space(); + self.print_expr_maybe_paren(expr, parser::PREC_JUMP); } } ast::ExprKind::Try(ref e) => { @@ -2139,9 +2133,8 @@ impl<'a> State<'a> { self.s.word("::"); let item_segment = path.segments.last().unwrap(); self.print_ident(item_segment.ident); - match item_segment.args { - Some(ref args) => self.print_generic_args(args, colons_before_params), - None => {} + if let Some(ref args) = item_segment.args { + self.print_generic_args(args, colons_before_params) } } diff --git a/src/librustc_builtin_macros/format_foreign.rs b/src/librustc_builtin_macros/format_foreign.rs index e6a87e4d82586..6b0c9f1018b6c 100644 --- a/src/librustc_builtin_macros/format_foreign.rs +++ b/src/librustc_builtin_macros/format_foreign.rs @@ -27,11 +27,8 @@ pub mod printf { } pub fn set_position(&mut self, start: usize, end: usize) { - match self { - Substitution::Format(ref mut fmt) => { - fmt.position = InnerSpan::new(start, end); - } - _ => {} + if let Substitution::Format(ref mut fmt) = self { + fmt.position = InnerSpan::new(start, end); } } @@ -311,9 +308,8 @@ pub mod printf { let at = { let start = s.find('%')?; - match s[start + 1..].chars().next()? { - '%' => return Some((Substitution::Escape, &s[start + 2..])), - _ => { /* fall-through */ } + if let '%' = s[start + 1..].chars().next()? { + return Some((Substitution::Escape, &s[start + 2..])); } Cur::new_at(&s[..], start) diff --git a/src/librustc_codegen_llvm/debuginfo/metadata.rs b/src/librustc_codegen_llvm/debuginfo/metadata.rs index 20d07b2f8ce82..b90c7e51ccd69 100644 --- a/src/librustc_codegen_llvm/debuginfo/metadata.rs +++ b/src/librustc_codegen_llvm/debuginfo/metadata.rs @@ -1869,16 +1869,14 @@ fn prepare_enum_metadata( let layout = cx.layout_of(enum_type); - match (&layout.abi, &layout.variants) { - ( - &layout::Abi::Scalar(_), - &layout::Variants::Multiple { - discr_kind: layout::DiscriminantKind::Tag, - ref discr, - .. - }, - ) => return FinalMetadata(discriminant_type_metadata(discr.value)), - _ => {} + if let ( + &layout::Abi::Scalar(_), + &layout::Variants::Multiple { + discr_kind: layout::DiscriminantKind::Tag, ref discr, .. + }, + ) = (&layout.abi, &layout.variants) + { + return FinalMetadata(discriminant_type_metadata(discr.value)); } if use_enum_fallback(cx) { diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 2319760204a9e..87777bd674bf2 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -177,9 +177,8 @@ impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> { impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> { fn pre(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) { - match node { - pprust::AnnNode::Expr(_) => s.popen(), - _ => {} + if let pprust::AnnNode::Expr(_) = node { + s.popen(); } } fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) { @@ -232,9 +231,8 @@ impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> { } } fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) { - match node { - pprust_hir::AnnNode::Expr(_) => s.popen(), - _ => {} + if let pprust_hir::AnnNode::Expr(_) = node { + s.popen(); } } fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) { @@ -339,21 +337,17 @@ impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> { self.tables.set(old_tables); } fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) { - match node { - pprust_hir::AnnNode::Expr(_) => s.popen(), - _ => {} + if let pprust_hir::AnnNode::Expr(_) = node { + s.popen(); } } fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) { - match node { - pprust_hir::AnnNode::Expr(expr) => { - s.s.space(); - s.s.word("as"); - s.s.space(); - s.s.word(self.tables.get().expr_ty(expr).to_string()); - s.pclose(); - } - _ => {} + if let pprust_hir::AnnNode::Expr(expr) = node { + s.s.space(); + s.s.word("as"); + s.s.space(); + s.s.word(self.tables.get().expr_ty(expr).to_string()); + s.pclose(); } } } diff --git a/src/librustc_errors/emitter.rs b/src/librustc_errors/emitter.rs index 94053b98cd75b..3a7e108ddafa7 100644 --- a/src/librustc_errors/emitter.rs +++ b/src/librustc_errors/emitter.rs @@ -1719,7 +1719,7 @@ impl EmitterWriter { if !self.short_message { for child in children { let span = child.render_span.as_ref().unwrap_or(&child.span); - match self.emit_message_default( + if let Err(err) = self.emit_message_default( &span, &child.styled_message(), &None, @@ -1727,15 +1727,14 @@ impl EmitterWriter { max_line_num_len, true, ) { - Err(e) => panic!("failed to emit error: {}", e), - _ => (), + panic!("failed to emit error: {}", err); } } for sugg in suggestions { if sugg.style == SuggestionStyle::CompletelyHidden { // do not display this suggestion, it is meant only for tools } else if sugg.style == SuggestionStyle::HideCodeAlways { - match self.emit_message_default( + if let Err(e) = self.emit_message_default( &MultiSpan::new(), &[(sugg.msg.to_owned(), Style::HeaderMsg)], &None, @@ -1743,16 +1742,13 @@ impl EmitterWriter { max_line_num_len, true, ) { - Err(e) => panic!("failed to emit error: {}", e), - _ => (), + panic!("failed to emit error: {}", e); } - } else { - match self.emit_suggestion_default(sugg, &Level::Help, max_line_num_len) - { - Err(e) => panic!("failed to emit error: {}", e), - _ => (), - } - } + } else if let Err(e) = + self.emit_suggestion_default(sugg, &Level::Help, max_line_num_len) + { + panic!("failed to emit error: {}", e); + }; } } } @@ -1762,10 +1758,11 @@ impl EmitterWriter { let mut dst = self.dst.writable(); match writeln!(dst) { Err(e) => panic!("failed to emit error: {}", e), - _ => match dst.flush() { - Err(e) => panic!("failed to emit error: {}", e), - _ => (), - }, + _ => { + if let Err(e) = dst.flush() { + panic!("failed to emit error: {}", e) + } + } } } } @@ -2149,11 +2146,8 @@ impl<'a> Write for WritableDst<'a> { impl<'a> Drop for WritableDst<'a> { fn drop(&mut self) { - match *self { - WritableDst::Buffered(ref mut dst, ref mut buf) => { - drop(dst.print(buf)); - } - _ => {} + if let WritableDst::Buffered(ref mut dst, ref mut buf) = self { + drop(dst.print(buf)); } } } diff --git a/src/librustc_expand/mbe/macro_rules.rs b/src/librustc_expand/mbe/macro_rules.rs index 0e70fdbd9c146..7d2c4fbf7af32 100644 --- a/src/librustc_expand/mbe/macro_rules.rs +++ b/src/librustc_expand/mbe/macro_rules.rs @@ -354,20 +354,19 @@ fn generic_extension<'cx>( mbe::TokenTree::Delimited(_, ref delim) => &delim.tts[..], _ => continue, }; - match parse_tt(&mut Cow::Borrowed(&parser_from_cx(sess, arg.clone())), lhs_tt) { - Success(_) => { - if comma_span.is_dummy() { - err.note("you might be missing a comma"); - } else { - err.span_suggestion_short( - comma_span, - "missing comma here", - ", ".to_string(), - Applicability::MachineApplicable, - ); - } + if let Success(_) = + parse_tt(&mut Cow::Borrowed(&parser_from_cx(sess, arg.clone())), lhs_tt) + { + if comma_span.is_dummy() { + err.note("you might be missing a comma"); + } else { + err.span_suggestion_short( + comma_span, + "missing comma here", + ", ".to_string(), + Applicability::MachineApplicable, + ); } - _ => {} } } } diff --git a/src/librustc_hir_pretty/lib.rs b/src/librustc_hir_pretty/lib.rs index f30af78659f3b..8ba14ab5d0b5a 100644 --- a/src/librustc_hir_pretty/lib.rs +++ b/src/librustc_hir_pretty/lib.rs @@ -2036,13 +2036,10 @@ impl<'a> State<'a> { } GenericParamKind::Type { ref default, .. } => { self.print_bounds(":", param.bounds); - match default { - Some(default) => { - self.s.space(); - self.word_space("="); - self.print_type(&default) - } - _ => {} + if let Some(default) = default { + self.s.space(); + self.word_space("="); + self.print_type(&default) } } GenericParamKind::Const { ref ty } => { @@ -2145,9 +2142,8 @@ impl<'a> State<'a> { } self.end(); - match decl.output { - hir::FnRetTy::Return(ref output) => self.maybe_print_comment(output.span.lo()), - _ => {} + if let hir::FnRetTy::Return(ref output) = decl.output { + self.maybe_print_comment(output.span.lo()) } } @@ -2222,12 +2218,9 @@ impl<'a> State<'a> { } pub fn print_extern_opt_abi(&mut self, opt_abi: Option) { - match opt_abi { - Some(abi) => { - self.word_nbsp("extern"); - self.word_nbsp(abi.to_string()) - } - None => {} + if let Some(abi) = opt_abi { + self.word_nbsp("extern"); + self.word_nbsp(abi.to_string()) } } diff --git a/src/librustc_infer/infer/error_reporting/mod.rs b/src/librustc_infer/infer/error_reporting/mod.rs index 4ffdd94cca771..925f92edd7da9 100644 --- a/src/librustc_infer/infer/error_reporting/mod.rs +++ b/src/librustc_infer/infer/error_reporting/mod.rs @@ -1386,13 +1386,9 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { // For some types of errors, expected-found does not make // sense, so just ignore the values we were given. - match terr { - TypeError::CyclicTy(_) => { - values = None; - } - _ => {} + if let TypeError::CyclicTy(_) = terr { + values = None; } - struct OpaqueTypesVisitor<'tcx> { types: FxHashMap>, expected: FxHashMap>, @@ -1613,60 +1609,57 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { exp_found: &ty::error::ExpectedFound>, diag: &mut DiagnosticBuilder<'tcx>, ) { - match (&exp_found.expected.kind, &exp_found.found.kind) { - (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) => { - if let ty::Adt(found_def, found_substs) = found_ty.kind { - let path_str = format!("{:?}", exp_def); - if exp_def == &found_def { - let opt_msg = "you can convert from `&Option` to `Option<&T>` using \ + if let (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) = + (&exp_found.expected.kind, &exp_found.found.kind) + { + if let ty::Adt(found_def, found_substs) = found_ty.kind { + let path_str = format!("{:?}", exp_def); + if exp_def == &found_def { + let opt_msg = "you can convert from `&Option` to `Option<&T>` using \ `.as_ref()`"; - let result_msg = "you can convert from `&Result` to \ + let result_msg = "you can convert from `&Result` to \ `Result<&T, &E>` using `.as_ref()`"; - let have_as_ref = &[ - ("std::option::Option", opt_msg), - ("core::option::Option", opt_msg), - ("std::result::Result", result_msg), - ("core::result::Result", result_msg), - ]; - if let Some(msg) = have_as_ref - .iter() - .filter_map( - |(path, msg)| if &path_str == path { Some(msg) } else { None }, - ) - .next() - { - let mut show_suggestion = true; - for (exp_ty, found_ty) in exp_substs.types().zip(found_substs.types()) { - match exp_ty.kind { - ty::Ref(_, exp_ty, _) => { - match (&exp_ty.kind, &found_ty.kind) { - (_, ty::Param(_)) - | (_, ty::Infer(_)) - | (ty::Param(_), _) - | (ty::Infer(_), _) => {} - _ if ty::TyS::same_type(exp_ty, found_ty) => {} - _ => show_suggestion = false, - }; - } - ty::Param(_) | ty::Infer(_) => {} - _ => show_suggestion = false, + let have_as_ref = &[ + ("std::option::Option", opt_msg), + ("core::option::Option", opt_msg), + ("std::result::Result", result_msg), + ("core::result::Result", result_msg), + ]; + if let Some(msg) = have_as_ref + .iter() + .filter_map(|(path, msg)| if &path_str == path { Some(msg) } else { None }) + .next() + { + let mut show_suggestion = true; + for (exp_ty, found_ty) in exp_substs.types().zip(found_substs.types()) { + match exp_ty.kind { + ty::Ref(_, exp_ty, _) => { + match (&exp_ty.kind, &found_ty.kind) { + (_, ty::Param(_)) + | (_, ty::Infer(_)) + | (ty::Param(_), _) + | (ty::Infer(_), _) => {} + _ if ty::TyS::same_type(exp_ty, found_ty) => {} + _ => show_suggestion = false, + }; } + ty::Param(_) | ty::Infer(_) => {} + _ => show_suggestion = false, } - if let (Ok(snippet), true) = - (self.tcx.sess.source_map().span_to_snippet(span), show_suggestion) - { - diag.span_suggestion( - span, - msg, - format!("{}.as_ref()", snippet), - Applicability::MachineApplicable, - ); - } + } + if let (Ok(snippet), true) = + (self.tcx.sess.source_map().span_to_snippet(span), show_suggestion) + { + diag.span_suggestion( + span, + msg, + format!("{}.as_ref()", snippet), + Applicability::MachineApplicable, + ); } } } } - _ => {} } } @@ -1955,42 +1948,41 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { "...", ); - match (&sup_origin, &sub_origin) { - (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) => { - debug!("report_sub_sup_conflict: var_origin={:?}", var_origin); - debug!("report_sub_sup_conflict: sub_region={:?}", sub_region); - debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin); - debug!("report_sub_sup_conflict: sup_region={:?}", sup_region); - debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin); - debug!("report_sub_sup_conflict: sup_trace={:?}", sup_trace); - debug!("report_sub_sup_conflict: sub_trace={:?}", sub_trace); - debug!("report_sub_sup_conflict: sup_trace.values={:?}", sup_trace.values); - debug!("report_sub_sup_conflict: sub_trace.values={:?}", sub_trace.values); - - if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) = - (self.values_str(&sup_trace.values), self.values_str(&sub_trace.values)) - { - if sub_expected == sup_expected && sub_found == sup_found { - note_and_explain_region( - self.tcx, - region_scope_tree, - &mut err, - "...but the lifetime must also be valid for ", - sub_region, - "...", - ); - err.span_note( - sup_trace.cause.span, - &format!("...so that the {}", sup_trace.cause.as_requirement_str()), - ); + if let (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) = + (&sup_origin, &sub_origin) + { + debug!("report_sub_sup_conflict: var_origin={:?}", var_origin); + debug!("report_sub_sup_conflict: sub_region={:?}", sub_region); + debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin); + debug!("report_sub_sup_conflict: sup_region={:?}", sup_region); + debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin); + debug!("report_sub_sup_conflict: sup_trace={:?}", sup_trace); + debug!("report_sub_sup_conflict: sub_trace={:?}", sub_trace); + debug!("report_sub_sup_conflict: sup_trace.values={:?}", sup_trace.values); + debug!("report_sub_sup_conflict: sub_trace.values={:?}", sub_trace.values); + + if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) = + (self.values_str(&sup_trace.values), self.values_str(&sub_trace.values)) + { + if sub_expected == sup_expected && sub_found == sup_found { + note_and_explain_region( + self.tcx, + region_scope_tree, + &mut err, + "...but the lifetime must also be valid for ", + sub_region, + "...", + ); + err.span_note( + sup_trace.cause.span, + &format!("...so that the {}", sup_trace.cause.as_requirement_str()), + ); - err.note_expected_found(&"", sup_expected, &"", sup_found); - err.emit(); - return; - } + err.note_expected_found(&"", sup_expected, &"", sup_found); + err.emit(); + return; } } - _ => {} } self.note_region_origin(&mut err, &sup_origin); diff --git a/src/librustc_infer/infer/error_reporting/nice_region_error/trait_impl_difference.rs b/src/librustc_infer/infer/error_reporting/nice_region_error/trait_impl_difference.rs index 7083e8e78faa6..a2cd54b48d520 100644 --- a/src/librustc_infer/infer/error_reporting/nice_region_error/trait_impl_difference.rs +++ b/src/librustc_infer/infer/error_reporting/nice_region_error/trait_impl_difference.rs @@ -22,26 +22,25 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { _sup, ) = error.clone() { - match (&sup_origin, &sub_origin) { - (&Subtype(ref sup_trace), &Subtype(ref sub_trace)) => { - if let ( - ValuePairs::Types(sub_expected_found), - ValuePairs::Types(sup_expected_found), - CompareImplMethodObligation { trait_item_def_id, .. }, - ) = (&sub_trace.values, &sup_trace.values, &sub_trace.cause.code) - { - if sup_expected_found == sub_expected_found { - self.emit_err( - var_origin.span(), - sub_expected_found.expected, - sub_expected_found.found, - self.tcx().def_span(*trait_item_def_id), - ); - return Some(ErrorReported); - } + if let (&Subtype(ref sup_trace), &Subtype(ref sub_trace)) = + (&sup_origin, &sub_origin) + { + if let ( + ValuePairs::Types(sub_expected_found), + ValuePairs::Types(sup_expected_found), + CompareImplMethodObligation { trait_item_def_id, .. }, + ) = (&sub_trace.values, &sup_trace.values, &sub_trace.cause.code) + { + if sup_expected_found == sub_expected_found { + self.emit_err( + var_origin.span(), + sub_expected_found.expected, + sub_expected_found.found, + self.tcx().def_span(*trait_item_def_id), + ); + return Some(ErrorReported); } } - _ => {} } } } diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index 937164fb55d9d..646febec72334 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -645,41 +645,35 @@ declare_lint_pass!( impl EarlyLintPass for AnonymousParameters { fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) { - match it.kind { - ast::AssocItemKind::Fn(_, ref sig, _, _) => { - for arg in sig.decl.inputs.iter() { - match arg.pat.kind { - ast::PatKind::Ident(_, ident, None) => { - if ident.name == kw::Invalid { - cx.struct_span_lint(ANONYMOUS_PARAMETERS, arg.pat.span, |lint| { - let ty_snip = cx.sess.source_map().span_to_snippet(arg.ty.span); - - let (ty_snip, appl) = if let Ok(ref snip) = ty_snip { - (snip.as_str(), Applicability::MachineApplicable) - } else { - ("", Applicability::HasPlaceholders) - }; + if let ast::AssocItemKind::Fn(_, ref sig, _, _) = it.kind { + for arg in sig.decl.inputs.iter() { + if let ast::PatKind::Ident(_, ident, None) = arg.pat.kind { + if ident.name == kw::Invalid { + cx.struct_span_lint(ANONYMOUS_PARAMETERS, arg.pat.span, |lint| { + let ty_snip = cx.sess.source_map().span_to_snippet(arg.ty.span); + + let (ty_snip, appl) = if let Ok(ref snip) = ty_snip { + (snip.as_str(), Applicability::MachineApplicable) + } else { + ("", Applicability::HasPlaceholders) + }; - lint.build( - "anonymous parameters are deprecated and will be \ + lint.build( + "anonymous parameters are deprecated and will be \ removed in the next edition.", - ) - .span_suggestion( - arg.pat.span, - "try naming the parameter or explicitly \ + ) + .span_suggestion( + arg.pat.span, + "try naming the parameter or explicitly \ ignoring it", - format!("_: {}", ty_snip), - appl, - ) - .emit(); - }) - } - } - _ => (), + format!("_: {}", ty_snip), + appl, + ) + .emit(); + }) } } } - _ => (), } } } @@ -887,18 +881,14 @@ declare_lint_pass!(MutableTransmutes => [MUTABLE_TRANSMUTES]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes { fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) { use rustc_target::spec::abi::Abi::RustIntrinsic; - - match get_transmute_from_to(cx, expr).map(|(ty1, ty2)| (&ty1.kind, &ty2.kind)) { - Some((&ty::Ref(_, _, from_mt), &ty::Ref(_, _, to_mt))) => { - if to_mt == hir::Mutability::Mut && from_mt == hir::Mutability::Not { - let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \ + if let Some((&ty::Ref(_, _, from_mt), &ty::Ref(_, _, to_mt))) = + get_transmute_from_to(cx, expr).map(|(ty1, ty2)| (&ty1.kind, &ty2.kind)) + { + if to_mt == hir::Mutability::Mut && from_mt == hir::Mutability::Not { + let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \ consider instead using an UnsafeCell"; - cx.struct_span_lint(MUTABLE_TRANSMUTES, expr.span, |lint| { - lint.build(msg).emit() - }); - } + cx.struct_span_lint(MUTABLE_TRANSMUTES, expr.span, |lint| lint.build(msg).emit()); } - _ => (), } fn get_transmute_from_to<'a, 'tcx>( diff --git a/src/librustc_lint/context.rs b/src/librustc_lint/context.rs index 4d644ce69eac2..12543cf83ddb2 100644 --- a/src/librustc_lint/context.rs +++ b/src/librustc_lint/context.rs @@ -787,9 +787,8 @@ impl<'a, 'tcx> LateContext<'a, 'tcx> { let mut path = print_prefix(self)?; // Skip `::{{constructor}}` on tuple/unit structs. - match disambiguated_data.data { - DefPathData::Ctor => return Ok(path), - _ => {} + if let DefPathData::Ctor = disambiguated_data.data { + return Ok(path); } path.push(disambiguated_data.data.as_symbol()); diff --git a/src/librustc_lint/internal.rs b/src/librustc_lint/internal.rs index d8c685f2b22ff..6de8fb45d223d 100644 --- a/src/librustc_lint/internal.rs +++ b/src/librustc_lint/internal.rs @@ -175,18 +175,15 @@ fn lint_ty_kind_usage(cx: &LateContext<'_, '_>, segment: &PathSegment<'_>) -> bo } fn is_ty_or_ty_ctxt(cx: &LateContext<'_, '_>, ty: &Ty<'_>) -> Option { - match &ty.kind { - TyKind::Path(qpath) => { - if let QPath::Resolved(_, path) = qpath { - let did = path.res.opt_def_id()?; - if cx.tcx.is_diagnostic_item(sym::Ty, did) { - return Some(format!("Ty{}", gen_args(path.segments.last().unwrap()))); - } else if cx.tcx.is_diagnostic_item(sym::TyCtxt, did) { - return Some(format!("TyCtxt{}", gen_args(path.segments.last().unwrap()))); - } + if let TyKind::Path(qpath) = &ty.kind { + if let QPath::Resolved(_, path) = qpath { + let did = path.res.opt_def_id()?; + if cx.tcx.is_diagnostic_item(sym::Ty, did) { + return Some(format!("Ty{}", gen_args(path.segments.last().unwrap()))); + } else if cx.tcx.is_diagnostic_item(sym::TyCtxt, did) { + return Some(format!("TyCtxt{}", gen_args(path.segments.last().unwrap()))); } } - _ => {} } None diff --git a/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs index d14a3f0ff0673..78a67ae6afe73 100644 --- a/src/librustc_lint/unused.rs +++ b/src/librustc_lint/unused.rs @@ -285,12 +285,9 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes { let attr_info = attr.ident().and_then(|ident| self.builtin_attributes.get(&ident.name)); if let Some(&&(name, ty, ..)) = attr_info { - match ty { - AttributeType::Whitelisted => { - debug!("{:?} is Whitelisted", name); - return; - } - _ => (), + if let AttributeType::Whitelisted = ty { + debug!("{:?} is Whitelisted", name); + return; } } diff --git a/src/librustc_metadata/rmeta/encoder.rs b/src/librustc_metadata/rmeta/encoder.rs index aeea7db9e9e8b..f6e2730cb5761 100644 --- a/src/librustc_metadata/rmeta/encoder.rs +++ b/src/librustc_metadata/rmeta/encoder.rs @@ -1623,12 +1623,9 @@ impl EncodeContext<'tcx> { } fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) { - match expr.kind { - hir::ExprKind::Closure(..) => { - let def_id = self.tcx.hir().local_def_id(expr.hir_id); - self.encode_info_for_closure(def_id); - } - _ => {} + if let hir::ExprKind::Closure(..) = expr.kind { + let def_id = self.tcx.hir().local_def_id(expr.hir_id); + self.encode_info_for_closure(def_id); } } diff --git a/src/librustc_middle/mir/interpret/allocation.rs b/src/librustc_middle/mir/interpret/allocation.rs index ada02ceb5cbf3..0e75f34629e0e 100644 --- a/src/librustc_middle/mir/interpret/allocation.rs +++ b/src/librustc_middle/mir/interpret/allocation.rs @@ -379,12 +379,9 @@ impl<'tcx, Tag: Copy, Extra: AllocationExtra> Allocation { // *Now*, we better make sure that the inside is free of relocations too. self.check_relocations(cx, ptr, size)?; } else { - match self.relocations.get(&ptr.offset) { - Some(&(tag, alloc_id)) => { - let ptr = Pointer::new_with_tag(alloc_id, Size::from_bytes(bits), tag); - return Ok(ScalarMaybeUndef::Scalar(ptr.into())); - } - None => {} + if let Some(&(tag, alloc_id)) = self.relocations.get(&ptr.offset) { + let ptr = Pointer::new_with_tag(alloc_id, Size::from_bytes(bits), tag); + return Ok(ScalarMaybeUndef::Scalar(ptr.into())); } } // We don't. Just return the bits. @@ -437,11 +434,8 @@ impl<'tcx, Tag: Copy, Extra: AllocationExtra> Allocation { write_target_uint(endian, dst, bytes).unwrap(); // See if we have to also write a relocation. - match val { - Scalar::Ptr(val) => { - self.relocations.insert(ptr.offset, (val.tag, val.alloc_id)); - } - _ => {} + if let Scalar::Ptr(val) = val { + self.relocations.insert(ptr.offset, (val.tag, val.alloc_id)); } Ok(()) diff --git a/src/librustc_middle/ty/layout.rs b/src/librustc_middle/ty/layout.rs index bfe9ed200a154..54fde52ba3a77 100644 --- a/src/librustc_middle/ty/layout.rs +++ b/src/librustc_middle/ty/layout.rs @@ -1356,11 +1356,8 @@ impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> { { let mut used_variants = BitSet::new_empty(info.variant_fields.len()); for assignment in &assignments { - match assignment { - Assigned(idx) => { - used_variants.insert(*idx); - } - _ => {} + if let Assigned(idx) = assignment { + used_variants.insert(*idx); } } if used_variants.count() < 2 { diff --git a/src/librustc_middle/ty/print/pretty.rs b/src/librustc_middle/ty/print/pretty.rs index 0993b738b44e8..5c365a57cd12d 100644 --- a/src/librustc_middle/ty/print/pretty.rs +++ b/src/librustc_middle/ty/print/pretty.rs @@ -318,18 +318,15 @@ pub trait PrettyPrinter<'tcx>: debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key); // For a constructor, we want the name of its parent rather than . - match cur_def_key.disambiguated_data.data { - DefPathData::Ctor => { - let parent = DefId { - krate: def_id.krate, - index: cur_def_key - .parent - .expect("`DefPathData::Ctor` / `VariantData` missing a parent"), - }; + if let DefPathData::Ctor = cur_def_key.disambiguated_data.data { + let parent = DefId { + krate: def_id.krate, + index: cur_def_key + .parent + .expect("`DefPathData::Ctor` / `VariantData` missing a parent"), + }; - cur_def_key = self.tcx().def_key(parent); - } - _ => {} + cur_def_key = self.tcx().def_key(parent); } let visible_parent = match visible_parent_map.get(&def_id).cloned() { @@ -1420,9 +1417,8 @@ impl Printer<'tcx> for FmtPrinter<'_, 'tcx, F> { self = print_prefix(self)?; // Skip `::{{constructor}}` on tuple/unit structs. - match disambiguated_data.data { - DefPathData::Ctor => return Ok(self), - _ => {} + if let DefPathData::Ctor = disambiguated_data.data { + return Ok(self); } // FIXME(eddyb) `name` should never be empty, but it @@ -1784,11 +1780,8 @@ impl FmtPrinter<'_, 'tcx, F> { struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet); impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> { fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool { - match *r { - ty::ReLateBound(_, ty::BrNamed(_, name)) => { - self.0.insert(name); - } - _ => {} + if let ty::ReLateBound(_, ty::BrNamed(_, name)) = *r { + self.0.insert(name); } r.super_visit_with(self) } diff --git a/src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs b/src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs index 428c3b44f630e..a4bed18dcef9b 100644 --- a/src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs +++ b/src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs @@ -549,14 +549,13 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { place: &Place<'tcx>, borrowed_place: &Place<'tcx>, ) { - match (&place.projection[..], &borrowed_place.projection[..]) { - ([ProjectionElem::Index(_)], [ProjectionElem::Index(_)]) => { - err.help( - "consider using `.split_at_mut(position)` or similar method to obtain \ + if let ([ProjectionElem::Index(_)], [ProjectionElem::Index(_)]) = + (&place.projection[..], &borrowed_place.projection[..]) + { + err.help( + "consider using `.split_at_mut(position)` or similar method to obtain \ two mutable non-overlapping sub-slices", - ); - } - _ => {} + ); } } diff --git a/src/librustc_mir/borrow_check/diagnostics/explain_borrow.rs b/src/librustc_mir/borrow_check/diagnostics/explain_borrow.rs index ca42ac805ec72..a3ab36b844390 100644 --- a/src/librustc_mir/borrow_check/diagnostics/explain_borrow.rs +++ b/src/librustc_mir/borrow_check/diagnostics/explain_borrow.rs @@ -227,29 +227,26 @@ impl BorrowExplanation { span: Span, region_name: &RegionName, ) { - match category { - ConstraintCategory::OpaqueType => { - if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(span) { - let suggestable_name = if region_name.was_named() { - region_name.to_string() - } else { - "'_".to_string() - }; + if let ConstraintCategory::OpaqueType = category { + if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(span) { + let suggestable_name = if region_name.was_named() { + region_name.to_string() + } else { + "'_".to_string() + }; - err.span_suggestion( - span, - &format!( - "you can add a bound to the {}to make it last less than \ + err.span_suggestion( + span, + &format!( + "you can add a bound to the {}to make it last less than \ `'static` and match `{}`", - category.description(), - region_name, - ), - format!("{} + {}", snippet, suggestable_name), - Applicability::Unspecified, - ); - } + category.description(), + region_name, + ), + format!("{} + {}", snippet, suggestable_name), + Applicability::Unspecified, + ); } - _ => {} } } } diff --git a/src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs b/src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs index 5d6d287b72a39..2fe72e1aa086a 100644 --- a/src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs +++ b/src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs @@ -497,62 +497,60 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { let mut look_at_return = true; // If we can detect the expression to be an `fn` call where the closure was an argument, // we point at the `fn` definition argument... - match node { - hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Call(func, args), .. }) => { - let arg_pos = args - .iter() - .enumerate() - .filter(|(_, arg)| arg.span == self.body.span) - .map(|(pos, _)| pos) - .next(); - let def_id = hir.local_def_id(item_id); - let tables = self.infcx.tcx.typeck_tables_of(def_id); - if let Some(ty::FnDef(def_id, _)) = - tables.node_type_opt(func.hir_id).as_ref().map(|ty| &ty.kind) - { - let arg = match hir.get_if_local(*def_id) { - Some(hir::Node::Item(hir::Item { - ident, - kind: hir::ItemKind::Fn(sig, ..), - .. - })) - | Some(hir::Node::TraitItem(hir::TraitItem { - ident, - kind: hir::TraitItemKind::Fn(sig, _), - .. - })) - | Some(hir::Node::ImplItem(hir::ImplItem { - ident, - kind: hir::ImplItemKind::Fn(sig, _), - .. - })) => Some( - arg_pos - .and_then(|pos| { - sig.decl.inputs.get( - pos + if sig.decl.implicit_self.has_implicit_self() { - 1 - } else { - 0 - }, - ) - }) - .map(|arg| arg.span) - .unwrap_or(ident.span), - ), - _ => None, - }; - if let Some(span) = arg { - err.span_label(span, "change this to accept `FnMut` instead of `Fn`"); - err.span_label(func.span, "expects `Fn` instead of `FnMut`"); - if self.infcx.tcx.sess.source_map().is_multiline(self.body.span) { - err.span_label(self.body.span, "in this closure"); - } - look_at_return = false; + if let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Call(func, args), .. }) = node { + let arg_pos = args + .iter() + .enumerate() + .filter(|(_, arg)| arg.span == self.body.span) + .map(|(pos, _)| pos) + .next(); + let def_id = hir.local_def_id(item_id); + let tables = self.infcx.tcx.typeck_tables_of(def_id); + if let Some(ty::FnDef(def_id, _)) = + tables.node_type_opt(func.hir_id).as_ref().map(|ty| &ty.kind) + { + let arg = match hir.get_if_local(*def_id) { + Some(hir::Node::Item(hir::Item { + ident, + kind: hir::ItemKind::Fn(sig, ..), + .. + })) + | Some(hir::Node::TraitItem(hir::TraitItem { + ident, + kind: hir::TraitItemKind::Fn(sig, _), + .. + })) + | Some(hir::Node::ImplItem(hir::ImplItem { + ident, + kind: hir::ImplItemKind::Fn(sig, _), + .. + })) => Some( + arg_pos + .and_then(|pos| { + sig.decl.inputs.get( + pos + if sig.decl.implicit_self.has_implicit_self() { + 1 + } else { + 0 + }, + ) + }) + .map(|arg| arg.span) + .unwrap_or(ident.span), + ), + _ => None, + }; + if let Some(span) = arg { + err.span_label(span, "change this to accept `FnMut` instead of `Fn`"); + err.span_label(func.span, "expects `Fn` instead of `FnMut`"); + if self.infcx.tcx.sess.source_map().is_multiline(self.body.span) { + err.span_label(self.body.span, "in this closure"); } + look_at_return = false; } } - _ => {} } + if look_at_return && hir.get_return_block(closure_id).is_some() { // ...otherwise we are probably in the tail expression of the function, point at the // return type. diff --git a/src/librustc_mir/borrow_check/used_muts.rs b/src/librustc_mir/borrow_check/used_muts.rs index 1197d3d50e464..eb1527b874ebe 100644 --- a/src/librustc_mir/borrow_check/used_muts.rs +++ b/src/librustc_mir/borrow_check/used_muts.rs @@ -76,16 +76,13 @@ impl<'visit, 'cx, 'tcx> Visitor<'tcx> for GatherUsedMutsVisitor<'visit, 'cx, 'tc } fn visit_statement(&mut self, statement: &Statement<'tcx>, _location: Location) { - match &statement.kind { - StatementKind::Assign(box (into, _)) => { - debug!( - "visit_statement: statement={:?} local={:?} \ + if let StatementKind::Assign(box (into, _)) = &statement.kind { + debug!( + "visit_statement: statement={:?} local={:?} \ never_initialized_mut_locals={:?}", - statement, into.local, self.never_initialized_mut_locals - ); - self.remove_never_initialized_mut_locals(into); - } - _ => {} + statement, into.local, self.never_initialized_mut_locals + ); + self.remove_never_initialized_mut_locals(into); } } diff --git a/src/librustc_mir/dataflow/framework/graphviz.rs b/src/librustc_mir/dataflow/framework/graphviz.rs index a85c428d3bfa4..bdd411213594e 100644 --- a/src/librustc_mir/dataflow/framework/graphviz.rs +++ b/src/librustc_mir/dataflow/framework/graphviz.rs @@ -229,26 +229,22 @@ where } // Write any changes caused by terminator-specific effects - match terminator.kind { - mir::TerminatorKind::Call { destination: Some(_), .. } => { - let num_state_columns = self.num_state_columns(); - self.write_row(w, "", "(on successful return)", |this, w, fmt| { - write!( - w, - r#""#, - colspan = num_state_columns, - fmt = fmt, - )?; - - let state_on_unwind = this.results.get().clone(); - this.results.seek_after_assume_success(terminator_loc); - write_diff(w, this.results.analysis(), &state_on_unwind, this.results.get())?; - - write!(w, "") - })?; - } - - _ => {} + if let mir::TerminatorKind::Call { destination: Some(_), .. } = terminator.kind { + let num_state_columns = self.num_state_columns(); + self.write_row(w, "", "(on successful return)", |this, w, fmt| { + write!( + w, + r#""#, + colspan = num_state_columns, + fmt = fmt, + )?; + + let state_on_unwind = this.results.get().clone(); + this.results.seek_after_assume_success(terminator_loc); + write_diff(w, this.results.analysis(), &state_on_unwind, this.results.get())?; + + write!(w, "") + })?; }; write!(w, "") diff --git a/src/librustc_mir/dataflow/impls/mod.rs b/src/librustc_mir/dataflow/impls/mod.rs index 3572d460274bc..3ffa771cb05a1 100644 --- a/src/librustc_mir/dataflow/impls/mod.rs +++ b/src/librustc_mir/dataflow/impls/mod.rs @@ -544,18 +544,15 @@ impl<'tcx> GenKillAnalysis<'tcx> for EverInitializedPlaces<'_, 'tcx> { ); trans.gen_all(init_loc_map[location].iter().copied()); - match stmt.kind { - mir::StatementKind::StorageDead(local) => { - // End inits for StorageDead, so that an immutable variable can - // be reinitialized on the next iteration of the loop. - let move_path_index = rev_lookup.find_local(local); - debug!( - "stmt {:?} at loc {:?} clears the ever initialized status of {:?}", - stmt, location, &init_path_map[move_path_index] - ); - trans.kill_all(init_path_map[move_path_index].iter().copied()); - } - _ => {} + if let mir::StatementKind::StorageDead(local) = stmt.kind { + // End inits for StorageDead, so that an immutable variable can + // be reinitialized on the next iteration of the loop. + let move_path_index = rev_lookup.find_local(local); + debug!( + "stmt {:?} at loc {:?} clears the ever initialized status of {:?}", + stmt, location, &init_path_map[move_path_index] + ); + trans.kill_all(init_path_map[move_path_index].iter().copied()); } } diff --git a/src/librustc_mir/dataflow/move_paths/builder.rs b/src/librustc_mir/dataflow/move_paths/builder.rs index 6918d165a2bc5..1f4455318a4cf 100644 --- a/src/librustc_mir/dataflow/move_paths/builder.rs +++ b/src/librustc_mir/dataflow/move_paths/builder.rs @@ -144,15 +144,16 @@ impl<'b, 'a, 'tcx> Gatherer<'b, 'a, 'tcx> { }, )); } - ty::Array(..) => match elem { - ProjectionElem::Index(..) => { + + ty::Array(..) => { + if let ProjectionElem::Index(..) = elem { return Err(MoveError::cannot_move_out_of( self.loc, InteriorOfSliceOrArray { ty: place_ty, is_index: true }, )); } - _ => {} - }, + } + _ => {} }; diff --git a/src/librustc_mir/interpret/intrinsics/type_name.rs b/src/librustc_mir/interpret/intrinsics/type_name.rs index 30dcb5deb35d8..b81a454cac408 100644 --- a/src/librustc_mir/interpret/intrinsics/type_name.rs +++ b/src/librustc_mir/interpret/intrinsics/type_name.rs @@ -129,9 +129,8 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> { self = print_prefix(self)?; // Skip `::{{constructor}}` on tuple/unit structs. - match disambiguated_data.data { - DefPathData::Ctor => return Ok(self), - _ => {} + if disambiguated_data.data == DefPathData::Ctor { + return Ok(self); } self.path.push_str("::"); diff --git a/src/librustc_mir/interpret/operator.rs b/src/librustc_mir/interpret/operator.rs index 42b4f62a08c61..e81cd8b3d00d7 100644 --- a/src/librustc_mir/interpret/operator.rs +++ b/src/librustc_mir/interpret/operator.rs @@ -198,13 +198,10 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // We need a special check for overflowing remainder: // "int_min % -1" overflows and returns 0, but after casting things to a larger int // type it does *not* overflow nor give an unrepresentable result! - match bin_op { - Rem => { - if r == -1 && l == (1 << (size.bits() - 1)) { - return Ok((Scalar::from_int(0, size), true, left_layout.ty)); - } + if bin_op == Rem { + if r == -1 && l == (1 << (size.bits() - 1)) { + return Ok((Scalar::from_int(0, size), true, left_layout.ty)); } - _ => {} } let l = self.sign_extend(l, left_layout) as i128; diff --git a/src/librustc_mir/monomorphize/collector.rs b/src/librustc_mir/monomorphize/collector.rs index 939a8d837b8be..1106eba104682 100644 --- a/src/librustc_mir/monomorphize/collector.rs +++ b/src/librustc_mir/monomorphize/collector.rs @@ -988,12 +988,9 @@ impl ItemLikeVisitor<'v> for RootCollector<'_, 'v> { } fn visit_impl_item(&mut self, ii: &'v hir::ImplItem<'v>) { - match ii.kind { - hir::ImplItemKind::Fn(hir::FnSig { .. }, _) => { - let def_id = self.tcx.hir().local_def_id(ii.hir_id); - self.push_if_root(def_id); - } - _ => { /* nothing to do here */ } + if let hir::ImplItemKind::Fn(hir::FnSig { .. }, _) = ii.kind { + let def_id = self.tcx.hir().local_def_id(ii.hir_id); + self.push_if_root(def_id); } } } diff --git a/src/librustc_mir/transform/check_unsafety.rs b/src/librustc_mir/transform/check_unsafety.rs index d22e0d513cf20..e0ff82b1e64f1 100644 --- a/src/librustc_mir/transform/check_unsafety.rs +++ b/src/librustc_mir/transform/check_unsafety.rs @@ -396,42 +396,40 @@ impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> { ProjectionElem::Field(..) => { let ty = Place::ty_from(place.local, proj_base, &self.body.local_decls, self.tcx).ty; - match ty.kind { - ty::Adt(def, _) => match self.tcx.layout_scalar_valid_range(def.did) { - (Bound::Unbounded, Bound::Unbounded) => {} - _ => { - let (description, details) = if is_mut_use { - ( - "mutation of layout constrained field", - "mutating layout constrained fields cannot statically be \ + if let ty::Adt(def, _) = ty.kind { + if self.tcx.layout_scalar_valid_range(def.did) + != (Bound::Unbounded, Bound::Unbounded) + { + let (description, details) = if is_mut_use { + ( + "mutation of layout constrained field", + "mutating layout constrained fields cannot statically be \ checked for valid values", - ) + ) - // Check `is_freeze` as late as possible to avoid cycle errors - // with opaque types. - } else if !place.ty(self.body, self.tcx).ty.is_freeze( - self.tcx, - self.param_env, - self.source_info.span, - ) { - ( - "borrow of layout constrained field with interior \ + // Check `is_freeze` as late as possible to avoid cycle errors + // with opaque types. + } else if !place.ty(self.body, self.tcx).ty.is_freeze( + self.tcx, + self.param_env, + self.source_info.span, + ) { + ( + "borrow of layout constrained field with interior \ mutability", - "references to fields of layout constrained fields \ + "references to fields of layout constrained fields \ lose the constraints. Coupled with interior mutability, \ the field can be changed to invalid values", - ) - } else { - continue; - }; - self.require_unsafe( - description, - details, - UnsafetyViolationKind::GeneralAndConstFn, - ); - } - }, - _ => {} + ) + } else { + continue; + }; + self.require_unsafe( + description, + details, + UnsafetyViolationKind::GeneralAndConstFn, + ); + } } } _ => {} diff --git a/src/librustc_mir/transform/generator.rs b/src/librustc_mir/transform/generator.rs index aa247a00849fc..230a835b910d2 100644 --- a/src/librustc_mir/transform/generator.rs +++ b/src/librustc_mir/transform/generator.rs @@ -675,10 +675,9 @@ impl dataflow::ResultsVisitor<'mir, 'tcx> for StorageConflictVisitor<'mir, 'tcx, impl<'body, 'tcx, 's> StorageConflictVisitor<'body, 'tcx, 's> { fn apply_state(&mut self, flow_state: &BitSet, loc: Location) { // Ignore unreachable blocks. - match self.body.basic_blocks()[loc.block].terminator().kind { - TerminatorKind::Unreachable => return, - _ => (), - }; + if self.body.basic_blocks()[loc.block].terminator().kind == TerminatorKind::Unreachable { + return; + } let mut eligible_storage_live = flow_state.clone(); eligible_storage_live.intersect(&self.stored_locals); diff --git a/src/librustc_mir/transform/promote_consts.rs b/src/librustc_mir/transform/promote_consts.rs index 12f3ed6986faf..34fa12e1b5683 100644 --- a/src/librustc_mir/transform/promote_consts.rs +++ b/src/librustc_mir/transform/promote_consts.rs @@ -1064,16 +1064,15 @@ pub fn promote_candidates<'tcx>( match candidate { Candidate::Repeat(Location { block, statement_index }) | Candidate::Ref(Location { block, statement_index }) => { - match &body[block].statements[statement_index].kind { - StatementKind::Assign(box (place, _)) => { - if let Some(local) = place.as_local() { - if temps[local] == TempState::PromotedOut { - // Already promoted. - continue; - } + if let StatementKind::Assign(box (place, _)) = + &body[block].statements[statement_index].kind + { + if let Some(local) = place.as_local() { + if temps[local] == TempState::PromotedOut { + // Already promoted. + continue; } } - _ => {} } } Candidate::Argument { .. } => {} @@ -1137,15 +1136,12 @@ pub fn promote_candidates<'tcx>( _ => true, }); let terminator = block.terminator_mut(); - match &terminator.kind { - TerminatorKind::Drop { location: place, target, .. } => { - if let Some(index) = place.as_local() { - if promoted(index) { - terminator.kind = TerminatorKind::Goto { target: *target }; - } + if let TerminatorKind::Drop { location: place, target, .. } = &terminator.kind { + if let Some(index) = place.as_local() { + if promoted(index) { + terminator.kind = TerminatorKind::Goto { target: *target }; } } - _ => {} } } diff --git a/src/librustc_mir/transform/remove_noop_landing_pads.rs b/src/librustc_mir/transform/remove_noop_landing_pads.rs index b188e39eda0f3..5e4fd061c7666 100644 --- a/src/librustc_mir/transform/remove_noop_landing_pads.rs +++ b/src/librustc_mir/transform/remove_noop_landing_pads.rs @@ -107,16 +107,13 @@ impl RemoveNoopLandingPads { } } - match body[bb].terminator_mut().unwind_mut() { - Some(unwind) => { - if *unwind == Some(resume_block) { - debug!(" removing noop landing pad"); - jumps_folded -= 1; - landing_pads_removed += 1; - *unwind = None; - } + if let Some(unwind) = body[bb].terminator_mut().unwind_mut() { + if *unwind == Some(resume_block) { + debug!(" removing noop landing pad"); + jumps_folded -= 1; + landing_pads_removed += 1; + *unwind = None; } - _ => {} } let is_nop_landing_pad = self.is_nop_landing_pad(bb, body, &nop_landing_pads); diff --git a/src/librustc_mir/util/pretty.rs b/src/librustc_mir/util/pretty.rs index 26e6073bd5667..bd7725c1b5af3 100644 --- a/src/librustc_mir/util/pretty.rs +++ b/src/librustc_mir/util/pretty.rs @@ -391,8 +391,8 @@ impl Visitor<'tcx> for ExtraComments<'tcx> { fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) { self.super_rvalue(rvalue, location); - match rvalue { - Rvalue::Aggregate(kind, _) => match **kind { + if let Rvalue::Aggregate(kind, _) = rvalue { + match **kind { AggregateKind::Closure(def_id, substs) => { self.push("closure"); self.push(&format!("+ def_id: {:?}", def_id)); @@ -412,9 +412,7 @@ impl Visitor<'tcx> for ExtraComments<'tcx> { } _ => {} - }, - - _ => {} + } } } } diff --git a/src/librustc_mir_build/hair/pattern/_match.rs b/src/librustc_mir_build/hair/pattern/_match.rs index 9b40a8e6bfbc8..03f668d562e78 100644 --- a/src/librustc_mir_build/hair/pattern/_match.rs +++ b/src/librustc_mir_build/hair/pattern/_match.rs @@ -1974,15 +1974,12 @@ fn slice_pat_covered_by_const<'tcx>( .zip(prefix) .chain(data[data.len() - suffix.len()..].iter().zip(suffix)) { - match pat.kind { - box PatKind::Constant { value } => { - let b = value.eval_bits(tcx, param_env, pat.ty); - assert_eq!(b as u8 as u128, b); - if b as u8 != *ch { - return Ok(false); - } + if let box PatKind::Constant { value } = pat.kind { + let b = value.eval_bits(tcx, param_env, pat.ty); + assert_eq!(b as u8 as u128, b); + if b as u8 != *ch { + return Ok(false); } - _ => {} } } @@ -2197,8 +2194,8 @@ fn split_grouped_constructors<'p, 'tcx>( let head_ctors = matrix.heads().filter_map(|pat| pat_constructor(tcx, param_env, pat)); for ctor in head_ctors { - match ctor { - Slice(slice) => match slice.pattern_kind() { + if let Slice(slice) = ctor { + match slice.pattern_kind() { FixedLen(len) => { max_fixed_len = cmp::max(max_fixed_len, len); } @@ -2206,8 +2203,7 @@ fn split_grouped_constructors<'p, 'tcx>( max_prefix_len = cmp::max(max_prefix_len, prefix); max_suffix_len = cmp::max(max_suffix_len, suffix); } - }, - _ => {} + } } } diff --git a/src/librustc_mir_build/hair/pattern/mod.rs b/src/librustc_mir_build/hair/pattern/mod.rs index d40d3922f18c4..f15d2fc5caa03 100644 --- a/src/librustc_mir_build/hair/pattern/mod.rs +++ b/src/librustc_mir_build/hair/pattern/mod.rs @@ -1058,18 +1058,15 @@ crate fn compare_const_vals<'tcx>( } if let ty::Str = ty.kind { - match (a.val, b.val) { - ( - ty::ConstKind::Value(a_val @ ConstValue::Slice { .. }), - ty::ConstKind::Value(b_val @ ConstValue::Slice { .. }), - ) => { - let a_bytes = get_slice_bytes(&tcx, a_val); - let b_bytes = get_slice_bytes(&tcx, b_val); - return from_bool(a_bytes == b_bytes); - } - _ => (), + if let ( + ty::ConstKind::Value(a_val @ ConstValue::Slice { .. }), + ty::ConstKind::Value(b_val @ ConstValue::Slice { .. }), + ) = (a.val, b.val) + { + let a_bytes = get_slice_bytes(&tcx, a_val); + let b_bytes = get_slice_bytes(&tcx, b_val); + return from_bool(a_bytes == b_bytes); } } - fallback() } diff --git a/src/librustc_passes/dead.rs b/src/librustc_passes/dead.rs index 44f73c184000e..830bd255dfc3f 100644 --- a/src/librustc_passes/dead.rs +++ b/src/librustc_passes/dead.rs @@ -300,12 +300,9 @@ impl<'a, 'tcx> Visitor<'tcx> for MarkSymbolVisitor<'a, 'tcx> { } fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) { - match ty.kind { - TyKind::Def(item_id, _) => { - let item = self.tcx.hir().expect_item(item_id.id); - intravisit::walk_item(self, item); - } - _ => (), + if let TyKind::Def(item_id, _) = ty.kind { + let item = self.tcx.hir().expect_item(item_id.id); + intravisit::walk_item(self, item); } intravisit::walk_ty(self, ty); } diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index 428d0a3a4dbca..567022fe4052f 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -1096,52 +1096,46 @@ impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, 'tcx> { } fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { - match expr.kind { - hir::ExprKind::Struct(ref qpath, fields, ref base) => { - let res = self.tables.qpath_res(qpath, expr.hir_id); - let adt = self.tables.expr_ty(expr).ty_adt_def().unwrap(); - let variant = adt.variant_of_res(res); - if let Some(ref base) = *base { - // If the expression uses FRU we need to make sure all the unmentioned fields - // are checked for privacy (RFC 736). Rather than computing the set of - // unmentioned fields, just check them all. - for (vf_index, variant_field) in variant.fields.iter().enumerate() { - let field = fields - .iter() - .find(|f| self.tcx.field_index(f.hir_id, self.tables) == vf_index); - let (use_ctxt, span) = match field { - Some(field) => (field.ident.span, field.span), - None => (base.span, base.span), - }; - self.check_field(use_ctxt, span, adt, variant_field, true); - } - } else { - for field in fields { - let use_ctxt = field.ident.span; - let index = self.tcx.field_index(field.hir_id, self.tables); - self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false); - } + if let hir::ExprKind::Struct(ref qpath, fields, ref base) = expr.kind { + let res = self.tables.qpath_res(qpath, expr.hir_id); + let adt = self.tables.expr_ty(expr).ty_adt_def().unwrap(); + let variant = adt.variant_of_res(res); + if let Some(ref base) = *base { + // If the expression uses FRU we need to make sure all the unmentioned fields + // are checked for privacy (RFC 736). Rather than computing the set of + // unmentioned fields, just check them all. + for (vf_index, variant_field) in variant.fields.iter().enumerate() { + let field = fields + .iter() + .find(|f| self.tcx.field_index(f.hir_id, self.tables) == vf_index); + let (use_ctxt, span) = match field { + Some(field) => (field.ident.span, field.span), + None => (base.span, base.span), + }; + self.check_field(use_ctxt, span, adt, variant_field, true); + } + } else { + for field in fields { + let use_ctxt = field.ident.span; + let index = self.tcx.field_index(field.hir_id, self.tables); + self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false); } } - _ => {} } intravisit::walk_expr(self, expr); } fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) { - match pat.kind { - PatKind::Struct(ref qpath, fields, _) => { - let res = self.tables.qpath_res(qpath, pat.hir_id); - let adt = self.tables.pat_ty(pat).ty_adt_def().unwrap(); - let variant = adt.variant_of_res(res); - for field in fields { - let use_ctxt = field.ident.span; - let index = self.tcx.field_index(field.hir_id, self.tables); - self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false); - } + if let PatKind::Struct(ref qpath, fields, _) = pat.kind { + let res = self.tables.qpath_res(qpath, pat.hir_id); + let adt = self.tables.pat_ty(pat).ty_adt_def().unwrap(); + let variant = adt.variant_of_res(res); + for field in fields { + let use_ctxt = field.ident.span; + let index = self.tcx.field_index(field.hir_id, self.tables); + self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false); } - _ => {} } intravisit::walk_pat(self, pat); diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index dc3f110636876..05eb524dff5e3 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -848,10 +848,9 @@ impl<'l, 'tcx> DumpVisitor<'l, 'tcx> { if let Some(ref generic_args) = seg.args { if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args { for arg in &data.args { - match arg { - ast::AngleBracketedArg::Arg(ast::GenericArg::Type(ty)) => self.visit_ty(ty), - _ => {} - } + if let ast::AngleBracketedArg::Arg(ast::GenericArg::Type(ty)) = arg { + self.visit_ty(ty) + }; } } } diff --git a/src/librustc_symbol_mangling/legacy.rs b/src/librustc_symbol_mangling/legacy.rs index e742b445af216..01e9356b42f46 100644 --- a/src/librustc_symbol_mangling/legacy.rs +++ b/src/librustc_symbol_mangling/legacy.rs @@ -308,9 +308,8 @@ impl Printer<'tcx> for SymbolPrinter<'tcx> { self = print_prefix(self)?; // Skip `::{{constructor}}` on tuple/unit structs. - match disambiguated_data.data { - DefPathData::Ctor => return Ok(self), - _ => {} + if let DefPathData::Ctor = disambiguated_data.data { + return Ok(self); } if self.keep_within_component { diff --git a/src/librustc_target/abi/call/riscv.rs b/src/librustc_target/abi/call/riscv.rs index 7cd3a0900941d..a916a53f0cbf7 100644 --- a/src/librustc_target/abi/call/riscv.rs +++ b/src/librustc_target/abi/call/riscv.rs @@ -300,23 +300,18 @@ fn classify_arg<'a, Ty, C>( } fn extend_integer_width<'a, Ty>(arg: &mut ArgAbi<'a, Ty>, xlen: u64) { - match arg.layout.abi { - Abi::Scalar(ref scalar) => { - match scalar.value { - abi::Int(i, _) => { - // 32-bit integers are always sign-extended - if i.size().bits() == 32 && xlen > 32 { - if let PassMode::Direct(ref mut attrs) = arg.mode { - attrs.set(ArgAttribute::SExt); - return; - } - } + if let Abi::Scalar(ref scalar) = arg.layout.abi { + if let abi::Int(i, _) = scalar.value { + // 32-bit integers are always sign-extended + if i.size().bits() == 32 && xlen > 32 { + if let PassMode::Direct(ref mut attrs) = arg.mode { + attrs.set(ArgAttribute::SExt); + return; } - _ => (), } } - _ => (), } + arg.extend_integer_width_to(xlen); } diff --git a/src/librustc_trait_selection/traits/auto_trait.rs b/src/librustc_trait_selection/traits/auto_trait.rs index a3908c9c31c04..e01f5bfbcb3da 100644 --- a/src/librustc_trait_selection/traits/auto_trait.rs +++ b/src/librustc_trait_selection/traits/auto_trait.rs @@ -314,19 +314,17 @@ impl AutoTraitFinder<'tcx> { &Ok(Some(ref vtable)) => { // If we see an explicit negative impl (e.g., `impl !Send for MyStruct`), // we immediately bail out, since it's impossible for us to continue. - match vtable { - Vtable::VtableImpl(VtableImplData { impl_def_id, .. }) => { - // Blame 'tidy' for the weird bracket placement. - if infcx.tcx.impl_polarity(*impl_def_id) == ty::ImplPolarity::Negative { - debug!( - "evaluate_nested_obligations: found explicit negative impl\ + + if let Vtable::VtableImpl(VtableImplData { impl_def_id, .. }) = vtable { + // Blame 'tidy' for the weird bracket placement. + if infcx.tcx.impl_polarity(*impl_def_id) == ty::ImplPolarity::Negative { + debug!( + "evaluate_nested_obligations: found explicit negative impl\ {:?}, bailing out", - impl_def_id - ); - return None; - } + impl_def_id + ); + return None; } - _ => {} } let obligations = vtable.clone().nested_obligations().into_iter(); @@ -417,80 +415,77 @@ impl AutoTraitFinder<'tcx> { ) { let mut should_add_new = true; user_computed_preds.retain(|&old_pred| { - match (&new_pred, old_pred) { - (&ty::Predicate::Trait(new_trait, _), ty::Predicate::Trait(old_trait, _)) => { - if new_trait.def_id() == old_trait.def_id() { - let new_substs = new_trait.skip_binder().trait_ref.substs; - let old_substs = old_trait.skip_binder().trait_ref.substs; - - if !new_substs.types().eq(old_substs.types()) { - // We can't compare lifetimes if the types are different, - // so skip checking `old_pred`. - return true; - } + if let (&ty::Predicate::Trait(new_trait, _), ty::Predicate::Trait(old_trait, _)) = + (&new_pred, old_pred) + { + if new_trait.def_id() == old_trait.def_id() { + let new_substs = new_trait.skip_binder().trait_ref.substs; + let old_substs = old_trait.skip_binder().trait_ref.substs; + + if !new_substs.types().eq(old_substs.types()) { + // We can't compare lifetimes if the types are different, + // so skip checking `old_pred`. + return true; + } - for (new_region, old_region) in - new_substs.regions().zip(old_substs.regions()) - { - match (new_region, old_region) { - // If both predicates have an `ReLateBound` (a HRTB) in the - // same spot, we do nothing. - ( - ty::RegionKind::ReLateBound(_, _), - ty::RegionKind::ReLateBound(_, _), - ) => {} - - (ty::RegionKind::ReLateBound(_, _), _) - | (_, ty::RegionKind::ReVar(_)) => { - // One of these is true: - // The new predicate has a HRTB in a spot where the old - // predicate does not (if they both had a HRTB, the previous - // match arm would have executed). A HRBT is a 'stricter' - // bound than anything else, so we want to keep the newer - // predicate (with the HRBT) in place of the old predicate. - // - // OR - // - // The old predicate has a region variable where the new - // predicate has some other kind of region. An region - // variable isn't something we can actually display to a user, - // so we choose their new predicate (which doesn't have a region - // variable). - // - // In both cases, we want to remove the old predicate, - // from `user_computed_preds`, and replace it with the new - // one. Having both the old and the new - // predicate in a `ParamEnv` would confuse `SelectionContext`. - // - // We're currently in the predicate passed to 'retain', - // so we return `false` to remove the old predicate from - // `user_computed_preds`. - return false; - } - (_, ty::RegionKind::ReLateBound(_, _)) - | (ty::RegionKind::ReVar(_), _) => { - // This is the opposite situation as the previous arm. - // One of these is true: - // - // The old predicate has a HRTB lifetime in a place where the - // new predicate does not. - // - // OR - // - // The new predicate has a region variable where the old - // predicate has some other type of region. - // - // We want to leave the old - // predicate in `user_computed_preds`, and skip adding - // new_pred to `user_computed_params`. - should_add_new = false - } - _ => {} + for (new_region, old_region) in new_substs.regions().zip(old_substs.regions()) { + match (new_region, old_region) { + // If both predicates have an `ReLateBound` (a HRTB) in the + // same spot, we do nothing. + ( + ty::RegionKind::ReLateBound(_, _), + ty::RegionKind::ReLateBound(_, _), + ) => {} + + (ty::RegionKind::ReLateBound(_, _), _) + | (_, ty::RegionKind::ReVar(_)) => { + // One of these is true: + // The new predicate has a HRTB in a spot where the old + // predicate does not (if they both had a HRTB, the previous + // match arm would have executed). A HRBT is a 'stricter' + // bound than anything else, so we want to keep the newer + // predicate (with the HRBT) in place of the old predicate. + // + // OR + // + // The old predicate has a region variable where the new + // predicate has some other kind of region. An region + // variable isn't something we can actually display to a user, + // so we choose their new predicate (which doesn't have a region + // variable). + // + // In both cases, we want to remove the old predicate, + // from `user_computed_preds`, and replace it with the new + // one. Having both the old and the new + // predicate in a `ParamEnv` would confuse `SelectionContext`. + // + // We're currently in the predicate passed to 'retain', + // so we return `false` to remove the old predicate from + // `user_computed_preds`. + return false; + } + (_, ty::RegionKind::ReLateBound(_, _)) + | (ty::RegionKind::ReVar(_), _) => { + // This is the opposite situation as the previous arm. + // One of these is true: + // + // The old predicate has a HRTB lifetime in a place where the + // new predicate does not. + // + // OR + // + // The new predicate has a region variable where the old + // predicate has some other type of region. + // + // We want to leave the old + // predicate in `user_computed_preds`, and skip adding + // new_pred to `user_computed_params`. + should_add_new = false } + _ => {} } } } - _ => {} } true }); diff --git a/src/librustc_trait_selection/traits/error_reporting/on_unimplemented.rs b/src/librustc_trait_selection/traits/error_reporting/on_unimplemented.rs index 48a052c608f6f..213769d721d73 100644 --- a/src/librustc_trait_selection/traits/error_reporting/on_unimplemented.rs +++ b/src/librustc_trait_selection/traits/error_reporting/on_unimplemented.rs @@ -219,11 +219,8 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { } if let ty::Dynamic(traits, _) = self_ty.kind { for t in *traits.skip_binder() { - match t { - ty::ExistentialPredicate::Trait(trait_ref) => { - flags.push((sym::_Self, Some(self.tcx.def_path_str(trait_ref.def_id)))) - } - _ => {} + if let ty::ExistentialPredicate::Trait(trait_ref) = t { + flags.push((sym::_Self, Some(self.tcx.def_path_str(trait_ref.def_id)))) } } } diff --git a/src/librustc_trait_selection/traits/wf.rs b/src/librustc_trait_selection/traits/wf.rs index ede6fa015fccf..59b56d673fb00 100644 --- a/src/librustc_trait_selection/traits/wf.rs +++ b/src/librustc_trait_selection/traits/wf.rs @@ -737,17 +737,14 @@ fn get_generic_bound_spans( } fn is_self_path(kind: &hir::TyKind<'_>) -> bool { - match kind { - hir::TyKind::Path(hir::QPath::Resolved(None, path)) => { - let mut s = path.segments.iter(); - if let (Some(segment), None) = (s.next(), s.next()) { - if segment.ident.name == kw::SelfUpper { - // `type(Self)` - return true; - } + if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = kind { + let mut s = path.segments.iter(); + if let (Some(segment), None) = (s.next(), s.next()) { + if segment.ident.name == kw::SelfUpper { + // `type(Self)` + return true; } } - _ => {} } false } diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index aca5624d55c96..932032bb2b45f 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -1785,9 +1785,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { )); } } - - match (&potential_assoc_types[..], &trait_bounds) { - ([], [bound]) => match &bound.trait_ref.path.segments[..] { + if let ([], [bound]) = (&potential_assoc_types[..], &trait_bounds) { + match &bound.trait_ref.path.segments[..] { // FIXME: `trait_ref.path.span` can point to a full path with multiple // segments, even though `trait_ref.path.segments` is of length `1`. Work // around that bug here, even though it should be fixed elsewhere. @@ -1819,8 +1818,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { .collect(); } _ => {} - }, - _ => {} + } } names.sort(); trait_bound_spans.sort(); diff --git a/src/librustc_typeck/check/method/confirm.rs b/src/librustc_typeck/check/method/confirm.rs index 63f7ba5baac3b..a16555b3df056 100644 --- a/src/librustc_typeck/check/method/confirm.rs +++ b/src/librustc_typeck/check/method/confirm.rs @@ -551,12 +551,11 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { } // If we have an autoref followed by unsizing at the end, fix the unsize target. - match adjustments[..] { - [.., Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), .. }, Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), ref mut target }] => - { - *target = method.sig.inputs()[0]; - } - _ => {} + + if let [.., Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), .. }, Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), ref mut target }] = + adjustments[..] + { + *target = method.sig.inputs()[0]; } } } diff --git a/src/librustc_typeck/check/method/suggest.rs b/src/librustc_typeck/check/method/suggest.rs index 9bfeafbfc9fac..c8632086771f9 100644 --- a/src/librustc_typeck/check/method/suggest.rs +++ b/src/librustc_typeck/check/method/suggest.rs @@ -558,26 +558,21 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .hir() .as_local_hir_id(def.did) .map(|id| self.tcx.hir().get(id)); - match node { - Some(hir::Node::Item(hir::Item { kind, .. })) => { - if let Some(g) = kind.generics() { - let key = match &g.where_clause.predicates[..] { - [.., pred] => { - (pred.span().shrink_to_hi(), false) - } - [] => ( - g.where_clause - .span_for_predicates_or_empty_place(), - true, - ), - }; - type_params - .entry(key) - .or_insert_with(FxHashSet::default) - .insert(obligation.to_owned()); - } + if let Some(hir::Node::Item(hir::Item { kind, .. })) = node { + if let Some(g) = kind.generics() { + let key = match &g.where_clause.predicates[..] { + [.., pred] => (pred.span().shrink_to_hi(), false), + [] => ( + g.where_clause + .span_for_predicates_or_empty_place(), + true, + ), + }; + type_params + .entry(key) + .or_insert_with(FxHashSet::default) + .insert(obligation.to_owned()); } - _ => {} } } } diff --git a/src/librustc_typeck/check/writeback.rs b/src/librustc_typeck/check/writeback.rs index cccd84c2b884a..2b2ebb3135fd1 100644 --- a/src/librustc_typeck/check/writeback.rs +++ b/src/librustc_typeck/check/writeback.rs @@ -213,18 +213,17 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { tables.adjustments_mut().get_mut(base.hir_id).map(|a| { // Discard the need for a mutable borrow - match a.pop() { - // Extra adjustment made when indexing causes a drop - // of size information - we need to get rid of it - // Since this is "after" the other adjustment to be - // discarded, we do an extra `pop()` - Some(Adjustment { - kind: Adjust::Pointer(PointerCast::Unsize), .. - }) => { - // So the borrow discard actually happens here - a.pop(); - } - _ => {} + + // Extra adjustment made when indexing causes a drop + // of size information - we need to get rid of it + // Since this is "after" the other adjustment to be + // discarded, we do an extra `pop()` + if let Some(Adjustment { + kind: Adjust::Pointer(PointerCast::Unsize), .. + }) = a.pop() + { + // So the borrow discard actually happens here + a.pop(); } }); }