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

feat: add lsp formatting #3433

Merged
merged 4 commits into from Nov 22, 2023
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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions tooling/lsp/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ codespan-lsp.workspace = true
codespan-reporting.workspace = true
lsp-types.workspace = true
nargo.workspace = true
nargo_fmt.workspace = true
nargo_toml.workspace = true
noirc_driver.workspace = true
noirc_errors.workspace = true
Expand Down
14 changes: 11 additions & 3 deletions tooling/lsp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#![cfg_attr(not(test), warn(unused_crate_dependencies, unused_extern_crates))]

use std::{
collections::HashMap,
future::Future,
ops::{self, ControlFlow},
path::{Path, PathBuf},
Expand All @@ -26,8 +27,8 @@ use notifications::{
on_did_open_text_document, on_did_save_text_document, on_exit, on_initialized,
};
use requests::{
on_code_lens_request, on_initialize, on_profile_run_request, on_shutdown, on_test_run_request,
on_tests_request,
on_code_lens_request, on_formatting, on_initialize, on_profile_run_request, on_shutdown,
on_test_run_request, on_tests_request,
};
use serde_json::Value as JsonValue;
use tower::Service;
Expand All @@ -45,11 +46,17 @@ pub struct LspState {
root_path: Option<PathBuf>,
client: ClientSocket,
solver: WrapperSolver,
input_files: HashMap<String, String>,
}

impl LspState {
fn new(client: &ClientSocket, solver: impl BlackBoxFunctionSolver + 'static) -> Self {
Self { client: client.clone(), root_path: None, solver: WrapperSolver(Box::new(solver)) }
Self {
client: client.clone(),
root_path: None,
solver: WrapperSolver(Box::new(solver)),
input_files: HashMap::new(),
}
}
}

Expand All @@ -63,6 +70,7 @@ impl NargoLspService {
let mut router = Router::new(state);
router
.request::<request::Initialize, _>(on_initialize)
.request::<request::Formatting, _>(on_formatting)
.request::<request::Shutdown, _>(on_shutdown)
.request::<request::CodeLens, _>(on_code_lens_request)
.request::<request::NargoTests, _>(on_tests_request)
Expand Down
16 changes: 10 additions & 6 deletions tooling/lsp/src/notifications/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,23 +30,27 @@ pub(super) fn on_did_change_configuration(
}

pub(super) fn on_did_open_text_document(
_state: &mut LspState,
_params: DidOpenTextDocumentParams,
state: &mut LspState,
params: DidOpenTextDocumentParams,
) -> ControlFlow<Result<(), async_lsp::Error>> {
state.input_files.insert(params.text_document.uri.to_string(), params.text_document.text);
ControlFlow::Continue(())
}

pub(super) fn on_did_change_text_document(
_state: &mut LspState,
_params: DidChangeTextDocumentParams,
state: &mut LspState,
params: DidChangeTextDocumentParams,
) -> ControlFlow<Result<(), async_lsp::Error>> {
let text = params.content_changes.into_iter().next().unwrap().text;
state.input_files.insert(params.text_document.uri.to_string(), text);
ControlFlow::Continue(())
}

pub(super) fn on_did_close_text_document(
_state: &mut LspState,
_params: DidCloseTextDocumentParams,
state: &mut LspState,
params: DidCloseTextDocumentParams,
) -> ControlFlow<Result<(), async_lsp::Error>> {
state.input_files.remove(&params.text_document.uri.to_string());
ControlFlow::Continue(())
}

Expand Down
53 changes: 46 additions & 7 deletions tooling/lsp/src/requests/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use std::future::Future;

use crate::types::{CodeLensOptions, InitializeParams, TextDocumentSyncOptions};
use crate::types::{CodeLensOptions, InitializeParams};
use async_lsp::ResponseError;
use lsp_types::{Position, TextDocumentSyncCapability, TextDocumentSyncKind};
use nargo_fmt::Config;

use crate::{
types::{InitializeResult, NargoCapability, NargoTestsOptions, ServerCapabilities},
Expand Down Expand Up @@ -35,8 +37,7 @@ pub(crate) fn on_initialize(
state.root_path = params.root_uri.and_then(|root_uri| root_uri.to_file_path().ok());

async {
let text_document_sync =
TextDocumentSyncOptions { save: Some(true.into()), ..Default::default() };
let text_document_sync = TextDocumentSyncCapability::Kind(TextDocumentSyncKind::FULL);

let code_lens = CodeLensOptions { resolve_provider: Some(false) };

Expand All @@ -50,15 +51,52 @@ pub(crate) fn on_initialize(

Ok(InitializeResult {
capabilities: ServerCapabilities {
text_document_sync: Some(text_document_sync.into()),
text_document_sync: Some(text_document_sync),
code_lens_provider: Some(code_lens),
document_formatting_provider: true,
nargo: Some(nargo),
},
server_info: None,
})
}
}

pub(crate) fn on_formatting(
state: &mut LspState,
params: lsp_types::DocumentFormattingParams,
) -> impl Future<Output = Result<Option<Vec<lsp_types::TextEdit>>, ResponseError>> {
std::future::ready(on_formatting_inner(state, params))
}

fn on_formatting_inner(
state: &LspState,
params: lsp_types::DocumentFormattingParams,
) -> Result<Option<Vec<lsp_types::TextEdit>>, ResponseError> {
let path = params.text_document.uri.to_string();

if let Some(source) = state.input_files.get(&path) {
let (module, errors) = noirc_frontend::parse_program(source);
if !errors.is_empty() {
return Ok(None);
}

let new_text = nargo_fmt::format(source, module, &Config::default());

let start_position = Position { line: 0, character: 0 };
let end_position = Position {
line: source.lines().count() as u32,
character: source.chars().count() as u32,
};

Ok(Some(vec![lsp_types::TextEdit {
range: lsp_types::Range::new(start_position, end_position),
new_text,
}]))
} else {
Ok(None)
}
}

pub(crate) fn on_shutdown(
_state: &mut LspState,
_params: (),
Expand All @@ -70,7 +108,7 @@ pub(crate) fn on_shutdown(
mod initialization {
use async_lsp::ClientSocket;
use lsp_types::{
CodeLensOptions, InitializeParams, TextDocumentSyncCapability, TextDocumentSyncOptions,
CodeLensOptions, InitializeParams, TextDocumentSyncCapability, TextDocumentSyncKind,
};
use tokio::test;

Expand All @@ -88,10 +126,11 @@ mod initialization {
assert!(matches!(
response.capabilities,
ServerCapabilities {
text_document_sync: Some(TextDocumentSyncCapability::Options(
TextDocumentSyncOptions { save: Some(_), .. }
text_document_sync: Some(TextDocumentSyncCapability::Kind(
TextDocumentSyncKind::FULL
)),
code_lens_provider: Some(CodeLensOptions { resolve_provider: Some(false) }),
document_formatting_provider: true,
..
}
));
Expand Down
7 changes: 5 additions & 2 deletions tooling/lsp/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub(crate) use lsp_types::{
DidChangeConfigurationParams, DidChangeTextDocumentParams, DidCloseTextDocumentParams,
DidOpenTextDocumentParams, DidSaveTextDocumentParams, InitializeParams, InitializedParams,
LogMessageParams, MessageType, Position, PublishDiagnosticsParams, Range, ServerInfo,
TextDocumentSyncCapability, TextDocumentSyncOptions, Url,
TextDocumentSyncCapability, Url,
};

pub(crate) mod request {
Expand All @@ -24,7 +24,7 @@ pub(crate) mod request {
};

// Re-providing lsp_types that we don't need to override
pub(crate) use lsp_types::request::{CodeLensRequest as CodeLens, Shutdown};
pub(crate) use lsp_types::request::{CodeLensRequest as CodeLens, Formatting, Shutdown};

#[derive(Debug)]
pub(crate) struct Initialize;
Expand Down Expand Up @@ -112,6 +112,9 @@ pub(crate) struct ServerCapabilities {
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) code_lens_provider: Option<CodeLensOptions>,

/// The server provides document formatting.
pub(crate) document_formatting_provider: bool,

/// The server handles and provides custom nargo messages.
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) nargo: Option<NargoCapability>,
Expand Down
Loading