Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat: Harper's dictionary now infers some information based on the affix expansions
Elijah Potterdf42c939a30c
diff --git a/Cargo.lock b/Cargo.lockindex f6b3c2814..bc897585a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -533,7 +533,6 @@ dependencies = ["hashbrown","is-macro","itertools 0.13.0",- "once_cell","paste","pulldown-cmark","rand",diff --git a/harper-cli/src/main.rs b/harper-cli/src/main.rsindex fdd0ac804..66e6b0687 100644--- a/harper-cli/src/main.rs+++ b/harper-cli/src/main.rs@@ -34,10 +34,7 @@ fn main() -> anyhow::Result<()> {Args::Lint { file, count } => {let (doc, source) = load_file(&file)?;- let mut linter = LintGroup::new(- LintGroupConfig::default(),- FullDictionary::create_from_curated()- );+ let mut linter = LintGroup::new(LintGroupConfig::default(), FullDictionary::curated());let mut lints = linter.lint(&doc);if count {@@ -89,7 +86,7 @@ fn main() -> anyhow::Result<()> {fn load_file(file: &Path) -> anyhow::Result<(Document, String)> {let source = std::fs::read_to_string(file)?;- let parser: Box<dyn harper_core::parsers::Parser> =+ let mut parser: Box<dyn harper_core::parsers::Parser> =if let Some("md") = file.extension().map(|v| v.to_str().unwrap()) {Box::new(Markdown)} else {@@ -100,5 +97,5 @@ fn load_file(file: &Path) -> anyhow::Result<(Document, String)> {)};- Ok((Document::new(&source, Box::new(parser)), source))+ Ok((Document::new_curated(&source, &mut parser), source))}diff --git a/harper-comments/src/comment_parsers/jsdoc.rs b/harper-comments/src/comment_parsers/jsdoc.rsindex 2d7680893..1d8334fd9 100644--- a/harper-comments/src/comment_parsers/jsdoc.rs+++ b/harper-comments/src/comment_parsers/jsdoc.rs@@ -153,20 +153,24 @@ mod tests {#[test]fn escapes_loop() {let source = "/** This should _not_cause an infinite loop: {@ */";- let parser = CommentParser::new_from_language_id("javascript").unwrap();- Document::new(source, Box::new(parser));+ let mut parser = CommentParser::new_from_language_id("javascript").unwrap();+ Document::new_curated(source, &mut parser);}#[test]fn handles_inline_link() {let source = "/** See {@link MyClass} and [MyClass's foo property]{@link MyClass#foo}. */";- let parser = CommentParser::new_from_language_id("javascript").unwrap();- let document = Document::new(source, Box::new(parser));-- assert_eq!(- document.tokens().map(|t| t.kind).collect::<Vec<_>>(),- vec![- TokenKind::blank_word(),+ let mut parser = CommentParser::new_from_language_id("javascript").unwrap();+ let document = Document::new_curated(source, &mut parser);++ assert!(matches!(+ document+ .tokens()+ .map(|t| t.kind)+ .collect::<Vec<_>>()+ .as_slice(),+ &[+ TokenKind::Word(..),TokenKind::Space(1),TokenKind::Unlintable,TokenKind::Unlintable,@@ -175,14 +179,14 @@ mod tests {TokenKind::Unlintable,TokenKind::Unlintable,TokenKind::Space(1),- TokenKind::blank_word(),+ TokenKind::Word(..),TokenKind::Space(1),TokenKind::Punctuation(Punctuation::OpenSquare),- TokenKind::blank_word(),+ TokenKind::Word(..),TokenKind::Space(1),- TokenKind::blank_word(),+ TokenKind::Word(..),TokenKind::Space(1),- TokenKind::blank_word(),+ TokenKind::Word(..),TokenKind::Punctuation(Punctuation::CloseSquare),TokenKind::Unlintable,TokenKind::Unlintable,@@ -195,14 +199,14 @@ mod tests {TokenKind::Punctuation(Punctuation::Period),TokenKind::Newline(1),]- );+ ));}#[test]fn handles_class() {let source = "/** @class Circle representing a circle. */";- let parser = CommentParser::new_from_language_id("javascript").unwrap();- let document = Document::new(source, Box::new(parser));+ let mut parser = CommentParser::new_from_language_id("javascript").unwrap();+ let document = Document::new_curated(source, &mut parser);assert!(document.tokens()diff --git a/harper-comments/tests/language_support.rs b/harper-comments/tests/language_support.rsindex 6793aa35b..448ad076a 100644--- a/harper-comments/tests/language_support.rs+++ b/harper-comments/tests/language_support.rs@@ -19,12 +19,13 @@ macro_rules! create_test {));- let parser = CommentParser::new_from_filename(Path::new(filename)).unwrap();- let document = Document::new(&source, Box::new(parser));+ let mut parser = CommentParser::new_from_filename(Path::new(filename)).unwrap();+ let dict = FullDictionary::curated();+ let document = Document::new(&source, &mut parser, &dict);let mut linter = LintGroup::new(LintGroupConfig::default(),- FullDictionary::create_from_curated()+ dict);let lints = linter.lint(&document);diff --git a/harper-comments/tests/language_support_sources/javadoc_complex.java b/harper-comments/tests/language_support_sources/javadoc_complex.javaindex 2c2bb23d8..a3ae0b532 100644--- a/harper-comments/tests/language_support_sources/javadoc_complex.java+++ b/harper-comments/tests/language_support_sources/javadoc_complex.java@@ -19,7 +19,7 @@ class TestClass {/*** This doc has a link in it: {@link this sould b ignor} but not tis*- * @param this is an other test.+ * @param name this is an other test.*/public static void greet(String name) {System.out.println("Hello " + name + ".");diff --git a/harper-core/Cargo.toml b/harper-core/Cargo.tomlindex 1d2e41c8a..493718a71 100644--- a/harper-core/Cargo.toml+++ b/harper-core/Cargo.toml@@ -12,7 +12,6 @@ blanket = "0.4.0"hashbrown = { version = "0.14.3", features = ["serde"] }is-macro = "0.3.0"itertools = "0.13.0"-once_cell = "1.19.0"paste = "1.0.14"pulldown-cmark = "0.11.0"serde = { version = "1.0.197", features = ["derive"] }diff --git a/harper-core/affixes.json b/harper-core/affixes.jsonindex 063e5b8f0..5c0fa1431 100644--- a/harper-core/affixes.json+++ b/harper-core/affixes.json@@ -10,11 +10,8 @@"condition": "."}],- "adds_metadata": {- "kind": null,- "tense": null,- "plural": null- }+ "adds_metadata": {},+ "gifts_metadata": {}},"L": {"suffix": true,@@ -26,11 +23,8 @@"condition": "."}],- "adds_metadata": {- "kind": null,- "tense": null,- "plural": null- }+ "adds_metadata": {},+ "gifts_metadata": {}},"E": {"suffix": false,@@ -42,11 +36,8 @@"condition": "."}],- "adds_metadata": {- "kind": null,- "tense": null,- "plural": null- }+ "adds_metadata": {},+ "gifts_metadata": {}},"Y": {"suffix": true,@@ -58,11 +49,8 @@"condition": "."}],- "adds_metadata": {- "kind": null,- "tense": null,- "plural": null- }+ "adds_metadata": {},+ "gifts_metadata": {}},"U": {"suffix": false,@@ -74,11 +62,8 @@"condition": "."}],- "adds_metadata": {- "kind": null,- "tense": null,- "plural": null- }+ "adds_metadata": {},+ "gifts_metadata": {}},"H": {"suffix": true,@@ -95,11 +80,8 @@"condition": "[^y]"}],- "adds_metadata": {- "kind": null,- "tense": null,- "plural": null- }+ "adds_metadata": {},+ "gifts_metadata": {}},"T": {"suffix": true,@@ -126,11 +108,8 @@"condition": "[^ey]"}],- "adds_metadata": {- "kind": null,- "tense": null,- "plural": null- }+ "adds_metadata": {},+ "gifts_metadata": {}},"R": {"suffix": true,@@ -157,11 +136,8 @@"condition": "[^ey]"}],- "adds_metadata": {- "kind": null,- "tense": null,- "plural": null- }+ "adds_metadata": {},+ "gifts_metadata": {}},"C": {"suffix": false,@@ -173,11 +149,8 @@"condition": "."}],- "adds_metadata": {- "kind": null,- "tense": null,- "plural": null- }+ "adds_metadata": {},+ "gifts_metadata": {}},"V": {"suffix": true,@@ -194,11 +167,8 @@"condition": "[^e]"}],- "adds_metadata": {- "kind": null,- "tense": null,- "plural": null- }+ "adds_metadata": {},+ "gifts_metadata": {}},"N": {"suffix": true,@@ -220,11 +190,8 @@"condition": "[^ey]"}],- "adds_metadata": {- "kind": null,- "tense": null,- "plural": null- }+ "adds_metadata": {},+ "gifts_metadata": {}},"A": {"suffix": false,@@ -236,11 +203,8 @@"condition": "."}],- "adds_metadata": {- "kind": null,- "tense": null,- "plural": null- }+ "adds_metadata": {},+ "gifts_metadata": {}},"Z": {"suffix": true,@@ -267,11 +231,8 @@"condition": "[^ey]"}],- "adds_metadata": {- "kind": null,- "tense": null,- "plural": null- }+ "adds_metadata": {},+ "gifts_metadata": {}},"P": {"suffix": true,@@ -293,11 +254,8 @@"condition": "[^y]"}],- "adds_metadata": {- "kind": null,- "tense": null,- "plural": null- }+ "adds_metadata": {},+ "gifts_metadata": {}},"M": {"suffix": true,@@ -310,9 +268,12 @@}],"adds_metadata": {- "kind": null,- "tense": null,- "plural": null+ "possessive": true+ },+ "gifts_metadata": {+ "kind": {+ "kind": "Noun"+ }}},"F": {@@ -325,11 +286,8 @@"condition": "."}],- "adds_metadata": {- "kind": null,- "tense": null,- "plural": null- }+ "adds_metadata": {},+ "gifts_metadata": {}},"B": {"suffix": true,@@ -351,11 +309,8 @@"condition": "[^aeiou]e"}],- "adds_metadata": {- "kind": null,- "tense": null,- "plural": null- }+ "adds_metadata": {},+ "gifts_metadata": {}},"S": {"suffix": true,@@ -383,10 +338,12 @@}],"adds_metadata": {- "kind": null,- "tense": null,- "plural": true- }+ "kind": {+ "kind": "Noun",+ "plural": true+ }+ },+ "gifts_metadata": {}},"D": {"suffix": true,@@ -414,9 +371,15 @@}],"adds_metadata": {- "kind": null,- "tense": null,- "plural": null+ "kind": {+ "kind": "Adjective"+ }+ },+ "gifts_metadata": {+ "kind": {+ "kind": "Noun",+ "is_proper": null+ }}},"G": {@@ -435,9 +398,14 @@}],"adds_metadata": {- "kind": null,- "tense": null,- "plural": null+ "kind": {+ "kind": "Adjective"+ }+ },+ "gifts_metadata": {+ "kind": {+ "kind": "Verb"+ }}},"Q": {@@ -450,11 +418,8 @@"condition": "."}],- "adds_metadata": {- "kind": null,- "tense": null,- "plural": null- }+ "adds_metadata": {},+ "gifts_metadata": {}},"O": {"suffix": true,@@ -466,11 +431,8 @@"condition": "."}],- "adds_metadata": {- "kind": null,- "tense": null,- "plural": null- }+ "adds_metadata": {},+ "gifts_metadata": {}},"I": {"suffix": false,@@ -482,11 +444,8 @@"condition": "."}],- "adds_metadata": {- "kind": null,- "tense": null,- "plural": null- }+ "adds_metadata": {},+ "gifts_metadata": {}},"X": {"suffix": true,@@ -508,11 +467,8 @@"condition": "[^ey]"}],- "adds_metadata": {- "kind": null,- "tense": null,- "plural": null- }+ "adds_metadata": {},+ "gifts_metadata": {}},"J": {"suffix": true,@@ -529,11 +485,8 @@"condition": "[^e]"}],- "adds_metadata": {- "kind": null,- "tense": null,- "plural": null- }+ "adds_metadata": {},+ "gifts_metadata": {}}}}diff --git a/harper-core/benches/parse_demo.rs b/harper-core/benches/parse_demo.rsindex a31c20754..04de0527b 100644--- a/harper-core/benches/parse_demo.rs+++ b/harper-core/benches/parse_demo.rs@@ -9,15 +9,15 @@ static DEMO: &str = include_str!("../../demo.md");#[divan::bench]fn parse_demo(bencher: Bencher) {bencher.bench_local(|| {- let _document = Document::new_markdown(black_box(DEMO));+ let _document = Document::new_markdown_curated(black_box(DEMO));});}#[divan::bench]fn lint_demo(bencher: Bencher) {- let dictionary = FullDictionary::create_from_curated();+ let dictionary = FullDictionary::curated();let mut lint_set = LintGroup::new(Default::default(), dictionary);- let document = Document::new_markdown(black_box(DEMO));+ let document = Document::new_markdown_curated(black_box(DEMO));bencher.bench_local(|| {lint_set.lint(&document);@@ -26,10 +26,10 @@ fn lint_demo(bencher: Bencher) {#[divan::bench]fn lint_demo_uncached(bencher: Bencher) {- let dictionary = FullDictionary::create_from_curated();+ let dictionary = FullDictionary::curated();bencher.bench_local(|| {let mut lint_set = LintGroup::new(LintGroupConfig::default(), dictionary.clone());- let document = Document::new_markdown(black_box(DEMO));+ let document = Document::new_markdown_curated(black_box(DEMO));lint_set.lint(&document);});diff --git a/harper-core/dictionary.dict b/harper-core/dictionary.dictindex bcfdf7693..d1e7a6cf4 100644--- a/harper-core/dictionary.dict+++ b/harper-core/dictionary.dict@@ -8695,10 +8695,10 @@ Salvadorian/MSSalvatore/MSalween/MSalyut/M-Sam/M-Samantha/M-Samar/M-Samara/M+sam/m+samantha/m+samar/m+samara/mSamaritan/MSSamarkand/MSammie/M@@ -25995,7 +25995,8 @@ gyroscopicgyve/MGDSh'mh/NRSXZGVJ-ha/SH+ha/H+hashaberdasher/SMhaberdashery/SMhabiliment/SMdiff --git a/harper-core/src/document.rs b/harper-core/src/document.rsindex 770a2a9c3..413ad1d3e 100644--- a/harper-core/src/document.rs+++ b/harper-core/src/document.rs@@ -5,59 +5,73 @@ use std::fmt::Display;use itertools::Itertools;use paste::paste;-use crate::linting::Suggestion;use crate::parsers::{Markdown, Parser, PlainEnglish};use crate::punctuation::Punctuation;use crate::span::Span;use crate::token::NumberSuffix;use crate::vec_ext::VecExt;-use crate::{FatToken, Lrc, Token, TokenKind, TokenStringExt};+use crate::{Dictionary, FatToken, FullDictionary, Lrc, Token, TokenKind, TokenStringExt};pub struct Document {source: Lrc<Vec<char>>,- tokens: Vec<Token>,- parser: Box<dyn Parser>+ tokens: Vec<Token>}impl Default for Document {fn default() -> Self {- Self::new("", Box::new(PlainEnglish))+ Self::new("", &mut PlainEnglish, &FullDictionary::curated())}}impl Document {/// Lexes and parses text to produce a document.- /// Choosing to parse with markdown may have a performance penalty- pub fn new(text: &str, parser: Box<dyn Parser>) -> Self {+ pub fn new(text: &str, parser: &mut impl Parser, dictionary: &impl Dictionary) -> Self {let source: Vec<_> = text.chars().collect();- Self::new_from_vec(Lrc::new(source), parser)+ Self::new_from_vec(Lrc::new(source), parser, dictionary)}- pub fn new_from_vec(source: Lrc<Vec<char>>, parser: Box<dyn Parser>) -> Self {- let mut doc = Self {- source,- tokens: Vec::new(),- parser- };- doc.parse();+ /// Lexes and parses text to produce a document.+ pub fn new_curated(text: &str, parser: &mut impl Parser) -> Self {+ let source: Vec<_> = text.chars().collect();++ Self::new_from_vec(Lrc::new(source), parser, &FullDictionary::curated())+ }++ pub fn new_from_vec(+ source: Lrc<Vec<char>>,+ parser: &mut impl Parser,+ dictionary: &impl Dictionary+ ) -> Self {+ let tokens = parser.parse(&source);++ let mut document = Self { source, tokens };+ document.parse(dictionary);++ document+ }++ pub fn new_plain_english_curated(text: &str) -> Self {+ Self::new(text, &mut PlainEnglish, &FullDictionary::curated())+ }- doc+ pub fn new_plain_english(text: &str, dictionary: &impl Dictionary) -> Self {+ Self::new(text, &mut PlainEnglish, dictionary)}- pub fn new_plain_english(text: &str) -> Self {- Self::new(text, Box::new(PlainEnglish))+ /// Create a new Markdown document using the curated dictionary for tagging.+ pub fn new_markdown_curated(text: &str) -> Self {+ Self::new(text, &mut Markdown, &FullDictionary::curated())}- pub fn new_markdown(text: &str) -> Self {- Self::new(text, Box::new(Markdown))+ pub fn new_markdown(text: &str, dictionary: &impl Dictionary) -> Self {+ Self::new(text, &mut Markdown, dictionary)}/// Re-parse important language constructs.////// Should be run after every change to the underlying [`Self::source`].- fn parse(&mut self) {- self.tokens = self.parser.parse(&self.source);+ fn parse(&mut self, dictionary: &impl Dictionary) {self.condense_spaces();self.condense_newlines();self.newlines_to_breaks();@@ -65,6 +79,14 @@ impl Document {self.condense_dotted_initialisms();self.condense_number_suffixes();self.match_quotes();++ for token in self.tokens.iter_mut() {+ if let TokenKind::Word(meta) = &mut token.kind {+ let word_source = token.span.get_content(&self.source);+ let found_meta = dictionary.get_word_metadata(word_source);+ *meta = meta.or(&found_meta);+ }+ }}/// Convert all sets of newlines greater than 2 to paragraph breaks.@@ -264,35 +286,6 @@ impl Document {&self.source}- pub fn apply_suggestion(&mut self, suggestion: &Suggestion, span: Span) {- let source = Lrc::make_mut(&mut self.source);-- match suggestion {- Suggestion::ReplaceWith(chars) => {- // Avoid allocation if possible- if chars.len() == span.len() {- for (index, c) in chars.iter().enumerate() {- source[index + span.start] = *c- }- } else {- let popped = source.split_off(span.start);-- source.extend(chars);- source.extend(popped.into_iter().skip(span.len()));- }- }- Suggestion::Remove => {- for i in span.end..source.len() {- source[i - span.len()] = source[i];- }-- source.truncate(source.len() - span.len());- }- }-- self.parse();- }-/// Searches for quotation marks and fills the/// [`Punctuation::Quote::twin_loc`] field. This is on a best effort/// basis.@@ -586,14 +579,13 @@ mod tests {use itertools::Itertools;use super::Document;- use crate::parsers::{Markdown, PlainEnglish};use crate::token::TokenStringExt;- use crate::{Span, Token, TokenKind};+ use crate::Span;#[test]fn parses_sentences_correctly() {let text = "There were three little pigs. They built three little homes.";- let document = Document::new(text, Box::new(PlainEnglish));+ let document = Document::new_plain_english_curated(text);let mut sentence_strs = vec![];@@ -613,12 +605,11 @@ mod tests {}fn assert_condensed_contractions(text: &str, final_tok_count: usize) {- let document = Document::new(text, Box::new(PlainEnglish));+ let document = Document::new_plain_english_curated(text);assert_eq!(document.tokens.len(), final_tok_count);- let markdown_parser = Markdown;- let document = Document::new(text, Box::new(markdown_parser));+ let document = Document::new_markdown_curated(text);assert_eq!(document.tokens.len(), final_tok_count);}@@ -651,19 +642,16 @@ mod tests {#[test]fn selects_token_at_char_index() {let text = "There were three little pigs. They built three little homes.";- let document = Document::new(text, Box::new(PlainEnglish));+ let document = Document::new_plain_english_curated(text);- assert_eq!(- document.get_token_at_char_index(19),- Some(Token {- kind: TokenKind::blank_word(),- span: Span::new(17, 23)- })- )+ let got = document.get_token_at_char_index(19).unwrap();++ assert!(got.kind.is_word());+ assert_eq!(got.span, Span::new(17, 23));}fn assert_token_count(source: &str, count: usize) {- let document = Document::new_plain_english(source);+ let document = Document::new_plain_english_curated(source);dbg!(document.tokens().map(|t| t.kind).collect_vec());assert_eq!(document.tokens.len(), count);diff --git a/harper-core/src/language_detection.rs b/harper-core/src/language_detection.rsindex a351d56a7..f0571a8d0 100644--- a/harper-core/src/language_detection.rs+++ b/harper-core/src/language_detection.rs@@ -43,16 +43,16 @@ mod tests {use crate::{Document, FullDictionary};fn assert_not_english(source: &'static str) {- let dict = FullDictionary::create_from_curated();- let doc = Document::new_plain_english(source);+ let dict = FullDictionary::curated();+ let doc = Document::new_plain_english(source, &dict);let is_likely_english = is_likely_english(&doc, &dict);dbg!(source);assert!(!is_likely_english);}fn assert_english(source: &'static str) {- let dict = FullDictionary::create_from_curated();- let doc = Document::new_plain_english(source);+ let dict = FullDictionary::curated();+ let doc = Document::new_plain_english(source, &dict);let is_likely_english = is_likely_english(&doc, &dict);dbg!(source);assert!(is_likely_english);diff --git a/harper-core/src/linting/matcher.rs b/harper-core/src/linting/matcher.rsindex 9d27f7045..a01b608fa 100644--- a/harper-core/src/linting/matcher.rs+++ b/harper-core/src/linting/matcher.rs@@ -14,6 +14,9 @@ use crate::{#[derive(Debug, PartialEq, PartialOrd, Clone)]struct PatternToken {+ /// The general variant of the token.+ /// The inner data of the [`TokenKind`] should be replaced with the default+ /// value.kind: TokenKind,content: Option<CharString>}@@ -22,7 +25,7 @@ impl PatternToken {fn from_token(token: Token, document: &Document) -> Self {if token.kind.is_word() {Self {- kind: token.kind,+ kind: token.kind.with_default_data(),content: Some(document.get_span_content(token.span).into())}} else {@@ -346,6 +349,15 @@ impl Linter for Matcher {};let t_pattern = PatternToken::from_token(token, document);+ if pattern.content.is_some()+ && matches!(+ pattern.content.clone().unwrap().as_slice(),+ &['T', 'h', 'e', 'r', 'e']+ )+ {+ dbg!(&t_pattern);+ dbg!(pattern);+ }if t_pattern != *pattern {break;@@ -385,17 +397,17 @@ mod tests {#[test]fn matches_therefore() {- let document = Document::new_plain_english("There fore.");+ let document = Document::new_plain_english_curated("There fore.");let mut matcher = Matcher::new();let lints = matcher.lint(&document);- assert!(lints.len() == 1);+ assert_eq!(lints.len(), 1);}#[test]fn matches_ellipsis() {- let document = Document::new_plain_english("...");+ let document = Document::new_plain_english_curated("...");let mut matcher = Matcher::new();let lints = matcher.lint(&document);- assert!(lints.len() == 1);+ assert_eq!(lints.len(), 1);}}diff --git a/harper-core/src/linting/mod.rs b/harper-core/src/linting/mod.rsindex 68719854a..a5df164ad 100644--- a/harper-core/src/linting/mod.rs+++ b/harper-core/src/linting/mod.rs@@ -19,17 +19,21 @@ pub use lint_group::{LintGroup, LintGroupConfig};use crate::Document;+#[cfg(not(feature = "concurrent"))]+pub trait Linter {+ fn lint(&mut self, document: &Document) -> Vec<Lint>;+}+#[cfg(feature = "concurrent")]pub trait Linter: Send + Sync {fn lint(&mut self, document: &Document) -> Vec<Lint>;}#[cfg(test)]mod tests {- use crate::parsers::Markdown;use crate::{Document, Linter};pub fn assert_lint_count(text: &str, mut linter: impl Linter, count: usize) {- let test = Document::new(text, Box::new(Markdown));+ let test = Document::new_markdown_curated(text);let lints = linter.lint(&test);dbg!(&lints);assert_eq!(lints.len(), count);diff --git a/harper-core/src/punctuation.rs b/harper-core/src/punctuation.rsindex c57e11ccc..6d8fb731f 100644--- a/harper-core/src/punctuation.rs+++ b/harper-core/src/punctuation.rs@@ -1,7 +1,7 @@use is_macro::Is;use serde::{Deserialize, Serialize};-#[derive(Debug, Is, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd)]+#[derive(Debug, Is, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Default)]#[serde(tag = "kind")]pub enum Punctuation {/// `…`@@ -13,6 +13,7 @@ pub enum Punctuation {/// `&`Ampersand,/// `.`+ #[default]Period,/// `!`Bang,diff --git a/harper-core/src/spell/dictionary.rs b/harper-core/src/spell/dictionary.rsindex 80f7f0ef5..8fce77296 100644--- a/harper-core/src/spell/dictionary.rs+++ b/harper-core/src/spell/dictionary.rs@@ -1,9 +1,23 @@use blanket::blanket;+use crate::WordMetadata;++#[cfg(not(feature = "concurrent"))]+#[blanket(derive(Rc))]+pub trait Dictionary: Clone {+ fn contains_word(&self, word: &[char]) -> bool;+ fn words_iter(&self) -> impl Iterator<Item = &'_ [char]>;+ /// Iterate over all the words in the dictionary of a given length+ fn words_with_len_iter(&self, len: usize) -> Box<dyn Iterator<Item = &'_ [char]> + '_>;+ fn get_word_metadata(&self, word: &[char]) -> WordMetadata;+}++#[cfg(feature = "concurrent")]#[blanket(derive(Arc))]pub trait Dictionary: Send + Sync + Clone {fn contains_word(&self, word: &[char]) -> bool;fn words_iter(&self) -> impl Iterator<Item = &'_ [char]>;/// Iterate over all the words in the dictionary of a given lengthfn words_with_len_iter(&self, len: usize) -> Box<dyn Iterator<Item = &'_ [char]> + '_>;+ fn get_word_metadata(&self, word: &[char]) -> WordMetadata;}diff --git a/harper-core/src/spell/full_dictionary.rs b/harper-core/src/spell/full_dictionary.rsindex 102dc663a..9d2ad07be 100644--- a/harper-core/src/spell/full_dictionary.rs+++ b/harper-core/src/spell/full_dictionary.rs@@ -1,11 +1,10 @@use hashbrown::HashMap;-use once_cell::sync::Lazy;use smallvec::{SmallVec, ToSmallVec};use super::dictionary::Dictionary;use super::hunspell::{parse_default_attribute_list, parse_default_word_list};use super::seq_to_normalized;-use crate::{CharString, WordMetadata};+use crate::{CharString, Lrc, WordMetadata};/// A full, fat dictionary./// All of the elements are stored in-memory.@@ -26,27 +25,32 @@ pub struct FullDictionary {word_map: HashMap<CharString, WordMetadata>}-fn uncached_inner_new() -> FullDictionary {+fn uncached_inner_new() -> Lrc<FullDictionary> {let word_list = parse_default_word_list().unwrap();let attr_list = parse_default_attribute_list();// There will be at _least_ this number of wordslet mut word_map = HashMap::with_capacity(word_list.len());- attr_list.expand_marked_words(word_list, &mut word_map);+ attr_list.expand_marked_words(+ word_list.into_iter().map(|w| (w, WordMetadata::default())),+ &mut word_map+ );let mut words: Vec<CharString> = word_map.iter().map(|(v, _)| v.clone()).collect();words.sort();words.dedup();- FullDictionary {+ Lrc::new(FullDictionary {word_map,word_len_starts: FullDictionary::create_len_starts(&mut words),words- }+ })}-static DICT: Lazy<FullDictionary> = Lazy::new(uncached_inner_new);+thread_local! {+ static DICT: Lrc<FullDictionary> = uncached_inner_new();+}impl FullDictionary {pub fn new() -> Self {@@ -59,8 +63,8 @@ impl FullDictionary {/// Create a dictionary from the curated Hunspell dictionary included/// in the Harper binary.- pub fn create_from_curated() -> Self {- DICT.clone()+ pub fn curated() -> Lrc<Self> {+ DICT.with(|v| v.clone())}/// Appends words to the dictionary.@@ -134,6 +138,17 @@ impl Dictionary for FullDictionary {Box::new(self.words[start..end].iter().map(|v| v.as_slice()))}+ fn get_word_metadata(&self, word: &[char]) -> WordMetadata {+ let normalized = seq_to_normalized(word);+ let lowercase: SmallVec<_> = normalized.iter().flat_map(|c| c.to_lowercase()).collect();++ self.word_map+ .get(normalized.as_ref())+ .or(self.word_map.get(&lowercase))+ .copied()+ .unwrap_or_default()+ }+fn contains_word(&self, word: &[char]) -> bool {let normalized = seq_to_normalized(word);let lowercase: SmallVec<_> = normalized.iter().flat_map(|c| c.to_lowercase()).collect();@@ -150,7 +165,7 @@ mod tests {#[test]fn curated_contains_no_duplicates() {- let dict = FullDictionary::create_from_curated();+ let dict = FullDictionary::curated();assert!(dict.words_iter().all_unique());}}diff --git a/harper-core/src/spell/hunspell/attribute_list.rs b/harper-core/src/spell/hunspell/attribute_list.rsindex 953b26c0d..68c486087 100644--- a/harper-core/src/spell/hunspell/attribute_list.rs+++ b/harper-core/src/spell/hunspell/attribute_list.rs@@ -1,6 +1,6 @@use hashbrown::HashMap;use serde::{Deserialize, Serialize};-use smallvec::ToSmallVec;+use smallvec::{smallvec, ToSmallVec};use super::affix_replacement::AffixReplacement;use super::expansion::{Expansion, HumanReadableExpansion};@@ -33,22 +33,30 @@ impl AttributeList {pub fn expand_marked_word(&self,word: MarkedWord,+ metadata: WordMetadata,dest: &mut HashMap<CharString, WordMetadata>) {dest.reserve(word.attributes.len() + 1);+ let mut gifted_metadata = WordMetadata::default();for attr in &word.attributes {let Some(expansion) = self.affixes.get(attr) else {continue;};- let mut new_words = HashMap::new();+ let mut new_words: HashMap<CharString, WordMetadata> = HashMap::new();for replacement in &expansion.replacements {if let Some(replaced) =Self::apply_replacement(replacement, &word.letters, expansion.suffix){- new_words.insert(replaced, expansion.adds_metadata);+ if let Some(val) = new_words.get_mut(&replaced) {+ *val = val.or(&expansion.adds_metadata);+ } else {+ new_words.insert(replaced, expansion.adds_metadata.or(&metadata));+ }++ gifted_metadata = gifted_metadata.or(&expansion.gifts_metadata);}}@@ -64,21 +72,34 @@ impl AttributeList {}}- for (new_word, _metadata) in new_words {+ if new_words.get(&smallvec!['h', 'a', 's']).is_some() {+ dbg!(&word);+ }++ for (new_word, metadata) in new_words {self.expand_marked_word(MarkedWord {letters: new_word,attributes: opp_attr.clone()},+ metadata,dest);}} else {- dest.extend(new_words.into_iter());+ for (key, value) in new_words.into_iter() {+ if let Some(val) = dest.get_mut(&key) {+ *val = val.or(&value);+ } else {+ dest.insert(key, value);+ }+ }}}- dest.insert(word.letters, WordMetadata::default());+ if !dest.contains_key(&word.letters) {+ dest.insert(word.letters, metadata.or(&gifted_metadata));+ }}/// Expand an iterator of marked words into strings.@@ -86,11 +107,11 @@ impl AttributeList {/// unique.pub fn expand_marked_words(&self,- words: impl IntoIterator<Item = MarkedWord>,+ words: impl IntoIterator<Item = (MarkedWord, WordMetadata)>,dest: &mut HashMap<CharString, WordMetadata>) {- for word in words {- self.expand_marked_word(word, dest);+ for (word, word_metadata) in words {+ self.expand_marked_word(word, word_metadata, dest);}}diff --git a/harper-core/src/spell/hunspell/expansion.rs b/harper-core/src/spell/hunspell/expansion.rsindex 46a86f7f5..d34ae47af 100644--- a/harper-core/src/spell/hunspell/expansion.rs+++ b/harper-core/src/spell/hunspell/expansion.rs@@ -11,8 +11,11 @@ pub struct Expansion {pub cross_product: bool,pub replacements: Vec<AffixReplacement>,/// When the expansion is applied, the resulting word will have fields- /// overwritten with the none-null properties from here.- pub adds_metadata: WordMetadata+ /// overwritten with the non-null properties from here.+ pub adds_metadata: WordMetadata,+ /// When the expansion is applied, the __parent__ word will have the fields+ /// overwritten with the non-null properties from here.+ pub gifts_metadata: WordMetadata}impl Expansion {@@ -25,7 +28,8 @@ impl Expansion {.iter().map(AffixReplacement::to_human_readable).collect(),- adds_metadata: self.adds_metadata+ adds_metadata: self.adds_metadata,+ gifts_metadata: self.gifts_metadata}}}@@ -35,7 +39,8 @@ pub struct HumanReadableExpansion {pub suffix: bool,pub cross_product: bool,pub replacements: Vec<HumanReadableAffixReplacement>,- pub adds_metadata: WordMetadata+ pub adds_metadata: WordMetadata,+ pub gifts_metadata: WordMetadata}impl HumanReadableExpansion {@@ -50,7 +55,8 @@ impl HumanReadableExpansion {suffix: self.suffix,cross_product: self.cross_product,replacements,- adds_metadata: self.adds_metadata+ adds_metadata: self.adds_metadata,+ gifts_metadata: self.gifts_metadata})}}diff --git a/harper-core/src/spell/hunspell/mod.rs b/harper-core/src/spell/hunspell/mod.rsindex 92f1e3a73..ec2970604 100644--- a/harper-core/src/spell/hunspell/mod.rs+++ b/harper-core/src/spell/hunspell/mod.rs@@ -34,7 +34,7 @@ mod tests {use super::word_list::parse_word_list;use super::{parse_default_attribute_list, parse_default_word_list};use crate::spell::hunspell::attribute_list::HumanReadableAttributeList;- use crate::{CharString, WordMetadata};+ use crate::{CharString, WordKind, WordMetadata};pub const TEST_WORD_LIST: &str = "3\nhello\ntry/B\nwork/AB";@@ -56,7 +56,8 @@ mod tests {"adds_metadata": {"kind": null,"tense": null- }+ },+ "gifts_metadata": {}},"B": {"suffix": true,@@ -76,7 +77,8 @@ mod tests {"adds_metadata": {"kind": null,"tense": null- }+ },+ "gifts_metadata": {}}}}))@@ -85,7 +87,10 @@ mod tests {let mut expanded = HashMap::new();- attributes.expand_marked_words(words, &mut expanded);+ attributes.expand_marked_words(+ words.into_iter().map(|w| (w, WordMetadata::default())),+ &mut expanded+ );let expanded: Vec<String> = expanded.into_iter().map(|v| v.0.into_iter().collect())@@ -124,8 +129,15 @@ mod tests {}],"adds_metadata": {- "kind": null,- "tense": null+ "kind": {+ "kind": "Noun",+ "is_plural": true+ }+ },+ "gifts_metadata": {+ "kind": {+ "kind": "Noun",+ }}},"M": {@@ -141,7 +153,8 @@ mod tests {"adds_metadata": {"kind": null,"tense": null- }+ },+ "gifts_metadata": {}}}}))@@ -150,9 +163,34 @@ mod tests {let mut expanded: HashMap<CharString, WordMetadata> = HashMap::new();- attributes.expand_marked_words(words, &mut expanded);+ attributes.expand_marked_words(+ words.into_iter().map(|w| (w, WordMetadata::default())),+ &mut expanded+ );- assert!(expanded.contains_key(&split("giants")))+ assert_eq!(+ expanded.get(&split("giant")),+ Some(&WordMetadata {+ kind: Some(WordKind::Noun {+ is_proper: None,+ is_plural: None+ }),+ tense: None,+ possessive: None+ })+ );++ assert_eq!(+ expanded.get(&split("giants")),+ Some(&WordMetadata {+ kind: Some(WordKind::Noun {+ is_proper: None,+ is_plural: Some(true)+ }),+ tense: None,+ possessive: None+ })+ )}fn build_expanded() -> HashMap<CharString, WordMetadata> {@@ -161,7 +199,10 @@ mod tests {let mut expanded = HashMap::new();- attributes.expand_marked_words(words, &mut expanded);+ attributes.expand_marked_words(+ words.into_iter().map(|w| (w, WordMetadata::default())),+ &mut expanded+ );expanded}@@ -190,6 +231,27 @@ mod tests {assert!(expanded.contains_key(&split("repo's")));}+ #[test]+ fn expanded_contains_possessive_abandonment() {+ assert_eq!(+ build_expanded()+ .get(&split("abandonment's"))+ .unwrap()+ .possessive,+ Some(true)+ )+ }++ #[test]+ fn has_is_not_a_noun() {+ let expanded = build_expanded();++ let has = expanded.get(&split("has"));+ assert!(has.is_some());++ assert!(!matches!(has.unwrap().kind, Some(WordKind::Noun { .. })))+ }+fn split(text: &str) -> CharString {text.chars().collect()}diff --git a/harper-core/src/spell/merged_dictionary.rs b/harper-core/src/spell/merged_dictionary.rsindex 5e851c8d6..5e6bbabc9 100644--- a/harper-core/src/spell/merged_dictionary.rs+++ b/harper-core/src/spell/merged_dictionary.rs@@ -1,6 +1,7 @@use std::sync::Arc;use super::dictionary::Dictionary;+use crate::WordMetadata;/// A simple wrapper over [`Dictionary`] that allows/// one to merge multiple dictionaries without copying.@@ -49,6 +50,14 @@ wherefalse}+ fn get_word_metadata(&self, word: &[char]) -> WordMetadata {+ let mut found_metadata = WordMetadata::default();+ for child in &self.children {+ found_metadata = found_metadata.or(&child.get_word_metadata(word));+ }+ found_metadata+ }+fn words_iter(&self) -> impl Iterator<Item = &'_ [char]> {self.children.iter().flat_map(|c| c.words_iter())}diff --git a/harper-core/src/spell/mod.rs b/harper-core/src/spell/mod.rsindex 6e6835904..929f3a8e7 100644--- a/harper-core/src/spell/mod.rs+++ b/harper-core/src/spell/mod.rs@@ -214,12 +214,8 @@ mod tests {#[test]fn produces_no_duplicates() {- let results = suggest_correct_spelling_str(- "punctation",- 100,- 3,- &FullDictionary::create_from_curated()- );+ let results =+ suggest_correct_spelling_str("punctation", 100, 3, &FullDictionary::curated());dbg!(&results, results.iter().unique().collect_vec());diff --git a/harper-core/src/token.rs b/harper-core/src/token.rsindex 9eaa6f63c..013889633 100644--- a/harper-core/src/token.rs+++ b/harper-core/src/token.rs@@ -57,6 +57,28 @@ pub enum TokenKind {ParagraphBreak}+impl TokenKind {+ /// Checks that `self` is the same enum variant as `other`, regardless of+ /// whether the inner metadata is also equal.+ pub fn matches_variant_of(&self, other: &Self) -> bool {+ self.with_default_data() == other.with_default_data()+ }++ /// Produces a copy of `self` with any inner data replaced with it's default+ /// value. Useful for making comparisons on just the variant of the+ /// enum.+ pub fn with_default_data(&self) -> Self {+ match self {+ TokenKind::Word(_) => TokenKind::Word(Default::default()),+ TokenKind::Punctuation(_) => TokenKind::Punctuation(Default::default()),+ TokenKind::Number(..) => TokenKind::Number(Default::default(), Default::default()),+ TokenKind::Space(_) => TokenKind::Space(Default::default()),+ TokenKind::Newline(_) => TokenKind::Newline(Default::default()),+ _ => *self+ }+ }+}+impl TokenKind {/// Construct a [`TokenKind::Word`] with no metadata.pub fn blank_word() -> Self {diff --git a/harper-core/src/word_metadata.rs b/harper-core/src/word_metadata.rsindex 40c1c8e08..5a53b7638 100644--- a/harper-core/src/word_metadata.rs+++ b/harper-core/src/word_metadata.rs@@ -2,9 +2,19 @@ use serde::{Deserialize, Serialize};#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, PartialOrd)]pub struct WordMetadata {- kind: Option<WordKind>,- tense: Option<Tense>,- plural: Option<bool>+ pub kind: Option<WordKind>,+ pub tense: Option<Tense>,+ pub possessive: Option<bool>+}++impl WordMetadata {+ pub fn or(&self, other: &Self) -> Self {+ Self {+ kind: self.kind.or(other.kind),+ tense: self.tense.or(other.tense),+ possessive: self.possessive.or(other.possessive)+ }+ }}#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, PartialOrd)]@@ -15,9 +25,13 @@ pub enum Tense {}#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, PartialOrd)]+#[serde(tag = "kind")]pub enum WordKind {Verb,- Noun { is_proper: bool },+ Noun {+ is_proper: Option<bool>,+ is_plural: Option<bool>+ },Adjective,Adverb}diff --git a/harper-core/tests/run_tests.rs b/harper-core/tests/run_tests.rsindex e4509c696..8c91c75eb 100644--- a/harper-core/tests/run_tests.rs+++ b/harper-core/tests/run_tests.rs@@ -14,11 +14,12 @@ macro_rules! create_test {));- let document = Document::new_markdown(&source);+ let dict = FullDictionary::curated();+ let document = Document::new_markdown(&source, &dict);let mut linter = LintGroup::new(LintGroupConfig::default(),- FullDictionary::create_from_curated()+ dict);let lints = linter.lint(&document);diff --git a/harper-html/tests/run_tests.rs b/harper-html/tests/run_tests.rsindex f2e2d1ced..6092fc7ca 100644--- a/harper-html/tests/run_tests.rs+++ b/harper-html/tests/run_tests.rs@@ -14,11 +14,12 @@ macro_rules! create_test {));- let document = Document::new_markdown(&source);+ let dict = FullDictionary::curated();+ let document = Document::new_markdown(&source, &dict);let mut linter = LintGroup::new(LintGroupConfig::default(),- FullDictionary::create_from_curated()+ dict);let lints = linter.lint(&document);diff --git a/harper-ls/src/backend.rs b/harper-ls/src/backend.rsindex c678d8410..5082954e8 100644--- a/harper-ls/src/backend.rs+++ b/harper-ls/src/backend.rs@@ -11,6 +11,7 @@ use harper_core::{FullDictionary,LintGroup,Linter,+ Lrc,MergedDictionary,Token,TokenKind,@@ -61,8 +62,9 @@ use crate::pos_conv::range_to_span;#[derive(Default)]struct DocumentState {document: Document,- ident_dict: Arc<FullDictionary>,- linter: LintGroup<MergedDictionary<FullDictionary>>,+ ident_dict: Lrc<FullDictionary>,+ dict: Lrc<MergedDictionary<FullDictionary>>,+ linter: LintGroup<Lrc<MergedDictionary<FullDictionary>>>,language_id: Option<String>}@@ -76,7 +78,7 @@ pub struct Backend {impl Backend {pub fn new(client: Client, config: Config) -> Self {- let dictionary = FullDictionary::create_from_curated();+ let dictionary = FullDictionary::curated();Self {client,@@ -234,7 +236,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?.into()),language_id: language_id.map(|v| v.to_string())@@ -248,7 +250,7 @@ impl Backend {};doc_state.document =- if let Some(ts_parser) = CommentParser::new_from_language_id(language_id) {+ if let Some(mut ts_parser) = CommentParser::new_from_language_id(language_id) {let source: Vec<char> = text.chars().collect();let source = Arc::new(source);@@ -259,20 +261,22 @@ impl Backend {doc_state.ident_dict = new_dict.clone();let mut merged = self.generate_file_dictionary(url).await?;merged.add_dictionary(new_dict);+ let merged = Arc::new(merged);- doc_state.linter = LintGroup::new(config_lock.lint_config, merged);+ doc_state.linter = LintGroup::new(config_lock.lint_config, merged.clone());+ doc_state.dict = merged.clone();}}- Document::new_from_vec(source, Box::new(ts_parser))+ Document::new_from_vec(source, &mut ts_parser, &doc_state.dict)} else if language_id == "markdown" {- Document::new(text, Box::new(Markdown))+ Document::new(text, &mut Markdown, &doc_state.dict)} else if language_id == "gitcommit" {- Document::new(text, Box::new(GitCommitParser))+ Document::new(text, &mut GitCommitParser, &doc_state.dict)} else if language_id == "html" {- Document::new(text, Box::new(HtmlParser::default()))+ Document::new(text, &mut HtmlParser::default(), &doc_state.dict)} else if language_id == "mail" {- Document::new(text, Box::new(PlainEnglish))+ Document::new(text, &mut PlainEnglish, &doc_state.dict)} else {doc_lock.remove(url);return Ok(());diff --git a/harper-wasm/src/lib.rs b/harper-wasm/src/lib.rsindex 1ecc026cd..0d1c4d5c2 100644--- a/harper-wasm/src/lib.rs+++ b/harper-wasm/src/lib.rs@@ -7,10 +7,10 @@ use harper_core::{remove_overlaps, Document, FullDictionary, LintGroup, Linter,use once_cell::sync::Lazy;use wasm_bindgen::prelude::wasm_bindgen;-static LINTER: Lazy<Mutex<LintGroup<FullDictionary>>> = Lazy::new(|| {+static LINTER: Lazy<Mutex<LintGroup<Lrc<FullDictionary>>>> = Lazy::new(|| {Mutex::new(LintGroup::new(Default::default(),- FullDictionary::create_from_curated()+ FullDictionary::curated()))});@@ -39,7 +39,8 @@ pub fn lint(text: String) -> Vec<Lint> {let source: Vec<_> = text.chars().collect();let source = Lrc::new(source);- let document = Document::new_from_vec(source.clone(), Box::new(Markdown));+ let document =+ Document::new_from_vec(source.clone(), &mut Markdown, &FullDictionary::curated());let mut lints = LINTER.lock().unwrap().lint(&document);@@ -57,10 +58,33 @@ pub fn apply_suggestion(span: Span,suggestion: &Suggestion) -> Result<String, String> {- let mut document = Document::new_markdown(&text);- document.apply_suggestion(&suggestion.inner, span.into());+ let mut source: Vec<_> = text.chars().collect();+ let span: harper_core::Span = span.into();++ match &suggestion.inner {+ harper_core::Suggestion::ReplaceWith(chars) => {+ // Avoid allocation if possible+ if chars.len() == span.len() {+ for (index, c) in chars.iter().enumerate() {+ source[index + span.start] = *c+ }+ } else {+ let popped = source.split_off(span.start);++ source.extend(chars);+ source.extend(popped.into_iter().skip(span.len()));+ }+ }+ harper_core::Suggestion::Remove => {+ for i in span.end..source.len() {+ source[i - span.len()] = source[i];+ }++ source.truncate(source.len() - span.len());+ }+ }- Ok(document.get_full_string())+ Ok(source.iter().collect())}#[wasm_bindgen]