11412: fix: Include `fn`/`type`/`const` keyword in trait impl completion item source ranges r=Veykril a=The0x539

Fixes #11301

If the user has typed, say, `fn de` while implementing `Default`, or `type Ta` when implementing `Deref`, then the resulting completion suggestion will replace the entire "line", which, on its own, is fine.
However, the use of `ctx.source_range()` in this code was meant that `source_range` field of the `CompletionItem` covers only the identifier and not the preceding keyword.

Over in `rust_analyzer::to_proto::completion_item`, this caused the LSP completion response to be broken up into a text edit that replaces `de` with `fn default() -> Self {` and then an entry in `additional_text_edits` to remove the extra `fn`.
I'm pretty sure that using the field like that is (slightly) out of [spec](https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#completionItem):
> Edits must not overlap [...] with the main edit
> Additional text edits should be used to change text **unrelated to the current cursor position**

VS Code supports `additionalTextEdits` in such a way that this doesn't seem like a problem, so has gone largely unnoticed.
The various LSP clients I've tried, however, do not, and as a result this bug has been haunting me for ages.

Co-authored-by: The0x539 <the0x539@gmail.com>
This commit is contained in:
bors[bot] 2022-02-05 11:54:07 +00:00 committed by GitHub
commit dd05d12055
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -145,10 +145,10 @@ fn add_function_impl(
} else {
CompletionItemKind::SymbolKind(SymbolKind::Function)
};
let mut item = CompletionItem::new(completion_kind, ctx.source_range(), label);
item.lookup_by(fn_name).set_documentation(func.docs(ctx.db));
let range = replacement_range(ctx, fn_def_node);
let mut item = CompletionItem::new(completion_kind, range, label);
item.lookup_by(fn_name).set_documentation(func.docs(ctx.db));
if let Some(source) = ctx.sema.source(func) {
let assoc_item = ast::AssocItem::Fn(source.value);
@ -209,7 +209,7 @@ fn add_type_alias_impl(
let snippet = format!("type {} = ", alias_name);
let range = replacement_range(ctx, type_def_node);
let mut item = CompletionItem::new(SymbolKind::TypeAlias, ctx.source_range(), &snippet);
let mut item = CompletionItem::new(SymbolKind::TypeAlias, range, &snippet);
item.text_edit(TextEdit::replace(range, snippet))
.lookup_by(alias_name)
.set_documentation(type_alias.docs(ctx.db));
@ -237,7 +237,7 @@ fn add_const_impl(
let snippet = make_const_compl_syntax(&transformed_const);
let range = replacement_range(ctx, const_def_node);
let mut item = CompletionItem::new(SymbolKind::Const, ctx.source_range(), &snippet);
let mut item = CompletionItem::new(SymbolKind::Const, range, &snippet);
item.text_edit(TextEdit::replace(range, snippet))
.lookup_by(const_name)
.set_documentation(const_.docs(ctx.db));