Skip to content

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

feat: rename FullDictionary and add some doc comments

Grant Lemonsb84d105c3322
diff --git a/harper-comments/src/comment_parser.rs b/harper-comments/src/comment_parser.rs
index 297901c73..a72e722e6 100644
--- a/harper-comments/src/comment_parser.rs
+++ b/harper-comments/src/comment_parser.rs
@@ -2,7 +2,7 @@ use std::path::Path;
use comment_parsers::{Go, JavaDoc, JsDoc, Unit};
use harper_core::parsers::{self, MarkdownOptions, Parser};
-use harper_core::{FullDictionary, Token};
+use harper_core::{MutableDictionary, Token};
use harper_tree_sitter::TreeSitterMasker;
use tree_sitter::Node;
@@ -13,7 +13,7 @@ pub struct CommentParser {
}
impl CommentParser {
- pub fn create_ident_dict(&self, source: &[char]) -> Option<FullDictionary> {
+ pub fn create_ident_dict(&self, source: &[char]) -> Option<MutableDictionary> {
self.inner.masker.create_ident_dict(source)
}
diff --git a/harper-core/src/lib.rs b/harper-core/src/lib.rs
index 4e9325da9..20ceb2153 100644
--- a/harper-core/src/lib.rs
+++ b/harper-core/src/lib.rs
@@ -38,7 +38,7 @@ pub use mask::{Mask, Masker};
pub use number::{Number, NumberSuffix};
pub use punctuation::{Punctuation, Quote};
pub use span::Span;
-pub use spell::{Dictionary, FstDictionary, FullDictionary, MergedDictionary};
+pub use spell::{Dictionary, FstDictionary, MutableDictionary, MergedDictionary};
pub use sync::Lrc;
pub use title_case::{make_title_case, make_title_case_str};
pub use token::Token;
diff --git a/harper-core/src/linting/lint_group.rs b/harper-core/src/linting/lint_group.rs
index 7ac6a6302..108aebca8 100644
--- a/harper-core/src/linting/lint_group.rs
+++ b/harper-core/src/linting/lint_group.rs
@@ -295,13 +295,13 @@ impl<T: Dictionary + Default> Default for LintGroup<T> {
#[cfg(test)]
mod tests {
- use crate::{linting::Linter, Document, FstDictionary, FullDictionary};
+ use crate::{linting::Linter, Document, FstDictionary, MutableDictionary};
use super::{LintGroup, LintGroupConfig};
#[test]
fn can_get_all_descriptions() {
- let group = LintGroup::<FullDictionary>::default();
+ let group = LintGroup::<MutableDictionary>::default();
group.all_descriptions();
}
diff --git a/harper-core/src/parsers/collapse_identifiers.rs b/harper-core/src/parsers/collapse_identifiers.rs
index abdfae4b7..38d86d878 100644
--- a/harper-core/src/parsers/collapse_identifiers.rs
+++ b/harper-core/src/parsers/collapse_identifiers.rs
@@ -61,7 +61,7 @@ impl Parser for CollapseIdentifiers {
mod tests {
use crate::{
parsers::{PlainEnglish, StrParser},
- FstDictionary, FullDictionary, MergedDictionary, WordMetadata,
+ FstDictionary, MutableDictionary, MergedDictionary, WordMetadata,
};
use super::*;
@@ -99,7 +99,7 @@ mod tests {
.parse_str(source);
assert_eq!(tokens.len(), 13);
- let mut dict = FullDictionary::new();
+ let mut dict = MutableDictionary::new();
dict.append_word_str("separated_identifier", WordMetadata::default());
let mut merged_dict = MergedDictionary::new();
@@ -123,7 +123,7 @@ mod tests {
assert_eq!(tokens.len(), 13);
- let mut dict = FullDictionary::new();
+ let mut dict = MutableDictionary::new();
dict.append_word_str("separated-identifier", WordMetadata::default());
let mut merged_dict = MergedDictionary::new();
@@ -147,7 +147,7 @@ mod tests {
.parse_str(source);
assert_eq!(tokens.len(), 15);
- let mut dict = FullDictionary::new();
+ let mut dict = MutableDictionary::new();
dict.append_word_str("separated_identifier_token", WordMetadata::default());
let mut merged_dict = MergedDictionary::new();
@@ -170,7 +170,7 @@ mod tests {
.parse_str(source);
assert_eq!(tokens.len(), 17);
- let mut dict = FullDictionary::new();
+ let mut dict = MutableDictionary::new();
dict.append_word_str("separated_identifier", WordMetadata::default());
let mut merged_dict = MergedDictionary::new();
@@ -193,7 +193,7 @@ mod tests {
.parse_str(source);
assert_eq!(tokens.len(), 15);
- let mut dict = FullDictionary::new();
+ let mut dict = MutableDictionary::new();
dict.append_word_str("separated_identifier", WordMetadata::default());
dict.append_word_str("identifier_token", WordMetadata::default());
@@ -217,7 +217,7 @@ mod tests {
.parse_str(source);
assert_eq!(tokens.len(), 15);
- let mut dict = FullDictionary::new();
+ let mut dict = MutableDictionary::new();
dict.append_word_str("separated_identifier_token", WordMetadata::default());
dict.append_word_str("separated_identifier", WordMetadata::default());
diff --git a/harper-core/src/spell/dictionary.rs b/harper-core/src/spell/dictionary.rs
index d7860dc89..403f29b86 100644
--- a/harper-core/src/spell/dictionary.rs
+++ b/harper-core/src/spell/dictionary.rs
@@ -5,8 +5,7 @@ use crate::WordMetadata;
/// An in-memory database that contains everything necessary to parse and analyze English text.
///
-/// See also: [`FstDictionary`](super::FstDictionary) and
-/// [`FullDictionary`](super::FullDictionary).
+/// See also: [`super::FstDictionary`] and [`super::MutableDictionary`].
#[blanket(derive(Arc))]
pub trait Dictionary: Send + Sync {
/// Check if the dictionary contains a given word.
diff --git a/harper-core/src/spell/fst_dictionary.rs b/harper-core/src/spell/fst_dictionary.rs
index 89c23ef95..816048043 100644
--- a/harper-core/src/spell/fst_dictionary.rs
+++ b/harper-core/src/spell/fst_dictionary.rs
@@ -1,6 +1,6 @@
use super::{
hunspell::{parse_default_attribute_list, parse_default_word_list},
- seq_to_normalized, FullDictionary,
+ seq_to_normalized, MutableDictionary,
};
use fst::{map::StreamWithState, IntoStreamer, Map as FstMap, Streamer};
use hashbrown::HashMap;
@@ -13,9 +13,13 @@ use crate::{CharString, CharStringExt, WordMetadata};
use super::Dictionary;
use super::FuzzyMatchResult;
+/// An immutable dictionary allowing for very fast spellchecking.
+///
+/// For dictionaries with changing contents, such as user and file dictionaries, prefer
+/// [`super::MutableDictionary`].
pub struct FstDictionary {
- /// Underlying FullDictionary used for everything except fuzzy finding
- full_dict: Arc<FullDictionary>,
+ /// Underlying [`super::MutableDictionary`] used for everything except fuzzy finding
+ full_dict: Arc<MutableDictionary>,
/// Used for fuzzy-finding the index of words or metadata
word_map: FstMap<Vec<u8>>,
/// Used for fuzzy-finding the index of words or metadata
@@ -79,7 +83,7 @@ impl FstDictionary {
.expect("Insertion not in lexicographical order!");
}
- let mut full_dict = FullDictionary::new();
+ let mut full_dict = MutableDictionary::new();
full_dict.extend_words(words.iter().cloned());
let fst_bytes = builder.into_inner().unwrap();
diff --git a/harper-core/src/spell/mod.rs b/harper-core/src/spell/mod.rs
index 5cbe4f768..f7c3e2c99 100644
--- a/harper-core/src/spell/mod.rs
+++ b/harper-core/src/spell/mod.rs
@@ -6,14 +6,14 @@ use crate::{CharString, CharStringExt, WordMetadata};
pub use self::dictionary::Dictionary;
pub use self::fst_dictionary::FstDictionary;
-pub use self::full_dictionary::FullDictionary;
pub use self::merged_dictionary::MergedDictionary;
+pub use self::mutable_dictionary::MutableDictionary;
mod dictionary;
mod fst_dictionary;
-mod full_dictionary;
pub mod hunspell;
mod merged_dictionary;
+mod mutable_dictionary;
#[derive(PartialEq, Debug, Hash, Eq)]
pub struct FuzzyMatchResult<'a> {
@@ -131,7 +131,7 @@ mod tests {
use super::{
order_suggestions, seq_to_normalized, suggest_correct_spelling_str, Dictionary,
- FstDictionary, FullDictionary,
+ FstDictionary, MutableDictionary,
};
const RESULT_LIMIT: usize = 100;
@@ -227,7 +227,7 @@ mod tests {
"ned",
RESULT_LIMIT,
MAX_EDIT_DIST,
- &FullDictionary::curated(),
+ &MutableDictionary::curated(),
);
dbg!(&results);
@@ -283,7 +283,7 @@ mod tests {
"Im",
RESULT_LIMIT,
MAX_EDIT_DIST,
- &FullDictionary::curated(),
+ &MutableDictionary::curated(),
);
dbg!(&results);
@@ -311,7 +311,7 @@ mod tests {
"hvllo",
RESULT_LIMIT,
MAX_EDIT_DIST,
- &FullDictionary::curated(),
+ &MutableDictionary::curated(),
);
dbg!(&results);
@@ -339,7 +339,7 @@ mod tests {
"aboot",
RESULT_LIMIT,
MAX_EDIT_DIST,
- &FullDictionary::curated(),
+ &MutableDictionary::curated(),
);
dbg!(&results);
diff --git a/harper-core/src/spell/full_dictionary.rs b/harper-core/src/spell/mutable_dictionary.rs
similarity index 88%
rename from harper-core/src/spell/full_dictionary.rs
rename to harper-core/src/spell/mutable_dictionary.rs
index 3f18c47d6..a88fed755 100644
--- a/harper-core/src/spell/full_dictionary.rs
+++ b/harper-core/src/spell/mutable_dictionary.rs
@@ -14,10 +14,16 @@ use crate::{CharString, CharStringExt, WordMetadata};
use super::dictionary::Dictionary;
use super::FuzzyMatchResult;
-/// A full, fat dictionary.
-/// All elements are stored in-memory.
+/// A basic dictionary that allows words to be added.
+/// This is useful for user and file dictionaries that may change at runtime.
+///
+/// For immutable use-cases, such as the curated dictionary, prefer [`super::FstDictionary`],
+/// as it is much faster.
+///
+/// To combine the contents of multiple dictionaries, regardless of type, use
+/// [`super::MergedDictionary`].
#[derive(Debug, Clone, Eq, PartialEq)]
-pub struct FullDictionary {
+pub struct MutableDictionary {
/// Storing a separate [`Vec`] for iterations speeds up spellchecking by
/// ~16% at the cost of additional memory.
///
@@ -35,7 +41,7 @@ pub struct FullDictionary {
/// The uncached function that is used to produce the original copy of the
/// curated dictionary.
-fn uncached_inner_new() -> Arc<FullDictionary> {
+fn uncached_inner_new() -> Arc<MutableDictionary> {
let word_list = parse_default_word_list().unwrap();
let attr_list = parse_default_attribute_list();
@@ -50,18 +56,18 @@ fn uncached_inner_new() -> Arc<FullDictionary> {
words.dedup();
words.sort_unstable_by_key(|w| w.len());
- Arc::new(FullDictionary {
+ Arc::new(MutableDictionary {
word_map,
- word_len_starts: FullDictionary::create_len_starts(&words),
+ word_len_starts: MutableDictionary::create_len_starts(&words),
words,
})
}
lazy_static! {
- static ref DICT: Arc<FullDictionary> = uncached_inner_new();
+ static ref DICT: Arc<MutableDictionary> = uncached_inner_new();
}
-impl FullDictionary {
+impl MutableDictionary {
pub fn new() -> Self {
Self {
words: Vec::new(),
@@ -130,13 +136,13 @@ impl FullDictionary {
}
}
-impl Default for FullDictionary {
+impl Default for MutableDictionary {
fn default() -> Self {
Self::new()
}
}
-impl Dictionary for FullDictionary {
+impl Dictionary for MutableDictionary {
fn get_word_metadata(&self, word: &[char]) -> WordMetadata {
let normalized = seq_to_normalized(word);
let lowercase: CharString = normalized.to_lower();
@@ -259,11 +265,11 @@ mod tests {
use crate::CharString;
use itertools::Itertools;
- use crate::{Dictionary, FullDictionary};
+ use crate::{Dictionary, MutableDictionary};
#[test]
fn words_with_len_contains_self() {
- let dict = FullDictionary::curated();
+ let dict = MutableDictionary::curated();
let word: CharString = "hello".chars().collect();
let words_with_same_len = dict.words_with_len_iter(word.len()).collect_vec();
@@ -272,53 +278,53 @@ mod tests {
#[test]
fn curated_contains_no_duplicates() {
- let dict = FullDictionary::curated();
+ let dict = MutableDictionary::curated();
assert!(dict.words.iter().all_unique());
}
#[test]
fn curated_matches_capitalized() {
- let dict = FullDictionary::curated();
+ let dict = MutableDictionary::curated();
assert!(dict.contains_word_str("this"));
assert!(dict.contains_word_str("This"));
}
#[test]
fn this_is_noun() {
- let dict = FullDictionary::curated();
+ let dict = MutableDictionary::curated();
assert!(dict.get_word_metadata_str("this").is_noun());
assert!(dict.get_word_metadata_str("This").is_noun());
}
#[test]
fn than_is_conjunction() {
- let dict = FullDictionary::curated();
+ let dict = MutableDictionary::curated();
assert!(dict.get_word_metadata_str("than").is_conjunction());
assert!(dict.get_word_metadata_str("Than").is_conjunction());
}
#[test]
fn herself_is_pronoun() {
- let dict = FullDictionary::curated();
+ let dict = MutableDictionary::curated();
assert!(dict.get_word_metadata_str("herself").is_pronoun_noun());
assert!(dict.get_word_metadata_str("Herself").is_pronoun_noun());
}
#[test]
fn discussion_171() {
- let dict = FullDictionary::curated();
+ let dict = MutableDictionary::curated();
assert!(dict.contains_word_str("natively"));
}
#[test]
fn im_is_common() {
- let dict = FullDictionary::curated();
+ let dict = MutableDictionary::curated();
assert!(dict.get_word_metadata_str("I'm").common);
}
#[test]
fn fuzzy_result_sorted_by_edit_distance() {
- let dict = FullDictionary::curated();
+ let dict = MutableDictionary::curated();
let results = dict.fuzzy_match_str("hello", 3, 100);
let is_sorted_by_dist = results
@@ -332,7 +338,7 @@ mod tests {
#[test]
fn there_is_not_a_pronoun() {
- let dict = FullDictionary::curated();
+ let dict = MutableDictionary::curated();
assert!(!dict.get_word_metadata_str("there").is_noun());
assert!(!dict.get_word_metadata_str("there").is_pronoun_noun());
diff --git a/harper-literate-haskell/src/lib.rs b/harper-literate-haskell/src/lib.rs
index 20dd89148..0d39005bd 100644
--- a/harper-literate-haskell/src/lib.rs
+++ b/harper-literate-haskell/src/lib.rs
@@ -1,7 +1,7 @@
use harper_comments::CommentParser;
use harper_core::{
parsers::{Markdown, MarkdownOptions, Mask, Parser},
- FullDictionary, Lrc, Masker, Token,
+ MutableDictionary, Lrc, Masker, Token,
};
mod masker;
@@ -28,7 +28,7 @@ impl LiterateHaskellParser {
&self,
source: &[char],
markdown_options: MarkdownOptions,
- ) -> Option<FullDictionary> {
+ ) -> Option<MutableDictionary> {
let parser = CommentParser::new_from_language_id("haskell", markdown_options).unwrap();
let mask = LiterateHaskellMasker::code_only().create_mask(source);
diff --git a/harper-ls/src/backend.rs b/harper-ls/src/backend.rs
index a11972ee7..a4d4fe325 100644
--- a/harper-ls/src/backend.rs
+++ b/harper-ls/src/backend.rs
@@ -7,7 +7,7 @@ use harper_comments::CommentParser;
use harper_core::linting::{LintGroup, LintGroupConfig};
use harper_core::parsers::{CollapseIdentifiers, IsolateEnglish, Markdown, Parser, PlainEnglish};
use harper_core::{
- Dictionary, Document, FstDictionary, FullDictionary, MergedDictionary, WordMetadata,
+ Dictionary, Document, FstDictionary, MergedDictionary, MutableDictionary, WordMetadata,
};
use harper_html::HtmlParser;
use harper_literate_haskell::LiterateHaskellParser;
@@ -50,7 +50,7 @@ impl Backend {
}
/// Load a specific file's dictionary
- async fn load_file_dictionary(&self, url: &Url) -> anyhow::Result<FullDictionary> {
+ async fn load_file_dictionary(&self, url: &Url) -> anyhow::Result<MutableDictionary> {
let path = self
.get_file_dict_path(url)
.await
@@ -59,7 +59,7 @@ impl Backend {
load_dict(path)
.await
.map_err(|err| info!("{err}"))
- .or(Ok(FullDictionary::new()))
+ .or(Ok(MutableDictionary::new()))
}
/// Compute the location of the file's specific dictionary
@@ -80,13 +80,13 @@ impl Backend {
.context("Unable to save the dictionary to path.")
}
- async fn load_user_dictionary(&self) -> FullDictionary {
+ async fn load_user_dictionary(&self) -> MutableDictionary {
let config = self.config.read().await;
load_dict(&config.user_dict_path)
.await
.map_err(|err| info!("{err}"))
- .unwrap_or(FullDictionary::new())
+ .unwrap_or(MutableDictionary::new())
}
async fn save_user_dictionary(&self, dict: impl Dictionary) -> Result<()> {
@@ -177,7 +177,7 @@ impl Backend {
async fn use_ident_dict<'a>(
backend: &'a Backend,
- new_dict: Arc<FullDictionary>,
+ new_dict: Arc<MutableDictionary>,
parser: impl Parser + 'static,
url: &'a Url,
doc_state: &'a mut DocumentState,
diff --git a/harper-ls/src/dictionary_io.rs b/harper-ls/src/dictionary_io.rs
index 5583cb4b8..dfbb5908a 100644
--- a/harper-ls/src/dictionary_io.rs
+++ b/harper-ls/src/dictionary_io.rs
@@ -1,7 +1,7 @@
use anyhow::anyhow;
use std::path::{Component, Path, PathBuf};
-use harper_core::{Dictionary, FullDictionary, WordMetadata};
+use harper_core::{Dictionary, MutableDictionary, WordMetadata};
use tokio::fs::{self, File};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader, BufWriter, Result};
use tower_lsp::lsp_types::Url;
@@ -38,7 +38,7 @@ async fn write_word_list(dict: impl Dictionary, mut w: impl AsyncWrite + Unpin)
}
/// Load a dictionary from a file on disk.
-pub async fn load_dict(path: impl AsRef<Path>) -> Result<FullDictionary> {
+pub async fn load_dict(path: impl AsRef<Path>) -> Result<MutableDictionary> {
let file = File::open(path.as_ref()).await?;
let read = BufReader::new(file);
@@ -48,12 +48,12 @@ pub async fn load_dict(path: impl AsRef<Path>) -> Result<FullDictionary> {
/// 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> {
+async fn dict_from_word_list(mut r: impl AsyncRead + Unpin) -> Result<MutableDictionary> {
let mut str = String::new();
r.read_to_string(&mut str).await?;
- let mut dict = FullDictionary::new();
+ let mut dict = MutableDictionary::new();
dict.extend_words(
str.lines()
.map(|l| (l.chars().collect::<Vec<char>>(), WordMetadata::default())),
diff --git a/harper-ls/src/document_state.rs b/harper-ls/src/document_state.rs
index 1bab0e0e9..b99334dc8 100644
--- a/harper-ls/src/document_state.rs
+++ b/harper-ls/src/document_state.rs
@@ -2,13 +2,13 @@ use crate::config::{CodeActionConfig, DiagnosticSeverity};
use crate::diagnostics::{lint_to_code_actions, lints_to_diagnostics};
use crate::pos_conv::range_to_span;
use harper_core::linting::{Lint, LintGroup, Linter};
-use harper_core::{Document, FullDictionary, IgnoredLints, MergedDictionary, TokenKind};
+use harper_core::{Document, IgnoredLints, MergedDictionary, MutableDictionary, TokenKind};
use harper_core::{Lrc, Token};
use tower_lsp::lsp_types::{CodeActionOrCommand, Command, Diagnostic, Range, Url};
pub struct DocumentState {
pub document: Document,
- pub ident_dict: Lrc<FullDictionary>,
+ pub ident_dict: Lrc<MutableDictionary>,
pub dict: Lrc<MergedDictionary>,
pub linter: LintGroup<Lrc<MergedDictionary>>,
pub language_id: Option<String>,
diff --git a/harper-tree-sitter/src/lib.rs b/harper-tree-sitter/src/lib.rs
index 1eb53e3d7..16c04ed18 100644
--- a/harper-tree-sitter/src/lib.rs
+++ b/harper-tree-sitter/src/lib.rs
@@ -1,6 +1,6 @@
use std::collections::HashSet;
-use harper_core::{FullDictionary, Mask, Masker, Span, WordMetadata};
+use harper_core::{MutableDictionary, Mask, Masker, Span, WordMetadata};
use tree_sitter::{Language, Node, Tree, TreeCursor};
/// A Harper [`Masker`] that wraps a given tree-sitter language and a condition,
@@ -26,7 +26,7 @@ impl TreeSitterMasker {
parser.parse(text, None)
}
- pub fn create_ident_dict(&self, source: &[char]) -> Option<FullDictionary> {
+ pub fn create_ident_dict(&self, source: &[char]) -> Option<MutableDictionary> {
let text: String = source.iter().collect();
// Byte-indexed
@@ -52,7 +52,7 @@ impl TreeSitterMasker {
.map(|ident| (ident, WordMetadata::default()))
.collect();
- let mut dictionary = FullDictionary::new();
+ let mut dictionary = MutableDictionary::new();
dictionary.extend_words(idents);
Some(dictionary)
diff --git a/harper-wasm/src/lib.rs b/harper-wasm/src/lib.rs
index f90100472..c4cfb22da 100644
--- a/harper-wasm/src/lib.rs
+++ b/harper-wasm/src/lib.rs
@@ -6,7 +6,7 @@ use std::sync::Arc;
use harper_core::language_detection::is_doc_likely_english;
use harper_core::linting::{LintGroup, LintGroupConfig, Linter as _};
use harper_core::parsers::{IsolateEnglish, Markdown, Parser, PlainEnglish};
-use harper_core::{remove_overlaps, Document, FstDictionary, FullDictionary, IgnoredLints, Lrc};
+use harper_core::{remove_overlaps, Document, FstDictionary, IgnoredLints, Lrc, MutableDictionary};
use serde::{Deserialize, Serialize};
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::JsValue;
@@ -147,7 +147,8 @@ impl Linter {
let parser = language.create_parser();
- let document = Document::new_from_vec(source.clone(), &parser, &FullDictionary::curated());
+ let document =
+ Document::new_from_vec(source.clone(), &parser, &MutableDictionary::curated());
let mut lints = self.lint_group.lint(&document);