wip: Fetching diagnostics, parsing notifications.

pull/5/head
Blaž Hrastnik 4 years ago
parent f03830b047
commit 13cb442850

21
Cargo.lock generated

@ -128,9 +128,9 @@ dependencies = [
[[package]]
name = "async-task"
version = "4.0.2"
version = "4.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ab27c1aa62945039e44edaeee1dc23c74cc0c303dd5fe0fb462a184f1c3a518"
checksum = "e91831deabf0d6d7ec49552e489aed63b7456a7a3c46cff62adad428110b0af0"
[[package]]
name = "atomic-waker"
@ -446,6 +446,7 @@ dependencies = [
"anyhow",
"futures-util",
"glob",
"helix-core",
"jsonrpc-core",
"lsp-types",
"pathdiff",
@ -767,9 +768,9 @@ checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]]
name = "polling"
version = "2.0.1"
version = "2.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab773feb154f12c49ffcfd66ab8bdcf9a1843f950db48b0d8be9d4393783b058"
checksum = "a2a7bc6b2a29e632e45451c941832803a18cce6781db04de8a04696cdca8bde4"
dependencies = [
"cfg-if",
"libc",
@ -878,18 +879,18 @@ checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
[[package]]
name = "serde"
version = "1.0.116"
version = "1.0.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96fe57af81d28386a513cbc6858332abc6117cfdb5999647c6444b8f43a370a5"
checksum = "b88fa983de7720629c9387e9f517353ed404164b1e482c970a90c1a4aaf7dc1a"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.116"
version = "1.0.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f630a6370fd8e457873b4bd2ffdae75408bc291ba72be773772a4c2a065d9ae8"
checksum = "cbd1ae72adb44aab48f325a02444a5fc079349a8d804c1fc922aed3f7454c74e"
dependencies = [
"proc-macro2",
"quote",
@ -992,9 +993,9 @@ dependencies = [
[[package]]
name = "syn"
version = "1.0.44"
version = "1.0.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e03e57e4fcbfe7749842d53e24ccb9aa12b7252dbe5e91d2acad31834c8b8fdd"
checksum = "ea9c5432ff16d6152371f808fb5a871cd67368171b09bb21b43df8e4a47a3556"
dependencies = [
"proc-macro2",
"quote",

@ -7,6 +7,8 @@ edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
helix-core = { path = "../helix-core" }
lsp-types = { version = "0.82", features = ["proposed"] }
smol = "1.2"
url = "2"

File diff suppressed because one or more lines are too long

@ -1,18 +1,22 @@
mod transport;
use transport::{Payload, Transport};
use std::collections::HashMap;
use jsonrpc_core as jsonrpc;
use lsp_types as lsp;
use serde_json::Value;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use smol::channel::{Receiver, Sender};
use smol::io::{BufReader, BufWriter};
use smol::prelude::*;
use smol::process::{Child, ChildStderr, ChildStdin, ChildStdout, Command, Stdio};
use smol::Executor;
use futures_util::{select, FutureExt};
use smol::{
channel::{Receiver, Sender},
io::{BufReader, BufWriter},
process::{Child, ChildStderr, Command, Stdio},
Executor,
};
/// A type representing all possible values sent from the server to the client.
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
@ -27,14 +31,40 @@ enum Message {
Call(jsonrpc::Call),
}
#[derive(Debug, PartialEq, Clone)]
enum Notification {}
impl Notification {
pub fn parse(method: &str, params: jsonrpc::Params) {
use lsp::notification::Notification as _;
match method {
lsp::notification::PublishDiagnostics::METHOD => {
let params: lsp::PublishDiagnosticsParams = params
.parse()
.expect("Failed to parse PublishDiagnostics params");
println!("{:?}", params);
// TODO: need to loop over diagnostics and distinguish them by URI
}
_ => println!("unhandled notification: {}", method),
}
}
}
pub struct Client {
process: Child,
stderr: BufReader<ChildStderr>,
outgoing: Sender<Payload>,
incoming: Receiver<Message>,
pub request_counter: u64,
capabilities: Option<lsp::ServerCapabilities>,
// TODO: handle PublishDiagnostics Version
diagnostics: HashMap<lsp::Url, Vec<lsp::Diagnostic>>,
}
impl Client {
@ -58,11 +88,14 @@ impl Client {
Client {
process,
stderr,
outgoing,
incoming,
request_counter: 0,
capabilities: None,
diagnostics: HashMap::new(),
}
}
@ -187,191 +220,45 @@ impl Client {
// Text document
// -------------------------------------------------------------------------------------------
pub async fn text_document_did_open(&mut self) -> anyhow::Result<()> {
pub async fn text_document_did_open(
&mut self,
state: &helix_core::State,
) -> anyhow::Result<()> {
self.notify::<lsp::notification::DidOpenTextDocument>(lsp::DidOpenTextDocumentParams {
text_document: lsp::TextDocumentItem {
uri: lsp::Url::parse(".")?,
language_id: "rust".to_string(),
uri: lsp::Url::from_file_path(
std::fs::canonicalize(state.path.as_ref().unwrap()).unwrap(),
)
.unwrap(),
language_id: "rust".to_string(), // TODO: hardcoded for now
version: 0,
text: "".to_string(),
text: String::from(&state.doc),
},
})
.await
}
pub async fn text_document_did_change(&mut self) -> anyhow::Result<()> {
unimplemented!()
}
// will_save / will_save_wait_until
pub async fn text_document_did_save(&mut self) -> anyhow::Result<()> {
unimplemented!()
// TODO: trigger any time history.commit_revision happens
pub async fn text_document_did_change(
&mut self,
state: &helix_core::State,
) -> anyhow::Result<()> {
self.notify::<lsp::notification::DidSaveTextDocument>(lsp::DidSaveTextDocumentParams {
text_document: lsp::TextDocumentIdentifier::new(
lsp::Url::from_file_path(state.path.as_ref().unwrap()).unwrap(),
),
text: None, // TODO?
})
.await
}
pub async fn text_document_did_close(&mut self) -> anyhow::Result<()> {
unimplemented!()
}
}
enum Payload {
Request {
chan: Sender<anyhow::Result<Value>>,
value: jsonrpc::MethodCall,
},
Notification(jsonrpc::Notification),
}
struct Transport {
incoming: Sender<Message>,
outgoing: Receiver<Payload>,
pending_requests: HashMap<jsonrpc::Id, Sender<anyhow::Result<Value>>>,
headers: HashMap<String, String>,
writer: BufWriter<ChildStdin>,
reader: BufReader<ChildStdout>,
}
impl Transport {
pub fn start(
ex: &Executor,
reader: BufReader<ChildStdout>,
writer: BufWriter<ChildStdin>,
) -> (Receiver<Message>, Sender<Payload>) {
let (incoming, rx) = smol::channel::unbounded();
let (tx, outgoing) = smol::channel::unbounded();
let transport = Self {
reader,
writer,
incoming,
outgoing,
pending_requests: Default::default(),
headers: Default::default(),
};
ex.spawn(transport.duplex()).detach();
(rx, tx)
}
async fn recv(
reader: &mut (impl AsyncBufRead + Unpin),
headers: &mut HashMap<String, String>,
) -> Result<Message, std::io::Error> {
// read headers
loop {
let mut header = String::new();
// detect pipe closed if 0
reader.read_line(&mut header).await?;
let header = header.trim();
if header.is_empty() {
break;
}
let parts: Vec<&str> = header.split(": ").collect();
if parts.len() != 2 {
// return Err(Error::new(ErrorKind::Other, "Failed to parse header"));
panic!()
}
headers.insert(parts[0].to_string(), parts[1].to_string());
}
// find content-length
let content_length = headers.get("Content-Length").unwrap().parse().unwrap();
let mut content = vec![0; content_length];
reader.read_exact(&mut content).await?;
let msg = String::from_utf8(content).unwrap();
// read data
// try parsing as output (server response) or call (server request)
let output: serde_json::Result<Message> = serde_json::from_str(&msg);
Ok(output?)
}
pub async fn send_payload(&mut self, payload: Payload) -> anyhow::Result<()> {
match payload {
Payload::Request { chan, value } => {
self.pending_requests.insert(value.id.clone(), chan);
let json = serde_json::to_string(&value)?;
self.send(json).await
}
Payload::Notification(value) => {
let json = serde_json::to_string(&value)?;
self.send(json).await
}
}
}
pub async fn send(&mut self, request: String) -> anyhow::Result<()> {
println!("-> {}", request);
// send the headers
self.writer
.write_all(format!("Content-Length: {}\r\n\r\n", request.len()).as_bytes())
.await?;
// send the body
self.writer.write_all(request.as_bytes()).await?;
self.writer.flush().await?;
Ok(())
}
pub async fn recv_response(&mut self, output: jsonrpc::Output) -> anyhow::Result<()> {
match output {
jsonrpc::Output::Success(jsonrpc::Success { id, result, .. }) => {
println!("<- {}", result);
let tx = self
.pending_requests
.remove(&id)
.expect("pending_request with id not found!");
tx.send(Ok(result)).await?;
}
jsonrpc::Output::Failure(_) => panic!("recv fail"),
msg => unimplemented!("{:?}", msg),
}
Ok(())
}
// will_save / will_save_wait_until
pub async fn duplex(mut self) {
loop {
select! {
// client -> server
msg = self.outgoing.next().fuse() => {
if msg.is_none() {
break;
}
let msg = msg.unwrap();
self.send_payload(msg).await.unwrap();
}
// server <- client
msg = Self::recv(&mut self.reader, &mut self.headers).fuse() => {
if msg.is_err() {
break;
}
let msg = msg.unwrap();
match msg {
Message::Output(output) => self.recv_response(output).await.unwrap(),
Message::Notification(_) => {
// dispatch
}
Message::Call(_) => {
// dispatch
}
};
}
}
}
pub async fn text_document_did_save(&mut self) -> anyhow::Result<()> {
unimplemented!()
}
}

@ -0,0 +1,189 @@
use std::collections::HashMap;
use crate::{Message, Notification};
use jsonrpc_core as jsonrpc;
use lsp_types as lsp;
use serde_json::Value;
use smol::prelude::*;
use smol::{
channel::{Receiver, Sender},
io::{BufReader, BufWriter},
process::{ChildStderr, ChildStdin, ChildStdout},
Executor,
};
pub(crate) enum Payload {
Request {
chan: Sender<anyhow::Result<Value>>,
value: jsonrpc::MethodCall,
},
Notification(jsonrpc::Notification),
}
pub(crate) struct Transport {
incoming: Sender<Message>,
outgoing: Receiver<Payload>,
pending_requests: HashMap<jsonrpc::Id, Sender<anyhow::Result<Value>>>,
headers: HashMap<String, String>,
writer: BufWriter<ChildStdin>,
reader: BufReader<ChildStdout>,
}
impl Transport {
pub fn start(
ex: &Executor,
reader: BufReader<ChildStdout>,
writer: BufWriter<ChildStdin>,
) -> (Receiver<Message>, Sender<Payload>) {
let (incoming, rx) = smol::channel::unbounded();
let (tx, outgoing) = smol::channel::unbounded();
let transport = Self {
reader,
writer,
incoming,
outgoing,
pending_requests: Default::default(),
headers: Default::default(),
};
ex.spawn(transport.duplex()).detach();
(rx, tx)
}
async fn recv(
reader: &mut (impl AsyncBufRead + Unpin),
headers: &mut HashMap<String, String>,
) -> Result<Message, std::io::Error> {
// read headers
loop {
let mut header = String::new();
// detect pipe closed if 0
reader.read_line(&mut header).await?;
let header = header.trim();
if header.is_empty() {
break;
}
let parts: Vec<&str> = header.split(": ").collect();
if parts.len() != 2 {
// return Err(Error::new(ErrorKind::Other, "Failed to parse header"));
panic!()
}
headers.insert(parts[0].to_string(), parts[1].to_string());
}
// find content-length
let content_length = headers.get("Content-Length").unwrap().parse().unwrap();
let mut content = vec![0; content_length];
reader.read_exact(&mut content).await?;
let msg = String::from_utf8(content).unwrap();
// read data
// try parsing as output (server response) or call (server request)
let output: serde_json::Result<Message> = serde_json::from_str(&msg);
Ok(output?)
}
pub async fn send_payload(&mut self, payload: Payload) -> anyhow::Result<()> {
match payload {
Payload::Request { chan, value } => {
self.pending_requests.insert(value.id.clone(), chan);
let json = serde_json::to_string(&value)?;
self.send(json).await
}
Payload::Notification(value) => {
let json = serde_json::to_string(&value)?;
self.send(json).await
}
}
}
pub async fn send(&mut self, request: String) -> anyhow::Result<()> {
println!("-> {}", request);
// send the headers
self.writer
.write_all(format!("Content-Length: {}\r\n\r\n", request.len()).as_bytes())
.await?;
// send the body
self.writer.write_all(request.as_bytes()).await?;
self.writer.flush().await?;
Ok(())
}
pub async fn recv_msg(&mut self, msg: Message) -> anyhow::Result<()> {
match msg {
Message::Output(output) => self.recv_response(output).await?,
Message::Notification(jsonrpc::Notification { method, params, .. }) => {
let notification = Notification::parse(&method, params);
println!("<- {} {:?}", method, notification);
// dispatch
}
Message::Call(call) => {
println!("<- {:?}", call);
// dispatch
}
_ => unreachable!(),
};
Ok(())
}
pub async fn recv_response(&mut self, output: jsonrpc::Output) -> anyhow::Result<()> {
match output {
jsonrpc::Output::Success(jsonrpc::Success { id, result, .. }) => {
println!("<- {}", result);
let tx = self
.pending_requests
.remove(&id)
.expect("pending_request with id not found!");
tx.send(Ok(result)).await?;
}
jsonrpc::Output::Failure(_) => panic!("recv fail"),
msg => unimplemented!("{:?}", msg),
}
Ok(())
}
pub async fn duplex(mut self) {
use futures_util::{select, FutureExt};
loop {
select! {
// client -> server
msg = self.outgoing.next().fuse() => {
if msg.is_none() {
break;
}
let msg = msg.unwrap();
self.send_payload(msg).await.unwrap();
}
// server <- client
msg = Self::recv(&mut self.reader, &mut self.headers).fuse() => {
if msg.is_err() {
break;
}
let msg = msg.unwrap();
self.recv_msg(msg).await.unwrap();
}
}
}
}
}

@ -30,9 +30,11 @@ fn main() -> Result<(), Error> {
smol::block_on(async {
let res = lsp.initialize().await;
// Application::new(args).unwrap().run().await;
let state = helix_core::State::load("test.rs".into(), &[]).unwrap();
let res = lsp.text_document_did_open(&state).await;
loop {}
// Application::new(args).unwrap().run().await;
});
Ok(())

Loading…
Cancel
Save