Skip to content

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

feat: separated tree-sitter Masker to own crate

Elijah Potter0f5c0f3df8c0
diff --git a/Cargo.lock b/Cargo.lock
index f357a6d7a..d85773956 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -503,6 +503,7 @@ name = "harper-comments"
version = "0.8.8"
dependencies = [
"harper-core",
+ "harper-tree-sitter",
"itertools 0.12.1",
"paste",
"tree-sitter",
@@ -564,6 +565,14 @@ dependencies = [
"tracing-subscriber",
]
+[[package]]
+name = "harper-tree-sitter"
+version = "0.8.8"
+dependencies = [
+ "harper-core",
+ "tree-sitter",
+]
+
[[package]]
name = "harper-wasm"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 5cd96d9ab..0490665ff 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,5 +1,5 @@
[workspace]
-members = [ "harper-cli", "harper-core", "harper-ls", "harper-comments", "harper-wasm"]
+members = [ "harper-cli", "harper-core", "harper-ls", "harper-comments", "harper-wasm", "harper-tree-sitter"]
resolver = "2"
[profile.release]
diff --git a/harper-cli/src/main.rs b/harper-cli/src/main.rs
index 85be6b75c..ea8e4cbc1 100644
--- a/harper-cli/src/main.rs
+++ b/harper-cli/src/main.rs
@@ -5,7 +5,7 @@ use std::path::{Path, PathBuf};
use anyhow::format_err;
use ariadne::{Color, Label, Report, ReportKind, Source};
use clap::Parser;
-use harper_comments::TreeSitterParser;
+use harper_comments::CommentParser;
use harper_core::{remove_overlaps, Document, FullDictionary, LintGroup, LintGroupConfig, Linter};
#[derive(Debug, Parser)]
@@ -88,7 +88,7 @@ fn main() -> anyhow::Result<()> {
fn load_file(file: &Path) -> anyhow::Result<(Document, String)> {
let source = std::fs::read_to_string(file)?;
- let parser = TreeSitterParser::new_from_filename(file)
+ let parser = CommentParser::new_from_filename(file)
.ok_or(format_err!("Could not detect language ID."))?;
Ok((Document::new(&source, Box::new(parser)), source))
diff --git a/harper-comments/Cargo.toml b/harper-comments/Cargo.toml
index 53fbb0b01..8ef0fe671 100644
--- a/harper-comments/Cargo.toml
+++ b/harper-comments/Cargo.toml
@@ -9,6 +9,7 @@ repository = "https://github.com/elijah-potter/harper"
[dependencies]
harper-core = { path = "../harper-core", version = "0.8.0" }
+harper-tree-sitter = { path = "../harper-tree-sitter", version = "0.8.0" }
tree-sitter = "0.20.10"
tree-sitter-rust = "0.20.4"
tree-sitter-typescript = "0.20.3"
diff --git a/harper-comments/src/tree_sitter_parser.rs b/harper-comments/src/comment_parser.rs
similarity index 80%
rename from harper-comments/src/tree_sitter_parser.rs
rename to harper-comments/src/comment_parser.rs
index d6d1a3964..0f6e17cea 100644
--- a/harper-comments/src/tree_sitter_parser.rs
+++ b/harper-comments/src/comment_parser.rs
@@ -1,17 +1,18 @@
use std::path::Path;
-use crate::{comment_parsers, tree_sitter_masker::TreeSitterMasker};
use comment_parsers::{Go, JsDoc, Unit};
-use harper_core::{
- parsers::{self, Parser},
- FullDictionary, Token,
-};
+use harper_core::parsers::{self, Parser};
+use harper_core::{FullDictionary, Token};
+use harper_tree_sitter::TreeSitterMasker;
+use tree_sitter::Node;
-pub struct TreeSitterParser {
- inner: parsers::Mask<TreeSitterMasker, Box<dyn Parser>>,
+use crate::comment_parsers;
+
+pub struct CommentParser {
+ inner: parsers::Mask<TreeSitterMasker, Box<dyn Parser>>
}
-impl TreeSitterParser {
+impl CommentParser {
pub fn create_ident_dict(&self, source: &[char]) -> Option<FullDictionary> {
self.inner.masker.create_ident_dict(source)
}
@@ -34,17 +35,20 @@ impl TreeSitterParser {
"lua" => tree_sitter_lua::language(),
"sh" => tree_sitter_bash::language(),
"java" => tree_sitter_java::language(),
- _ => return None,
+ _ => return None
};
let comment_parser: Box<dyn Parser> = match language_id {
"javascriptreact" | "typescript" | "typescriptreact" | "javascript" => Box::new(JsDoc),
"go" => Box::new(Go),
- _ => Box::new(Unit),
+ _ => Box::new(Unit)
};
Some(Self {
- inner: parsers::Mask::new(TreeSitterMasker::new(language), comment_parser),
+ inner: parsers::Mask::new(
+ TreeSitterMasker::new(language, Self::node_condition),
+ comment_parser
+ )
})
}
@@ -77,12 +81,16 @@ impl TreeSitterParser {
"sh" => "sh",
"bash" => "sh",
"java" => "java",
- _ => return None,
+ _ => return None
})
}
+
+ fn node_condition(n: &Node) -> bool {
+ n.kind().contains("comment")
+ }
}
-impl Parser for TreeSitterParser {
+impl Parser for CommentParser {
fn parse(&mut self, source: &[char]) -> Vec<Token> {
self.inner.parse(source)
}
diff --git a/harper-comments/src/comment_parsers/jsdoc.rs b/harper-comments/src/comment_parsers/jsdoc.rs
index 4db6b908a..7512493b9 100644
--- a/harper-comments/src/comment_parsers/jsdoc.rs
+++ b/harper-comments/src/comment_parsers/jsdoc.rs
@@ -17,7 +17,7 @@ impl Parser for JsDoc {
new_tokens.push(Token::new(
Span::new_with_len(line.len(), 1),
- harper_core::TokenKind::Newline(1),
+ harper_core::TokenKind::Newline(1)
));
new_tokens
@@ -159,19 +159,19 @@ fn parse_inline_tag(tag_name: &[char], tokens: &[Token], source: &[char]) -> Opt
mod tests {
use harper_core::{Document, Punctuation, TokenKind};
- use crate::TreeSitterParser;
+ use crate::CommentParser;
#[test]
fn escapes_loop() {
let source = "/** This should _not_cause an infinite loop: {@ */";
- let parser = TreeSitterParser::new_from_language_id("javascript").unwrap();
+ let parser = CommentParser::new_from_language_id("javascript").unwrap();
Document::new(source, Box::new(parser));
}
#[test]
fn handles_inline_link() {
let source = "/** See {@link MyClass} and [MyClass's foo property]{@link MyClass#foo}. */";
- let parser = TreeSitterParser::new_from_language_id("javascript").unwrap();
+ let parser = CommentParser::new_from_language_id("javascript").unwrap();
let document = Document::new(source, Box::new(parser));
assert_eq!(
@@ -212,7 +212,7 @@ mod tests {
#[test]
fn handles_class() {
let source = "/** @class Circle representing a circle. */";
- let parser = TreeSitterParser::new_from_language_id("javascript").unwrap();
+ let parser = CommentParser::new_from_language_id("javascript").unwrap();
let document = Document::new(source, Box::new(parser));
assert!(document
diff --git a/harper-comments/src/comment_parsers/unit.rs b/harper-comments/src/comment_parsers/unit.rs
index 07eb144f6..2cd505401 100644
--- a/harper-comments/src/comment_parsers/unit.rs
+++ b/harper-comments/src/comment_parsers/unit.rs
@@ -22,7 +22,7 @@ impl Parser for Unit {
new_tokens.push(Token::new(
Span::new_with_len(line.len(), 1),
- harper_core::TokenKind::Newline(1),
+ harper_core::TokenKind::Newline(1)
));
new_tokens
diff --git a/harper-comments/src/lib.rs b/harper-comments/src/lib.rs
index f7b014eb2..ac56cb948 100644
--- a/harper-comments/src/lib.rs
+++ b/harper-comments/src/lib.rs
@@ -1,7 +1,6 @@
#![doc = include_str!("../README.md")]
mod better;
+mod comment_parser;
mod comment_parsers;
-mod tree_sitter_masker;
-mod tree_sitter_parser;
-pub use tree_sitter_parser::TreeSitterParser;
+pub use comment_parser::CommentParser;
diff --git a/harper-comments/tests/language_support.rs b/harper-comments/tests/language_support.rs
index b25c9c256..9d73e2d27 100644
--- a/harper-comments/tests/language_support.rs
+++ b/harper-comments/tests/language_support.rs
@@ -1,6 +1,6 @@
use std::path::Path;
-use harper_comments::TreeSitterParser;
+use harper_comments::CommentParser;
use harper_core::{Document, FullDictionary, LintGroup, LintGroupConfig, Linter};
/// Creates a unit test checking that the linting of a source file in
@@ -19,7 +19,7 @@ macro_rules! create_test {
)
);
- let parser = TreeSitterParser::new_from_filename(Path::new(filename)).unwrap();
+ let parser = CommentParser::new_from_filename(Path::new(filename)).unwrap();
let document = Document::new(&source, Box::new(parser));
let mut linter = LintGroup::new(
diff --git a/harper-core/src/document.rs b/harper-core/src/document.rs
index ef732befd..3ab9d6198 100644
--- a/harper-core/src/document.rs
+++ b/harper-core/src/document.rs
@@ -1,4 +1,3 @@
-use crate::Lrc;
use std::cmp::Ordering;
use std::collections::VecDeque;
use std::fmt::Display;
@@ -11,12 +10,12 @@ use crate::parsers::{Markdown, Parser, PlainEnglish};
use crate::punctuation::Punctuation;
use crate::span::Span;
use crate::token::NumberSuffix;
-use crate::{FatToken, Token, TokenKind, TokenStringExt};
+use crate::{FatToken, Lrc, Token, TokenKind, TokenStringExt};
pub struct Document {
source: Lrc<Vec<char>>,
tokens: Vec<Token>,
- parser: Box<dyn Parser>,
+ parser: Box<dyn Parser>
}
impl Default for Document {
@@ -38,7 +37,7 @@ impl Document {
let mut doc = Self {
source,
tokens: Vec::new(),
- parser,
+ parser
};
doc.parse();
@@ -103,7 +102,7 @@ impl Document {
&old[indices
.last()
.map(|v| v + stretch_len)
- .unwrap_or(indices.len())..],
+ .unwrap_or(indices.len())..]
);
}
@@ -243,7 +242,7 @@ impl Document {
pub fn get_full_string(&self) -> String {
self.get_span_content_str(Span {
start: 0,
- end: self.source.len(),
+ end: self.source.len()
})
}
@@ -503,7 +502,7 @@ fn is_chunk_terminator(token: &TokenKind) -> bool {
match token {
TokenKind::Punctuation(punct) => [Punctuation::Comma].contains(punct),
- _ => false,
+ _ => false
}
}
@@ -512,11 +511,11 @@ fn is_sentence_terminator(token: &TokenKind) -> bool {
TokenKind::Punctuation(punct) => [
Punctuation::Period,
Punctuation::Bang,
- Punctuation::Question,
+ Punctuation::Question
]
.contains(punct),
TokenKind::Newline(count) => *count >= 2,
- _ => false,
+ _ => false
}
}
@@ -637,7 +636,7 @@ mod tests {
assert_token_count("This is the 3rd test", 9);
assert_token_count(
"It works even with weird capitalization like this: 600nD",
- 18,
+ 18
);
}
diff --git a/harper-core/src/linting/spell_check.rs b/harper-core/src/linting/spell_check.rs
index f19d99bbc..a36aa79b1 100644
--- a/harper-core/src/linting/spell_check.rs
+++ b/harper-core/src/linting/spell_check.rs
@@ -9,17 +9,17 @@ use crate::{CharString, Dictionary, TokenStringExt};
pub struct SpellCheck<T>
where
- T: Dictionary,
+ T: Dictionary
{
dictionary: T,
- word_cache: HashMap<CharString, Vec<CharString>>,
+ word_cache: HashMap<CharString, Vec<CharString>>
}
impl<T: Dictionary> SpellCheck<T> {
pub fn new(dictionary: T) -> Self {
Self {
dictionary,
- word_cache: HashMap::new(),
+ word_cache: HashMap::new()
}
}
}
@@ -87,7 +87,7 @@ impl<T: Dictionary> Linter for SpellCheck<T> {
"Did you mean to spell “{}” this way?",
document.get_span_content_str(word.span)
),
- priority: 63,
+ priority: 63
})
}
diff --git a/harper-core/src/mask/mod.rs b/harper-core/src/mask/mod.rs
index 2300d8304..5b87edae0 100644
--- a/harper-core/src/mask/mod.rs
+++ b/harper-core/src/mask/mod.rs
@@ -1,10 +1,9 @@
-use itertools::Itertools;
-
use crate::Span;
-/// A Masker is a tool that can be composed to eliminate chunks of text from being parsed.
-/// They can be composed to do things like isolate comments from a programming language or disable
-/// linting for languages that have been determined to not be English.
+/// A Masker is a tool that can be composed to eliminate chunks of text from
+/// being parsed. They can be composed to do things like isolate comments from a
+/// programming language or disable linting for languages that have been
+/// determined to not be English.
pub trait Masker: Send + Sync {
fn create_mask(&mut self, source: &[char]) -> Mask;
}
@@ -13,20 +12,21 @@ pub struct Mask {
// Right now, there aren't any use-cases where we can't treat this as a stack.
//
// Assumed that no elements overlap and exist in sorted order.
- pub(self) allowed: Vec<Span>,
+ pub(self) allowed: Vec<Span>
}
impl Mask {
- /// Create a new Mask for a given piece of text, marking all text as disallowed.
+ /// Create a new Mask for a given piece of text, marking all text as
+ /// disallowed.
pub fn new_blank() -> Self {
Self {
- allowed: Vec::new(),
+ allowed: Vec::new()
}
}
pub fn iter_allowed<'a>(
&'a self,
- source: &'a [char],
+ source: &'a [char]
) -> impl Iterator<Item = (Span, &'a [char])> + '_ {
self.allowed.iter().map(|s| (*s, s.get_content(source)))
}
diff --git a/harper-core/src/parsers/mask.rs b/harper-core/src/parsers/mask.rs
index 47a8af456..65dca812c 100644
--- a/harper-core/src/parsers/mask.rs
+++ b/harper-core/src/parsers/mask.rs
@@ -1,21 +1,21 @@
-use crate::{mask::Masker, Span, Token, TokenKind};
-
use super::Parser;
+use crate::mask::Masker;
+use crate::{Token, TokenKind};
/// Composes a Masker and a Parser to parse only masked chunks of text.
pub struct Mask<M, P>
where
M: Masker,
- P: Parser,
+ P: Parser
{
pub masker: M,
- pub parser: P,
+ pub parser: P
}
impl<M, P> Mask<M, P>
where
M: Masker,
- P: Parser,
+ P: Parser
{
pub fn new(masker: M, parser: P) -> Self {
Self { masker, parser }
@@ -25,7 +25,7 @@ where
impl<M, P> Parser for Mask<M, P>
where
M: Masker,
- P: Parser,
+ P: Parser
{
fn parse(&mut self, source: &[char]) -> Vec<Token> {
let mask = self.masker.create_mask(source);
diff --git a/harper-core/src/parsers/mod.rs b/harper-core/src/parsers/mod.rs
index 94fd5779d..1140b8a48 100644
--- a/harper-core/src/parsers/mod.rs
+++ b/harper-core/src/parsers/mod.rs
@@ -20,7 +20,7 @@ pub trait StrParser {
impl<T> StrParser for T
where
- T: Parser,
+ T: Parser
{
fn parse_str(&mut self, source: impl AsRef<str>) -> Vec<Token> {
let source: Vec<_> = source.as_ref().chars().collect();
@@ -37,7 +37,7 @@ mod tests {
fn assert_tokens_eq(
test_str: impl AsRef<str>,
expected: &[TokenKind],
- parser: &mut impl Parser,
+ parser: &mut impl Parser
) {
let chars: Vec<_> = test_str.as_ref().chars().collect();
let tokens = parser.parse(&chars);
@@ -74,8 +74,8 @@ mod tests {
Space(1),
Word,
Space(1),
- Word,
- ],
+ Word
+ ]
)
}
@@ -91,8 +91,8 @@ mod tests {
Space(1),
Word,
Space(1),
- Word,
- ],
+ Word
+ ]
);
}
@@ -108,8 +108,8 @@ mod tests {
Newline(2),
Word,
Space(1),
- Word,
- ],
+ Word
+ ]
);
}
diff --git a/harper-core/src/sync.rs b/harper-core/src/sync.rs
index 30a24bc42..8c78a269a 100644
--- a/harper-core/src/sync.rs
+++ b/harper-core/src/sync.rs
@@ -1,5 +1,4 @@
-#[cfg(feature = "concurrent")]
-pub use std::sync::Arc as Lrc;
-
#[cfg(not(feature = "concurrent"))]
pub use std::rc::Rc as Lrc;
+#[cfg(feature = "concurrent")]
+pub use std::sync::Arc as Lrc;
diff --git a/harper-ls/src/backend.rs b/harper-ls/src/backend.rs
index cd57a2d1c..c9ee9249d 100644
--- a/harper-ls/src/backend.rs
+++ b/harper-ls/src/backend.rs
@@ -2,23 +2,48 @@ use std::collections::HashMap;
use std::path::{Component, PathBuf};
use std::sync::Arc;
-use harper_comments::TreeSitterParser;
+use harper_comments::CommentParser;
use harper_core::parsers::{Markdown, PlainEnglish};
use harper_core::{
- Dictionary, Document, FullDictionary, LintGroup, Linter, MergedDictionary, Token, TokenKind,
+ Dictionary,
+ Document,
+ FullDictionary,
+ LintGroup,
+ Linter,
+ MergedDictionary,
+ Token,
+ TokenKind
};
use serde_json::Value;
use tokio::sync::{Mutex, RwLock};
use tower_lsp::jsonrpc::Result;
use tower_lsp::lsp_types::notification::PublishDiagnostics;
use tower_lsp::lsp_types::{
- CodeActionOrCommand, CodeActionParams, CodeActionProviderCapability, CodeActionResponse,
- Command, Diagnostic, DidChangeConfigurationParams, DidChangeTextDocumentParams,
- DidCloseTextDocumentParams, DidOpenTextDocumentParams, DidSaveTextDocumentParams,
- ExecuteCommandOptions, ExecuteCommandParams, InitializeParams, InitializeResult,
- InitializedParams, MessageType, PublishDiagnosticsParams, Range, ServerCapabilities,
- TextDocumentSyncCapability, TextDocumentSyncKind, TextDocumentSyncOptions,
- TextDocumentSyncSaveOptions, Url,
+ CodeActionOrCommand,
+ CodeActionParams,
+ CodeActionProviderCapability,
+ CodeActionResponse,
+ Command,
+ Diagnostic,
+ DidChangeConfigurationParams,
+ DidChangeTextDocumentParams,
+ DidCloseTextDocumentParams,
+ DidOpenTextDocumentParams,
+ DidSaveTextDocumentParams,
+ ExecuteCommandOptions,
+ ExecuteCommandParams,
+ InitializeParams,
+ InitializeResult,
+ InitializedParams,
+ MessageType,
+ PublishDiagnosticsParams,
+ Range,
+ ServerCapabilities,
+ TextDocumentSyncCapability,
+ TextDocumentSyncKind,
+ TextDocumentSyncOptions,
+ TextDocumentSyncSaveOptions,
+ Url
};
use tower_lsp::{Client, LanguageServer};
use tracing::{error, info, instrument};
@@ -34,7 +59,7 @@ struct DocumentState {
document: Document,
ident_dict: Arc<FullDictionary>,
linter: LintGroup<MergedDictionary<FullDictionary>>,
- language_id: Option<String>,
+ language_id: Option<String>
}
/// Deallocate
@@ -42,7 +67,7 @@ pub struct Backend {
client: Client,
static_dictionary: Arc<FullDictionary>,
config: RwLock<Config>,
- doc_state: Mutex<HashMap<Url, DocumentState>>,
+ doc_state: Mutex<HashMap<Url, DocumentState>>
}
impl Backend {
@@ -53,7 +78,7 @@ impl Backend {
client,
static_dictionary: dictionary.into(),
doc_state: Mutex::new(HashMap::new()),
- config: RwLock::new(config),
+ config: RwLock::new(config)
}
}
@@ -148,7 +173,7 @@ impl Backend {
#[instrument(skip(self))]
async fn generate_file_dictionary(
&self,
- url: &Url,
+ url: &Url
) -> anyhow::Result<MergedDictionary<FullDictionary>> {
let (global_dictionary, file_dictionary) = tokio::join!(
self.generate_global_dictionary(),
@@ -165,11 +190,11 @@ impl Backend {
async fn update_document_from_file(
&self,
url: &Url,
- language_id: Option<&str>,
+ language_id: Option<&str>
) -> anyhow::Result<()> {
let content = match tokio::fs::read_to_string(
url.to_file_path()
- .map_err(|_| anyhow::format_err!("Could not extract file path."))?,
+ .map_err(|_| anyhow::format_err!("Could not extract file path."))?
)
.await
{
@@ -188,7 +213,7 @@ impl Backend {
&self,
url: &Url,
text: &str,
- language_id: Option<&str>,
+ language_id: Option<&str>
) -> anyhow::Result<()> {
let mut doc_lock = self.doc_state.lock().await;
let config_lock = self.config.read().await;
@@ -200,7 +225,7 @@ impl Backend {
let mut doc_state = DocumentState {
linter: LintGroup::new(
config_lock.lint_config,
- self.generate_file_dictionary(url).await?,
+ self.generate_file_dictionary(url).await?
),
language_id: language_id
.map(|v| v.to_string())
@@ -214,7 +239,7 @@ impl Backend {
};
doc_state.document =
- if let Some(ts_parser) = TreeSitterParser::new_from_language_id(language_id) {
+ if let Some(ts_parser) = CommentParser::new_from_language_id(language_id) {
let source: Vec<char> = text.chars().collect();
let source = Arc::new(source);
@@ -251,7 +276,7 @@ impl Backend {
async fn generate_code_actions(
&self,
url: &Url,
- range: Range,
+ range: Range
) -> Result<Vec<CodeActionOrCommand>> {
let (config, mut doc_states) = tokio::join!(self.config.read(), self.doc_state.lock());
let Some(doc_state) = doc_states.get_mut(url) else {
@@ -283,7 +308,7 @@ impl Backend {
actions.push(CodeActionOrCommand::Command(Command::new(
"Open URL".to_string(),
"HarperOpen".to_string(),
- Some(vec![doc_state.document.get_span_content_str(span).into()]),
+ Some(vec![doc_state.document.get_span_content_str(span).into()])
)))
}
@@ -303,7 +328,7 @@ impl Backend {
lints_to_diagnostics(
doc_state.document.get_full_content(),
&lints,
- config.diagnostic_severity,
+ config.diagnostic_severity
)
}
@@ -314,7 +339,7 @@ impl Backend {
let result = PublishDiagnosticsParams {
uri: url.clone(),
diagnostics,
- version: None,
+ version: None
};
self.client
@@ -344,12 +369,12 @@ impl LanguageServer for Backend {
change: Some(TextDocumentSyncKind::FULL),
will_save: None,
will_save_wait_until: None,
- save: Some(TextDocumentSyncSaveOptions::Supported(true)),
- },
+ save: Some(TextDocumentSyncSaveOptions::Supported(true))
+ }
)),
..Default::default()
- },
+ }
})
}
@@ -380,7 +405,7 @@ impl LanguageServer for Backend {
.update_document(
&params.text_document.uri,
&params.text_document.text,
- Some(&params.text_document.language_id),
+ Some(&params.text_document.language_id)
)
.await;
@@ -469,7 +494,7 @@ impl LanguageServer for Backend {
error!("Unable to open URL: {}", err);
}
},
- _ => (),
+ _ => ()
}
Ok(None)
@@ -500,7 +525,7 @@ impl LanguageServer for Backend {
// Update documents with new config
futures::future::join_all(
keys.iter()
- .map(|key| self.update_document_from_file(key, None)),
+ .map(|key| self.update_document_from_file(key, None))
)
.await;
}
diff --git a/harper-tree-sitter/Cargo.toml b/harper-tree-sitter/Cargo.toml
new file mode 100644
index 000000000..be92b6f90
--- /dev/null
+++ b/harper-tree-sitter/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "harper-tree-sitter"
+version = "0.8.8"
+edition = "2021"
+description = "The language checker for developers."
+license = "Apache-2.0"
+readme = "README.md"
+repository = "https://github.com/elijah-potter/harper"
+
+[dependencies]
+harper-core = { path = "../harper-core", version = "0.8.0" }
+tree-sitter = "0.20.10"
diff --git a/harper-comments/src/tree_sitter_masker.rs b/harper-tree-sitter/src/lib.rs
similarity index 85%
rename from harper-comments/src/tree_sitter_masker.rs
rename to harper-tree-sitter/src/lib.rs
index 09c0df740..36d347eb7 100644
--- a/harper-comments/src/tree_sitter_masker.rs
+++ b/harper-tree-sitter/src/lib.rs
@@ -1,18 +1,21 @@
use std::collections::HashSet;
-use harper_core::{FullDictionary, Span};
-use harper_core::{Mask, Masker};
+use harper_core::{FullDictionary, Mask, Masker, Span};
use tree_sitter::{Language, Node, Tree, TreeCursor};
-/// A Harper parser that wraps various comment parsers that
-/// exclusively parses comments in any language supported by [`tree_sitter`].
+/// A Harper [`Masker`] that wraps a given tree-sitter language and a condition,
+/// allowing you to selectively parse only specific tree-sitter nodes.
pub struct TreeSitterMasker {
language: Language,
+ node_condition: fn(&Node) -> bool
}
impl TreeSitterMasker {
- pub fn new(language: Language) -> Self {
- Self { language }
+ pub fn new(language: Language, node_condition: fn(&Node) -> bool) -> Self {
+ Self {
+ language,
+ node_condition
+ }
}
fn parse_root(&self, text: &str) -> Option<Tree> {
@@ -55,9 +58,9 @@ impl TreeSitterMasker {
/// Visits the children of a TreeSitter node, searching for comments.
///
/// Returns the BYTE spans of the comment position.
- fn extract_comments(cursor: &mut TreeCursor, comments: &mut Vec<Span>) {
+ fn extract_comments(&self, cursor: &mut TreeCursor, comments: &mut Vec<Span>) {
Self::visit_nodes(cursor, &mut |node: &Node| {
- if node.kind().contains("comment") {
+ if (self.node_condition)(node) {
comments.push(node.byte_range().into());
}
});
@@ -94,7 +97,7 @@ impl Masker for TreeSitterMasker {
let mut comments_spans = Vec::new();
- Self::extract_comments(&mut root.walk(), &mut comments_spans);
+ self.extract_comments(&mut root.walk(), &mut comments_spans);
byte_spans_to_char_spans(&mut comments_spans, &text);
let mut mask = Mask::new_blank();
diff --git a/harper-wasm/src/lib.rs b/harper-wasm/src/lib.rs
index 3991c86eb..1ecc026cd 100644
--- a/harper-wasm/src/lib.rs
+++ b/harper-wasm/src/lib.rs
@@ -10,7 +10,7 @@ use wasm_bindgen::prelude::wasm_bindgen;
static LINTER: Lazy<Mutex<LintGroup<FullDictionary>>> = Lazy::new(|| {
Mutex::new(LintGroup::new(
Default::default(),
- FullDictionary::create_from_curated(),
+ FullDictionary::create_from_curated()
))
});
@@ -55,7 +55,7 @@ pub fn lint(text: String) -> Vec<Lint> {
pub fn apply_suggestion(
text: String,
span: Span,
- suggestion: &Suggestion,
+ suggestion: &Suggestion
) -> Result<String, String> {
let mut document = Document::new_markdown(&text);
document.apply_suggestion(&suggestion.inner, span.into());
@@ -65,13 +65,13 @@ pub fn apply_suggestion(
#[wasm_bindgen]
pub struct Suggestion {
- inner: harper_core::Suggestion,
+ inner: harper_core::Suggestion
}
#[wasm_bindgen]
pub enum SuggestionKind {
Replace,
- Remove,
+ Remove
}
#[wasm_bindgen]
@@ -86,14 +86,14 @@ impl Suggestion {
pub fn get_replacement_text(&self) -> String {
match &self.inner {
harper_core::Suggestion::Remove => "".to_string(),
- harper_core::Suggestion::ReplaceWith(chars) => chars.iter().collect(),
+ harper_core::Suggestion::ReplaceWith(chars) => chars.iter().collect()
}
}
pub fn kind(&self) -> SuggestionKind {
match &self.inner {
harper_core::Suggestion::Remove => SuggestionKind::Remove,
- harper_core::Suggestion::ReplaceWith(_) => SuggestionKind::Replace,
+ harper_core::Suggestion::ReplaceWith(_) => SuggestionKind::Replace
}
}
}
@@ -101,7 +101,7 @@ impl Suggestion {
#[wasm_bindgen]
pub struct Lint {
inner: harper_core::Lint,
- source: Lrc<Vec<char>>,
+ source: Lrc<Vec<char>>
}
#[wasm_bindgen]
@@ -144,7 +144,7 @@ impl Lint {
#[wasm_bindgen]
pub struct Span {
pub start: usize,
- pub end: usize,
+ pub end: usize
}
#[wasm_bindgen]