Skip to content

Commit 36c344e

Browse files
committed
feat: do not add new enum if it already exists
1 parent 5445aef commit 36c344e

File tree

1 file changed

+40
-1
lines changed

1 file changed

+40
-1
lines changed

src/tools/rust-analyzer/crates/ide-assists/src/handlers/bool_to_enum.rs

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -461,7 +461,17 @@ fn add_enum_def(
461461
usages: &UsageSearchResult,
462462
target_node: SyntaxNode,
463463
target_module: &hir::Module,
464-
) {
464+
) -> Option<()> {
465+
if ctx
466+
.find_node_at_offset::<ast::SourceFile>()?
467+
.syntax()
468+
.children()
469+
.filter_map(|node| ast::Enum::cast(node).and_then(|e| ctx.sema.to_def(&e)))
470+
.any(|def| def.name(ctx.db()).as_str() == Some("Bool"))
471+
{
472+
return None;
473+
}
474+
465475
let make_enum_pub = usages
466476
.iter()
467477
.flat_map(|(_, refs)| refs)
@@ -480,6 +490,8 @@ fn add_enum_def(
480490
insert_before.text_range().start(),
481491
format!("{}\n\n{indent}", enum_def.syntax().text()),
482492
);
493+
494+
Some(())
483495
}
484496

485497
/// Finds where to put the new enum definition.
@@ -553,6 +565,33 @@ fn function(foo: Bool, bar: bool) {
553565
)
554566
}
555567

568+
#[test]
569+
fn no_duplicate_enums() {
570+
check_assist(
571+
bool_to_enum,
572+
r#"
573+
#[derive(PartialEq, Eq)]
574+
enum Bool { True, False }
575+
576+
fn function(foo: bool, $0bar: bool) {
577+
if bar {
578+
println!("bar");
579+
}
580+
}
581+
"#,
582+
r#"
583+
#[derive(PartialEq, Eq)]
584+
enum Bool { True, False }
585+
586+
fn function(foo: bool, bar: Bool) {
587+
if bar == Bool::True {
588+
println!("bar");
589+
}
590+
}
591+
"#,
592+
)
593+
}
594+
556595
#[test]
557596
fn parameter_with_last_param_usage() {
558597
check_assist(

0 commit comments

Comments
 (0)