internal: Generally improve make::match_arm

`make::match_arm` should take a single `ast::Pat`, and callers can handle creating an `ast::OrPat` if need be. It should also take a proper `ast::MatchGuard`, instead of making one itself.
This commit is contained in:
Giga Bowser 2024-12-16 15:28:17 -05:00
parent 905e1e1fc0
commit 32ff06d51c
9 changed files with 53 additions and 56 deletions

View file

@ -153,8 +153,7 @@ impl<N: AstNode + Clone> AstNodeEdit for N {}
#[test]
fn test_increase_indent() {
let arm_list = {
let arm =
make::match_arm(iter::once(make::wildcard_pat().into()), None, make::ext::expr_unit());
let arm = make::match_arm(make::wildcard_pat().into(), None, make::ext::expr_unit());
make::match_arm_list([arm.clone(), arm])
};
assert_eq!(

View file

@ -787,15 +787,21 @@ pub fn path_pat(path: ast::Path) -> ast::Pat {
}
}
pub fn match_arm(
pats: impl IntoIterator<Item = ast::Pat>,
guard: Option<ast::Expr>,
expr: ast::Expr,
) -> ast::MatchArm {
let pats_str = pats.into_iter().join(" | ");
/// Returns a `Pat` if the path has just one segment, an `OrPat` otherwise.
pub fn or_pat(pats: impl IntoIterator<Item = ast::Pat>, leading_pipe: bool) -> ast::Pat {
let leading_pipe = if leading_pipe { "| " } else { "" };
let pats = pats.into_iter().join(" | ");
return from_text(&format!("{leading_pipe}{pats}"));
fn from_text(text: &str) -> ast::Pat {
ast_from_text(&format!("fn f({text}: ())"))
}
}
pub fn match_arm(pat: ast::Pat, guard: Option<ast::MatchGuard>, expr: ast::Expr) -> ast::MatchArm {
return match guard {
Some(guard) => from_text(&format!("{pats_str} if {guard} => {expr}")),
None => from_text(&format!("{pats_str} => {expr}")),
Some(guard) => from_text(&format!("{pat} {guard} => {expr}")),
None => from_text(&format!("{pat} => {expr}")),
};
fn from_text(text: &str) -> ast::MatchArm {
@ -816,6 +822,14 @@ pub fn match_arm_with_guard(
}
}
pub fn match_guard(condition: ast::Expr) -> ast::MatchGuard {
return from_text(&format!("if {condition}"));
fn from_text(text: &str) -> ast::MatchGuard {
ast_from_text(&format!("fn f() {{ match () {{() {text} => () }}"))
}
}
pub fn match_arm_list(arms: impl IntoIterator<Item = ast::MatchArm>) -> ast::MatchArmList {
let arms_str = arms.into_iter().fold(String::new(), |mut acc, arm| {
let needs_comma = arm.expr().is_none_or(|it| !it.is_block_like());

View file

@ -335,7 +335,7 @@ mod tests {
#[test]
fn basic_usage() {
let root = make::match_arm(
[make::wildcard_pat().into()],
make::wildcard_pat().into(),
None,
make::expr_tuple([
make::expr_bin_op(