Skip to content

Commit

Permalink
feat: switch to tower-lsp (lspower archived)
Browse files Browse the repository at this point in the history
  • Loading branch information
polarmutex committed May 2, 2022
1 parent 5d9ad9a commit 1bc67b3
Show file tree
Hide file tree
Showing 14 changed files with 351 additions and 297 deletions.
252 changes: 143 additions & 109 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ clap = "3.1"
dashmap = "5.3"
log4rs = "1"
log = "0.4"
lspower = "1.5"
tower-lsp = "0.17.0"
regex = "1"
ropey = "1.4"
thiserror = "1.0"
Expand Down
10 changes: 5 additions & 5 deletions src/core/beancount_data.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::core::RopeExt;
use dashmap::DashMap;
use log::debug;
use lspower::lsp;
use std::collections::HashSet;
use tower_lsp::lsp_types;

pub struct FlaggedEntry {
_file: String,
Expand All @@ -16,9 +16,9 @@ pub struct FlaggedEntry {
//}

pub struct BeancountData {
accounts: DashMap<lsp::Url, Vec<String>>,
txn_strings: DashMap<lsp::Url, Vec<String>>,
pub flagged_entries: DashMap<lsp::Url, Vec<FlaggedEntry>>,
accounts: DashMap<lsp_types::Url, Vec<String>>,
txn_strings: DashMap<lsp_types::Url, Vec<String>>,
pub flagged_entries: DashMap<lsp_types::Url, Vec<FlaggedEntry>>,
}

impl BeancountData {
Expand All @@ -33,7 +33,7 @@ impl BeancountData {
}
}

pub fn update_data(&self, uri: lsp::Url, tree: &tree_sitter::Tree, content: &ropey::Rope) {
pub fn update_data(&self, uri: lsp_types::Url, tree: &tree_sitter::Tree, content: &ropey::Rope) {
let mut cursor = tree.root_node().walk();

// Update account opens
Expand Down
4 changes: 2 additions & 2 deletions src/core/document.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use lspower::lsp;
use tower_lsp::lsp_types;

#[derive(Clone)]
pub struct Document {
Expand All @@ -7,7 +7,7 @@ pub struct Document {
}

impl Document {
pub fn open(params: lsp::DidOpenTextDocumentParams) -> Self {
pub fn open(params: lsp_types::DidOpenTextDocumentParams) -> Self {
let content = ropey::Rope::from(params.text_document.text);
let content = content;
Self { content }
Expand Down
14 changes: 7 additions & 7 deletions src/core/error.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
use crate::core;
use lspower::lsp;
use thiserror::Error;
use tower_lsp::lsp_types;

/// Runtime errors for the LSP server.
#[allow(clippy::enum_variant_names)]
#[derive(Debug, Error)]
pub enum Error {
/// Error that occurs when [`core::Session.client`] is accessed and is `None`.
#[error("ClientNotInitialzed")]
ClientNotInitialized,
//#[error("ClientNotInitialzed")]
//ClientNotInitialized,
/// Error that occurs when a session resource is requested and does not exist.
#[error("core::SessionResourceNotFound: kind={kind:?}, uri={uri:?}")]
SessionResourceNotFound {
/// The kind of the requested session resource.
kind: core::session::SessionResourceKind,
/// The URL of the requested session resource.
uri: lsp::Url,
uri: lsp_types::Url,
},

#[error("I/O error")]
Expand All @@ -34,12 +34,12 @@ pub enum Error {
UriToPathConversion,
}

/// Wrapper struct for converting [`anyhow::Error`] into [`lspower::jsonrpc::Error`].
/// Wrapper struct for converting [`anyhow::Error`] into [`tower_lsp::jsonrpc::Error`].
pub struct IntoJsonRpcError(pub anyhow::Error);

impl From<IntoJsonRpcError> for lspower::jsonrpc::Error {
impl From<IntoJsonRpcError> for tower_lsp::jsonrpc::Error {
fn from(error: IntoJsonRpcError) -> Self {
let mut rpc_error = lspower::jsonrpc::Error::internal_error();
let mut rpc_error = tower_lsp::jsonrpc::Error::internal_error();
rpc_error.data = Some(serde_json::to_value(format!("{}", error.0)).unwrap());
rpc_error
}
Expand Down
32 changes: 16 additions & 16 deletions src/core/rope.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// USED FORM https://github.com/silvanshade/lsp-text
use crate::core::{TextEdit, TextPosition};
use bytes::Bytes;
use lspower::lsp;
use ropey::{iter::Chunks, Rope};
use std::{convert::TryFrom, sync::Arc};
use tower_lsp::lsp_types;

use std::borrow::Cow;

Expand Down Expand Up @@ -76,14 +76,14 @@ impl ChunkWalker {

pub trait RopeExt {
fn apply_edit(&mut self, edit: &TextEdit);
fn build_edit<'a>(&self, change: &'a lsp::TextDocumentContentChangeEvent) -> anyhow::Result<TextEdit<'a>>;
fn byte_to_lsp_position(&self, offset: usize) -> lsp::Position;
fn build_edit<'a>(&self, change: &'a lsp_types::TextDocumentContentChangeEvent) -> anyhow::Result<TextEdit<'a>>;
fn byte_to_lsp_position(&self, offset: usize) -> lsp_types::Position;
fn byte_to_tree_sitter_point(&self, offset: usize) -> anyhow::Result<tree_sitter::Point>;
fn chunk_walker(self, byte_idx: usize) -> ChunkWalker;
fn lsp_position_to_core(&self, position: lsp::Position) -> anyhow::Result<TextPosition>;
fn lsp_position_to_utf16_cu(&self, position: lsp::Position) -> anyhow::Result<u32>;
fn lsp_range_to_tree_sitter_range(&self, range: lsp::Range) -> anyhow::Result<tree_sitter::Range>;
fn tree_sitter_range_to_lsp_range(&self, range: tree_sitter::Range) -> lsp::Range;
fn lsp_position_to_core(&self, position: lsp_types::Position) -> anyhow::Result<TextPosition>;
fn lsp_position_to_utf16_cu(&self, position: lsp_types::Position) -> anyhow::Result<u32>;
fn lsp_range_to_tree_sitter_range(&self, range: lsp_types::Range) -> anyhow::Result<tree_sitter::Range>;
fn tree_sitter_range_to_lsp_range(&self, range: tree_sitter::Range) -> lsp_types::Range;
fn utf8_text_for_tree_sitter_node<'rope, 'tree>(&'rope self, node: &tree_sitter::Node<'tree>) -> Cow<'rope, str>;
}

Expand All @@ -95,7 +95,7 @@ impl RopeExt for Rope {
}
}

fn build_edit<'a>(&self, change: &'a lsp::TextDocumentContentChangeEvent) -> anyhow::Result<TextEdit<'a>> {
fn build_edit<'a>(&self, change: &'a lsp_types::TextDocumentContentChangeEvent) -> anyhow::Result<TextEdit<'a>> {
let text = change.text.as_str();
let text_bytes = text.as_bytes();
let text_end_byte_idx = text_bytes.len();
Expand All @@ -105,7 +105,7 @@ impl RopeExt for Rope {
} else {
let start = self.byte_to_lsp_position(0);
let end = self.byte_to_lsp_position(text_end_byte_idx);
lsp::Range { start, end }
lsp_types::Range { start, end }
};

let start = self.lsp_position_to_core(range.start)?;
Expand Down Expand Up @@ -149,7 +149,7 @@ impl RopeExt for Rope {
})
}

fn byte_to_lsp_position(&self, byte_idx: usize) -> lsp::Position {
fn byte_to_lsp_position(&self, byte_idx: usize) -> lsp_types::Position {
let line_idx = self.byte_to_line(byte_idx);

let line_utf16_cu_idx = {
Expand All @@ -165,7 +165,7 @@ impl RopeExt for Rope {
let line = line_idx;
let character = character_utf16_cu_idx - line_utf16_cu_idx;

lsp::Position::new(line as u32, character as u32)
lsp_types::Position::new(line as u32, character as u32)
}

fn byte_to_tree_sitter_point(&self, byte_idx: usize) -> anyhow::Result<tree_sitter::Point> {
Expand All @@ -191,7 +191,7 @@ impl RopeExt for Rope {
}
}

fn lsp_position_to_core(&self, position: lsp::Position) -> anyhow::Result<TextPosition> {
fn lsp_position_to_core(&self, position: lsp_types::Position) -> anyhow::Result<TextPosition> {
let row_idx = position.line as usize;

let col_code_idx = position.character as usize;
Expand All @@ -218,7 +218,7 @@ impl RopeExt for Rope {
})
}

fn lsp_position_to_utf16_cu(&self, position: lsp::Position) -> anyhow::Result<u32> {
fn lsp_position_to_utf16_cu(&self, position: lsp_types::Position) -> anyhow::Result<u32> {
let line_idx = position.line as usize;
let line_utf16_cu_idx = {
let char_idx = self.line_to_char(line_idx);
Expand All @@ -229,7 +229,7 @@ impl RopeExt for Rope {
Ok(result)
}

fn lsp_range_to_tree_sitter_range(&self, range: lsp::Range) -> anyhow::Result<tree_sitter::Range> {
fn lsp_range_to_tree_sitter_range(&self, range: lsp_types::Range) -> anyhow::Result<tree_sitter::Range> {
let start = self.lsp_position_to_core(range.start)?;
let end = self.lsp_position_to_core(range.end)?;
let range = tree_sitter::Range {
Expand All @@ -241,10 +241,10 @@ impl RopeExt for Rope {
Ok(range)
}

fn tree_sitter_range_to_lsp_range(&self, range: tree_sitter::Range) -> lsp::Range {
fn tree_sitter_range_to_lsp_range(&self, range: tree_sitter::Range) -> lsp_types::Range {
let start = self.byte_to_lsp_position(range.start_byte as usize);
let end = self.byte_to_lsp_position(range.end_byte as usize);
lsp::Range::new(start, end)
lsp_types::Range::new(start, end)
}

fn utf8_text_for_tree_sitter_node<'rope, 'tree>(&'rope self, node: &tree_sitter::Node<'tree>) -> Cow<'rope, str> {
Expand Down
93 changes: 46 additions & 47 deletions src/core/session.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
use crate::{core, providers, server};
use crate::{core, providers};
use dashmap::{
mapref::one::{Ref, RefMut},
DashMap,
};
use linked_list::LinkedList;
use log::debug;
use lspower::lsp;
use providers::diagnostics;
use serde::{Deserialize, Serialize};
use std::{
env,
fs::read_to_string,
path::{Path, PathBuf},
};
use tokio::sync::{Mutex, RwLock};
use tower_lsp::lsp_types;

/// A tag representing of the kinds of session resource.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
Expand All @@ -25,17 +25,17 @@ pub enum SessionResourceKind {
Tree,
}

pub struct Session {
pub server_capabilities: RwLock<lsp::ServerCapabilities>,
pub client_capabilities: RwLock<Option<lsp::ClientCapabilities>>,
client: Option<lspower::Client>,
documents: DashMap<lsp::Url, core::Document>,
parsers: DashMap<lsp::Url, Mutex<tree_sitter::Parser>>,
pub forest: DashMap<lsp::Url, Mutex<tree_sitter::Tree>>,
pub root_journal_path: RwLock<Option<PathBuf>>,
pub bean_check_path: Option<PathBuf>,
pub beancount_data: core::BeancountData,
pub diagnostic_data: providers::DiagnosticData,
pub(crate) struct Session {
//pub(crate) server_capabilities: RwLock<lsp_types::ServerCapabilities>,
pub(crate) client_capabilities: RwLock<Option<lsp_types::ClientCapabilities>>,
pub(crate) client: tower_lsp::Client,
documents: DashMap<lsp_types::Url, core::Document>,
parsers: DashMap<lsp_types::Url, Mutex<tree_sitter::Parser>>,
pub(crate) forest: DashMap<lsp_types::Url, Mutex<tree_sitter::Tree>>,
pub(crate) root_journal_path: RwLock<Option<PathBuf>>,
//pub(crate) bean_check_path: Option<PathBuf>,
pub(crate) beancount_data: core::BeancountData,
pub(crate) diagnostic_data: diagnostics::DiagnosticData,
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
Expand All @@ -45,52 +45,45 @@ pub struct BeancountLspOptions {

impl Session {
/// Create a new [`Session`].
pub fn new(client: Option<lspower::Client>) -> anyhow::Result<Self> {
let server_capabilities = RwLock::new(server::capabilities());
pub fn new(client: tower_lsp::Client) -> Self {
//let server_capabilities = RwLock::new(server::capabilities());
let client_capabilities = RwLock::new(Default::default());
let documents = DashMap::new();
let parsers = DashMap::new();
let forest = DashMap::new();
let beancount_data = core::BeancountData::new();
let diagnostic_data = providers::DiagnosticData::new();
let diagnostic_data = diagnostics::DiagnosticData::new();

let bean_check_path = env::var_os("PATH").and_then(|paths| {
env::split_paths(&paths).find_map(|p| {
let full_path = p.join("bean-check");
//let bean_check_path = env::var_os("PATH").and_then(|paths| {
// env::split_paths(&paths).find_map(|p| {
// let full_path = p.join("bean-check");

if full_path.is_file() {
Some(full_path)
} else {
None
}
})
});
// if full_path.is_file() {
// Some(full_path)
// } else {
// None
// }
// })
//});

let root_journal_path = RwLock::new(None);

Ok(Session {
server_capabilities,
Self {
//server_capabilities,
client_capabilities,
client,
documents,
parsers,
forest,
root_journal_path,
bean_check_path,
//bean_check_path,
beancount_data,
diagnostic_data,
})
}

/// Retrieve the handle for the LSP client.
pub fn client(&self) -> anyhow::Result<&lspower::Client> {
self.client
.as_ref()
.ok_or_else(|| core::Error::ClientNotInitialized.into())
}
}

/// Insert a [`core::Document`] into the [`Session`].
pub fn insert_document(&self, uri: lsp::Url, document: core::Document) -> anyhow::Result<()> {
pub fn insert_document(&self, uri: lsp_types::Url, document: core::Document) -> anyhow::Result<()> {
let result = self.documents.insert(uri, document);
debug_assert!(result.is_none());
// let result = self.parsers.insert(uri.clone(), Mutex::new(document.parser));
Expand All @@ -101,7 +94,7 @@ impl Session {
}

/// Remove a [`core::Document`] from the [`Session`].
pub fn remove_document(&self, uri: &lsp::Url) -> anyhow::Result<()> {
pub fn remove_document(&self, uri: &lsp_types::Url) -> anyhow::Result<()> {
let result = self.documents.remove(uri);
debug_assert!(result.is_some());
// let result = self.parsers.remove(uri);
Expand All @@ -112,7 +105,7 @@ impl Session {
}

/// Get a reference to the [`core::Document`] in the [`Session`].
pub async fn get_document(&self, uri: &lsp::Url) -> anyhow::Result<Ref<'_, lsp::Url, core::Document>> {
pub async fn get_document(&self, uri: &lsp_types::Url) -> anyhow::Result<Ref<'_, lsp_types::Url, core::Document>> {
self.documents.get(uri).ok_or_else(|| {
let kind = SessionResourceKind::Document;
let uri = uri.clone();
Expand All @@ -121,7 +114,10 @@ impl Session {
}

/// Get a mutable reference to the [`core::Document`] in the [`Session`].
pub async fn get_mut_document(&self, uri: &lsp::Url) -> anyhow::Result<RefMut<'_, lsp::Url, core::Document>> {
pub async fn get_mut_document(
&self,
uri: &lsp_types::Url,
) -> anyhow::Result<RefMut<'_, lsp_types::Url, core::Document>> {
self.documents.get_mut(uri).ok_or_else(|| {
let kind = SessionResourceKind::Document;
let uri = uri.clone();
Expand All @@ -131,8 +127,8 @@ impl Session {

pub async fn get_mut_parser(
&self,
uri: &lsp::Url,
) -> anyhow::Result<RefMut<'_, lsp::Url, Mutex<tree_sitter::Parser>>> {
uri: &lsp_types::Url,
) -> anyhow::Result<RefMut<'_, lsp_types::Url, Mutex<tree_sitter::Parser>>> {
debug!("getting mutable parser {}", uri);
debug!("parser contains key {}", self.parsers.contains_key(uri));
self.parsers.get_mut(uri).ok_or_else(|| {
Expand All @@ -154,7 +150,10 @@ impl Session {

/// Get a mutable reference to the [`tree_sitter::Tree`] for a [`core::Document`] in the
/// [`Session`].
pub async fn get_mut_tree(&self, uri: &lsp::Url) -> anyhow::Result<RefMut<'_, lsp::Url, Mutex<tree_sitter::Tree>>> {
pub async fn get_mut_tree(
&self,
uri: &lsp_types::Url,
) -> anyhow::Result<RefMut<'_, lsp_types::Url, Mutex<tree_sitter::Tree>>> {
self.forest.get_mut(uri).ok_or_else(|| {
let kind = SessionResourceKind::Tree;
let uri = uri.clone();
Expand All @@ -164,7 +163,7 @@ impl Session {

// Issus to look at if running into issues with this
// https://github.com/silvanshade/lspower/issues/8
pub async fn parse_initial_forest(&self, root_url: lsp::Url) -> anyhow::Result<bool, anyhow::Error> {
pub async fn parse_initial_forest(&self, root_url: lsp_types::Url) -> anyhow::Result<bool, anyhow::Error> {
let mut seen_files = LinkedList::new();
// let root_pathbuf: String = self.root_journal_path.into_inner().unwrap().as_ref().as_os_str();
// let temp = self.root_journal_path.read().await;
Expand Down Expand Up @@ -224,7 +223,7 @@ impl Session {
} else {
path.to_path_buf()
};
let path_url = lsp::Url::from_file_path(path).unwrap();
let path_url = lsp_types::Url::from_file_path(path).unwrap();

Some(path_url)
});
Expand Down
Loading

0 comments on commit 1bc67b3

Please sign in to comment.