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

draft: lsp format #1632

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
33 changes: 29 additions & 4 deletions components/clarity-lsp/src/common/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ use clarinet_files::{FileAccessor, FileLocation, ProjectManifest};
use clarity_repl::clarity::diagnostic::Diagnostic;
use clarity_repl::repl::ContractDeployer;
use lsp_types::{
CompletionItem, CompletionParams, DocumentSymbol, DocumentSymbolParams, GotoDefinitionParams,
Hover, HoverParams, InitializeParams, InitializeResult, Location, SignatureHelp,
SignatureHelpParams,
CompletionItem, CompletionParams, DocumentFormattingParams, DocumentSymbol,
DocumentSymbolParams, GotoDefinitionParams, Hover, HoverParams, InitializeParams,
InitializeResult, Location, SignatureHelp, SignatureHelpParams, TextEdit,
};
use serde::{Deserialize, Serialize};
use std::sync::{Arc, RwLock};
Expand Down Expand Up @@ -258,6 +258,7 @@ pub enum LspRequest {
Definition(GotoDefinitionParams),
Hover(HoverParams),
DocumentSymbol(DocumentSymbolParams),
DocumentFormatting(DocumentFormattingParams),
Initialize(Box<InitializeParams>),
}

Expand All @@ -266,8 +267,9 @@ pub enum LspRequestResponse {
CompletionItems(Vec<CompletionItem>),
SignatureHelp(Option<SignatureHelp>),
Definition(Option<Location>),
DocumentSymbol(Vec<DocumentSymbol>),
Hover(Option<Hover>),
DocumentSymbol(Vec<DocumentSymbol>),
DocumentFormatting(Option<Vec<TextEdit>>),
Initialize(Box<InitializeResult>),
}

Expand Down Expand Up @@ -343,6 +345,28 @@ pub fn process_request(
Ok(LspRequestResponse::DocumentSymbol(document_symbols))
}

LspRequest::DocumentFormatting(param) => {
let file_url = param.text_document.uri;
let contract_location = match get_contract_location(&file_url) {
Some(contract_location) => contract_location,
None => return Ok(LspRequestResponse::DocumentFormatting(None)),
};

// todo: handling formatting options, should reconciliate `param.options` and `editor_state.settings.<formatting_options>`
// i saw that formatting_options accepts arbitrary custom props `[key: string]: boolean | integer | string;`
let formatted_file = editor_state
.try_read(|es| es.format_contract(&contract_location))
.unwrap_or_default();
println!("file formatted!");

match formatted_file {
Some(formatted_file) => Ok(LspRequestResponse::DocumentFormatting(Some(vec![
formatted_file,
]))),
None => Ok(LspRequestResponse::DocumentFormatting(None)),
}
}

LspRequest::Hover(params) => {
let file_url = params.text_document_position_params.text_document.uri;
let contract_location = match get_contract_location(&file_url) {
Expand All @@ -355,6 +379,7 @@ pub fn process_request(
.unwrap_or_default();
Ok(LspRequestResponse::Hover(hover_data))
}

_ => Err(format!("Unexpected command: {:?}", &command)),
}
}
Expand Down
1 change: 1 addition & 0 deletions components/clarity-lsp/src/common/requests/capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ pub fn get_capabilities(initialization_options: &InitializationOptions) -> Serve
}),
false => None,
},
document_formatting_provider: Some(lsp_types::OneOf::Left(true)),
..ServerCapabilities::default()
}
}
27 changes: 26 additions & 1 deletion components/clarity-lsp/src/common/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub struct ActiveContractData {
pub expressions: Option<Vec<SymbolicExpression>>,
pub definitions: Option<HashMap<(u32, u32), DefinitionLocation>>,
pub diagnostic: Option<ClarityDiagnostic>,
source: String,
pub source: String,
}

impl ActiveContractData {
Expand Down Expand Up @@ -349,6 +349,31 @@ impl EditorState {
ast_symbols.get_symbols(expressions)
}

pub fn format_contract(&self, contract_location: &FileLocation) -> Option<lsp_types::TextEdit> {
let active_contract = self.active_contracts.get(contract_location)?;
let source = &active_contract.source;

// call requests/formmatter.rs format_contract
let formatted = source.clone();

// start with a format all document strategy
let range = lsp_types::Range {
start: lsp_types::Position {
line: 0,
character: 0,
},
end: lsp_types::Position {
line: formatted.lines().count() as u32,
character: 0,
},
};

Some(lsp_types::TextEdit {
range,
new_text: formatted,
})
}

pub fn get_definition_location(
&self,
contract_location: &FileLocation,
Expand Down
17 changes: 13 additions & 4 deletions components/clarity-lsp/src/vscode_bridge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ use lsp_types::notification::{
Initialized, Notification,
};
use lsp_types::request::{
Completion, DocumentSymbolRequest, GotoDefinition, HoverRequest, Initialize, Request,
SignatureHelpRequest,
Completion, DocumentSymbolRequest, Formatting, GotoDefinition, HoverRequest, Initialize,
Request, SignatureHelpRequest,
};
use lsp_types::{
DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams,
Expand All @@ -26,7 +26,6 @@ use std::sync::{Arc, RwLock};
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::future_to_promise;

#[cfg(debug_assertions)]
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Not that println! won't be visible in wasm.

I just removed #[cfg(debug_assertions)] for debugging, don't remember how to enable it

use crate::utils::log;

#[wasm_bindgen]
Expand Down Expand Up @@ -249,6 +248,17 @@ impl LspVscodeBridge {
}
}

Formatting::METHOD => {
let lsp_response = process_request(
LspRequest::DocumentFormatting(decode_from_js(js_params)?),
&EditorStateInput::RwLock(self.editor_state_lock.clone()),
);
if let Ok(LspRequestResponse::DocumentFormatting(response)) = lsp_response {
log!("formatting response: {:?}", response);
return response.serialize(&serializer).map_err(|_| JsValue::NULL);
}
}

HoverRequest::METHOD => {
let lsp_response = process_request(
LspRequest::Hover(decode_from_js(js_params)?),
Expand All @@ -260,7 +270,6 @@ impl LspVscodeBridge {
}

_ => {
#[cfg(debug_assertions)]
log!("unexpected request ({})", method);
}
};
Expand Down
2 changes: 1 addition & 1 deletion components/clarity-vscode/server/src/serverBrowser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ declare const __EXTENSION_URL__: string;
new BrowserMessageWriter(self),
);

initSync(await wasmModule);
initSync({ module: await wasmModule });
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

fixes a warning i saw in the console. Not mandatory but will probably be needed in the future


const bridge = new LspVscodeBridge(
connection.sendDiagnostics,
Expand Down
14 changes: 8 additions & 6 deletions components/clarity-vscode/web-extension.code-workspace
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
{
"folders": [
{
"path": "./"
"path": "./",
},
{
"path": "../../"
}
"path": "../../",
},
],
"settings": {
"rust-analyzer.cargo.noDefaultFeatures": true,
"rust-analyzer.cargo.features": ["clarity-lsp/wasm"],
"rust-analyzer.cargo.allTargets": false,
"rust-analyzer.check.workspace": false,
"rust-analyzer.check.overrideCommand": [
"cargo",
"clippy",
"--no-default-features",
"--package=clarity-lsp",
"--features=wasm",
"--message-format=json"
]
}
"--message-format=json",
],
},
}
Loading