Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions library/core/src/macros/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,30 @@ pub macro assert_matches {
}
}
},
($left:expr, $(|)? $( $pattern:pat_param )|+ $( if let $($let_guards: tt)+ )? $(,)?) => {
match $left {
$( $pattern )|+ $( if let $($let_guards)+ )? => {}
ref left_val => {
$crate::panicking::assert_matches_failed(
left_val,
$crate::stringify!($($pattern)|+ $(if let $($let_guards)+)?),
$crate::option::Option::None
);
}
}
},
($left:expr, $(|)? $( $pattern:pat_param )|+ $( if let $($let_guards: tt)+ )?, $($arg:tt)+) => {
match $left {
$( $pattern )|+ $( if let $($let_guards)+ )? => {}
ref left_val => {
$crate::panicking::assert_matches_failed(
left_val,
$crate::stringify!($($pattern)|+ $(if let $($let_guards)+)?),
$crate::option::Option::Some($crate::format_args!($($arg)+))
);
}
}
},
}

/// Selects code at compile-time based on `cfg` predicates.
Expand Down Expand Up @@ -435,6 +459,13 @@ macro_rules! matches {
_ => false
}
};
($expression:expr, $pattern:pat $(if let $($let_guards:tt)+)? $(,)?) => {
#[allow(non_exhaustive_omitted_patterns)]
match $expression {
$pattern $(if let $($let_guards)+)? => true,
_ => false
}
};
}

/// Unwraps a result or propagates its error.
Expand Down
10 changes: 10 additions & 0 deletions library/coretests/tests/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,16 @@ fn matches_leading_pipe() {
matches!(1, | 1 | 2 | 3);
}

#[test]
fn matches_if_let_guard() {
use std::assert_matches;

assert!(
matches!(Some(Some(2_i32)), Some(inner) if let Some(value) = inner && value.pow(2) == 4)
);
assert_matches!(Some(Some(2_i32)), Some(inner) if let Some(value) = inner && value.pow(2) == 4);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs another test for assert_matches!() with a panic message.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, so looks like we can't simply use $(tt)+ to catch if-let guards because it also catches the comma and panic message.

Does this mean we have to start implementing it as a compiler built-in macro? Especially since we already have 4 arms here.

}

#[test]
fn cfg_select_basic() {
cfg_select! {
Expand Down
Loading