Skip to content

Commit 7c6dca9

Browse files
Rollup merge of #128978 - compiler-errors:assert-matches, r=jieyouxu
Use `assert_matches` around the compiler more It's a useful assertion, especially since it actually prints out the LHS.
2 parents bb35b88 + c361c92 commit 7c6dca9

File tree

39 files changed

+100
-49
lines changed

39 files changed

+100
-49
lines changed

compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
#![allow(rustc::diagnostic_outside_of_impl)]
44
#![allow(rustc::untranslatable_diagnostic)]
55

6+
use std::assert_matches::assert_matches;
7+
68
use rustc_errors::{Applicability, Diag};
79
use rustc_hir as hir;
810
use rustc_hir::intravisit::Visitor;
@@ -116,7 +118,7 @@ impl<'tcx> BorrowExplanation<'tcx> {
116118
// path_span must be `Some` as otherwise the if condition is true
117119
let path_span = path_span.unwrap();
118120
// path_span is only present in the case of closure capture
119-
assert!(matches!(later_use_kind, LaterUseKind::ClosureCapture));
121+
assert_matches!(later_use_kind, LaterUseKind::ClosureCapture);
120122
if !borrow_span.is_some_and(|sp| sp.overlaps(var_or_use_span)) {
121123
let path_label = "used here by closure";
122124
let capture_kind_label = message;
@@ -147,7 +149,7 @@ impl<'tcx> BorrowExplanation<'tcx> {
147149
// path_span must be `Some` as otherwise the if condition is true
148150
let path_span = path_span.unwrap();
149151
// path_span is only present in the case of closure capture
150-
assert!(matches!(later_use_kind, LaterUseKind::ClosureCapture));
152+
assert_matches!(later_use_kind, LaterUseKind::ClosureCapture);
151153
if borrow_span.map(|sp| !sp.overlaps(var_or_use_span)).unwrap_or(true) {
152154
let path_label = "used here by closure";
153155
let capture_kind_label = message;

compiler/rustc_codegen_llvm/src/asm.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::assert_matches::assert_matches;
2+
13
use libc::{c_char, c_uint};
24
use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
35
use rustc_codegen_ssa::mir::operand::OperandValue;
@@ -89,7 +91,7 @@ impl<'ll, 'tcx> AsmBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
8991
// if the target feature needed by the register class is
9092
// disabled. This is necessary otherwise LLVM will try
9193
// to actually allocate a register for the dummy output.
92-
assert!(matches!(reg, InlineAsmRegOrRegClass::Reg(_)));
94+
assert_matches!(reg, InlineAsmRegOrRegClass::Reg(_));
9395
clobbers.push(format!("~{}", reg_to_llvm(reg, None)));
9496
continue;
9597
} else {

compiler/rustc_codegen_llvm/src/intrinsic.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use std::assert_matches::assert_matches;
12
use std::cmp::Ordering;
23

34
use rustc_codegen_ssa::base::{compare_simd_types, wants_msvc_seh, wants_wasm_eh};
@@ -1142,7 +1143,7 @@ fn generic_simd_intrinsic<'ll, 'tcx>(
11421143
if cfg!(debug_assertions) {
11431144
for (ty, arg) in arg_tys.iter().zip(args) {
11441145
if ty.is_simd() {
1145-
assert!(matches!(arg.val, OperandValue::Immediate(_)));
1146+
assert_matches!(arg.val, OperandValue::Immediate(_));
11461147
}
11471148
}
11481149
}

compiler/rustc_codegen_llvm/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
#![allow(internal_features)]
99
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
1010
#![doc(rust_logo)]
11+
#![feature(assert_matches)]
1112
#![feature(exact_size_is_empty)]
1213
#![feature(extern_types)]
1314
#![feature(hash_raw_entry)]

compiler/rustc_codegen_ssa/src/back/write.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use std::any::Any;
2+
use std::assert_matches::assert_matches;
23
use std::marker::PhantomData;
34
use std::path::{Path, PathBuf};
45
use std::sync::mpsc::{channel, Receiver, Sender};
@@ -1963,7 +1964,7 @@ impl SharedEmitterMain {
19631964
sess.dcx().abort_if_errors();
19641965
}
19651966
Ok(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)) => {
1966-
assert!(matches!(level, Level::Error | Level::Warning | Level::Note));
1967+
assert_matches!(level, Level::Error | Level::Warning | Level::Note);
19671968
let msg = msg.strip_prefix("error: ").unwrap_or(&msg).to_string();
19681969
let mut err = Diag::<()>::new(sess.dcx(), level, msg);
19691970

compiler/rustc_codegen_ssa/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
#![allow(rustc::untranslatable_diagnostic)]
55
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
66
#![doc(rust_logo)]
7+
#![feature(assert_matches)]
78
#![feature(box_patterns)]
89
#![feature(if_let_guard)]
910
#![feature(let_chains)]

compiler/rustc_codegen_ssa/src/mir/operand.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use std::assert_matches::assert_matches;
12
use std::fmt;
23

34
use arrayvec::ArrayVec;
@@ -389,7 +390,7 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> {
389390
}
390391
// Newtype vector of array, e.g. #[repr(simd)] struct S([i32; 4]);
391392
(OperandValue::Immediate(llval), Abi::Aggregate { sized: true }) => {
392-
assert!(matches!(self.layout.abi, Abi::Vector { .. }));
393+
assert_matches!(self.layout.abi, Abi::Vector { .. });
393394

394395
let llfield_ty = bx.cx().backend_type(field);
395396

compiler/rustc_codegen_ssa/src/mir/rvalue.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::assert_matches::assert_matches;
2+
13
use arrayvec::ArrayVec;
24
use rustc_middle::ty::adjustment::PointerCoercion;
35
use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout};
@@ -220,7 +222,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
220222
match operand.val {
221223
OperandValue::Ref(source_place_val) => {
222224
assert_eq!(source_place_val.llextra, None);
223-
assert!(matches!(operand_kind, OperandValueKind::Ref));
225+
assert_matches!(operand_kind, OperandValueKind::Ref);
224226
Some(bx.load_operand(source_place_val.with_type(cast)).val)
225227
}
226228
OperandValue::ZeroSized => {

compiler/rustc_codegen_ssa/src/traits/builder.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::assert_matches::assert_matches;
2+
13
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
24
use rustc_middle::ty::layout::{HasParamEnv, TyAndLayout};
35
use rustc_middle::ty::{Instance, Ty};
@@ -254,10 +256,10 @@ pub trait BuilderMethods<'a, 'tcx>:
254256
} else {
255257
(in_ty, dest_ty)
256258
};
257-
assert!(matches!(
259+
assert_matches!(
258260
self.cx().type_kind(float_ty),
259261
TypeKind::Half | TypeKind::Float | TypeKind::Double | TypeKind::FP128
260-
));
262+
);
261263
assert_eq!(self.cx().type_kind(int_ty), TypeKind::Integer);
262264

263265
if let Some(false) = self.cx().sess().opts.unstable_opts.saturating_float_casts {

compiler/rustc_const_eval/src/check_consts/check.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
//! The `Visitor` responsible for actually checking a `mir::Body` for invalid operations.
22
3+
use std::assert_matches::assert_matches;
34
use std::mem;
45
use std::ops::Deref;
56

@@ -590,7 +591,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> {
590591
if is_int_bool_or_char(lhs_ty) && is_int_bool_or_char(rhs_ty) {
591592
// Int, bool, and char operations are fine.
592593
} else if lhs_ty.is_fn_ptr() || lhs_ty.is_unsafe_ptr() {
593-
assert!(matches!(
594+
assert_matches!(
594595
op,
595596
BinOp::Eq
596597
| BinOp::Ne
@@ -599,7 +600,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> {
599600
| BinOp::Ge
600601
| BinOp::Gt
601602
| BinOp::Offset
602-
));
603+
);
603604

604605
self.check_op(ops::RawPtrComparison);
605606
} else if lhs_ty.is_floating_point() || rhs_ty.is_floating_point() {

compiler/rustc_const_eval/src/interpret/call.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
//! Manages calling a concrete function (with known MIR body) with argument passing,
22
//! and returning the return value to the caller.
3+
use std::assert_matches::assert_matches;
34
use std::borrow::Cow;
45

56
use either::{Left, Right};
@@ -557,7 +558,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
557558
unwind,
558559
)? {
559560
assert!(!self.tcx.intrinsic(fallback.def_id()).unwrap().must_be_overridden);
560-
assert!(matches!(fallback.def, ty::InstanceKind::Item(_)));
561+
assert_matches!(fallback.def, ty::InstanceKind::Item(_));
561562
return self.init_fn_call(
562563
FnVal::Instance(fallback),
563564
(caller_abi, caller_fn_abi),

compiler/rustc_const_eval/src/interpret/intrinsics.rs

+5-3
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
//! looking at their MIR. Intrinsics/functions supported here are shared by CTFE
33
//! and miri.
44
5+
use std::assert_matches::assert_matches;
6+
57
use rustc_hir::def_id::DefId;
68
use rustc_middle::mir::{self, BinOp, ConstValue, NonDivergingIntrinsic};
79
use rustc_middle::ty::layout::{LayoutOf as _, TyAndLayout, ValidityRequirement};
@@ -510,7 +512,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
510512
dest: &MPlaceTy<'tcx, M::Provenance>,
511513
) -> InterpResult<'tcx> {
512514
assert_eq!(a.layout.ty, b.layout.ty);
513-
assert!(matches!(a.layout.ty.kind(), ty::Int(..) | ty::Uint(..)));
515+
assert_matches!(a.layout.ty.kind(), ty::Int(..) | ty::Uint(..));
514516

515517
// Performs an exact division, resulting in undefined behavior where
516518
// `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`.
@@ -536,8 +538,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
536538
r: &ImmTy<'tcx, M::Provenance>,
537539
) -> InterpResult<'tcx, Scalar<M::Provenance>> {
538540
assert_eq!(l.layout.ty, r.layout.ty);
539-
assert!(matches!(l.layout.ty.kind(), ty::Int(..) | ty::Uint(..)));
540-
assert!(matches!(mir_op, BinOp::Add | BinOp::Sub));
541+
assert_matches!(l.layout.ty.kind(), ty::Int(..) | ty::Uint(..));
542+
assert_matches!(mir_op, BinOp::Add | BinOp::Sub);
541543

542544
let (val, overflowed) =
543545
self.binary_op(mir_op.wrapping_to_overflowing().unwrap(), l, r)?.to_scalar_pair();

compiler/rustc_const_eval/src/interpret/operand.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -342,7 +342,7 @@ impl<'tcx, Prov: Provenance> ImmTy<'tcx, Prov> {
342342
}
343343
// extract fields from types with `ScalarPair` ABI
344344
(Immediate::ScalarPair(a_val, b_val), Abi::ScalarPair(a, b)) => {
345-
assert!(matches!(layout.abi, Abi::Scalar(..)));
345+
assert_matches!(layout.abi, Abi::Scalar(..));
346346
Immediate::from(if offset.bytes() == 0 {
347347
debug_assert_eq!(layout.size, a.size(cx));
348348
a_val

compiler/rustc_data_structures/src/graph/scc/mod.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
//! Typical examples would include: minimum element in SCC, maximum element
99
//! reachable from it, etc.
1010
11+
use std::assert_matches::debug_assert_matches;
1112
use std::fmt::Debug;
1213
use std::ops::Range;
1314

@@ -569,7 +570,7 @@ where
569570
// This None marks that we still have the initialize this node's frame.
570571
debug!(?depth, ?node);
571572

572-
debug_assert!(matches!(self.node_states[node], NodeState::NotVisited));
573+
debug_assert_matches!(self.node_states[node], NodeState::NotVisited);
573574

574575
// Push `node` onto the stack.
575576
self.node_states[node] = NodeState::BeingVisited {

compiler/rustc_data_structures/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
#![feature(array_windows)]
1919
#![feature(ascii_char)]
2020
#![feature(ascii_char_variants)]
21+
#![feature(assert_matches)]
2122
#![feature(auto_traits)]
2223
#![feature(cfg_match)]
2324
#![feature(core_intrinsics)]

compiler/rustc_errors/src/lib.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
1111
#![doc(rust_logo)]
1212
#![feature(array_windows)]
13+
#![feature(assert_matches)]
1314
#![feature(associated_type_defaults)]
1415
#![feature(box_into_inner)]
1516
#![feature(box_patterns)]
@@ -28,6 +29,7 @@
2829

2930
extern crate self as rustc_errors;
3031

32+
use std::assert_matches::assert_matches;
3133
use std::backtrace::{Backtrace, BacktraceStatus};
3234
use std::borrow::Cow;
3335
use std::cell::Cell;
@@ -1490,7 +1492,7 @@ impl DiagCtxtInner {
14901492
// Future breakages aren't emitted if they're `Level::Allow` or
14911493
// `Level::Expect`, but they still need to be constructed and
14921494
// stashed below, so they'll trigger the must_produce_diag check.
1493-
assert!(matches!(diagnostic.level, Error | Warning | Allow | Expect(_)));
1495+
assert_matches!(diagnostic.level, Error | Warning | Allow | Expect(_));
14941496
self.future_breakage_diagnostics.push(diagnostic.clone());
14951497
}
14961498

compiler/rustc_hir_analysis/src/check/intrinsicck.rs

+6-4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::assert_matches::debug_assert_matches;
2+
13
use rustc_ast::InlineAsmTemplatePiece;
24
use rustc_data_structures::fx::FxIndexSet;
35
use rustc_hir::{self as hir, LangItem};
@@ -457,17 +459,17 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
457459
}
458460
// Typeck has checked that Const operands are integers.
459461
hir::InlineAsmOperand::Const { anon_const } => {
460-
debug_assert!(matches!(
462+
debug_assert_matches!(
461463
self.tcx.type_of(anon_const.def_id).instantiate_identity().kind(),
462464
ty::Error(_) | ty::Int(_) | ty::Uint(_)
463-
));
465+
);
464466
}
465467
// Typeck has checked that SymFn refers to a function.
466468
hir::InlineAsmOperand::SymFn { anon_const } => {
467-
debug_assert!(matches!(
469+
debug_assert_matches!(
468470
self.tcx.type_of(anon_const.def_id).instantiate_identity().kind(),
469471
ty::Error(_) | ty::FnDef(..)
470-
));
472+
);
471473
}
472474
// AST lowering guarantees that SymStatic points to a static.
473475
hir::InlineAsmOperand::SymStatic { .. } => {}

compiler/rustc_hir_analysis/src/coherence/builtin.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! Check properties that are required by built-in traits and set
22
//! up data structures required by type-checking/codegen.
33
4+
use std::assert_matches::assert_matches;
45
use std::collections::BTreeMap;
56

67
use rustc_data_structures::fx::FxHashSet;
@@ -129,7 +130,7 @@ fn visit_implementation_of_const_param_ty(
129130
checker: &Checker<'_>,
130131
kind: LangItem,
131132
) -> Result<(), ErrorGuaranteed> {
132-
assert!(matches!(kind, LangItem::ConstParamTy | LangItem::UnsizedConstParamTy));
133+
assert_matches!(kind, LangItem::ConstParamTy | LangItem::UnsizedConstParamTy);
133134

134135
let tcx = checker.tcx;
135136
let header = checker.impl_header;

compiler/rustc_hir_analysis/src/collect/generics_of.rs

+5-4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use std::assert_matches::assert_matches;
12
use std::ops::ControlFlow;
23

34
use hir::intravisit::{self, Visitor};
@@ -207,9 +208,9 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics {
207208
..
208209
}) => {
209210
if in_trait {
210-
assert!(matches!(tcx.def_kind(fn_def_id), DefKind::AssocFn))
211+
assert_matches!(tcx.def_kind(fn_def_id), DefKind::AssocFn);
211212
} else {
212-
assert!(matches!(tcx.def_kind(fn_def_id), DefKind::AssocFn | DefKind::Fn))
213+
assert_matches!(tcx.def_kind(fn_def_id), DefKind::AssocFn | DefKind::Fn);
213214
}
214215
Some(fn_def_id.to_def_id())
215216
}
@@ -218,9 +219,9 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics {
218219
..
219220
}) => {
220221
if in_assoc_ty {
221-
assert!(matches!(tcx.def_kind(parent), DefKind::AssocTy));
222+
assert_matches!(tcx.def_kind(parent), DefKind::AssocTy);
222223
} else {
223-
assert!(matches!(tcx.def_kind(parent), DefKind::TyAlias));
224+
assert_matches!(tcx.def_kind(parent), DefKind::TyAlias);
224225
}
225226
debug!("generics_of: parent of opaque ty {:?} is {:?}", def_id, parent);
226227
// Opaque types are always nested within another item, and

compiler/rustc_hir_analysis/src/collect/predicates_of.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::assert_matches::assert_matches;
2+
13
use hir::{HirId, Node};
24
use rustc_data_structures::fx::FxIndexSet;
35
use rustc_hir as hir;
@@ -601,7 +603,7 @@ pub(super) fn implied_predicates_with_filter(
601603
let Some(trait_def_id) = trait_def_id.as_local() else {
602604
// if `assoc_name` is None, then the query should've been redirected to an
603605
// external provider
604-
assert!(matches!(filter, PredicateFilter::SelfThatDefines(_)));
606+
assert_matches!(filter, PredicateFilter::SelfThatDefines(_));
605607
return tcx.explicit_super_predicates_of(trait_def_id);
606608
};
607609

compiler/rustc_hir_analysis/src/delegation.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::assert_matches::debug_assert_matches;
2+
13
use rustc_data_structures::fx::FxHashMap;
24
use rustc_hir::def::DefKind;
35
use rustc_hir::def_id::{DefId, LocalDefId};
@@ -63,7 +65,7 @@ enum FnKind {
6365
}
6466

6567
fn fn_kind<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> FnKind {
66-
debug_assert!(matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn));
68+
debug_assert_matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn);
6769

6870
let parent = tcx.parent(def_id);
6971
match tcx.def_kind(parent) {

compiler/rustc_hir_analysis/src/impl_wf_check.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
//! specialization errors. These things can (and probably should) be
99
//! fixed, but for the moment it's easier to do these checks early.
1010
11+
use std::assert_matches::debug_assert_matches;
12+
1113
use min_specialization::check_min_specialization;
1214
use rustc_data_structures::fx::FxHashSet;
1315
use rustc_errors::codes::*;
@@ -54,7 +56,7 @@ mod min_specialization;
5456
pub fn check_impl_wf(tcx: TyCtxt<'_>, impl_def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
5557
let min_specialization = tcx.features().min_specialization;
5658
let mut res = Ok(());
57-
debug_assert!(matches!(tcx.def_kind(impl_def_id), DefKind::Impl { .. }));
59+
debug_assert_matches!(tcx.def_kind(impl_def_id), DefKind::Impl { .. });
5860
res = res.and(enforce_impl_params_are_constrained(tcx, impl_def_id));
5961
if min_specialization {
6062
res = res.and(check_min_specialization(tcx, impl_def_id));

compiler/rustc_hir_analysis/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ This API is completely unstable and subject to change.
6262
#![allow(rustc::untranslatable_diagnostic)]
6363
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
6464
#![doc(rust_logo)]
65+
#![feature(assert_matches)]
6566
#![feature(control_flow_enum)]
6667
#![feature(if_let_guard)]
6768
#![feature(iter_intersperse)]

0 commit comments

Comments
 (0)