Skip to content

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

Code Actions fully work

Elijah Potter703da16cd19e
diff --git a/Cargo.lock b/Cargo.lock
index 503150e5e..34d40db4a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -45,18 +45,66 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "allocator-api2"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5"
+
[[package]]
name = "anes"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
+[[package]]
+name = "anstream"
+version = "0.6.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e2e1ebcb11de5c03c67de28a7df593d32191b44939c482e97702baaaa6ab6a5"
+dependencies = [
+ "anstyle",
+ "anstyle-parse",
+ "anstyle-query",
+ "anstyle-wincon",
+ "colorchoice",
+ "utf8parse",
+]
+
[[package]]
name = "anstyle"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7079075b41f533b8c61d2a4d073c4676e1f8b249ff94a393b0595db304e0dd87"
+[[package]]
+name = "anstyle-parse"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c75ac65da39e5fe5ab759307499ddad880d724eed2f6ce5b5e8a26f4f387928c"
+dependencies = [
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle-query"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e28923312444cdd728e4738b3f9c9cac739500909bb3d3c94b43551b16517648"
+dependencies = [
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "anstyle-wincon"
+version = "3.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1cd54b81ec8d6180e24654d0b371ad22fc3dd083b6ff8ba325b72e00c87660a7"
+dependencies = [
+ "anstyle",
+ "windows-sys 0.52.0",
+]
+
[[package]]
name = "async-trait"
version = "0.1.77"
@@ -174,6 +222,39 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223"
+[[package]]
+name = "cached"
+version = "0.47.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69b0116662497bc24e4b177c90eaf8870e39e2714c3fcfa296327a93f593fc21"
+dependencies = [
+ "ahash",
+ "cached_proc_macro",
+ "cached_proc_macro_types",
+ "hashbrown",
+ "instant",
+ "once_cell",
+ "thiserror",
+]
+
+[[package]]
+name = "cached_proc_macro"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c878c71c2821aa2058722038a59a67583a4240524687c6028571c9b395ded61f"
+dependencies = [
+ "darling",
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "cached_proc_macro_types"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a4f925191b4367301851c6d99b09890311d74b0d43f274c0b34c86d308a3663"
+
[[package]]
name = "cast"
version = "0.3.0"
@@ -229,6 +310,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e578d6ec4194633722ccf9544794b71b1385c3c027efe0c55db226fc880865c"
dependencies = [
"clap_builder",
+ "clap_derive",
]
[[package]]
@@ -237,8 +319,22 @@ version = "4.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4df4df40ec50c46000231c914968278b1eb05098cf8f1b3a518a95030e71d1c7"
dependencies = [
+ "anstream",
"anstyle",
"clap_lex",
+ "strsim",
+]
+
+[[package]]
+name = "clap_derive"
+version = "4.4.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf9804afaaf59a91e75b022a30fb7229a7901f60c755489cc61c9b423b836442"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.48",
]
[[package]]
@@ -247,6 +343,12 @@ version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "702fc72eb24e5a1e48ce58027a675bc24edd52096d5397d4aea7c6dd9eca0bd1"
+[[package]]
+name = "colorchoice"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7"
+
[[package]]
name = "console_error_panic_hook"
version = "0.1.7"
@@ -318,6 +420,41 @@ version = "0.8.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "248e3bacc7dc6baa3b21e405ee045c3047101a49145e7e9eca583ab4c2ca5345"
+[[package]]
+name = "darling"
+version = "0.14.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b750cb3417fd1b327431a470f388520309479ab0bf5e323505daf0290cd3850"
+dependencies = [
+ "darling_core",
+ "darling_macro",
+]
+
+[[package]]
+name = "darling_core"
+version = "0.14.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "109c1ca6e6b7f82cc233a97004ea8ed7ca123a9af07a8230878fcfda9b158bf0"
+dependencies = [
+ "fnv",
+ "ident_case",
+ "proc-macro2",
+ "quote",
+ "strsim",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "darling_macro"
+version = "0.14.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4aab4dbc9f7611d8b55048a3a16d2d010c2c8334e46304b40ac1cc14bf3b48e"
+dependencies = [
+ "darling_core",
+ "quote",
+ "syn 1.0.109",
+]
+
[[package]]
name = "dashmap"
version = "5.5.3"
@@ -481,6 +618,8 @@ dependencies = [
name = "harper-ls"
version = "0.1.0"
dependencies = [
+ "cached",
+ "clap",
"harper-core",
"tokio",
"tower-lsp",
@@ -518,6 +657,16 @@ name = "hashbrown"
version = "0.14.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604"
+dependencies = [
+ "ahash",
+ "allocator-api2",
+]
+
+[[package]]
+name = "heck"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
[[package]]
name = "hermit-abi"
@@ -582,6 +731,12 @@ dependencies = [
"want",
]
+[[package]]
+name = "ident_case"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
+
[[package]]
name = "idna"
version = "0.5.0"
@@ -592,6 +747,15 @@ dependencies = [
"unicode-normalization",
]
+[[package]]
+name = "instant"
+version = "0.1.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"
+dependencies = [
+ "cfg-if",
+]
+
[[package]]
name = "is-macro"
version = "0.3.5"
@@ -1142,6 +1306,12 @@ dependencies = [
"windows-sys 0.48.0",
]
+[[package]]
+name = "strsim"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
+
[[package]]
name = "syn"
version = "1.0.109"
@@ -1170,6 +1340,26 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160"
+[[package]]
+name = "thiserror"
+version = "1.0.56"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d54378c645627613241d077a3a79db965db602882668f9136ac42af9ecb730ad"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.56"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa0faa943b50f3db30a20aa7e265dbc66076993efed8463e8de414e5d06d3471"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.48",
+]
+
[[package]]
name = "thread_local"
version = "1.1.7"
@@ -1419,6 +1609,12 @@ dependencies = [
"serde",
]
+[[package]]
+name = "utf8parse"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a"
+
[[package]]
name = "valuable"
version = "0.1.0"
diff --git a/harper-core/src/linting/lint.rs b/harper-core/src/linting/lint.rs
index 6b80c9261..42e3fd8a6 100644
--- a/harper-core/src/linting/lint.rs
+++ b/harper-core/src/linting/lint.rs
@@ -1,5 +1,6 @@
use std::fmt::Display;
+use is_macro::Is;
use serde::{Deserialize, Serialize};
use crate::{document::Document, span::Span, Dictionary};
@@ -12,7 +13,7 @@ pub struct Lint {
pub message: String,
}
-#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, Is)]
pub enum LintKind {
Spelling,
Capitalization,
@@ -20,7 +21,7 @@ pub enum LintKind {
WrongQuotes,
}
-#[derive(Debug, Clone, Serialize, Deserialize)]
+#[derive(Debug, Clone, Serialize, Deserialize, Is)]
pub enum Suggestion {
ReplaceWith(Vec<char>),
}
@@ -29,7 +30,7 @@ impl Display for Suggestion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Suggestion::ReplaceWith(with) => {
- write!(f, "Replace with: {}", with.iter().collect::<String>())
+ write!(f, "Replace with: “{}”", with.iter().collect::<String>())
}
}
}
diff --git a/harper-core/src/span.rs b/harper-core/src/span.rs
index b322d9c52..fe4890999 100644
--- a/harper-core/src/span.rs
+++ b/harper-core/src/span.rs
@@ -54,8 +54,9 @@ mod tests {
#[test]
fn overlaps() {
- assert!(Span::new(0, 5).overlaps_with(&Span::new(3, 6)));
- assert!(Span::new(0, 5).overlaps_with(&Span::new(2, 3)));
- assert!(Span::new(0, 5).overlaps_with(&Span::new(4, 5)));
+ assert!(Span::new(0, 5).overlaps_with(Span::new(3, 6)));
+ assert!(Span::new(0, 5).overlaps_with(Span::new(2, 3)));
+ assert!(Span::new(0, 5).overlaps_with(Span::new(4, 5)));
+ assert!(Span::new(0, 5).overlaps_with(Span::new(4, 4)));
}
}
diff --git a/harper-ls/Cargo.toml b/harper-ls/Cargo.toml
index a57d39c95..b528b8bdb 100644
--- a/harper-ls/Cargo.toml
+++ b/harper-ls/Cargo.toml
@@ -7,3 +7,5 @@ edition = "2021"
harper-core = { path = "../harper-core" }
tower-lsp = "0.20.0"
tokio = { version = "1.35.1", features = ["full"] }
+clap = { version = "4.4.18", features = ["derive"] }
+cached = "0.47.0"
diff --git a/harper-ls/src/backend.rs b/harper-ls/src/backend.rs
index 58e27cb9c..69c833b1f 100644
--- a/harper-ls/src/backend.rs
+++ b/harper-ls/src/backend.rs
@@ -1,13 +1,16 @@
use tower_lsp::{
jsonrpc::Result,
lsp_types::{
- notification::PublishDiagnostics, DidSaveTextDocumentParams, InitializeParams,
- InitializeResult, InitializedParams, MessageType, PublishDiagnosticsParams,
+ notification::PublishDiagnostics, CodeActionOrCommand, CodeActionParams,
+ CodeActionProviderCapability, CodeActionResponse, DidChangeTextDocumentParams,
+ DidCloseTextDocumentParams, DidOpenTextDocumentParams, DidSaveTextDocumentParams,
+ InitializeParams, InitializeResult, InitializedParams, MessageType,
+ PublishDiagnosticsParams, ServerCapabilities, Url,
},
Client, LanguageServer,
};
-use crate::diagnostics::generate_diagnostics;
+use crate::diagnostics::{generate_code_actions, generate_diagnostics};
pub struct Backend {
client: Client,
@@ -17,12 +20,32 @@ impl Backend {
pub fn new(client: Client) -> Self {
Self { client }
}
+
+ async fn publish_diagnostics(&self, url: &Url) {
+ let diagnostics = generate_diagnostics(url).unwrap();
+
+ let result = PublishDiagnosticsParams {
+ uri: url.clone(),
+ diagnostics,
+ version: None,
+ };
+
+ self.client
+ .send_notification::<PublishDiagnostics>(result)
+ .await;
+ }
}
#[tower_lsp::async_trait]
impl LanguageServer for Backend {
async fn initialize(&self, _: InitializeParams) -> Result<InitializeResult> {
- Ok(InitializeResult::default())
+ Ok(InitializeResult {
+ server_info: None,
+ capabilities: ServerCapabilities {
+ code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
+ ..Default::default()
+ },
+ })
}
async fn initialized(&self, _: InitializedParams) {
@@ -36,16 +59,43 @@ impl LanguageServer for Backend {
}
async fn did_save(&self, params: DidSaveTextDocumentParams) {
- let diagnostics = generate_diagnostics(&params.text_document.uri).unwrap();
+ self.client
+ .log_message(MessageType::INFO, "File saved!")
+ .await;
- let result = PublishDiagnosticsParams {
- uri: params.text_document.uri,
- diagnostics,
- version: None,
- };
+ self.publish_diagnostics(&params.text_document.uri).await;
+ }
+ async fn did_open(&self, _: DidOpenTextDocumentParams) {
self.client
- .send_notification::<PublishDiagnostics>(result)
+ .log_message(MessageType::INFO, "File opened!")
+ .await;
+ }
+
+ async fn did_change(&self, _: DidChangeTextDocumentParams) {
+ self.client
+ .log_message(MessageType::INFO, "File changed!")
+ .await;
+ }
+
+ async fn did_close(&self, _: DidCloseTextDocumentParams) {
+ self.client
+ .log_message(MessageType::INFO, "File closed!")
+ .await;
+ }
+
+ async fn code_action(&self, params: CodeActionParams) -> Result<Option<CodeActionResponse>> {
+ let actions = generate_code_actions(&params.text_document.uri, params.range)?;
+
+ self.client
+ .log_message(MessageType::INFO, format!("{:?}", actions))
.await;
+
+ Ok(Some(
+ actions
+ .into_iter()
+ .map(CodeActionOrCommand::CodeAction)
+ .collect(),
+ ))
}
}
diff --git a/harper-ls/src/diagnostics.rs b/harper-ls/src/diagnostics.rs
index 89d9db58e..e903d214a 100644
--- a/harper-ls/src/diagnostics.rs
+++ b/harper-ls/src/diagnostics.rs
@@ -1,14 +1,15 @@
use harper_core::{all_linters, Dictionary, Document, Lint, Span, Suggestion};
-use std::{fs::read, io::Read};
+use std::collections::HashMap;
+use std::fs::read;
use tower_lsp::jsonrpc::{ErrorCode, Result};
use tower_lsp::lsp_types::{
- CodeAction, CodeActionKind, Diagnostic, Location, Position, Range, Url,
+ CodeAction, CodeActionKind, Diagnostic, Position, Range, TextEdit, Url, WorkspaceEdit,
};
pub fn generate_diagnostics(file_url: &Url) -> Result<Vec<Diagnostic>> {
let file_str = open_url(file_url)?;
let source_chars: Vec<_> = file_str.chars().collect();
- let lints = lint_string(&file_str);
+ let lints = lint_string(file_str);
let diagnostics = lints
.into_iter()
@@ -21,7 +22,7 @@ pub fn generate_diagnostics(file_url: &Url) -> Result<Vec<Diagnostic>> {
pub fn generate_code_actions(url: &Url, range: Range) -> Result<Vec<CodeAction>> {
let file_str = open_url(url)?;
let source_chars: Vec<_> = file_str.chars().collect();
- let lints = lint_string(&file_str);
+ let lints = lint_string(file_str);
// Find lints whose span overlaps with range
let span = range_to_span(&source_chars, range);
@@ -29,22 +30,42 @@ pub fn generate_code_actions(url: &Url, range: Range) -> Result<Vec<CodeAction>>
let actions = lints
.into_iter()
.filter(|lint| lint.span.overlaps_with(span))
- .flat_map(|lint| lint_to_code_actions(&lint).collect::<Vec<_>>())
+ .flat_map(|lint| lint_to_code_actions(&lint, url, &source_chars).collect::<Vec<_>>())
.collect();
Ok(actions)
}
-fn lint_to_code_actions(lint: &Lint) -> impl Iterator<Item = CodeAction> + '_ {
- lint.suggestions.iter().map(|suggestion| CodeAction {
- title: suggestion.to_string(),
- kind: Some(CodeActionKind::QUICKFIX),
- diagnostics: None,
- edit: None,
- command: None,
- is_preferred: None,
- disabled: None,
- data: None,
+fn lint_to_code_actions<'a>(
+ lint: &'a Lint,
+ url: &'a Url,
+ source: &'a [char],
+) -> impl Iterator<Item = CodeAction> + 'a {
+ lint.suggestions.iter().flat_map(|suggestion| {
+ let range = span_to_range(source, lint.span);
+
+ let Suggestion::ReplaceWith(with) = suggestion;
+ Some(CodeAction {
+ title: suggestion.to_string(),
+ kind: Some(CodeActionKind::QUICKFIX),
+ diagnostics: None,
+ edit: Some(WorkspaceEdit {
+ changes: Some(HashMap::from([(
+ url.clone(),
+ vec![TextEdit {
+ range,
+
+ new_text: with.iter().collect(),
+ }],
+ )])),
+ document_changes: None,
+ change_annotations: None,
+ }),
+ command: None,
+ is_preferred: None,
+ disabled: None,
+ data: None,
+ })
})
}
@@ -54,8 +75,9 @@ fn open_url(url: &Url) -> Result<String> {
Ok(String::from_utf8(file).unwrap())
}
-fn lint_string(text: &str) -> Vec<Lint> {
- let document = Document::new(text);
+#[cached::proc_macro::cached]
+fn lint_string(text: String) -> Vec<Lint> {
+ let document = Document::new(&text);
let dictionary = Dictionary::new();
all_linters(&document, dictionary)
}
@@ -109,9 +131,10 @@ fn position_to_index(source: &[char], position: Position) -> usize {
let line_start_idx = newline_indices
.take(position.line as usize)
- .next()
+ .last()
.unwrap_or(0);
- line_start_idx + position.character as usize
+
+ line_start_idx + position.character as usize + 1
}
fn range_to_span(source: &[char], range: Range) -> Span {
@@ -120,3 +143,33 @@ fn range_to_span(source: &[char], range: Range) -> Span {
Span::new(start, end)
}
+
+#[cfg(test)]
+mod tests {
+ use tower_lsp::lsp_types::Position;
+
+ use super::{index_to_position, position_to_index};
+
+ #[test]
+ fn reversible_position_conv() {
+ let source: Vec<_> = "There was a man,\n his voice had timbre,\n unlike a boy."
+ .chars()
+ .collect();
+
+ let a = Position {
+ line: 2,
+ character: 3,
+ };
+
+ let b = position_to_index(&source, a);
+
+ assert_eq!(b, 43);
+
+ let c = index_to_position(&source, b);
+
+ let d = position_to_index(&source, a);
+
+ assert_eq!(a, c);
+ assert_eq!(b, d);
+ }
+}
diff --git a/harper-ls/src/main.rs b/harper-ls/src/main.rs
index 2653f7d42..e4fa77243 100644
--- a/harper-ls/src/main.rs
+++ b/harper-ls/src/main.rs
@@ -1,13 +1,31 @@
+use tokio::net::TcpListener;
mod backend;
mod diagnostics;
+
use backend::Backend;
+use clap::Parser;
use tower_lsp::{LspService, Server};
+#[derive(Debug, Parser)]
+struct Args {
+ #[arg(short, long, default_value_t = false)]
+ stdio: bool,
+}
+
#[tokio::main]
async fn main() {
+ let args = Args::parse();
+
let (service, socket) = LspService::new(Backend::new);
- let stdin = tokio::io::stdin();
- let stdout = tokio::io::stdout();
- Server::new(stdin, stdout, socket).serve(service).await;
+ if args.stdio {
+ let stdin = tokio::io::stdin();
+ let stdout = tokio::io::stdout();
+ Server::new(stdin, stdout, socket).serve(service).await;
+ } else {
+ let listener = TcpListener::bind("127.0.0.1:4000").await.unwrap();
+ let (stream, _) = listener.accept().await.unwrap();
+ let (read, write) = tokio::io::split(stream);
+ Server::new(read, write, socket).serve(service).await;
+ }
}
diff --git a/nvim.lua b/nvim.lua
deleted file mode 100644
index d0f703c30..000000000
--- a/nvim.lua
+++ /dev/null
@@ -1,14 +0,0 @@
--- This is a script used to debug `harper-ls` in NeoVim.
-
--- vim.lsp.start({
--- name = "example",
--- cmd = vim.lsp.rpc.connect("127.0.0.1", 4000),
--- root_dir = "."
--- })
-
-
-vim.lsp.start({
- name = "harper_ls",
- cmd = {"cargo", "run", "--bin", "harper-ls"},
- root_dir = "."
-})