diff --git a/crates/ide/src/rename.rs b/crates/ide/src/rename.rs index e46cb5a781..f17c1fa5c6 100644 --- a/crates/ide/src/rename.rs +++ b/crates/ide/src/rename.rs @@ -421,19 +421,28 @@ fn text_edit_from_self_param(self_param: &ast::SelfParam, new_name: &str) -> Opt None } - let impl_def = self_param.syntax().ancestors().find_map(ast::Impl::cast)?; - let type_name = target_type_name(&impl_def)?; + match self_param.syntax().ancestors().find_map(ast::Impl::cast) { + Some(impl_def) => { + let type_name = target_type_name(&impl_def)?; - let mut replacement_text = String::from(new_name); - replacement_text.push_str(": "); - match (self_param.amp_token(), self_param.mut_token()) { - (Some(_), None) => replacement_text.push('&'), - (Some(_), Some(_)) => replacement_text.push_str("&mut "), - (_, _) => (), - }; - replacement_text.push_str(type_name.as_str()); + let mut replacement_text = String::from(new_name); + replacement_text.push_str(": "); + match (self_param.amp_token(), self_param.mut_token()) { + (Some(_), None) => replacement_text.push('&'), + (Some(_), Some(_)) => replacement_text.push_str("&mut "), + (_, _) => (), + }; + replacement_text.push_str(type_name.as_str()); - Some(TextEdit::replace(self_param.syntax().text_range(), replacement_text)) + Some(TextEdit::replace(self_param.syntax().text_range(), replacement_text)) + } + None => { + cov_mark::hit!(rename_self_outside_of_methods); + let mut replacement_text = String::from(new_name); + replacement_text.push_str(": _"); + Some(TextEdit::replace(self_param.syntax().text_range(), replacement_text)) + } + } } #[cfg(test)] @@ -1977,6 +1986,26 @@ impl Foo { ); } + #[test] + fn test_self_outside_of_methods() { + cov_mark::check!(rename_self_outside_of_methods); + check( + "foo", + r#" +fn f($0self) -> i32 { + use self as _; + self.i +} +"#, + r#" +fn f(foo: _) -> i32 { + use self as _; + foo.i +} +"#, + ); + } + #[test] fn test_self_in_path_to_parameter() { check(