Get JSON LSP running, still work to be done

This commit is contained in:
Isaac Clayton
2022-07-07 15:20:27 +02:00
parent 38d7321511
commit fbaff615a3
7 changed files with 269 additions and 88 deletions
+22 -4
View File
@@ -2,7 +2,7 @@ use core::panic;
use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{parse_macro_input, ItemFn, Visibility};
use syn::{parse_macro_input, FnArg, ItemFn, Type, Visibility};
#[proc_macro_attribute]
pub fn bind(args: TokenStream, function: TokenStream) -> TokenStream {
@@ -21,7 +21,17 @@ pub fn bind(args: TokenStream, function: TokenStream) -> TokenStream {
let variadic = inner_fn.sig.inputs.len();
let i = (0..variadic).map(syn::Index::from);
let t = (0..variadic).map(|_| quote! { _ });
let t: Vec<Type> = inner_fn
.sig
.inputs
.iter()
.map(|x| match x {
FnArg::Receiver(_) => {
panic!("all arguments must have specified types, no `self` allowed")
}
FnArg::Typed(item) => *item.ty.clone(),
})
.collect();
// this is cursed...
let (args, ty) = if variadic != 1 {
@@ -34,7 +44,8 @@ pub fn bind(args: TokenStream, function: TokenStream) -> TokenStream {
},
)
} else {
(quote! { data }, quote! { _ })
let ty = &t[0];
(quote! { data }, quote! { #ty })
};
TokenStream::from(quote! {
@@ -48,7 +59,14 @@ pub fn bind(args: TokenStream, function: TokenStream) -> TokenStream {
let data = unsafe { buffer.to_vec() };
// operation
let data: #ty = ::plugin::bincode::deserialize(&data).unwrap();
let data: #ty = match ::plugin::bincode::deserialize(&data) {
Ok(d) => d,
Err(e) => {
println!("data: {:?}", data);
println!("error: {}", e);
panic!("Data passed to function not deserializable.")
},
};
let result = #inner_fn_name(#args);
let new_data: Result<Vec<u8>, _> = ::plugin::bincode::serialize(&result);
let new_data = new_data.unwrap();
+2
View File
@@ -6,6 +6,8 @@ edition = "2021"
[dependencies]
wasmtime = "0.37.0"
wasmtime-wasi = "0.37.0"
wasi-common = "0.37.0"
anyhow = { version = "1.0", features = ["std"] }
serde = "1.0"
serde_json = "1.0"
bincode = "1.3"
+51 -12
View File
@@ -1,10 +1,13 @@
use std::{collections::HashMap, fs::File, path::Path};
use std::{fs::File, os::unix::prelude::AsRawFd, path::Path};
use anyhow::{anyhow, Error};
use serde::{de::DeserializeOwned, Serialize};
use wasmtime::{Engine, Func, Instance, Linker, Memory, MemoryType, Module, Store, TypedFunc};
use wasmtime_wasi::{dir, Dir, WasiCtx, WasiCtxBuilder};
use wasi_common::{dir, file};
use wasmtime::{Engine, Instance, Linker, Module, Store, TypedFunc};
use wasmtime_wasi::{Dir, WasiCtx, WasiCtxBuilder};
pub struct WasiResource(u32);
pub struct Wasi {
engine: Engine,
@@ -50,8 +53,13 @@ impl Wasi {
pub fn init(plugin: WasiPlugin) -> Result<Self, Error> {
let engine = Engine::default();
let mut linker = Linker::new(&engine);
linker.func_wrap("env", "hello", |x: u32| x * 2).unwrap();
linker.func_wrap("env", "bye", |x: u32| x / 2).unwrap();
println!("linking");
wasmtime_wasi::add_to_linker(&mut linker, |s| s)?;
println!("linked");
let mut store: Store<_> = Store::new(&engine, plugin.wasi_ctx);
println!("moduling");
@@ -60,13 +68,13 @@ impl Wasi {
linker.module(&mut store, "", &module)?;
println!("linked again");
let instance = linker.instantiate(&mut store, &module)?;
println!("instantiated");
let alloc_buffer = instance.get_typed_func(&mut store, "__alloc_buffer")?;
// let free_buffer = instance.get_typed_func(&mut store, "__free_buffer")?;
println!("can alloc");
Ok(Wasi {
engine,
module,
@@ -77,20 +85,48 @@ impl Wasi {
})
}
pub fn attach_file<T: AsRef<Path>>(&mut self, path: T) -> Result<(), Error> {
/// Attaches a file or directory the the given system path to the runtime.
/// Note that the resource must be freed by calling `remove_resource` afterwards.
pub fn attach_path<T: AsRef<Path>>(&mut self, path: T) -> Result<WasiResource, Error> {
// grab the WASI context
let ctx = self.store.data_mut();
// open the file we want, and convert it into the right type
// this is a footgun and a half
let file = File::open(&path).unwrap();
let dir = Dir::from_std_file(file);
// this is a footgun and a half.
let dir = dir::Dir::from_cap_std(dir);
ctx.push_preopened_dir(Box::new(dir), path)?;
let dir = Box::new(wasmtime_wasi::dir::Dir::from_cap_std(dir));
// grab an empty file descriptor, specify capabilities
let fd = ctx.table().push(Box::new(()))?;
dbg!(fd);
let caps = dir::DirCaps::all();
let file_caps = file::FileCaps::all();
// insert the directory at the given fd,
// return a handle to the resource
ctx.insert_dir(fd, dir, caps, file_caps, path.as_ref().to_path_buf());
Ok(WasiResource(fd))
}
/// Returns `true` if the resource existed and was removed.
pub fn remove_resource(&mut self, resource: WasiResource) -> Result<(), Error> {
self.store
.data_mut()
.table()
.delete(resource.0)
.ok_or_else(|| anyhow!("Resource did not exist, but a valid handle was passed in"))?;
Ok(())
}
// pub fn remove_file<T: AsRef<Path>>(&mut self, path: T) -> Result<(), Error> {
// let ctx = self.store.data_mut();
// ctx.remove
// Ok(())
// pub fn with_resource<T>(
// &mut self,
// resource: WasiResource,
// callback: fn(&mut Self) -> Result<T, Error>,
// ) -> Result<T, Error> {
// let result = callback(self);
// self.remove_resource(resource)?;
// return result;
// }
// So this call function is kinda a dance, I figured it'd be a good idea to document it.
@@ -142,6 +178,9 @@ impl Wasi {
handle: &str,
arg: A,
) -> Result<R, Error> {
dbg!(&handle);
// dbg!(serde_json::to_string(&arg)).unwrap();
// serialize the argument using bincode
let arg = bincode::serialize(&arg)?;
let arg_buffer_len = arg.len();
+33 -19
View File
@@ -2,6 +2,7 @@ use super::installation::{npm_install_packages, npm_package_latest_version};
use anyhow::{anyhow, Context, Result};
use client::http::HttpClient;
use futures::{future::BoxFuture, FutureExt, StreamExt};
use isahc::http::version;
use language::{LanguageServerName, LspAdapter};
use parking_lot::{Mutex, RwLock};
use plugin_runtime::{Wasi, WasiPlugin};
@@ -42,7 +43,7 @@ impl LspAdapter for LanguagePluginLspAdapter {
}
fn server_args<'a>(&'a self) -> Vec<String> {
self.runtime.lock().call("args", ()).unwrap()
self.runtime.lock().call("server_args", ()).unwrap()
}
fn fetch_latest_server_version(
@@ -65,27 +66,38 @@ impl LspAdapter for LanguagePluginLspAdapter {
fn fetch_server_binary(
&self,
versions: Box<dyn 'static + Send + Any>,
version: Box<dyn 'static + Send + Any>,
_: Arc<dyn HttpClient>,
container_dir: PathBuf,
) -> BoxFuture<'static, Result<PathBuf>> {
// TODO: async runtime
let version = version.downcast::<String>().unwrap();
let mut runtime = self.runtime.lock();
let result = runtime.attach_file(&container_dir);
let result = match result {
Ok(_) => runtime.call("fetch_server_binary", container_dir),
Err(e) => Err(e),
};
let result: Result<PathBuf, _> = (|| {
let handle = runtime.attach_path(&container_dir)?;
let result = runtime
.call::<_, Option<PathBuf>>("fetch_server_binary", container_dir)?
.ok_or_else(|| anyhow!("Could not load cached server binary"));
runtime.remove_resource(handle)?;
result
})();
async move { result }.boxed()
}
fn cached_server_binary(&self, container_dir: PathBuf) -> BoxFuture<'static, Option<PathBuf>> {
let result = self
.runtime
.lock()
.call("cached_server_binary", container_dir);
async move { result }.log_err().boxed()
let mut runtime = self.runtime.lock();
let result: Option<PathBuf> = (|| {
let handle = runtime.attach_path(&container_dir).ok()?;
let result = runtime
.call::<_, Option<PathBuf>>("cached_server_binary", container_dir)
.ok()?;
runtime.remove_resource(handle).ok()?;
result
})();
async move { result }.boxed()
}
fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
@@ -113,11 +125,13 @@ impl LspAdapter for LanguagePluginLspAdapter {
}
fn initialization_options(&self) -> Option<serde_json::Value> {
let result = self
.runtime
.lock()
.call("initialization_options", ())
.unwrap();
Some(result)
// self.runtime
// .lock()
// .call::<_, Option<serde_json::Value>>("initialization_options", ())
// .unwrap()
Some(json!({
"provideFormatter": true
}))
}
}