Skip to content
This repository has been archived by the owner on Oct 24, 2023. It is now read-only.

feat: implement default global settings #12

Merged
merged 1 commit into from
Oct 1, 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.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
mktemp = "0.5"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1.32.0", features = ["fs", "io-std", "macros", "process", "rt-multi-thread"] }
Expand Down
17 changes: 17 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use std::{borrow::Cow, error::Error};

use serde_json::Value;

pub(crate) fn map_err_to_internal_error(e: impl Error, msg: String) -> tower_lsp::jsonrpc::Error {
let mut err = tower_lsp::jsonrpc::Error::internal_error();
err.data = Some(Value::String(format!("{e:?}")));
err.message = Cow::from(msg);
err
}

pub(crate) fn map_err_to_parse_error(e: impl Error, msg: String) -> tower_lsp::jsonrpc::Error {
let mut err = tower_lsp::jsonrpc::Error::parse_error();
err.data = Some(Value::String(format!("{e:?}")));
err.message = Cow::from(msg);
err
}
181 changes: 95 additions & 86 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,36 @@
#![deny(clippy::all, unsafe_code)]
#![deny(clippy::all, clippy::pedantic, unsafe_code)]

use std::borrow::Cow;
use std::{borrow::Cow, ffi::OsStr, sync::RwLock};

use error::map_err_to_parse_error;
use nu::{
convert_position, convert_span, find_line_breaks, run_compiler, IdeComplete, IdeGotoDef,
IdeHover, IdeSettings,
};

use nu::{convert_position, convert_span, find_line_breaks, IdeComplete, IdeGotoDef, IdeHover};
use serde_json::Value;
use tower_lsp::jsonrpc::Result;
#[allow(clippy::wildcard_imports)]
use tower_lsp::lsp_types::*;
use tower_lsp::{Client, LanguageServer, LspService, Server};

mod error;
mod nu;

#[derive(Debug)]
struct Backend {
client: Client,
ide_settings: RwLock<IdeSettings>,
}
impl Backend {
fn get_document_settings(&self) -> Result<IdeSettings> {
Ok(self
.ide_settings
.read()
.map_err(|e| {
tower_lsp::jsonrpc::Error::invalid_params(format!("cannot read settings: {e:?}"))
})?
.clone())
}
}

#[tower_lsp::async_trait]
Expand All @@ -34,6 +52,13 @@ impl LanguageServer for Backend {
text_document_sync: Some(TextDocumentSyncCapability::Kind(
TextDocumentSyncKind::NONE,
)),
workspace: Some(WorkspaceServerCapabilities {
workspace_folders: Some(WorkspaceFoldersServerCapabilities {
supported: Some(true),
change_notifications: Some(OneOf::Left(true)),
}),
..Default::default()
}),
..Default::default()
},
server_info: Some(ServerInfo {
Expand Down Expand Up @@ -64,37 +89,29 @@ impl LanguageServer for Backend {
.to_file_path()
.map_err(|e| {
tower_lsp::jsonrpc::Error::invalid_params(format!(
"cannot convert URI to filesystem path: {:?}",
e
"cannot convert URI to filesystem path: {e:?}",
))
})?;
let text = tokio::fs::read_to_string(&file_path).await.map_err(|e| {
tower_lsp::jsonrpc::Error::invalid_params(format!("cannot read file: {}", e))
tower_lsp::jsonrpc::Error::invalid_params(format!("cannot read file: {e:?}"))
})?;
let offset = convert_position(&params.text_document_position.position, &text);

// TODO: call nushell Rust code directly instead of via separate process
let output = tokio::process::Command::new("nu")
.args([
"--ide-complete",
&format!("{}", offset),
&format!("{}", file_path.display()),
])
.output()
.await
.map_err(|e| {
let mut err = tower_lsp::jsonrpc::Error::internal_error();
err.data = Some(Value::String(format!("{:?}", e)));
err.message = Cow::from("`nu --ide-complete` failed");
err
})?;
let offset = convert_position(params.text_document_position.position, &text);

let ide_settings = self.get_document_settings()?;
let output = run_compiler(
&text,
vec![
OsStr::new("--ide-complete"),
OsStr::new(&format!("{offset}")),
],
ide_settings,
params.text_document_position.text_document.uri,
)
.await?;

let complete: IdeComplete =
serde_json::from_slice(output.stdout.as_slice()).map_err(|e| {
let mut err = tower_lsp::jsonrpc::Error::parse_error();
err.data = Some(Value::String(format!("{:?}", e)));
err.message = Cow::from("failed to parse response from `nu --ide-complete`");
err
serde_json::from_slice(output.stdout.as_bytes()).map_err(|e| {
map_err_to_parse_error(e, format!("cannot parse response from {}", output.cmdline))
})?;

Ok(Some(CompletionResponse::Array(
Expand All @@ -117,45 +134,34 @@ impl LanguageServer for Backend {
.to_file_path()
.map_err(|e| {
tower_lsp::jsonrpc::Error::invalid_params(format!(
"cannot convert URI to filesystem path: {:?}",
e
"cannot convert URI to filesystem path: {e:?}",
))
})?;
let text = tokio::fs::read_to_string(&file_path).await.map_err(|e| {
tower_lsp::jsonrpc::Error::invalid_params(format!("cannot read file: {}", e))
tower_lsp::jsonrpc::Error::invalid_params(format!("cannot read file: {e:?}"))
})?;
let offset = convert_position(&params.text_document_position_params.position, &text);

// TODO: call nushell Rust code directly instead of via separate process
let output = tokio::process::Command::new("nu")
.args([
"--ide-goto-def",
&format!("{}", offset),
&format!("{}", file_path.display()),
])
.output()
.await
.map_err(|e| {
let mut err = tower_lsp::jsonrpc::Error::internal_error();
err.data = Some(Value::String(format!("{:?}", e)));
err.message = Cow::from("`nu --ide-goto-def` failed");
err
})?;
let offset = convert_position(params.text_document_position_params.position, &text);

let ide_settings = self.get_document_settings()?;
let output = run_compiler(
&text,
vec![
OsStr::new("--ide-goto-def"),
OsStr::new(&format!("{offset}")),
],
ide_settings,
params.text_document_position_params.text_document.uri,
)
.await?;

let goto_def: IdeGotoDef =
serde_json::from_slice(output.stdout.as_slice()).map_err(|e| {
let mut err = tower_lsp::jsonrpc::Error::parse_error();
err.data = Some(Value::String(format!("{:?}", e)));
err.message = Cow::from("failed to parse response from `nu --ide-goto-def`");
err
serde_json::from_slice(output.stdout.as_bytes()).map_err(|e| {
map_err_to_parse_error(e, format!("cannot parse response from {}", output.cmdline))
})?;

let line_breaks = find_line_breaks(&text);

if matches!(
goto_def.file.to_str(),
None | Some("") | Some("__prelude__")
) {
if matches!(goto_def.file.to_str(), None | Some("" | "__prelude__")) {
return Ok(None);
}

Expand All @@ -170,9 +176,8 @@ impl LanguageServer for Backend {
}

Ok(Some(GotoDefinitionResponse::Scalar(Location {
uri: Url::from_file_path(goto_def.file).map_err(|e| {
uri: Url::from_file_path(goto_def.file).map_err(|_| {
let mut err = tower_lsp::jsonrpc::Error::parse_error();
err.data = Some(Value::String(format!("{:?}", e)));
err.message = Cow::from(
"failed to parse filesystem path in response from `nu --ide-goto-def`",
);
Expand All @@ -193,36 +198,25 @@ impl LanguageServer for Backend {
.to_file_path()
.map_err(|e| {
tower_lsp::jsonrpc::Error::invalid_params(format!(
"cannot convert URI to filesystem path: {:?}",
e
"cannot convert URI to filesystem path: {e:?}",
))
})?;
let text = tokio::fs::read_to_string(&file_path).await.map_err(|e| {
tower_lsp::jsonrpc::Error::invalid_params(format!("cannot read file: {}", e))
tower_lsp::jsonrpc::Error::invalid_params(format!("cannot read file: {e:?}"))
})?;
let offset = convert_position(&params.text_document_position_params.position, &text);

// TODO: call nushell Rust code directly instead of via separate process
let output = tokio::process::Command::new("nu")
.args([
"--ide-hover",
&format!("{}", offset),
&format!("{}", file_path.display()),
])
.output()
.await
.map_err(|e| {
let mut err = tower_lsp::jsonrpc::Error::internal_error();
err.data = Some(Value::String(format!("{:?}", e)));
err.message = Cow::from("`nu --ide-hover` failed");
err
})?;
let offset = convert_position(params.text_document_position_params.position, &text);

let ide_settings = self.get_document_settings()?;
let output = run_compiler(
&text,
vec![OsStr::new("--ide-hover"), OsStr::new(&format!("{offset}"))],
ide_settings,
params.text_document_position_params.text_document.uri,
)
.await?;

let hover: IdeHover = serde_json::from_slice(output.stdout.as_slice()).map_err(|e| {
let mut err = tower_lsp::jsonrpc::Error::parse_error();
err.data = Some(Value::String(format!("{:?}", e)));
err.message = Cow::from("failed to parse response from `nu --ide-hover`");
err
let hover: IdeHover = serde_json::from_slice(output.stdout.as_bytes()).map_err(|e| {
map_err_to_parse_error(e, format!("cannot parse response from {}", output.cmdline))
})?;

let line_breaks = find_line_breaks(&text);
Expand All @@ -236,13 +230,28 @@ impl LanguageServer for Backend {
range,
}))
}

async fn did_change_workspace_folders(&self, params: DidChangeWorkspaceFoldersParams) {
self.client
.log_message(
MessageType::INFO,
format!(
"workspace folders: added={:?}; removed={:?}",
params.event.added, params.event.removed
),
)
.await;
}
}

#[tokio::main]
async fn main() {
let stdin = tokio::io::stdin();
let stdout = tokio::io::stdout();

let (service, socket) = LspService::new(|client| Backend { client });
let (service, socket) = LspService::new(|client| Backend {
client,
ide_settings: RwLock::new(IdeSettings::default()),
});
Server::new(stdin, stdout, socket).serve(service).await;
}
Loading