Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
refactor: metadata attribute naming and commenting (#1572)
Andrew Dunbar88dbd058b21a
diff --git a/harper-cli/src/annotate_tokens.rs b/harper-cli/src/annotate_tokens.rsindex e7a2473db..e6b6ebd7e 100644--- a/harper-cli/src/annotate_tokens.rs+++ b/harper-cli/src/annotate_tokens.rs@@ -47,7 +47,7 @@ impl Annotation {match annotation_type {AnnotationType::Upos => {if let TokenKind::Word(Some(metadata)) = &token.kind {- // Only annotate words (with word metadata) for `AnnotationType::Upos`.+ // Only annotate words (with dict word metadata) for `AnnotationType::Upos`.let pos_tag = metadata.pos_tag;Some(Self {span,diff --git a/harper-cli/src/main.rs b/harper-cli/src/main.rsindex d6791dec8..4f472cea1 100644--- a/harper-cli/src/main.rs+++ b/harper-cli/src/main.rs@@ -17,8 +17,8 @@ use harper_comments::CommentParser;use harper_core::linting::{LintGroup, Linter};use harper_core::parsers::{Markdown, MarkdownOptions, OrgMode, PlainEnglish};use harper_core::{- CharStringExt, Dialect, Document, Span, TokenKind, TokenStringExt, WordMetadata,- remove_overlaps, word_metadata_orthography::OrthFlags,+ CharStringExt, Dialect, DictWordMetadata, Document, Span, TokenKind, TokenStringExt,+ dict_word_metadata_orthography::OrthFlags, remove_overlaps,};use harper_literate_haskell::LiterateHaskellParser;#[cfg(feature = "training")]@@ -367,7 +367,7 @@ fn main() -> anyhow::Result<()> {Args::Metadata { words } => {let mut results = BTreeMap::new();for word in words {- let metadata = dictionary.get_word_metadata_str(&word);+ let metadata = dictionary.get_lexeme_metadata_str(&word);results.insert(word, metadata);}let json = serde_json::to_string_pretty(&results).unwrap();@@ -727,7 +727,7 @@ fn main() -> anyhow::Result<()> {let mut processed_words = HashMap::new();let mut longest_word = 0;for word in dictionary.words_iter() {- if let Some(metadata) = dictionary.get_word_metadata(word) {+ if let Some(metadata) = dictionary.get_lexeme_metadata(word) {let orth = metadata.orth_info;let bits = orth.bits() & case_bitmask.bits();@@ -855,7 +855,7 @@ fn print_word_derivations(word: &str, annot: &str, dictionary: &impl Dictionary)let children = dictionary.words_iter()- .filter(|e| dictionary.get_word_metadata(e).unwrap().derived_from == Some(id));+ .filter(|e| dictionary.get_lexeme_metadata(e).unwrap().derived_from == Some(id));println!(" - {word}");@@ -872,7 +872,7 @@ fn load_dict(path: &Path) -> anyhow::Result<MutableDictionary> {let mut dict = MutableDictionary::new();dict.extend_words(str.lines()- .map(|l| (l.chars().collect::<Vec<_>>(), WordMetadata::default())),+ .map(|l| (l.chars().collect::<Vec<_>>(), DictWordMetadata::default())),);Ok(dict)diff --git a/harper-core/src/word_metadata.rs b/harper-core/src/dict_word_metadata.rssimilarity index 97%rename from harper-core/src/word_metadata.rsrename to harper-core/src/dict_word_metadata.rsindex b6ca57630..3222cc596 100644--- a/harper-core/src/word_metadata.rs+++ b/harper-core/src/dict_word_metadata.rs@@ -9,15 +9,15 @@ use strum_macros::{Display, EnumCount, EnumString, VariantArray};use std::convert::TryFrom;+use crate::dict_word_metadata_orthography::OrthFlags;use crate::spell::WordId;-use crate::word_metadata_orthography::OrthFlags;use crate::{Document, TokenKind, TokenStringExt};/// This represents a "lexeme" or "headword" which is case-folded but affix-expanded./// So not only lemmata but also inflected forms are stored here, with "horn" and "horns" each-/// having their own lexeme, but "Ivy" and "ivy" share the same lexeme.+/// having their own lexeme, but "Ivy" and "ivy" sharing the same lexeme.#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, PartialOrd, Hash)]-pub struct WordMetadata {+pub struct DictWordMetadata {pub noun: Option<NounData>,pub pronoun: Option<PronounData>,pub verb: Option<VerbData>,@@ -106,7 +106,7 @@ macro_rules! generate_metadata_queries {};}-impl WordMetadata {+impl DictWordMetadata {/// If there is only one possible interpretation of the metadata, infer its UPOS tag.pub fn infer_pos_tag(&self) -> Option<UPOS> {// If an explicit POS tag exists, return it immediately.@@ -655,7 +655,7 @@ impl WordMetadata {// Orthographic queries- /// Does the lexeme for this word cover an all-lowercase variant? (e.g., "hello")+ /// Does the metadata for this word cover an all-lowercase variant? (e.g., "hello")////// This returns true if all letters in the word are lowercase. Words containing/// non-letter characters (like numbers or symbols) are only considered if all@@ -663,7 +663,7 @@ impl WordMetadata {pub fn is_lowercase(&self) -> bool {self.orth_info.contains(OrthFlags::LOWERCASE)}- /// Does the lexeme for this word cover a titlecase variant? (e.g., "Hello")+ /// Does the metadata for this word cover a titlecase variant? (e.g., "Hello")////// This returns true if the word is in titlecase form, which means:/// - The first letter is uppercase@@ -677,7 +677,7 @@ impl WordMetadata {pub fn is_titlecase(&self) -> bool {self.orth_info.contains(OrthFlags::TITLECASE)}- /// Does the lexeme for this word cover an all-uppercase variant? (e.g., "HELLO")+ /// Does the metadata for this word cover an all-uppercase variant? (e.g., "HELLO")////// This returns true if all letters in the word are uppercase. Words containing/// non-letter characters (like numbers or symbols) are only considered if all@@ -687,7 +687,7 @@ impl WordMetadata {pub fn is_allcaps(&self) -> bool {self.orth_info.contains(OrthFlags::ALLCAPS)}- /// Does the lexeme for this word cover a lower camel case variant? (e.g., "helloWorld")+ /// Does the metadata for this word cover a lower camel case variant? (e.g., "helloWorld")////// This returns true if the word is in lower camel case, which means:/// - The first letter is lowercase@@ -701,7 +701,7 @@ impl WordMetadata {pub fn is_lower_camel(&self) -> bool {self.orth_info.contains(OrthFlags::LOWER_CAMEL)}- /// Does the lexeme for this word cover an upper camel case / pascal case variant? (e.g., "HelloWorld")+ /// Does the metadata for this word cover an upper camel case / pascal case variant? (e.g., "HelloWorld")////// This returns true if the word is in upper camel case (also known as Pascal case), which means:/// - The first letter is uppercase@@ -721,7 +721,7 @@ impl WordMetadata {self.orth_info.contains(OrthFlags::UPPER_CAMEL)}- /// Does the lexeme for this word cover an apostrophized variant? (e.g., "doesn't")+ /// Does the metadata for this word cover an apostrophized variant? (e.g., "doesn't")pub fn is_apostrophized(&self) -> bool {self.orth_info.contains(OrthFlags::APOSTROPHE)}@@ -1100,11 +1100,11 @@ impl DialectFlags {// Count word dialects.document.iter_words().for_each(|w| {- if let TokenKind::Word(Some(word_metadata)) = &w.kind {+ if let TokenKind::Word(Some(lexeme_metadata)) = &w.kind {// If the token is a word, iterate though the dialects in `dialect_counters` and// increment those counters where the word has the respective dialect enabled.dialect_counters.iter_mut().for_each(|(dialect, count)| {- if word_metadata.dialects.is_dialect_enabled(*dialect) {+ if lexeme_metadata.dialects.is_dialect_enabled(*dialect) {*count += 1;}});@@ -1137,13 +1137,13 @@ impl Default for DialectFlags {#[cfg(test)]pub mod tests {- use crate::WordMetadata;+ use crate::DictWordMetadata;use crate::spell::{Dictionary, FstDictionary};- // Helper function to get word metadata from the curated dictionary- pub fn md(word: &str) -> WordMetadata {+ // Helper function to get metadata from the curated dictionary+ pub fn md(word: &str) -> DictWordMetadata {FstDictionary::curated()- .get_word_metadata_str(word)+ .get_lexeme_metadata_str(word).unwrap_or_else(|| panic!("Word '{word}' not found in dictionary")).into_owned()}@@ -1174,7 +1174,7 @@ pub mod tests {}mod noun {- use crate::word_metadata::tests::md;+ use crate::dict_word_metadata::tests::md;#[test]fn puppy_is_noun() {@@ -1336,10 +1336,10 @@ pub mod tests {}mod pronoun {- use crate::word_metadata::tests::md;+ use crate::dict_word_metadata::tests::md;mod i_me_myself {- use crate::word_metadata::tests::md;+ use crate::dict_word_metadata::tests::md;#[test]fn i_is_pronoun() {@@ -1394,7 +1394,7 @@ pub mod tests {}mod we_us_ourselves {- use crate::word_metadata::tests::md;+ use crate::dict_word_metadata::tests::md;#[test]fn we_is_pronoun() {@@ -1449,7 +1449,7 @@ pub mod tests {}mod you_yourself {- use crate::word_metadata::tests::md;+ use crate::dict_word_metadata::tests::md;#[test]fn you_is_pronoun() {@@ -1494,7 +1494,7 @@ pub mod tests {}mod he_him_himself {- use crate::word_metadata::tests::md;+ use crate::dict_word_metadata::tests::md;#[test]fn he_is_pronoun() {@@ -1549,7 +1549,7 @@ pub mod tests {}mod she_her_herself {- use crate::word_metadata::tests::md;+ use crate::dict_word_metadata::tests::md;#[test]fn she_is_pronoun() {@@ -1604,7 +1604,7 @@ pub mod tests {}mod it_itself {- use crate::word_metadata::tests::md;+ use crate::dict_word_metadata::tests::md;#[test]fn it_is_pronoun() {@@ -1646,7 +1646,7 @@ pub mod tests {}mod they_them_themselves {- use crate::word_metadata::tests::md;+ use crate::dict_word_metadata::tests::md;#[test]fn they_is_pronoun() {@@ -1766,7 +1766,7 @@ pub mod tests {}mod adjective {- use crate::{Degree, word_metadata::tests::md};+ use crate::{Degree, dict_word_metadata::tests::md};// Getting degrees@@ -1836,7 +1836,7 @@ pub mod tests {}mod verb {- use crate::word_metadata::tests::md;+ use crate::dict_word_metadata::tests::md;#[test]fn lemma_walk() {diff --git a/harper-core/src/word_metadata_orthography.rs b/harper-core/src/dict_word_metadata_orthography.rssimilarity index 97%rename from harper-core/src/word_metadata_orthography.rsrename to harper-core/src/dict_word_metadata_orthography.rsindex 34b0fc8c0..a77db0ab6 100644--- a/harper-core/src/word_metadata_orthography.rs+++ b/harper-core/src/dict_word_metadata_orthography.rs@@ -53,8 +53,8 @@ impl Default for OrthFlags {#[cfg(test)]mod tests {- use crate::word_metadata::tests::md;- use crate::word_metadata_orthography::OrthFlags;+ use crate::dict_word_metadata::tests::md;+ use crate::dict_word_metadata_orthography::OrthFlags;#[test]fn australia_lexeme_is_titlecase_even_when_word_is_lowercase() {diff --git a/harper-core/src/document.rs b/harper-core/src/document.rsindex e584ec385..2fe9cf323 100644--- a/harper-core/src/document.rs+++ b/harper-core/src/document.rs@@ -158,12 +158,12 @@ impl Document {let mut i = 0;- // Annotate word metadata+ // Annotate DictWord metadatafor token in sent.iter_mut() {if let TokenKind::Word(meta) = &mut token.kind {let word_source = token.span.get_content(&self.source);let mut found_meta = dictionary- .get_word_metadata(word_source)+ .get_lexeme_metadata(word_source).map(|c| c.into_owned());if let Some(inner) = &mut found_meta {diff --git a/harper-core/src/expr/fixed_phrase.rs b/harper-core/src/expr/fixed_phrase.rsindex 8399bd50f..6fc3c9ae9 100644--- a/harper-core/src/expr/fixed_phrase.rs+++ b/harper-core/src/expr/fixed_phrase.rs@@ -35,7 +35,7 @@ impl FixedPhrase {for token in doc.fat_tokens() {match token.kind {- TokenKind::Word(_word_metadata) => {+ TokenKind::Word(_lexeme_metadata) => {phrase = phrase.then(Word::from_chars(token.content.as_slice()));}TokenKind::Space(_) => {diff --git a/harper-core/src/expr/mergeable_words.rs b/harper-core/src/expr/mergeable_words.rsindex dffdc5f81..8cdab83b7 100644--- a/harper-core/src/expr/mergeable_words.rs+++ b/harper-core/src/expr/mergeable_words.rs@@ -2,14 +2,15 @@ use std::sync::Arc;use super::{Expr, SequenceExpr, SpaceOrHyphen};use crate::spell::{Dictionary, FstDictionary};-use crate::{CharString, Span, Token, WordMetadata};+use crate::{CharString, DictWordMetadata, Span, Token};-type PredicateFn = dyn Fn(Option<&WordMetadata>, Option<&WordMetadata>) -> bool + Send + Sync;+type PredicateFn =+ dyn Fn(Option<&DictWordMetadata>, Option<&DictWordMetadata>) -> bool + Send + Sync;-/// A [`Expr`] that identifies adjacent words that could potentially be merged into a single word.+/// An [`Expr`] that identifies adjacent words that could potentially be merged into a single word.////// This checks if two adjacent words could form a valid compound word, but first verifies-/// that the two words aren't already a valid lexeme in the dictionary (like "straight away").+/// that the two words aren't already a valid entry in the dictionary (like "straight away").pub struct MergeableWords {inner: SequenceExpr,dict: Arc<FstDictionary>,@@ -18,7 +19,10 @@ pub struct MergeableWords {impl MergeableWords {pub fn new(- predicate: impl Fn(Option<&WordMetadata>, Option<&WordMetadata>) -> bool + Send + Sync + 'static,+ predicate: impl Fn(Option<&DictWordMetadata>, Option<&DictWordMetadata>) -> bool+ + Send+ + Sync+ + 'static,) -> Self {Self {inner: SequenceExpr::default()@@ -45,11 +49,11 @@ impl MergeableWords {let mut compound = a_chars.clone();compound.push(' ');compound.extend_from_slice(&b_chars);- let meta_open = self.dict.get_word_metadata(&compound);+ let meta_open = self.dict.get_lexeme_metadata(&compound);// Then check if the closed compound exists in the dictionarycompound.remove(a_chars.len());- let meta_closed = self.dict.get_word_metadata(&compound);+ let meta_closed = self.dict.get_lexeme_metadata(&compound);if (self.predicate)(meta_closed.as_deref(), meta_open.as_deref()) {return Some(compound);@@ -81,9 +85,12 @@ impl Expr for MergeableWords {#[cfg(test)]mod tests {use super::MergeableWords;- use crate::{Document, WordMetadata};+ use crate::{DictWordMetadata, Document};- fn predicate(meta_closed: Option<&WordMetadata>, meta_open: Option<&WordMetadata>) -> bool {+ fn predicate(+ meta_closed: Option<&DictWordMetadata>,+ meta_open: Option<&DictWordMetadata>,+ ) -> bool {meta_open.is_none() && meta_closed.is_some_and(|m| m.is_noun() && !m.is_proper_noun())}diff --git a/harper-core/src/expr/similar_to_phrase.rs b/harper-core/src/expr/similar_to_phrase.rsindex 92fd810db..76094fd73 100644--- a/harper-core/src/expr/similar_to_phrase.rs+++ b/harper-core/src/expr/similar_to_phrase.rs@@ -33,7 +33,7 @@ impl SimilarToPhrase {for token in document.fat_tokens() {match token.kind {- TokenKind::Word(_word_metadata) => {+ TokenKind::Word(_lexeme_metadata) => {phrase = phrase.then(Word::from_chars(token.content.as_slice()));fuzzy_phrase = fuzzy_phrase.then(WithinEditDistance::new(token.content.into(), max_edit_dist));diff --git a/harper-core/src/lib.rs b/harper-core/src/lib.rsindex 2bf20f67b..6cd32558a 100644--- a/harper-core/src/lib.rs+++ b/harper-core/src/lib.rs@@ -4,6 +4,8 @@mod char_ext;mod char_string;mod currency;+pub mod dict_word_metadata;+pub mod dict_word_metadata_orthography;mod document;mod edit_distance;pub mod expr;@@ -26,14 +28,16 @@ mod token;mod token_kind;mod token_string_ext;mod vec_ext;-pub mod word_metadata;-pub mod word_metadata_orthography;use render_markdown::render_markdown;use std::collections::VecDeque;pub use char_string::{CharString, CharStringExt};pub use currency::Currency;+pub use dict_word_metadata::{+ AdverbData, ConjunctionData, Degree, DeterminerData, Dialect, DictWordMetadata, NounData,+ PronounData, VerbData, VerbForm,+};pub use document::Document;pub use fat_token::{FatStringToken, FatToken};pub use ignored_lints::{IgnoredLints, LintContext};@@ -48,10 +52,6 @@ pub use token::Token;pub use token_kind::TokenKind;pub use token_string_ext::TokenStringExt;pub use vec_ext::VecExt;-pub use word_metadata::{- AdverbData, ConjunctionData, Degree, DeterminerData, Dialect, NounData, PronounData, VerbData,- VerbForm, WordMetadata,-};/// Return harper-core versionpub fn core_version() -> &'static str {diff --git a/harper-core/src/linting/compound_nouns/mod.rs b/harper-core/src/linting/compound_nouns/mod.rsindex e1a0a0e3e..c45ab8291 100644--- a/harper-core/src/linting/compound_nouns/mod.rs+++ b/harper-core/src/linting/compound_nouns/mod.rs@@ -3,7 +3,7 @@ mod compound_noun_after_possessive;mod compound_noun_before_aux_verb;use super::{Lint, LintKind, Suggestion, merge_linters::merge_linters};-use crate::{CharStringExt, Token, WordMetadata};+use crate::{CharStringExt, DictWordMetadata, Token};// Helper function to check if a token is a content word (not a function word)pub(crate) fn is_content_word(tok: &Token, src: &[char]) -> bool {@@ -17,7 +17,10 @@ pub(crate) fn is_content_word(tok: &Token, src: &[char]) -> bool {&& (!meta.preposition || tok.span.get_content(src).eq_ignore_ascii_case_str("bar"))}-pub(crate) fn predicate(closed: Option<&WordMetadata>, open: Option<&WordMetadata>) -> bool {+pub(crate) fn predicate(+ closed: Option<&DictWordMetadata>,+ open: Option<&DictWordMetadata>,+) -> bool {open.is_none() && closed.is_some_and(|m| m.is_noun() && !m.is_proper_noun())}diff --git a/harper-core/src/linting/inflected_verb_after_to.rs b/harper-core/src/linting/inflected_verb_after_to.rsindex 097d54a7d..0f821be75 100644--- a/harper-core/src/linting/inflected_verb_after_to.rs+++ b/harper-core/src/linting/inflected_verb_after_to.rs@@ -42,7 +42,7 @@ impl<T: Dictionary> Linter for InflectedVerbAfterTo<T> {}let check_stem = |stem: &[char]| {- if let Some(metadata) = self.dictionary.get_word_metadata(stem)+ if let Some(metadata) = self.dictionary.get_lexeme_metadata(stem)&& metadata.is_verb()&& !metadata.is_noun(){@@ -79,9 +79,9 @@ impl<T: Dictionary> Linter for InflectedVerbAfterTo<T> {let ed_specific_heuristics = || {if let Some(prev) = document.get_next_word_from_offset(pi, -1) {let prev_chars = document.get_span_content(&prev.span);- if let Some(metadata) = self.dictionary.get_word_metadata(prev_chars) {- // adj: "able" to expects an infinitive verb- // verb: have/had/has/having to expects an infinitive verb+ if let Some(metadata) = self.dictionary.get_lexeme_metadata(prev_chars) {+ // adj: "able to" expects an infinitive verb+ // verb: "have/had/has/having to" expect an infinitive verbif metadata.is_adjective() || metadata.is_verb() {return ToVerbExpects::ExpectsInfinitive;}diff --git a/harper-core/src/linting/mass_plurals.rs b/harper-core/src/linting/mass_plurals.rsindex b4507de47..45d971131 100644--- a/harper-core/src/linting/mass_plurals.rs+++ b/harper-core/src/linting/mass_plurals.rs@@ -42,13 +42,13 @@ wherefn is_mass_noun_in_dictionary(&self, chars: &[char]) -> bool {self.dict- .get_word_metadata(chars)+ .get_lexeme_metadata(chars).is_some_and(|wmd| wmd.is_mass_noun_only())}fn is_mass_noun_in_dictionary_str(&self, s: &str) -> bool {self.dict- .get_word_metadata_str(s)+ .get_lexeme_metadata_str(s).is_some_and(|wmd| wmd.is_mass_noun_only())}}diff --git a/harper-core/src/linting/multiple_sequential_pronouns.rs b/harper-core/src/linting/multiple_sequential_pronouns.rsindex e71fe7250..ac422e29e 100644--- a/harper-core/src/linting/multiple_sequential_pronouns.rs+++ b/harper-core/src/linting/multiple_sequential_pronouns.rs@@ -30,7 +30,7 @@ impl MultipleSequentialPronouns {"our", "your", "their", // possessive adjectives, plural]));- // TODO: temporary sets of pronouns - remove when WordMetadata has this info+ // TODO: temporary sets of pronouns - remove when DictWordMetadata has this infolet subject_pronouns = Lrc::new(WordSet::new(&["i", "you", "he", "she", "it", // subject case, singular"we", "you", "they", // subject case, pluraldiff --git a/harper-core/src/linting/nominal_wants.rs b/harper-core/src/linting/nominal_wants.rsindex 300a33866..fe02ea0bb 100644--- a/harper-core/src/linting/nominal_wants.rs+++ b/harper-core/src/linting/nominal_wants.rs@@ -4,9 +4,9 @@ use crate::expr::Expr;use crate::expr::SequenceExpr;use crate::{Token,+ dict_word_metadata::Person,linting::{ExprLinter, Lint, LintKind, Suggestion},patterns::WordSet,- word_metadata::Person,};pub struct NominalWants {diff --git a/harper-core/src/linting/phrasal_verb_as_compound_noun.rs b/harper-core/src/linting/phrasal_verb_as_compound_noun.rsindex e03ae544e..ffdbe1cca 100644--- a/harper-core/src/linting/phrasal_verb_as_compound_noun.rs+++ b/harper-core/src/linting/phrasal_verb_as_compound_noun.rs@@ -103,10 +103,10 @@ impl Linter for PhrasalVerbAsCompoundNoun {// So far we only have a small number of phrasal verbs in the dictionary.let (verb_part_is_verb, phrasal_verb_is_verb) = (self.dict- .get_word_metadata(verb_part)+ .get_lexeme_metadata(verb_part).is_some_and(|md| md.verb.is_some()),self.dict- .get_word_metadata_str(&phrasal_verb)+ .get_lexeme_metadata_str(&phrasal_verb).is_some_and(|md| md.verb.is_some()),);diff --git a/harper-core/src/linting/spell_check.rs b/harper-core/src/linting/spell_check.rsindex 5f4a82dcb..cb40662c2 100644--- a/harper-core/src/linting/spell_check.rs+++ b/harper-core/src/linting/spell_check.rs@@ -47,7 +47,7 @@ impl<T: Dictionary> SpellCheck<T> {.filter(|v| {// ignore entries outside the configured dialectself.dictionary- .get_word_metadata(v)+ .get_lexeme_metadata(v).unwrap().dialects.is_dialect_enabled(self.dialect)@@ -129,16 +129,16 @@ impl<T: Dictionary> Linter for SpellCheck<T> {#[cfg(test)]mod tests {use super::SpellCheck;+ use crate::dict_word_metadata::DialectFlags;use crate::linting::Linter;use crate::spell::{Dictionary, FstDictionary, MergedDictionary, MutableDictionary};- use crate::word_metadata::DialectFlags;use crate::{Dialect,linting::tests::{assert_lint_count, assert_suggestion_result, assert_top3_suggestion_result,},};- use crate::{Document, WordMetadata};+ use crate::{DictWordMetadata, Document};// Capitalization tests@@ -416,7 +416,7 @@ mod tests {let mut user_dict = MutableDictionary::new();user_dict.append_word_str("Calibre",- WordMetadata {+ DictWordMetadata {dialects: DialectFlags::from_dialect(user_dialect),..Default::default()},diff --git a/harper-core/src/parsers/collapse_identifiers.rs b/harper-core/src/parsers/collapse_identifiers.rsindex e7bdb175e..bc23609d4 100644--- a/harper-core/src/parsers/collapse_identifiers.rs+++ b/harper-core/src/parsers/collapse_identifiers.rs@@ -64,7 +64,7 @@ mod tests {use super::*;use crate::spell::{FstDictionary, MergedDictionary, MutableDictionary};use crate::{- WordMetadata,+ DictWordMetadata,parsers::{PlainEnglish, StrParser},};@@ -102,7 +102,7 @@ mod tests {assert_eq!(tokens.len(), 13);let mut dict = MutableDictionary::new();- dict.append_word_str("separated_identifier", WordMetadata::default());+ dict.append_word_str("separated_identifier", DictWordMetadata::default());let mut merged_dict = MergedDictionary::new();merged_dict.add_dictionary(curated_dictionary);@@ -126,7 +126,7 @@ mod tests {assert_eq!(tokens.len(), 13);let mut dict = MutableDictionary::new();- dict.append_word_str("separated-identifier", WordMetadata::default());+ dict.append_word_str("separated-identifier", DictWordMetadata::default());let mut merged_dict = MergedDictionary::new();merged_dict.add_dictionary(curated_dictionary);@@ -150,7 +150,7 @@ mod tests {assert_eq!(tokens.len(), 15);let mut dict = MutableDictionary::new();- dict.append_word_str("separated_identifier_token", WordMetadata::default());+ dict.append_word_str("separated_identifier_token", DictWordMetadata::default());let mut merged_dict = MergedDictionary::new();merged_dict.add_dictionary(curated_dictionary);@@ -173,7 +173,7 @@ mod tests {assert_eq!(tokens.len(), 17);let mut dict = MutableDictionary::new();- dict.append_word_str("separated_identifier", WordMetadata::default());+ dict.append_word_str("separated_identifier", DictWordMetadata::default());let mut merged_dict = MergedDictionary::new();merged_dict.add_dictionary(curated_dictionary);@@ -196,8 +196,8 @@ mod tests {assert_eq!(tokens.len(), 15);let mut dict = MutableDictionary::new();- dict.append_word_str("separated_identifier", WordMetadata::default());- dict.append_word_str("identifier_token", WordMetadata::default());+ dict.append_word_str("separated_identifier", DictWordMetadata::default());+ dict.append_word_str("identifier_token", DictWordMetadata::default());let mut merged_dict = MergedDictionary::new();merged_dict.add_dictionary(curated_dictionary);@@ -220,8 +220,8 @@ mod tests {assert_eq!(tokens.len(), 15);let mut dict = MutableDictionary::new();- dict.append_word_str("separated_identifier_token", WordMetadata::default());- dict.append_word_str("separated_identifier", WordMetadata::default());+ dict.append_word_str("separated_identifier_token", DictWordMetadata::default());+ dict.append_word_str("separated_identifier", DictWordMetadata::default());let mut merged_dict = MergedDictionary::new();merged_dict.add_dictionary(curated_dictionary);diff --git a/harper-core/src/patterns/implies_quantity.rs b/harper-core/src/patterns/implies_quantity.rsindex feb9c1788..ccb232eb6 100644--- a/harper-core/src/patterns/implies_quantity.rs+++ b/harper-core/src/patterns/implies_quantity.rs@@ -13,8 +13,8 @@ pub struct ImpliesQuantity;impl ImpliesQuantity {pub fn implies_plurality(token: &Token, source: &[char]) -> Option<bool> {match &token.kind {- TokenKind::Word(Some(word_metadata)) => {- if word_metadata.is_determiner() {+ TokenKind::Word(Some(lexeme_metadata)) => {+ if lexeme_metadata.is_determiner() {return Some(false);}diff --git a/harper-core/src/spell/dictionary.rs b/harper-core/src/spell/dictionary.rsindex 9f70a632b..50a263b0c 100644--- a/harper-core/src/spell/dictionary.rs+++ b/harper-core/src/spell/dictionary.rs@@ -3,7 +3,7 @@ use std::borrow::Cow;use super::FuzzyMatchResult;use super::WordId;-use crate::WordMetadata;+use crate::DictWordMetadata;/// An in-memory database that contains everything necessary to parse and analyze English text.///@@ -33,12 +33,12 @@ pub trait Dictionary: Send + Sync {max_results: usize,) -> Vec<FuzzyMatchResult<'_>>;fn get_correct_capitalization_of(&self, word: &[char]) -> Option<&'_ [char]>;- /// Get the associated [`WordMetadata`] for any capitalization of a given word.- fn get_word_metadata(&self, word: &[char]) -> Option<Cow<'_, WordMetadata>>;- /// Get the associated [`WordMetadata`] for any capitalization of a given word.+ /// Get the associated [`DictWordMetadata`] for any capitalization of a given word.+ fn get_lexeme_metadata(&self, word: &[char]) -> Option<Cow<'_, DictWordMetadata>>;+ /// Get the associated [`DictWordMetadata`] for any capitalization of a given word./// If the word isn't in the dictionary, the resulting metadata will be/// empty.- fn get_word_metadata_str(&self, word: &str) -> Option<Cow<'_, WordMetadata>>;+ fn get_lexeme_metadata_str(&self, word: &str) -> Option<Cow<'_, DictWordMetadata>>;/// Iterate over the words in the dictionary.fn words_iter(&self) -> Box<dyn Iterator<Item = &'_ [char]> + Send + '_>;diff --git a/harper-core/src/spell/fst_dictionary.rs b/harper-core/src/spell/fst_dictionary.rsindex 6d53b10a5..23f917253 100644--- a/harper-core/src/spell/fst_dictionary.rs+++ b/harper-core/src/spell/fst_dictionary.rs@@ -5,7 +5,7 @@ use levenshtein_automata::{DFA, LevenshteinAutomatonBuilder};use std::borrow::Cow;use std::{cell::RefCell, sync::Arc};-use crate::{CharString, CharStringExt, WordMetadata};+use crate::{CharString, CharStringExt, DictWordMetadata};use super::Dictionary;use super::FuzzyMatchResult;@@ -20,7 +20,7 @@ pub struct FstDictionary {/// Used for fuzzy-finding the index of words or metadataword_map: FstMap<Vec<u8>>,/// Used for fuzzy-finding the index of words or metadata- words: Vec<(CharString, WordMetadata)>,+ words: Vec<(CharString, DictWordMetadata)>,}const EXPECTED_DISTANCE: u8 = 3;@@ -56,7 +56,7 @@ impl FstDictionary {/// Construct a new [`FstDictionary`] using a word list as a source./// This can be expensive, so only use this if fast fuzzy searches are worth it.- pub fn new(mut words: Vec<(CharString, WordMetadata)>) -> Self {+ pub fn new(mut words: Vec<(CharString, DictWordMetadata)>) -> Self {words.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));words.dedup_by(|(a, _), (b, _)| a == b);@@ -121,12 +121,12 @@ impl Dictionary for FstDictionary {self.mutable_dict.contains_word_str(word)}- fn get_word_metadata(&self, word: &[char]) -> Option<Cow<'_, WordMetadata>> {- self.mutable_dict.get_word_metadata(word)+ fn get_lexeme_metadata(&self, word: &[char]) -> Option<Cow<'_, DictWordMetadata>> {+ self.mutable_dict.get_lexeme_metadata(word)}- fn get_word_metadata_str(&self, word: &str) -> Option<Cow<'_, WordMetadata>> {- self.mutable_dict.get_word_metadata_str(word)+ fn get_lexeme_metadata_str(&self, word: &str) -> Option<Cow<'_, DictWordMetadata>> {+ self.mutable_dict.get_lexeme_metadata_str(word)}fn fuzzy_match(@@ -283,7 +283,7 @@ mod tests {fn on_is_not_nominal() {let dict = FstDictionary::curated();- assert!(!dict.get_word_metadata_str("on").unwrap().is_nominal());+ assert!(!dict.get_lexeme_metadata_str("on").unwrap().is_nominal());}#[test]@@ -316,7 +316,7 @@ mod tests {for contraction in contractions {dbg!(contraction);assert!(- dict.get_word_metadata_str(contraction)+ dict.get_lexeme_metadata_str(contraction).unwrap().derived_from.is_none()@@ -329,7 +329,7 @@ mod tests {let dict = FstDictionary::curated();assert_eq!(- dict.get_word_metadata_str("llamas")+ dict.get_lexeme_metadata_str("llamas").unwrap().derived_from.unwrap(),@@ -342,7 +342,7 @@ mod tests {let dict = FstDictionary::curated();assert_eq!(- dict.get_word_metadata_str("cats")+ dict.get_lexeme_metadata_str("cats").unwrap().derived_from.unwrap(),@@ -355,7 +355,7 @@ mod tests {let dict = FstDictionary::curated();assert_eq!(- dict.get_word_metadata_str("unhappy")+ dict.get_lexeme_metadata_str("unhappy").unwrap().derived_from.unwrap(),@@ -368,7 +368,7 @@ mod tests {let dict = FstDictionary::curated();assert_eq!(- dict.get_word_metadata_str("quickly")+ dict.get_lexeme_metadata_str("quickly").unwrap().derived_from.unwrap(),diff --git a/harper-core/src/spell/merged_dictionary.rs b/harper-core/src/spell/merged_dictionary.rsindex f080efb8c..06c8cd8b6 100644--- a/harper-core/src/spell/merged_dictionary.rs+++ b/harper-core/src/spell/merged_dictionary.rs@@ -7,7 +7,7 @@ use itertools::Itertools;use super::{FstDictionary, WordId};use super::{FuzzyMatchResult, dictionary::Dictionary};-use crate::{CharString, WordMetadata};+use crate::{CharString, DictWordMetadata};/// A simple wrapper over [`Dictionary`] that allows/// one to merge multiple dictionaries without copying.@@ -94,10 +94,10 @@ impl Dictionary for MergedDictionary {false}- fn get_word_metadata(&self, word: &[char]) -> Option<Cow<'_, WordMetadata>> {+ fn get_lexeme_metadata(&self, word: &[char]) -> Option<Cow<'_, DictWordMetadata>> {self.children.iter()- .filter_map(|d| d.get_word_metadata(word))+ .filter_map(|d| d.get_lexeme_metadata(word)).reduce(|acc, md| Cow::Owned(acc.or(&md)))}@@ -115,9 +115,9 @@ impl Dictionary for MergedDictionary {self.contains_word(&chars)}- fn get_word_metadata_str(&self, word: &str) -> Option<Cow<'_, WordMetadata>> {+ fn get_lexeme_metadata_str(&self, word: &str) -> Option<Cow<'_, DictWordMetadata>> {let chars: CharString = word.chars().collect();- self.get_word_metadata(&chars)+ self.get_lexeme_metadata(&chars)}fn fuzzy_match(diff --git a/harper-core/src/spell/mod.rs b/harper-core/src/spell/mod.rsindex c02f8812d..3d049926e 100644--- a/harper-core/src/spell/mod.rs+++ b/harper-core/src/spell/mod.rs@@ -1,7 +1,7 @@//! Contains the relevant code for performing dictionary lookups and spellchecking (i.e. fuzzy//! dictionary lookups).-use crate::{CharString, CharStringExt, WordMetadata};+use crate::{CharString, CharStringExt, DictWordMetadata};pub use self::dictionary::Dictionary;pub use self::fst_dictionary::FstDictionary;@@ -21,7 +21,7 @@ mod word_map;pub struct FuzzyMatchResult<'a> {pub word: &'a [char],pub edit_distance: u8,- pub metadata: std::borrow::Cow<'a, WordMetadata>,+ pub metadata: std::borrow::Cow<'a, DictWordMetadata>,}impl PartialOrd for FuzzyMatchResult<'_> {diff --git a/harper-core/src/spell/mutable_dictionary.rs b/harper-core/src/spell/mutable_dictionary.rsindex 7f179073b..1dca6eeb5 100644--- a/harper-core/src/spell/mutable_dictionary.rs+++ b/harper-core/src/spell/mutable_dictionary.rs@@ -9,7 +9,7 @@ use lazy_static::lazy_static;use std::borrow::Cow;use std::sync::Arc;-use crate::{CharString, CharStringExt, WordMetadata};+use crate::{CharString, CharStringExt, DictWordMetadata};use super::FuzzyMatchResult;use super::dictionary::Dictionary;@@ -57,7 +57,7 @@ impl MutableDictionary {// There will be at _least_ this number of wordslet mut word_map = WordMap::default();- attr_list.expand_marked_words(word_list, &mut word_map);+ attr_list.expand_annotated_words(word_list, &mut word_map);Ok(Self { word_map })}@@ -74,7 +74,7 @@ impl MutableDictionary {/// distinct calls to this function.pub fn extend_words(&mut self,- words: impl IntoIterator<Item = (impl AsRef<[char]>, WordMetadata)>,+ words: impl IntoIterator<Item = (impl AsRef<[char]>, DictWordMetadata)>,) {for (chars, metadata) in words.into_iter() {self.word_map.insert(WordMapEntry {@@ -88,7 +88,7 @@ impl MutableDictionary {////// If you are appending many words, consider using [`Self::extend_words`]/// instead.- pub fn append_word(&mut self, word: impl AsRef<[char]>, metadata: WordMetadata) {+ pub fn append_word(&mut self, word: impl AsRef<[char]>, metadata: DictWordMetadata) {self.extend_words(std::iter::once((word.as_ref(), metadata)))}@@ -96,7 +96,7 @@ impl MutableDictionary {////// If you are appending many words, consider using [`Self::extend_words`]/// instead.- pub fn append_word_str(&mut self, word: &str, metadata: WordMetadata) {+ pub fn append_word_str(&mut self, word: &str, metadata: DictWordMetadata) {self.append_word(word.chars().collect::<Vec<_>>(), metadata)}}@@ -108,7 +108,7 @@ impl Default for MutableDictionary {}impl Dictionary for MutableDictionary {- fn get_word_metadata(&self, word: &[char]) -> Option<Cow<'_, WordMetadata>> {+ fn get_lexeme_metadata(&self, word: &[char]) -> Option<Cow<'_, DictWordMetadata>> {self.word_map.get_with_chars(word).map(|v| Cow::Borrowed(&v.metadata))@@ -123,9 +123,9 @@ impl Dictionary for MutableDictionary {self.contains_word(&chars)}- fn get_word_metadata_str(&self, word: &str) -> Option<Cow<'_, WordMetadata>> {+ fn get_lexeme_metadata_str(&self, word: &str) -> Option<Cow<'_, DictWordMetadata>> {let chars: CharString = word.chars().collect();- self.get_word_metadata(&chars)+ self.get_lexeme_metadata(&chars)}fn get_correct_capitalization_of(&self, word: &[char]) -> Option<&'_ [char]> {@@ -188,7 +188,7 @@ impl Dictionary for MutableDictionary {.map(|(word, edit_distance)| FuzzyMatchResult {word,edit_distance,- metadata: self.get_word_metadata(word).unwrap(),+ metadata: self.get_lexeme_metadata(word).unwrap(),}).collect()}@@ -269,18 +269,29 @@ mod tests {assert!(dict.contains_word_str("This"));}+ // "This" is a determiner when used similarly to "the"+ // but when used alone it's a "demonstrative pronoun".+ // Harper previously wrongly classified it as a noun.#[test]fn this_is_determiner() {let dict = MutableDictionary::curated();- assert!(dict.get_word_metadata_str("this").unwrap().is_determiner());- assert!(dict.get_word_metadata_str("This").unwrap().is_determiner());+ assert!(+ dict.get_lexeme_metadata_str("this")+ .unwrap()+ .is_determiner()+ );+ assert!(+ dict.get_lexeme_metadata_str("This")+ .unwrap()+ .is_determiner()+ );}#[test]fn several_is_quantifier() {let dict = MutableDictionary::curated();assert!(- dict.get_word_metadata_str("several")+ dict.get_lexeme_metadata_str("several").unwrap().is_quantifier());@@ -289,27 +300,47 @@ mod tests {#[test]fn few_is_quantifier() {let dict = MutableDictionary::curated();- assert!(dict.get_word_metadata_str("few").unwrap().is_quantifier());+ assert!(dict.get_lexeme_metadata_str("few").unwrap().is_quantifier());}#[test]fn fewer_is_quantifier() {let dict = MutableDictionary::curated();- assert!(dict.get_word_metadata_str("fewer").unwrap().is_quantifier());+ assert!(+ dict.get_lexeme_metadata_str("fewer")+ .unwrap()+ .is_quantifier()+ );}#[test]fn than_is_conjunction() {let dict = MutableDictionary::curated();- assert!(dict.get_word_metadata_str("than").unwrap().is_conjunction());- assert!(dict.get_word_metadata_str("Than").unwrap().is_conjunction());+ assert!(+ dict.get_lexeme_metadata_str("than")+ .unwrap()+ .is_conjunction()+ );+ assert!(+ dict.get_lexeme_metadata_str("Than")+ .unwrap()+ .is_conjunction()+ );}#[test]fn herself_is_pronoun() {let dict = MutableDictionary::curated();- assert!(dict.get_word_metadata_str("herself").unwrap().is_pronoun());- assert!(dict.get_word_metadata_str("Herself").unwrap().is_pronoun());+ assert!(+ dict.get_lexeme_metadata_str("herself")+ .unwrap()+ .is_pronoun()+ );+ assert!(+ dict.get_lexeme_metadata_str("Herself")+ .unwrap()+ .is_pronoun()+ );}#[test]@@ -321,7 +352,7 @@ mod tests {#[test]fn im_is_common() {let dict = MutableDictionary::curated();- assert!(dict.get_word_metadata_str("I'm").unwrap().common);+ assert!(dict.get_lexeme_metadata_str("I'm").unwrap().common);}#[test]@@ -342,8 +373,8 @@ mod tests {fn there_is_not_a_pronoun() {let dict = MutableDictionary::curated();- assert!(!dict.get_word_metadata_str("there").unwrap().is_nominal());- assert!(!dict.get_word_metadata_str("there").unwrap().is_pronoun());+ assert!(!dict.get_lexeme_metadata_str("there").unwrap().is_nominal());+ assert!(!dict.get_lexeme_metadata_str("there").unwrap().is_pronoun());}#[test]@@ -369,7 +400,7 @@ mod tests {fn curated_contains_possessive_abandonment() {assert!(MutableDictionary::curated()- .get_word_metadata_str("abandonment's")+ .get_lexeme_metadata_str("abandonment's").unwrap().is_possessive_noun())@@ -379,7 +410,7 @@ mod tests {fn has_is_not_a_nominal() {let dict = MutableDictionary::curated();- let has = dict.get_word_metadata_str("has");+ let has = dict.get_lexeme_metadata_str("has");assert!(has.is_some());assert!(!has.unwrap().is_nominal())@@ -389,7 +420,7 @@ mod tests {fn is_is_linking_verb() {let dict = MutableDictionary::curated();- let is = dict.get_word_metadata_str("is");+ let is = dict.get_lexeme_metadata_str("is");assert!(is.is_some());assert!(is.unwrap().is_linking_verb());@@ -413,14 +444,14 @@ mod tests {fn apart_is_not_noun() {let dict = MutableDictionary::curated();- assert!(!dict.get_word_metadata_str("apart").unwrap().is_noun());+ assert!(!dict.get_lexeme_metadata_str("apart").unwrap().is_noun());}#[test]fn be_is_verb_lemma() {let dict = MutableDictionary::curated();- let is = dict.get_word_metadata_str("be");+ let is = dict.get_lexeme_metadata_str("be");assert!(is.is_some());assert!(is.unwrap().is_verb_lemma());diff --git a/harper-core/src/spell/rune/attribute_list.rs b/harper-core/src/spell/rune/attribute_list.rsindex ee65d7ec4..1197d17b3 100644--- a/harper-core/src/spell/rune/attribute_list.rs+++ b/harper-core/src/spell/rune/attribute_list.rs@@ -11,10 +11,10 @@ use super::expansion::{AffixEntryKind::{Prefix, Suffix},Expansion, HumanReadableExpansion,};-use super::word_list::MarkedWord;+use super::word_list::AnnotatedWord;+use crate::dict_word_metadata_orthography::OrthFlags;use crate::spell::WordId;-use crate::word_metadata_orthography::OrthFlags;-use crate::{CharString, CharStringExt, Span, WordMetadata};+use crate::{CharString, CharStringExt, DictWordMetadata, Span};#[derive(Debug, Clone)]pub struct AttributeList {@@ -42,98 +42,129 @@ impl AttributeList {.and_then(|parsed| parsed.into_normal())}- /// Expand [`MarkedWord`] into a list of full words, including itself.+ /// Expand an [`AnnotatedWord`] into a list of full words, including itself.///- /// Will append to the given `dest`;+ /// This function processes a word and its attributes to:+ /// 1. Apply properties to the base word+ /// 2. Generate derived words using affix rules+ /// 3. Handle conditional expansions+ /// 4. Manage cross-product expansions///- /// In the future, I want to make this function cleaner and faster.- pub fn expand_marked_word(&self, word: MarkedWord, dest: &mut WordMap) {- dest.reserve(word.attributes.len() + 1);- let mut gifted_metadata = WordMetadata::default();+ /// # Arguments+ /// * `word` - The word to expand, along with its attributes+ /// * `dest` - The WordMap to store the expanded words and their metadata+ pub fn expand_annotated_word(&self, annotated_word: AnnotatedWord, word_map: &mut WordMap) {+ // Pre-allocate space in the destination map for better performance+ word_map.reserve(annotated_word.annotations.len() + 1);- let orth_flags = check_orthography(&word);- gifted_metadata.orth_info = orth_flags;+ // Initialize base metadata that will be applied to all derived forms+ let mut base_metadata = DictWordMetadata::default();++ // Store metadata that should only be applied if certain conditions are met+ let orth_flags = check_orthography(&annotated_word);+ base_metadata.orth_info = orth_flags;let mut conditional_expansion_metadata = Vec::new();- for attr in &word.attributes {+ // First pass: Process all properties to build the base metadata+ // Properties directly modify the word's metadata (e.g., part of speech, usage)+ for attr in &annotated_word.annotations {let Some(property) = self.properties.get(attr) else {continue;};-- gifted_metadata.append(&property.metadata);+ base_metadata.append(&property.metadata);}- for attr in &word.attributes {+ // Second pass: Process all affix rules to generate derived forms+ for attr in &annotated_word.annotations {+ // Skip if this attribute isn't an affix rulelet Some(expansion) = self.affixes.get(attr) else {continue;};- gifted_metadata.append(&expansion.base_metadata);- let mut new_words: HashMap<CharString, WordMetadata> = HashMap::new();+ // Add any base metadata from this affix rule+ base_metadata.append(&expansion.base_metadata);++ // Track new words generated by this affix rule+ let mut new_words: HashMap<CharString, DictWordMetadata> = HashMap::new();+ // Apply each replacement rule in this affixfor replacement in &expansion.replacements {if let Some(replaced) =- Self::apply_replacement(replacement, &word.letters, expansion.kind)+ Self::apply_replacement(replacement, &annotated_word.letters, expansion.kind){+ // Get or create metadata for this new word formlet metadata = new_words.entry(replaced.clone()).or_default();++ // Process each target for this replacementfor target in &expansion.target {if let Some(condition) = &target.if_base {+ // Store conditional metadata to be applied laterconditional_expansion_metadata.push((replaced.clone(),target.metadata.clone(),condition.clone(),));} else {+ // Apply target metadata immediatelymetadata.append(&target.metadata);}}}}+ // Handle cross-product expansions (e.g., both prefix and suffix)if expansion.cross_product {- let mut opp_attr = Vec::new();+ // Collect attributes that should be applied to the opposite affix type+ let mut opposite_attributes = Vec::new();- for attr in &word.attributes {+ // Add properties that should propagate to derived forms+ for attr in &annotated_word.annotations {let Some(property) = self.properties.get(attr) else {continue;};- // This is the same logic as below, plus propagationif expansion.kind == Prefix || property.propagate {- opp_attr.push(*attr);+ opposite_attributes.push(*attr);}}- for attr in &word.attributes {+ // Add affix attributes of the opposite type+ for attr in &annotated_word.annotations {let Some(attr_def) = self.affixes.get(attr) else {continue;};- // This looks wrong but matches the old logic: if attr_def.suffix != expansion.suffix+ // This checks if the current affix is of the opposite typeif (attr_def.kind != Prefix) != (expansion.kind != Prefix) {- opp_attr.push(*attr);+ opposite_attributes.push(*attr);}}+ // Recursively process each new word formfor (new_word, metadata) in new_words {- self.expand_marked_word(- MarkedWord {+ self.expand_annotated_word(+ AnnotatedWord {letters: new_word.clone(),- attributes: opp_attr.clone(),+ annotations: opposite_attributes.clone(),},- dest,+ word_map,);- let t_metadata = dest.get_metadata_mut_chars(&new_word).unwrap();- t_metadata.append(&metadata);- t_metadata.derived_from = Some(WordId::from_word_chars(&word.letters))+ // Update the metadata of the expanded word+ let target_metadata = word_map.get_metadata_mut_chars(&new_word).unwrap();+ target_metadata.append(&metadata);+ target_metadata.derived_from =+ Some(WordId::from_word_chars(&annotated_word.letters));}} else {+ // Simple case: no cross-product expansion neededfor (key, mut value) in new_words.into_iter() {- value.derived_from = Some(WordId::from_word_chars(&word.letters));+ value.derived_from = Some(WordId::from_word_chars(&annotated_word.letters));- if let Some(val) = dest.get_metadata_mut_chars(&key) {- val.append(&value);+ if let Some(existing_metadata) = word_map.get_metadata_mut_chars(&key) {+ // Merge with existing metadata+ existing_metadata.append(&value);} else {- dest.insert(WordMapEntry {+ // Add new entry+ word_map.insert(WordMapEntry {canonical_spelling: key,metadata: value,});@@ -142,38 +173,46 @@ impl AttributeList {}}- let mut full_metadata = gifted_metadata;- if let Some(prev_val) = dest.get_with_chars(&word.letters) {- full_metadata.append(&prev_val.metadata);+ // Finalize the metadata for the base word+ let mut full_metadata = base_metadata;++ // Merge with any existing metadata for this word+ if let Some(existing_metadata) = word_map.get_with_chars(&annotated_word.letters) {+ full_metadata.append(&existing_metadata.metadata);}- dest.insert(WordMapEntry {+ // Store the final metadata for the base word+ word_map.insert(WordMapEntry {metadata: full_metadata.clone(),- canonical_spelling: word.letters,+ canonical_spelling: annotated_word.letters,});+ // Process any conditional expansionsfor (letters, metadata, condition) in conditional_expansion_metadata {+ // Check if the condition is satisfied by the base word's metadatalet condition_satisfied = full_metadata.or(&condition) == full_metadata;if !condition_satisfied {continue;}- dest.get_metadata_mut_chars(&letters)+ // Apply the conditional metadata+ word_map+ .get_metadata_mut_chars(&letters).unwrap().append(&metadata);}}- /// Expand an iterator of marked words into strings.+ /// Expand an iterator of annotated words into strings./// Note that this does __not__ guarantee that produced words will be/// unique.- pub fn expand_marked_words(+ pub fn expand_annotated_words(&self,- words: impl IntoIterator<Item = MarkedWord>,+ words: impl IntoIterator<Item = AnnotatedWord>,dest: &mut WordMap,) {for word in words {- self.expand_marked_word(word, dest);+ self.expand_annotated_word(word, dest);}}@@ -234,9 +273,9 @@ impl AttributeList {}/// Gather metadata about the orthography of a word.-fn check_orthography(word: &MarkedWord) -> OrthFlags {+fn check_orthography(word: &AnnotatedWord) -> OrthFlags {use crate::char_ext::CharExt;- use crate::word_metadata_orthography::OrthFlags;+ use crate::dict_word_metadata_orthography::OrthFlags;let mut ortho_flags = OrthFlags::default();let mut all_lower = true;@@ -430,12 +469,12 @@ fn check_roman_group<I: Iterator<Item = char>>(#[cfg(test)]mod tests {use super::*;- use crate::word_metadata_orthography::OrthFlags;+ use crate::dict_word_metadata_orthography::OrthFlags;fn check_orthography_str(s: &str) -> OrthFlags {- let word = MarkedWord {+ let word = AnnotatedWord {letters: s.chars().collect(),- attributes: Vec::new(),+ annotations: Vec::new(),};check_orthography(&word)}diff --git a/harper-core/src/spell/rune/expansion.rs b/harper-core/src/spell/rune/expansion.rsindex a143e4af8..2a3a913b1 100644--- a/harper-core/src/spell/rune/expansion.rs+++ b/harper-core/src/spell/rune/expansion.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};use super::Error;use super::affix_replacement::{AffixReplacement, HumanReadableAffixReplacement};-use crate::WordMetadata;+use crate::DictWordMetadata;#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]#[serde(rename_all = "snake_case")]@@ -11,19 +11,19 @@ pub enum AffixEntryKind {Prefix,}+/// Defines how a word can be transformed and what metadata to apply#[derive(Debug, Clone)]pub struct Expansion {- /// If `!true`, this is a prefix- /// But if `true` it may be a prefix but may be a property only+ /// Whether this is a prefix or suffix expansionpub kind: AffixEntryKind,+ /// If true, allows this expansion to be combined with others (e.g., both prefix and suffix)pub cross_product: bool,+ /// The replacement rules that define how to modify the wordpub replacements: Vec<AffixReplacement>,- /// When the expansion is applied, the resulting word will have this- /// metadata appended to it.+ /// Metadata to apply to the transformed wordpub target: Vec<MetadataExpansion>,- /// When the expansion is applied, the __parent__ word will have this- /// metadata appended to it.- pub base_metadata: WordMetadata,+ /// Metadata to apply to the base word when this expansion is applied+ pub base_metadata: DictWordMetadata,}impl Expansion {@@ -44,8 +44,8 @@ impl Expansion {#[derive(Debug, Clone, Serialize, Deserialize)]pub struct MetadataExpansion {- pub metadata: WordMetadata,- pub if_base: Option<WordMetadata>,+ pub metadata: DictWordMetadata,+ pub if_base: Option<DictWordMetadata>,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -54,7 +54,7 @@ pub struct HumanReadableExpansion {pub cross_product: bool,pub replacements: Vec<HumanReadableAffixReplacement>,pub target: Vec<MetadataExpansion>,- pub base_metadata: WordMetadata,+ pub base_metadata: DictWordMetadata,}impl HumanReadableExpansion {@@ -81,5 +81,5 @@ pub struct Property {#[serde(default)]pub propagate: bool,/// The metadata applied to the word.- pub metadata: WordMetadata,+ pub metadata: DictWordMetadata,}diff --git a/harper-core/src/spell/rune/mod.rs b/harper-core/src/spell/rune/mod.rsindex 851c1444b..7fc48dd55 100644--- a/harper-core/src/spell/rune/mod.rs+++ b/harper-core/src/spell/rune/mod.rs@@ -81,7 +81,7 @@ mod tests {let mut expanded = WordMap::default();- attributes.expand_marked_words(words, &mut expanded);+ attributes.expand_annotated_words(words, &mut expanded);let expanded: HashSet<String> = expanded.into_iter()@@ -127,7 +127,7 @@ mod tests {let mut expanded = WordMap::default();- attributes.expand_marked_words(words, &mut expanded);+ attributes.expand_annotated_words(words, &mut expanded);let expanded: HashSet<String> = expanded.into_iter().map(|v| v.canonical_spelling.to_string())@@ -206,7 +206,7 @@ mod tests {let mut expanded = WordMap::default();- attributes.expand_marked_words(words, &mut expanded);+ attributes.expand_annotated_words(words, &mut expanded);let giant_data = expanded.get_with_str("giant").unwrap();assert!(giant_data.metadata.is_noun());diff --git a/harper-core/src/spell/rune/word_list.rs b/harper-core/src/spell/rune/word_list.rsindex 733b7c842..040114472 100644--- a/harper-core/src/spell/rune/word_list.rs+++ b/harper-core/src/spell/rune/word_list.rs@@ -2,15 +2,15 @@ use super::Error;use crate::CharString;#[derive(Debug, Clone)]-pub struct MarkedWord {+pub struct AnnotatedWord {pub letters: CharString,- pub attributes: Vec<char>,+ pub annotations: Vec<char>,}/// Parse a Rune word list////// Returns [`None`] if the given string is invalid.-pub fn parse_word_list(source: &str) -> Result<Vec<MarkedWord>, Error> {+pub fn parse_word_list(source: &str) -> Result<Vec<AnnotatedWord>, Error> {let mut lines = source.lines();let approx_item_count = lines@@ -44,9 +44,9 @@ pub fn parse_word_list(source: &str) -> Result<Vec<MarkedWord>, Error> {attr = None;}- words.push(MarkedWord {+ words.push(AnnotatedWord {letters: word.chars().collect(),- attributes: attr.unwrap_or_default().chars().collect(),+ annotations: attr.unwrap_or_default().chars().collect(),})}@@ -62,7 +62,7 @@ mod tests {fn can_parse_test_file() {let list = parse_word_list(TEST_WORD_LIST).unwrap();- assert_eq!(list.last().unwrap().attributes.len(), 0);+ assert_eq!(list.last().unwrap().annotations.len(), 0);assert_eq!(list.len(), 4);}}diff --git a/harper-core/src/spell/word_map.rs b/harper-core/src/spell/word_map.rsindex 15378bb17..8f97ec884 100644--- a/harper-core/src/spell/word_map.rs+++ b/harper-core/src/spell/word_map.rs@@ -1,6 +1,6 @@use hashbrown::{HashMap, hash_map::IntoValues};-use crate::{CharString, WordMetadata};+use crate::{CharString, DictWordMetadata};use super::WordId;@@ -12,7 +12,7 @@ pub struct WordMap {#[derive(Debug, Clone, Eq, PartialEq, Hash)]pub struct WordMapEntry {- pub metadata: WordMetadata,+ pub metadata: DictWordMetadata,pub canonical_spelling: CharString,}@@ -53,14 +53,14 @@ impl WordMap {pub fn get_metadata_mut_chars(&mut self,chars: impl AsRef<[char]>,- ) -> Option<&mut WordMetadata> {+ ) -> Option<&mut DictWordMetadata> {let id = WordId::from_word_chars(chars);self.get_metadata_mut(&id)}/// Borrow a word's metadata mutably- pub fn get_metadata_mut(&mut self, id: &WordId) -> Option<&mut WordMetadata> {+ pub fn get_metadata_mut(&mut self, id: &WordId) -> Option<&mut DictWordMetadata> {self.inner.get_mut(id).map(|v| &mut v.metadata)}diff --git a/harper-core/src/title_case.rs b/harper-core/src/title_case.rsindex 453825abc..13625a8ec 100644--- a/harper-core/src/title_case.rs+++ b/harper-core/src/title_case.rs@@ -90,7 +90,7 @@ fn should_capitalize_token(tok: &Token, source: &[char], dict: &impl Dictionary)let mut metadata = Cow::Borrowed(metadata);- if let Some(metadata_lower) = dict.get_word_metadata(&chars_lower) {+ if let Some(metadata_lower) = dict.get_lexeme_metadata(&chars_lower) {metadata = Cow::Owned(metadata.clone().or(&metadata_lower));}diff --git a/harper-core/src/token_kind.rs b/harper-core/src/token_kind.rsindex 04530dd6f..10a1bcf55 100644--- a/harper-core/src/token_kind.rs+++ b/harper-core/src/token_kind.rs@@ -2,15 +2,15 @@ use harper_brill::UPOS;use is_macro::Is;use serde::{Deserialize, Serialize};-use crate::{Number, Punctuation, Quote, TokenKind::Word, WordMetadata};+use crate::{DictWordMetadata, Number, Punctuation, Quote, TokenKind::Word};-/// Generate wrapper code to pass a function call to the inner [`WordMetadata`],+/// Generate wrapper code to pass a function call to the inner [`DictWordMetadata`],/// if the token is indeed a word, while also emitting method-level documentation.macro_rules! delegate_to_metadata {($($method:ident),* $(,)?) => {$(#[doc = concat!(- "Delegates to [`WordMetadata::",+ "Delegates to [`DictWordMetadata::",stringify!($method),"`] when this token is a word.\n\n","Returns `false` if the token is not a word."@@ -33,7 +33,7 @@ macro_rules! delegate_to_metadata {#[serde(tag = "kind", content = "value")]pub enum TokenKind {/// `None` if the word does not exist in the dictionary.- Word(Option<WordMetadata>),+ Word(Option<DictWordMetadata>),Punctuation(Punctuation),Decade,Number(Number),@@ -53,7 +53,7 @@ pub enum TokenKind {}impl TokenKind {- // Word metadata delegation methods grouped by part of speech+ // DictWord metadata delegation methods grouped by part of speechdelegate_to_metadata! {// Nominal methods (nouns and pronouns)is_nominal,@@ -131,7 +131,7 @@ impl TokenKind {is_roman_numerals}- // Word metadata delegation methods not generated by macro+ // DictWord metadata delegation methods not generated by macropub fn is_preposition(&self) -> bool {let Word(Some(metadata)) = self else {return false;@@ -139,6 +139,8 @@ impl TokenKind {metadata.preposition}+ // Generic word is-methods+pub fn is_common_word(&self) -> bool {let Word(Some(metadata)) = self else {return true;@@ -369,4 +371,29 @@ mod tests {let tk = &doc.tokens().next().unwrap().kind;assert!(!tk.is_countable_noun());}++ #[test]+ fn oov_word_is_oov() {+ let doc = Document::new_plain_english_curated("nonexistentword");+ let tk = &doc.tokens().next().unwrap().kind;+ assert!(tk.is_oov());+ }++ #[test]+ fn known_word_is_not_oov() {+ let doc = Document::new_plain_english_curated("car");+ let tk = &doc.tokens().next().unwrap().kind;+ assert!(!tk.is_oov());+ }++ #[test]+ fn non_word_tokens_are_not_oov() {+ let doc = Document::new_plain_english_curated("Hello, world!");+ let tokens: Vec<_> = doc.tokens().collect();++ // Comma should not be OOV+ assert!(!tokens[1].kind.is_oov());+ // Exclamation mark should not be OOV+ assert!(!tokens[3].kind.is_oov());+ }}diff --git a/harper-core/tests/pos_tags.rs b/harper-core/tests/pos_tags.rsindex 026888bb0..de5827027 100644--- a/harper-core/tests/pos_tags.rs+++ b/harper-core/tests/pos_tags.rs@@ -24,11 +24,11 @@//!//! ## Tags//!-//! Tags are assigned based on the [`TokenKind`] and [`WordMetadata`] of a+//! Tags are assigned based on the [`TokenKind`] and [`DictWordMetadata`] of a//! token.//!//! - The tag of [`TokenKind::Word`] variants depends on their-//! [`WordMetadata`]. If they don't have any metadata, they are denoted by `?`.+//! [`DictWordMetadata`]. If they don't have any metadata, they are denoted by `?`.//! Otherwise, the tag is constructed as follows://!//! - Nouns are denoted by `N`.@@ -80,14 +80,14 @@//! - All other token kinds are denoted by their variant name.use std::borrow::Cow;+use harper_core::dict_word_metadata::VerbFormFlags;+use harper_core::dict_word_metadata_orthography::OrthFlags;use harper_core::spell::FstDictionary;-use harper_core::word_metadata::VerbFormFlags;-use harper_core::word_metadata_orthography::OrthFlags;-use harper_core::{Degree, Dialect, Document, TokenKind, WordMetadata};+use harper_core::{Degree, Dialect, DictWordMetadata, Document, TokenKind};mod snapshot;-fn format_word_tag(word: &WordMetadata) -> String {+fn format_word_tag(word: &DictWordMetadata) -> String {// These tags are inspired by the Penn Treebank POS tagsetlet mut tags = String::new();fn add(t: &str, tags: &mut String) {@@ -243,7 +243,7 @@ fn format_word_tag(word: &WordMetadata) -> String {/// Returns a vector of dialect annotation strings for the given word./// Handles both individual dialects and special groupings (NoAm, Comm).-fn get_dialect_annotations(word: &WordMetadata) -> Vec<&'static str> {+fn get_dialect_annotations(word: &DictWordMetadata) -> Vec<&'static str> {let mut annotations = Vec::new();let mut north_america = false;let mut commonwealth = false;diff --git a/harper-ls/src/backend.rs b/harper-ls/src/backend.rsindex 03e64cca7..1869959ca 100644--- a/harper-ls/src/backend.rs+++ b/harper-ls/src/backend.rs@@ -18,7 +18,7 @@ use harper_core::parsers::{CollapseIdentifiers, IsolateEnglish, Markdown, OrgMode, Parser, PlainEnglish,};use harper_core::spell::{Dictionary, FstDictionary, MergedDictionary, MutableDictionary};-use harper_core::{Dialect, Document, IgnoredLints, WordMetadata};+use harper_core::{Dialect, DictWordMetadata, Document, IgnoredLints};use harper_html::HtmlParser;use harper_literate_haskell::LiterateHaskellParser;use harper_stats::{Record, Stats};@@ -675,7 +675,7 @@ impl LanguageServer for Backend {let file_uri = second.parse().unwrap();let mut dict = self.load_user_dictionary().await;- dict.append_word(word, WordMetadata::default());+ dict.append_word(word, DictWordMetadata::default());self.save_user_dictionary(dict).await.map_err(|err| error!("{err}"))@@ -696,7 +696,7 @@ impl LanguageServer for Backend {let file_uri = second.parse().unwrap();let mut dict = self.load_workspace_dictionary().await;- dict.append_word(word, WordMetadata::default());+ dict.append_word(word, DictWordMetadata::default());self.save_workspace_dictionary(dict).await.map_err(|err| error!("{err}"))@@ -726,7 +726,7 @@ impl LanguageServer for Backend {return Ok(None);}};- dict.append_word(word, WordMetadata::default());+ dict.append_word(word, DictWordMetadata::default());self.save_file_dictionary(&file_uri, dict).awaitdiff --git a/harper-ls/src/dictionary_io.rs b/harper-ls/src/dictionary_io.rsindex de0a12f3a..6b519a4cd 100644--- a/harper-ls/src/dictionary_io.rs+++ b/harper-ls/src/dictionary_io.rs@@ -1,9 +1,9 @@-use harper_core::word_metadata::DialectFlags;+use harper_core::dict_word_metadata::DialectFlags;use itertools::Itertools;use std::path::Path;use harper_core::spell::{Dictionary, MutableDictionary};-use harper_core::{Dialect, WordMetadata};+use harper_core::{Dialect, DictWordMetadata};use tokio::fs::{self, File};use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader, BufWriter, Result};@@ -61,7 +61,7 @@ async fn dict_from_word_list(dict.extend_words(str.lines().map(|l| {(l.chars().collect::<Vec<char>>(),- WordMetadata {+ DictWordMetadata {dialects: DialectFlags::from_dialect(dialect),..Default::default()},@@ -106,7 +106,8 @@ mod tests {fn get_test_unsorted_dict() -> MutableDictionary {let mut test_unsorted_dict = MutableDictionary::new();test_unsorted_dict.extend_words(- TEST_UNSORTED_WORDS.map(|w| (w.chars().collect::<Vec<_>>(), WordMetadata::default())),+ TEST_UNSORTED_WORDS+ .map(|w| (w.chars().collect::<Vec<_>>(), DictWordMetadata::default())),);test_unsorted_dict}diff --git a/harper-tree-sitter/src/lib.rs b/harper-tree-sitter/src/lib.rsindex d5c37e2b0..3d7a0a94b 100644--- a/harper-tree-sitter/src/lib.rs+++ b/harper-tree-sitter/src/lib.rs@@ -1,7 +1,7 @@use std::collections::HashSet;use harper_core::spell::MutableDictionary;-use harper_core::{Mask, Masker, Span, WordMetadata};+use harper_core::{DictWordMetadata, Mask, Masker, Span};use tree_sitter::{Language, Node, Tree, TreeCursor};/// A Harper [`Masker`] that wraps a given tree-sitter language and a condition,@@ -50,7 +50,7 @@ impl TreeSitterMasker {let idents: Vec<_> = idents.into_iter()- .map(|ident| (ident, WordMetadata::default()))+ .map(|ident| (ident, DictWordMetadata::default())).collect();let mut dictionary = MutableDictionary::new();diff --git a/harper-typst/tests/tests.rs b/harper-typst/tests/tests.rsindex 762142dec..781c86eaf 100644--- a/harper-typst/tests/tests.rs+++ b/harper-typst/tests/tests.rs@@ -1,7 +1,7 @@use itertools::Itertools;use ordered_float::OrderedFloat;-use harper_core::{Document, NounData, Number, Punctuation, TokenKind, WordMetadata};+use harper_core::{DictWordMetadata, Document, NounData, Number, Punctuation, TokenKind};use harper_typst::Typst;#[test]@@ -262,7 +262,7 @@ fn smart_apostrophe_newline() {assert!(matches!(token_kinds.as_slice(),&[- TokenKind::Word(Some(WordMetadata {+ TokenKind::Word(Some(DictWordMetadata {noun: Some(NounData {is_possessive: Some(true),..diff --git a/harper-wasm/src/lib.rs b/harper-wasm/src/lib.rsindex a017ff7be..5bdacbc72 100644--- a/harper-wasm/src/lib.rs+++ b/harper-wasm/src/lib.rs@@ -8,7 +8,7 @@ use harper_core::language_detection::is_doc_likely_english;use harper_core::linting::{LintGroup, Linter as _};use harper_core::parsers::{IsolateEnglish, Markdown, Parser, PlainEnglish};use harper_core::{- CharString, Document, IgnoredLints, LintContext, Lrc, WordMetadata, remove_overlaps,+ CharString, DictWordMetadata, Document, IgnoredLints, LintContext, Lrc, remove_overlaps,spell::{Dictionary, FstDictionary, MergedDictionary, MutableDictionary},};use harper_stats::{Record, RecordKind, Stats};@@ -305,7 +305,7 @@ impl Linter {.extend_words(additional_words.iter().map(|word| {(word.chars().collect::<CharString>(),- WordMetadata::default(),+ DictWordMetadata::default(),)}));diff --git a/packages/web/src/routes/docs/contributors/dictionary/+page.md b/packages/web/src/routes/docs/contributors/dictionary/+page.mdindex 23aaf14f3..00ca1eb32 100644--- a/packages/web/src/routes/docs/contributors/dictionary/+page.md+++ b/packages/web/src/routes/docs/contributors/dictionary/+page.md@@ -34,16 +34,16 @@ In `annotations.json`, this expansion rule looks like this:"condition": "."}],- // The word metadata that should be applied to the expanded word.+ // The metadata that should be applied to the expanded word."target": {},- // The word metadata that should be applied to the base word.+ // The metadata that should be applied to the base word."base_metadata": {}}}```Those familiar with `hunspell` might notice some similarities with their dictionary format.-The main differences are the [metadata fields.](https://docs.rs/harper-core/latest/harper_core/word_metadata/struct.WordMetadata.html)+The main differences are the [metadata fields.](https://docs.rs/harper-core/latest/harper_core/lexeme_metadata/struct.LexemeMetadata.html)There is a separate section, `properties` that is specifically for special rules that add only metadata to the words they're applied to.