[ty] Add "kind" to completion suggestions

This makes use of the new `Type` field on `Completion` to figure out the
"kind" of a `Completion`.

The mapping here is perhaps a little suspect for some cases.

Closes astral-sh/ty#775
This commit is contained in:
Andrew Gallant 2025-07-08 15:44:00 -04:00 committed by Andrew Gallant
parent fea84e8777
commit 1eff0300d3
3 changed files with 134 additions and 6 deletions

View file

@ -1,10 +1,11 @@
use std::borrow::Cow;
use lsp_types::request::Completion;
use lsp_types::{CompletionItem, CompletionParams, CompletionResponse, Url};
use lsp_types::{CompletionItem, CompletionItemKind, CompletionParams, CompletionResponse, Url};
use ruff_db::source::{line_index, source_text};
use ty_ide::completion;
use ty_project::ProjectDatabase;
use ty_python_semantic::CompletionKind;
use crate::DocumentSnapshot;
use crate::document::PositionExt;
@ -55,10 +56,14 @@ impl BackgroundDocumentRequestHandler for CompletionRequestHandler {
let items: Vec<CompletionItem> = completions
.into_iter()
.enumerate()
.map(|(i, comp)| CompletionItem {
label: comp.name.into(),
sort_text: Some(format!("{i:-max_index_len$}")),
..Default::default()
.map(|(i, comp)| {
let kind = comp.kind(db).map(ty_kind_to_lsp_kind);
CompletionItem {
label: comp.name.into(),
kind,
sort_text: Some(format!("{i:-max_index_len$}")),
..Default::default()
}
})
.collect();
let response = CompletionResponse::Array(items);
@ -69,3 +74,38 @@ impl BackgroundDocumentRequestHandler for CompletionRequestHandler {
impl RetriableRequestHandler for CompletionRequestHandler {
const RETRY_ON_CANCELLATION: bool = true;
}
fn ty_kind_to_lsp_kind(kind: CompletionKind) -> CompletionItemKind {
// Gimme my dang globs in tight scopes!
#[allow(clippy::enum_glob_use)]
use self::CompletionKind::*;
// ref https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#completionItemKind
match kind {
Text => CompletionItemKind::TEXT,
Method => CompletionItemKind::METHOD,
Function => CompletionItemKind::FUNCTION,
Constructor => CompletionItemKind::CONSTRUCTOR,
Field => CompletionItemKind::FIELD,
Variable => CompletionItemKind::VARIABLE,
Class => CompletionItemKind::CLASS,
Interface => CompletionItemKind::INTERFACE,
Module => CompletionItemKind::MODULE,
Property => CompletionItemKind::PROPERTY,
Unit => CompletionItemKind::UNIT,
Value => CompletionItemKind::VALUE,
Enum => CompletionItemKind::ENUM,
Keyword => CompletionItemKind::KEYWORD,
Snippet => CompletionItemKind::SNIPPET,
Color => CompletionItemKind::COLOR,
File => CompletionItemKind::FILE,
Reference => CompletionItemKind::REFERENCE,
Folder => CompletionItemKind::FOLDER,
EnumMember => CompletionItemKind::ENUM_MEMBER,
Constant => CompletionItemKind::CONSTANT,
Struct => CompletionItemKind::STRUCT,
Event => CompletionItemKind::EVENT,
Operator => CompletionItemKind::OPERATOR,
TypeParameter => CompletionItemKind::TYPE_PARAMETER,
}
}