Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LSP inlay hints for str, int, float, bool, any types #1431

Merged
merged 3 commits into from
Jul 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion kclvm/tools/src/LSP/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ anyhow = { version = "1.0", default-features = false, features = ["std"] }
crossbeam-channel = { version = "0.5.7", default-features = false }
ra_ap_vfs = "0.0.149"
ra_ap_vfs-notify = "0.0.149"
lsp-types = { version = "0.93.0", default-features = false }
lsp-types = { version = "0.93.0", features = ["proposed"]}
threadpool = { version = "1.8.1", default-features = false }
salsa = { version = "0.16.1", default-features = false }
serde_json = { version = "1.0", default-features = false }
Expand Down
2 changes: 2 additions & 0 deletions kclvm/tools/src/LSP/src/capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ pub fn server_capabilities(client_caps: &ClientCapabilities) -> ServerCapabiliti
work_done_progress_options: WorkDoneProgressOptions {
work_done_progress: None,
},
completion_item: None,
}),
hover_provider: Some(HoverProviderCapability::Simple(true)),
definition_provider: Some(OneOf::Left(true)),
Expand All @@ -62,6 +63,7 @@ pub fn server_capabilities(client_caps: &ClientCapabilities) -> ServerCapabiliti
document_range_formatting_provider: Some(OneOf::Left(true)),
references_provider: Some(OneOf::Left(true)),
rename_provider: Some(OneOf::Left(true)),
inlay_hint_provider: Some(lsp_types::OneOf::Left(true)),
..Default::default()
}
}
96 changes: 96 additions & 0 deletions kclvm/tools/src/LSP/src/inlay_hints.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
use kclvm_ast::ast::{self, Program};
use kclvm_ast::pos::GetPos;
use kclvm_error::Position as KCLPos;
use kclvm_sema::core::{global_state::GlobalState, symbol::KCLSymbol};
use kclvm_sema::ty::TypeKind;
use lsp_types::{InlayHint, InlayHintLabelPart, Position as LspPosition, Range};
use std::convert::TryInto;

pub fn inlay_hints(file: &str, gs: &GlobalState, program: &Program) -> Option<Vec<InlayHint>> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add more comments on public functions.

let mut inlay_hints: Vec<InlayHint> = vec![];
let sema_db = gs.get_sema_db();
if let Some(file_sema) = sema_db.get_file_sema(file) {
let symbols = file_sema.get_symbols();
for symbol_ref in symbols {
if let Some(symbol) = gs.get_symbols().get_symbol(*symbol_ref) {
let (start, end) = symbol.get_range();
if has_type_assignment(program, &start) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this information should be obtained by extending the API of symbol, such as is_declaration/as_declaration (in the sema module), rather than recalculating it in the syntax tree, because for a large number of symbol computations, it requires a lot of computation. cc @He1pa Could you help review it and give more comments?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I also think that hint information should not be calculated here. Perhaps it is more appropriate to calculate it when traversing the AST in AdvancedResolver. My suggestion is to store hint-related information in the symbol's sema_info. You can abstract a struct to record this information, and use this struct toconstruct the results in lsp.

if let Some(hint) = generate_inlay_hint(symbol, gs, &start, &end) {
inlay_hints.push(hint);
}
}
}
}
}
Some(inlay_hints)
}

fn has_type_assignment(program: &Program, start: &KCLPos) -> bool {
if let Some(stmt_node) = program.pos_to_stmt(start) {
if let ast::Stmt::Assign(assign_stmt) = stmt_node.node {
if assign_stmt
.targets
.iter()
.any(|target| target.get_pos() == *start)
&& assign_stmt.ty.is_none()
{
return true;
}
}
}
false
}

fn generate_inlay_hint(
symbol: &KCLSymbol,
gs: &GlobalState,
start: &KCLPos,
end: &KCLPos,
) -> Option<InlayHint> {
match get_hint_label(symbol, gs) {
Some(label_parts) => {
let range = Range {
start: LspPosition::new(
(start.line - 1).try_into().unwrap(),
start.column.unwrap_or(0).try_into().unwrap(),
),
end: LspPosition::new(
(end.line - 1).try_into().unwrap(),
end.column.unwrap_or(0).try_into().unwrap(),
),
};
Some(InlayHint {
position: range.end,
label: lsp_types::InlayHintLabel::LabelParts(label_parts),
kind: None,
text_edits: None,
tooltip: None,
padding_left: Some(true),
padding_right: Some(true),
data: None,
})
}
None => None,
}
}

fn get_hint_label(symbol: &KCLSymbol, _gs: &GlobalState) -> Option<Vec<InlayHintLabelPart>> {
if let Some(ty) = &symbol.get_sema_info().ty {
let mut label_parts = Vec::new();

match &ty.kind {
TypeKind::Str | TypeKind::Bool | TypeKind::Int | TypeKind::Float | TypeKind::Any => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function type and schema type should also be included.

label_parts.push(InlayHintLabelPart {
value: format!("[: {}]", ty.ty_str()),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
value: format!("[: {}]", ty.ty_str()),
value: format!(": {}", ty.ty_str()),

..Default::default()
});
}
_ => {
return None;
}
}
Some(label_parts)
} else {
None
}
}
1 change: 1 addition & 0 deletions kclvm/tools/src/LSP/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ mod formatting;
mod from_lsp;
mod goto_def;
mod hover;
mod inlay_hints;
mod main_loop;
mod notification;
mod quick_fix;
Expand Down
2 changes: 2 additions & 0 deletions kclvm/tools/src/LSP/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ mod find_refs;
mod from_lsp;
mod goto_def;
mod hover;
mod inlay_hints;
mod main_loop;
mod notification;
mod quick_fix;
Expand Down Expand Up @@ -73,6 +74,7 @@ fn run_server() -> anyhow::Result<()> {
name: String::from("kcl-language-server"),
version: None,
}),
offset_encoding: None,
};

let initialize_result = serde_json::to_value(initialize_result)
Expand Down
27 changes: 26 additions & 1 deletion kclvm/tools/src/LSP/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ use crate::{
formatting::format,
from_lsp::{self, file_path_from_url, kcl_pos},
goto_def::goto_def,
hover, quick_fix,
hover,
inlay_hints::inlay_hints,
quick_fix,
semantic_token::semantic_tokens_full,
state::{log_message, LanguageServerSnapshot, LanguageServerState, Task},
};
Expand Down Expand Up @@ -58,6 +60,7 @@ impl LanguageServerState {
.on::<lsp_types::request::RangeFormatting>(handle_range_formatting)?
.on::<lsp_types::request::Rename>(handle_rename)?
.on::<lsp_types::request::SemanticTokensFullRequest>(handle_semantic_tokens_full)?
.on::<lsp_types::request::InlayHintRequest>(handle_inlay_hint)?
.finish();

Ok(())
Expand Down Expand Up @@ -439,3 +442,25 @@ pub(crate) fn handle_rename(
}
}
}

pub(crate) fn handle_inlay_hint(
snapshot: LanguageServerSnapshot,
params: lsp_types::InlayHintParams,
_sender: Sender<Task>,
) -> anyhow::Result<Option<Vec<lsp_types::InlayHint>>> {
let file = file_path_from_url(&params.text_document.uri)?;
let path = from_lsp::abs_path(&params.text_document.uri)?;
let db = match snapshot.try_get_db(&path.clone().into()) {
Ok(option_db) => match option_db {
Some(db) => db,
None => return Err(anyhow!(LSPError::Retry)),
},
Err(_) => return Ok(None),
};
let res = inlay_hints(&file, &db.gs, &db.prog);

if !snapshot.verify_request_version(db.version, &path)? {
return Err(anyhow!(LSPError::Retry));
}
Ok(res)
}
Loading