Skip to content

Offline, privacy-first grammar checker. Fast, open-source, Rust-powered

refactor(ls): move logic out of `Backend`

Elijah Pottereacff4b63ee0
diff --git a/harper-core/src/lib.rs b/harper-core/src/lib.rs
index b31bcf805..4871c44d5 100644
--- a/harper-core/src/lib.rs
+++ b/harper-core/src/lib.rs
@@ -29,6 +29,7 @@ pub use char_string::{CharString, CharStringExt};
pub use currency::Currency;
pub use document::Document;
pub use fat_token::FatToken;
+pub use ignored_lints::IgnoredLints;
use linting::Lint;
pub use mask::{Mask, Masker};
pub use punctuation::{Punctuation, Quote};
diff --git a/harper-ls/src/backend.rs b/harper-ls/src/backend.rs
index a98b83515..569bdafa1 100644
--- a/harper-ls/src/backend.rs
+++ b/harper-ls/src/backend.rs
@@ -32,8 +32,7 @@ use tower_lsp::{Client, LanguageServer};
use tracing::{error, info, warn};
use crate::config::Config;
-use crate::diagnostics::{lint_to_code_actions, lints_to_diagnostics};
-use crate::dictionary_io::{load_dict, save_dict};
+use crate::dictionary_io::{file_dict_name, load_dict, save_dict};
use crate::document_state::DocumentState;
use crate::git_commit_parser::GitCommitParser;
use crate::pos_conv::range_to_span;
@@ -53,33 +52,6 @@ impl Backend {
}
}
- /// Rewrites a path to a filename using the same conventions as
- /// [Neovim's undo-files](https://neovim.io/doc/user/options.html#'undodir').
- fn file_dict_name(url: &Url) -> anyhow::Result<PathBuf> {
- let mut rewritten = String::new();
-
- // We assume all URLs are local files and have a base.
- for seg in url
- .to_file_path()
- .map_err(|_| anyhow!("Unable to convert URL to file path."))?
- .components()
- {
- if !matches!(seg, Component::RootDir) {
- rewritten.push_str(&seg.as_os_str().to_string_lossy());
- rewritten.push('%');
- }
- }
-
- Ok(rewritten.into())
- }
-
- /// Get the location of the file's specific dictionary
- async fn get_file_dict_path(&self, url: &Url) -> anyhow::Result<PathBuf> {
- let config = self.config.read().await;
-
- Ok(config.file_dict_path.join(Self::file_dict_name(url)?))
- }
-
/// Load a specific file's dictionary
async fn load_file_dictionary(&self, url: &Url) -> anyhow::Result<FullDictionary> {
let path = self
@@ -93,6 +65,13 @@ impl Backend {
.or(Ok(FullDictionary::new()))
}
+ /// Compute the location of the file's specific dictionary
+ async fn get_file_dict_path(&self, url: &Url) -> anyhow::Result<PathBuf> {
+ let config = self.config.read().await;
+
+ Ok(config.file_dict_path.join(file_dict_name(url)?))
+ }
+
async fn save_file_dictionary(&self, url: &Url, dict: impl Dictionary) -> Result<()> {
save_dict(
self.get_file_dict_path(url)
@@ -294,36 +273,7 @@ impl Backend {
return Ok(Vec::new());
};
- let mut lints = doc_state.linter.lint(&doc_state.document);
- lints.sort_by_key(|l| l.priority);
-
- let source_chars = doc_state.document.get_full_content();
-
- // Find lints whole span overlaps with range
- let span = range_to_span(source_chars, range).with_len(1);
-
- let mut actions: Vec<CodeActionOrCommand> = lints
- .into_iter()
- .filter(|lint| lint.span.overlaps_with(span))
- .flat_map(|lint| {
- lint_to_code_actions(&lint, url, source_chars, &config.code_action_config)
- })
- .collect();
-
- if let Some(Token {
- kind: TokenKind::Url,
- span,
- ..
- }) = doc_state.document.get_token_at_char_index(span.start)
- {
- actions.push(CodeActionOrCommand::Command(Command::new(
- "Open URL".to_string(),
- "HarperOpen".to_string(),
- Some(vec![doc_state.document.get_span_content_str(span).into()]),
- )))
- }
-
- Ok(actions)
+ Ok(doc_state.generate_code_actions(range, &config.code_action_config))
}
async fn generate_diagnostics(&self, url: &Url) -> Vec<Diagnostic> {
@@ -332,14 +282,9 @@ impl Backend {
return Vec::new();
};
- let lints = doc_state.linter.lint(&doc_state.document);
let config = self.config.read().await;
- lints_to_diagnostics(
- doc_state.document.get_full_content(),
- &lints,
- config.diagnostic_severity,
- )
+ doc_state.generate_diagnostics(config.diagnostic_severity)
}
async fn publish_diagnostics(&self, url: &Url) {
diff --git a/harper-ls/src/dictionary_io.rs b/harper-ls/src/dictionary_io.rs
index 164e484b9..5583cb4b8 100644
--- a/harper-ls/src/dictionary_io.rs
+++ b/harper-ls/src/dictionary_io.rs
@@ -1,8 +1,10 @@
-use std::path::Path;
+use anyhow::anyhow;
+use std::path::{Component, Path, PathBuf};
use harper_core::{Dictionary, FullDictionary, WordMetadata};
use tokio::fs::{self, File};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader, BufWriter, Result};
+use tower_lsp::lsp_types::Url;
/// Save the contents of a dictionary to a file.
/// Ensures that the path to the destination exists.
@@ -20,6 +22,7 @@ pub async fn save_dict(path: impl AsRef<Path>, dict: impl Dictionary) -> Result<
Ok(())
}
+/// Write a dictionary somewhere.
async fn write_word_list(dict: impl Dictionary, mut w: impl AsyncWrite + Unpin) -> Result<()> {
let mut cur_str = String::new();
@@ -34,6 +37,7 @@ async fn write_word_list(dict: impl Dictionary, mut w: impl AsyncWrite + Unpin)
Ok(())
}
+/// Load a dictionary from a file on disk.
pub async fn load_dict(path: impl AsRef<Path>) -> Result<FullDictionary> {
let file = File::open(path.as_ref()).await?;
let read = BufReader::new(file);
@@ -41,7 +45,8 @@ pub async fn load_dict(path: impl AsRef<Path>) -> Result<FullDictionary> {
dict_from_word_list(read).await
}
-/// This function could definitely be optimized to use less memory.
+/// Load a dictionary from a list of words.
+/// It could definitely be optimized to use less memory.
/// Right now it isn't an issue.
async fn dict_from_word_list(mut r: impl AsyncRead + Unpin) -> Result<FullDictionary> {
let mut str = String::new();
@@ -56,3 +61,23 @@ async fn dict_from_word_list(mut r: impl AsyncRead + Unpin) -> Result<FullDictio
Ok(dict)
}
+
+/// Rewrites a path to a filename using the same conventions as
+/// [Neovim's undo-files](https://neovim.io/doc/user/options.html#'undodir').
+pub fn file_dict_name(url: &Url) -> anyhow::Result<PathBuf> {
+ let mut rewritten = String::new();
+
+ // We assume all URLs are local files and have a base.
+ for seg in url
+ .to_file_path()
+ .map_err(|_| anyhow!("Unable to convert URL to file path."))?
+ .components()
+ {
+ if !matches!(seg, Component::RootDir) {
+ rewritten.push_str(&seg.as_os_str().to_string_lossy());
+ rewritten.push('%');
+ }
+ }
+
+ Ok(rewritten.into())
+}
diff --git a/harper-ls/src/document_state.rs b/harper-ls/src/document_state.rs
index 119833262..01f8069ba 100644
--- a/harper-ls/src/document_state.rs
+++ b/harper-ls/src/document_state.rs
@@ -1,11 +1,75 @@
-use harper_core::linting::LintGroup;
-use harper_core::{Document, FullDictionary, Lrc, MergedDictionary};
+use crate::config::{CodeActionConfig, Config, DiagnosticSeverity};
+use crate::diagnostics::{lint_to_code_actions, lints_to_diagnostics};
+use crate::pos_conv::range_to_span;
+use harper_core::linting::{LintGroup, Linter};
+use harper_core::{Document, FullDictionary, MergedDictionary, TokenKind};
+use harper_core::{Lrc, Token};
+use tower_lsp::lsp_types::{CodeActionOrCommand, Command, Diagnostic, Range, Url};
-#[derive(Default)]
pub struct DocumentState {
pub document: Document,
pub ident_dict: Lrc<FullDictionary>,
pub dict: Lrc<MergedDictionary>,
pub linter: LintGroup<Lrc<MergedDictionary>>,
pub language_id: Option<String>,
+ pub url: Url,
+}
+
+impl DocumentState {
+ pub fn generate_diagnostics(&mut self, severity: DiagnosticSeverity) -> Vec<Diagnostic> {
+ let lints = self.linter.lint(&self.document);
+
+ lints_to_diagnostics(self.document.get_full_content(), &lints, severity)
+ }
+
+ /// Generate code actions results for a selected area.
+ pub fn generate_code_actions(
+ &mut self,
+ range: Range,
+ code_action_config: &CodeActionConfig,
+ ) -> Vec<CodeActionOrCommand> {
+ let mut lints = self.linter.lint(&self.document);
+ lints.sort_by_key(|l| l.priority);
+
+ let source_chars = self.document.get_full_content();
+
+ // Find lints whole span overlaps with range
+ let span = range_to_span(source_chars, range).with_len(1);
+
+ let mut actions: Vec<CodeActionOrCommand> = lints
+ .into_iter()
+ .filter(|lint| lint.span.overlaps_with(span))
+ .flat_map(|lint| {
+ lint_to_code_actions(&lint, &self.url, source_chars, &code_action_config)
+ })
+ .collect();
+
+ if let Some(Token {
+ kind: TokenKind::Url,
+ span,
+ ..
+ }) = self.document.get_token_at_char_index(span.start)
+ {
+ actions.push(CodeActionOrCommand::Command(Command::new(
+ "Open URL".to_string(),
+ "HarperOpen".to_string(),
+ Some(vec![self.document.get_span_content_str(span).into()]),
+ )))
+ }
+
+ actions
+ }
+}
+
+impl Default for DocumentState {
+ fn default() -> Self {
+ Self {
+ document: Default::default(),
+ ident_dict: Default::default(),
+ dict: Default::default(),
+ linter: Default::default(),
+ language_id: Default::default(),
+ url: Url::parse("https://example.net").unwrap(),
+ }
+ }
}