fix: generate method assist uses enclosing impl block instead of first found

This commit is contained in:
protonblu 2026-02-20 19:01:22 +05:30
parent 46a214b5d3
commit f858569371

View File

@ -146,10 +146,19 @@ fn gen_method(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
if !is_editable_crate(target_module.krate(ctx.db()), ctx.db()) {
return None;
}
//Change
let enclosing_impl = ctx.find_node_at_offset::<ast::Impl>();
let cursor_impl = enclosing_impl.filter(|impl_| {
ctx.sema.to_def(impl_).map_or(false, |def| def.self_ty(ctx.sema.db).as_adt() == Some(adt))
});
let (impl_, file) = get_adt_source(ctx, &adt, fn_name.text().as_str())?;
let (impl_, file) = if let Some(impl_) = cursor_impl {
(Some(impl_), ctx.vfs_file_id())
} else {
get_adt_source(ctx, &adt, fn_name.text().as_str())?
};
let target = get_method_target(ctx, &impl_, &adt)?;
//change
let function_builder = FunctionBuilder::from_method_call(
ctx,
&call,
@ -3205,5 +3214,45 @@ fn bar(arg: impl Fn(_) -> bool) {
}
"#,
);
}#[test]
fn generate_method_uses_current_impl_block() {
check_assist(
generate_function,
r"
struct Foo;
impl Foo {
fn new() -> Self {
Foo
}
}
impl Foo {
fn method1(&self) {
self.method2$0(42)
}
}
",
r"
struct Foo;
impl Foo {
fn new() -> Self {
Foo
}
}
impl Foo {
fn method1(&self) {
self.method2(42)
}
fn method2(&self, arg: i32) {
${0:todo!()}
}
}
",
)
}
}