Skip to content

Commit af68fc6

Browse files
authored
Merge pull request #21684 from akashchakrabortymsc-cmd/fix/generate-method-wrong-impl-block
fix: generate method assist uses enclosing impl block instead of first found
2 parents 46a214b + ab26b67 commit af68fc6

1 file changed

Lines changed: 50 additions & 1 deletion

File tree

crates/ide-assists/src/handlers/generate_function.rs

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,16 @@ fn gen_method(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
147147
return None;
148148
}
149149

150-
let (impl_, file) = get_adt_source(ctx, &adt, fn_name.text().as_str())?;
150+
let enclosing_impl = ctx.find_node_at_offset::<ast::Impl>();
151+
let cursor_impl = enclosing_impl.filter(|impl_| {
152+
ctx.sema.to_def(impl_).map_or(false, |def| def.self_ty(ctx.sema.db).as_adt() == Some(adt))
153+
});
154+
155+
let (impl_, file) = if let Some(impl_) = cursor_impl {
156+
(Some(impl_), ctx.vfs_file_id())
157+
} else {
158+
get_adt_source(ctx, &adt, fn_name.text().as_str())?
159+
};
151160
let target = get_method_target(ctx, &impl_, &adt)?;
152161

153162
let function_builder = FunctionBuilder::from_method_call(
@@ -3206,4 +3215,44 @@ fn bar(arg: impl Fn(_) -> bool) {
32063215
"#,
32073216
);
32083217
}
3218+
#[test]
3219+
fn generate_method_uses_current_impl_block() {
3220+
check_assist(
3221+
generate_function,
3222+
r"
3223+
struct Foo;
3224+
3225+
impl Foo {
3226+
fn new() -> Self {
3227+
Foo
3228+
}
3229+
}
3230+
3231+
impl Foo {
3232+
fn method1(&self) {
3233+
self.method2$0(42)
3234+
}
3235+
}
3236+
",
3237+
r"
3238+
struct Foo;
3239+
3240+
impl Foo {
3241+
fn new() -> Self {
3242+
Foo
3243+
}
3244+
}
3245+
3246+
impl Foo {
3247+
fn method1(&self) {
3248+
self.method2(42)
3249+
}
3250+
3251+
fn method2(&self, arg: i32) {
3252+
${0:todo!()}
3253+
}
3254+
}
3255+
",
3256+
)
3257+
}
32093258
}

0 commit comments

Comments
 (0)