Skip to content

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

refactor(core): remove `Copy` from `WordMetadata`

Elijah Pottere09baf9228b8
diff --git a/harper-cli/src/main.rs b/harper-cli/src/main.rs
index 895010539..1e9cac48e 100644
--- a/harper-cli/src/main.rs
+++ b/harper-cli/src/main.rs
@@ -334,7 +334,7 @@ fn main() -> anyhow::Result<()> {
let mut words = HashMap::new();
for word in doc.iter_words() {
- let chars = doc.get_span_content(word.span);
+ let chars = doc.get_span_content(&word.span);
words
.entry(chars.to_lower())
diff --git a/harper-comments/src/comment_parsers/javadoc.rs b/harper-comments/src/comment_parsers/javadoc.rs
index ef071488c..02f72affd 100644
--- a/harper-comments/src/comment_parsers/javadoc.rs
+++ b/harper-comments/src/comment_parsers/javadoc.rs
@@ -24,7 +24,7 @@ impl Parser for JavaDoc {
let mut cursor = 0;
while cursor < tokens.len() {
- let maybe_newline = tokens[cursor];
+ let maybe_newline = &tokens[cursor];
if let TokenKind::Newline(_) = maybe_newline.kind {
cursor += 1;
@@ -34,7 +34,7 @@ impl Parser for JavaDoc {
break;
}
- let maybe_removable = tokens[cursor];
+ let maybe_removable = &tokens[cursor];
if matches!(
maybe_removable.kind,
@@ -61,10 +61,10 @@ impl Parser for JavaDoc {
// Mark @tags as unlintable
for i in 3..tokens.len() {
- let a = tokens[i - 3];
- let b = tokens[i - 2];
- let c = tokens[i - 1];
- let d = tokens[i];
+ let a = &tokens[i - 3];
+ let b = &tokens[i - 2];
+ let c = &tokens[i - 1];
+ let d = &tokens[i];
if a.kind.is_at() && b.kind.is_word() && c.kind.is_space() && d.kind.is_word() {
tokens[i - 3].kind = TokenKind::Unlintable;
diff --git a/harper-comments/src/comment_parsers/jsdoc.rs b/harper-comments/src/comment_parsers/jsdoc.rs
index e7b46e00a..2aefb1286 100644
--- a/harper-comments/src/comment_parsers/jsdoc.rs
+++ b/harper-comments/src/comment_parsers/jsdoc.rs
@@ -184,7 +184,7 @@ mod tests {
assert!(matches!(
document
.tokens()
- .map(|t| t.kind)
+ .map(|t| t.kind.clone())
.collect::<Vec<_>>()
.as_slice(),
&[
diff --git a/harper-core/src/currency.rs b/harper-core/src/currency.rs
index 7e339c5c8..4ddc39b54 100644
--- a/harper-core/src/currency.rs
+++ b/harper-core/src/currency.rs
@@ -62,7 +62,7 @@ impl Currency {
}
/// Format an amount of the specific currency.
- pub fn format_amount(&self, amount: Number) -> String {
+ pub fn format_amount(&self, amount: &Number) -> String {
let c = self.to_char();
let amount = amount.to_string();
diff --git a/harper-core/src/document.rs b/harper-core/src/document.rs
index 9f1abbaf1..358d3dc37 100644
--- a/harper-core/src/document.rs
+++ b/harper-core/src/document.rs
@@ -131,7 +131,7 @@ impl Document {
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 = found_meta
+ *meta = found_meta.cloned()
}
}
}
@@ -181,7 +181,7 @@ impl Document {
fn condense_indices(&mut self, indices: &[usize], stretch_len: usize) {
// Update spans
for idx in indices {
- let end_tok = self.tokens[idx + stretch_len - 1];
+ let end_tok = self.tokens[idx + stretch_len - 1].clone();
let start_tok = &mut self.tokens[*idx];
start_tok.span.end = end_tok.span.end;
@@ -198,7 +198,7 @@ impl Document {
let mut iter = indices.iter().peekable();
while let (Some(a_idx), b) = (iter.next(), iter.peek()) {
- self.tokens.push(old[*a_idx]);
+ self.tokens.push(old[*a_idx].clone());
if let Some(b_idx) = b {
self.tokens
@@ -215,7 +215,7 @@ impl Document {
);
}
- pub fn get_token_at_char_index(&self, char_index: usize) -> Option<Token> {
+ pub fn get_token_at_char_index(&self, char_index: usize) -> Option<&Token> {
let index = self
.tokens
.binary_search_by(|t| {
@@ -227,17 +227,17 @@ impl Document {
})
.ok()?;
- Some(self.tokens[index])
+ Some(&self.tokens[index])
}
/// Defensively attempt to grab a specific token.
- pub fn get_token(&self, index: usize) -> Option<Token> {
- self.tokens.get(index).copied()
+ pub fn get_token(&self, index: usize) -> Option<&Token> {
+ self.tokens.get(index)
}
/// Get an iterator over all the tokens contained in the document.
- pub fn tokens(&self) -> impl Iterator<Item = Token> + '_ {
- self.tokens.iter().copied()
+ pub fn tokens(&self) -> impl Iterator<Item = &Token> + '_ {
+ self.tokens.iter()
}
/// Get an iterator over all the tokens contained in the document.
@@ -245,16 +245,16 @@ impl Document {
self.tokens().map(|token| token.to_fat(&self.source))
}
- pub fn get_span_content(&self, span: Span) -> &[char] {
+ pub fn get_span_content(&self, span: &Span) -> &[char] {
span.get_content(&self.source)
}
- pub fn get_span_content_str(&self, span: Span) -> String {
+ pub fn get_span_content_str(&self, span: &Span) -> String {
String::from_iter(self.get_span_content(span))
}
pub fn get_full_string(&self) -> String {
- self.get_span_content_str(Span {
+ self.get_span_content_str(&Span {
start: 0,
end: self.source.len(),
})
@@ -305,13 +305,13 @@ impl Document {
let mut replace_starts = Vec::new();
for idx in 0..self.tokens.len() - 1 {
- let b = self.tokens[idx + 1];
- let a = self.tokens[idx];
+ let b = &self.tokens[idx + 1];
+ let a = &self.tokens[idx];
// TODO: Allow spaces between `a` and `b`
- if let (TokenKind::Number(..), TokenKind::Word(..)) = (a.kind, b.kind) {
- if let Some(found_suffix) = NumberSuffix::from_chars(self.get_span_content(b.span))
+ if let (TokenKind::Number(..), TokenKind::Word(..)) = (&a.kind, &b.kind) {
+ if let Some(found_suffix) = NumberSuffix::from_chars(self.get_span_content(&b.span))
{
self.tokens[idx].kind.as_mut_number().unwrap().suffix = Some(found_suffix);
replace_starts.push(idx);
@@ -461,8 +461,8 @@ impl Document {
let mut initialism_start = None;
loop {
- let a = self.tokens[cursor - 1];
- let b = self.tokens[cursor];
+ let a = &self.tokens[cursor - 1];
+ let b = &self.tokens[cursor];
let is_initialism_chunk = a.kind.is_word() && a.span.len() == 1 && b.kind.is_period();
@@ -537,11 +537,11 @@ impl Document {
macro_rules! create_fns_on_doc {
($thing:ident) => {
paste! {
- fn [< first_ $thing >](&self) -> Option<Token> {
+ fn [< first_ $thing >](&self) -> Option<&Token> {
self.tokens.[< first_ $thing >]()
}
- fn [< last_ $thing >](&self) -> Option<Token> {
+ fn [< last_ $thing >](&self) -> Option<&Token> {
self.tokens.[< last_ $thing >]()
}
@@ -553,7 +553,7 @@ macro_rules! create_fns_on_doc {
self.tokens.[< iter_ $thing _indices >]()
}
- fn [<iter_ $thing s>](&self) -> impl Iterator<Item = Token> + '_ {
+ fn [<iter_ $thing s>](&self) -> impl Iterator<Item = &Token> + '_ {
self.tokens.[< iter_ $thing s >]()
}
}
@@ -581,11 +581,11 @@ impl TokenStringExt for Document {
create_fns_on_doc!(likely_homograph);
create_fns_on_doc!(comma);
- fn first_sentence_word(&self) -> Option<Token> {
+ fn first_sentence_word(&self) -> Option<&Token> {
self.tokens.first_sentence_word()
}
- fn first_non_whitespace(&self) -> Option<Token> {
+ fn first_non_whitespace(&self) -> Option<&Token> {
self.tokens.first_non_whitespace()
}
@@ -597,7 +597,7 @@ impl TokenStringExt for Document {
self.tokens.iter_linking_verb_indices()
}
- fn iter_linking_verbs(&self) -> impl Iterator<Item = Token> + '_ {
+ fn iter_linking_verbs(&self) -> impl Iterator<Item = &Token> + '_ {
self.tokens.iter_linking_verbs()
}
@@ -617,7 +617,7 @@ impl TokenStringExt for Document {
impl Display for Document {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for token in &self.tokens {
- write!(f, "{}", self.get_span_content_str(token.span))?;
+ write!(f, "{}", self.get_span_content_str(&token.span))?;
}
Ok(())
@@ -680,7 +680,7 @@ mod tests {
fn assert_token_count(source: &str, count: usize) {
let document = Document::new_plain_english_curated(source);
- dbg!(document.tokens().map(|t| t.kind).collect_vec());
+ dbg!(document.tokens().map(|t| t.kind.clone()).collect_vec());
assert_eq!(document.tokens.len(), count);
}
diff --git a/harper-core/src/linting/an_a.rs b/harper-core/src/linting/an_a.rs
index 2fe05e1b3..bc1bf213f 100644
--- a/harper-core/src/linting/an_a.rs
+++ b/harper-core/src/linting/an_a.rs
@@ -24,11 +24,11 @@ impl Linter for AnA {
continue;
}
- let first = chunk[first_idx];
- let second = chunk[second_idx];
+ let first = &chunk[first_idx];
+ let second = &chunk[second_idx];
- let chars_first = document.get_span_content(first.span);
- let chars_second = document.get_span_content(second.span);
+ let chars_first = document.get_span_content(&first.span);
+ let chars_second = document.get_span_content(&second.span);
// Break the second word on hyphens for this lint.
// Example: "An ML-based" is an acceptable noun phrase.
let chars_second = chars_second
diff --git a/harper-core/src/linting/capitalize_personal_pronouns.rs b/harper-core/src/linting/capitalize_personal_pronouns.rs
index 042fbcd8b..5558a36d1 100644
--- a/harper-core/src/linting/capitalize_personal_pronouns.rs
+++ b/harper-core/src/linting/capitalize_personal_pronouns.rs
@@ -15,7 +15,7 @@ impl Linter for CapitalizePersonalPronouns {
pronoun: Some(_), ..
})) = tok.kind
{
- if document.get_span_content(tok.span) == ['i'] {
+ if document.get_span_content(&tok.span) == ['i'] {
lints.push(Lint {
span: tok.span,
lint_kind: LintKind::Capitalization,
diff --git a/harper-core/src/linting/compound_nouns/general_compound_nouns.rs b/harper-core/src/linting/compound_nouns/general_compound_nouns.rs
index 11263f7b8..7a50fd897 100644
--- a/harper-core/src/linting/compound_nouns/general_compound_nouns.rs
+++ b/harper-core/src/linting/compound_nouns/general_compound_nouns.rs
@@ -75,7 +75,7 @@ impl PatternLinter for GeneralCompoundNouns {
// If the pattern matched, this will not return `None`.
let word =
self.split_pattern
- .get_merged_word(matched_tokens[2], matched_tokens[4], source)?;
+ .get_merged_word(&matched_tokens[2], &matched_tokens[4], source)?;
Some(Lint {
span,
diff --git a/harper-core/src/linting/compound_nouns/implied_instantiated_compound_nouns.rs b/harper-core/src/linting/compound_nouns/implied_instantiated_compound_nouns.rs
index f88745b41..cd804d6fe 100644
--- a/harper-core/src/linting/compound_nouns/implied_instantiated_compound_nouns.rs
+++ b/harper-core/src/linting/compound_nouns/implied_instantiated_compound_nouns.rs
@@ -42,7 +42,7 @@ impl PatternLinter for ImpliedInstantiatedCompoundNouns {
// If the pattern matched, this will not return `None`.
let word =
self.split_pattern
- .get_merged_word(matched_tokens[0], matched_tokens[2], source)?;
+ .get_merged_word(&matched_tokens[0], &matched_tokens[2], source)?;
Some(Lint {
span,
diff --git a/harper-core/src/linting/compound_nouns/implied_ownership_compound_nouns.rs b/harper-core/src/linting/compound_nouns/implied_ownership_compound_nouns.rs
index 820da721b..b144f0369 100644
--- a/harper-core/src/linting/compound_nouns/implied_ownership_compound_nouns.rs
+++ b/harper-core/src/linting/compound_nouns/implied_ownership_compound_nouns.rs
@@ -41,7 +41,7 @@ impl PatternLinter for ImpliedOwnershipCompoundNouns {
// If the pattern matched, this will not return `None`.
let word =
self.split_pattern
- .get_merged_word(matched_tokens[2], matched_tokens[4], source)?;
+ .get_merged_word(&matched_tokens[2], &matched_tokens[4], source)?;
Some(Lint {
span,
diff --git a/harper-core/src/linting/currency_placement.rs b/harper-core/src/linting/currency_placement.rs
index 1b13862a4..2e1826bc8 100644
--- a/harper-core/src/linting/currency_placement.rs
+++ b/harper-core/src/linting/currency_placement.rs
@@ -1,6 +1,6 @@
use itertools::Itertools;
-use crate::{Document, Token, TokenStringExt, remove_overlaps};
+use crate::{Document, Span, Token, TokenStringExt, remove_overlaps};
use super::{Lint, LintKind, Linter, Suggestion};
@@ -13,7 +13,7 @@ impl Linter for CurrencyPlacement {
for chunk in document.iter_chunks() {
for (a, b) in chunk.iter().tuple_windows() {
- lints.extend(generate_lint_for_tokens(*a, *b, document));
+ lints.extend(generate_lint_for_tokens(a, b, document));
}
for (p, a, b, c) in chunk.iter().tuple_windows() {
@@ -21,7 +21,7 @@ impl Linter for CurrencyPlacement {
continue;
}
- lints.extend(generate_lint_for_tokens(*a, *c, document));
+ lints.extend(generate_lint_for_tokens(a, c, document));
}
}
@@ -36,21 +36,16 @@ impl Linter for CurrencyPlacement {
}
// Given two tokens that may have an error, check if they do and create a [`Lint`].
-fn generate_lint_for_tokens(a: Token, b: Token, document: &Document) -> Option<Lint> {
- let matched_tokens = [a, b];
-
- let punct = matched_tokens
- .first_punctuation()?
- .kind
- .expect_punctuation();
+fn generate_lint_for_tokens(a: &Token, b: &Token, document: &Document) -> Option<Lint> {
+ let punct = a.kind.as_punctuation().or(b.kind.as_punctuation())?;
let currency = punct.as_currency()?;
- let number = matched_tokens.first_number()?.kind.expect_number();
+ let number = a.kind.as_number().or(b.kind.as_number())?;
- let span = matched_tokens.span().unwrap();
+ let span = Span::new(a.span.start, b.span.end);
let correct: Vec<_> = currency.format_amount(number).chars().collect();
- let actual = document.get_span_content(span);
+ let actual = document.get_span_content(&span);
if correct != actual {
Some(Lint {
diff --git a/harper-core/src/linting/ellipsis_length.rs b/harper-core/src/linting/ellipsis_length.rs
index 64052f1b1..adee68447 100644
--- a/harper-core/src/linting/ellipsis_length.rs
+++ b/harper-core/src/linting/ellipsis_length.rs
@@ -13,7 +13,7 @@ impl Linter for EllipsisLength {
let mut lints = Vec::new();
for tok in document.iter_ellipsiss() {
- let tok_content = document.get_span_content(tok.span);
+ let tok_content = document.get_span_content(&tok.span);
if tok_content.is_empty() {
continue;
diff --git a/harper-core/src/linting/hop_hope/to_hop.rs b/harper-core/src/linting/hop_hope/to_hop.rs
index 192bfb88e..e97b69866 100644
--- a/harper-core/src/linting/hop_hope/to_hop.rs
+++ b/harper-core/src/linting/hop_hope/to_hop.rs
@@ -42,7 +42,7 @@ impl PatternLinter for ToHop {
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
- let offending_word = matched_tokens[0];
+ let offending_word = &matched_tokens[0];
let word_chars = offending_word.span.get_content(source);
let word = word_chars.to_string();
let correct = Self::to_correct(&word)?;
diff --git a/harper-core/src/linting/hop_hope/to_hope.rs b/harper-core/src/linting/hop_hope/to_hope.rs
index 15c667c01..6fd1aa5b6 100644
--- a/harper-core/src/linting/hop_hope/to_hope.rs
+++ b/harper-core/src/linting/hop_hope/to_hope.rs
@@ -28,7 +28,7 @@ impl PatternLinter for ToHope {
}
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {
- let offending_word = matched_tokens[2];
+ let offending_word = &matched_tokens[2];
let word_chars = offending_word.span.get_content(source);
Some(Lint {
diff --git a/harper-core/src/linting/hyphenate_number_day.rs b/harper-core/src/linting/hyphenate_number_day.rs
index 8d6cfd684..7a17331df 100644
--- a/harper-core/src/linting/hyphenate_number_day.rs
+++ b/harper-core/src/linting/hyphenate_number_day.rs
@@ -42,8 +42,8 @@ impl PatternLinter for HyphenateNumberDay {
}
fn match_to_lint(&self, matched_tokens: &[Token], _source: &[char]) -> Option<Lint> {
- let number = matched_tokens[0].kind.expect_number();
- let space = matched_tokens[1];
+ let number = matched_tokens[0].kind.as_number()?;
+ let space = &matched_tokens[1];
Some(Lint {
span: space.span,
diff --git a/harper-core/src/linting/left_right_hand.rs b/harper-core/src/linting/left_right_hand.rs
index 0d641c025..d4aaddde8 100644
--- a/harper-core/src/linting/left_right_hand.rs
+++ b/harper-core/src/linting/left_right_hand.rs
@@ -30,7 +30,7 @@ impl PatternLinter for LeftRightHand {
}
fn match_to_lint(&self, matched_tokens: &[Token], _source: &[char]) -> Option<Lint> {
- let space = matched_tokens[1];
+ let space = &matched_tokens[1];
Some(Lint {
span: space.span,
diff --git a/harper-core/src/linting/linking_verbs.rs b/harper-core/src/linting/linking_verbs.rs
index 905e4aca2..cc71dabf7 100644
--- a/harper-core/src/linting/linking_verbs.rs
+++ b/harper-core/src/linting/linking_verbs.rs
@@ -1,4 +1,5 @@
use super::{Lint, LintKind, Linter};
+use crate::CharStringExt;
use crate::Document;
use crate::TokenStringExt;
@@ -13,25 +14,22 @@ impl Linter for LinkingVerbs {
for chunk in document.iter_chunks() {
// The word prior to "is" must be a nominal (noun or pronoun).
for idx in chunk.iter_linking_verb_indices() {
- let linking_verb = chunk[idx];
- let linking_verb_text = document.get_span_content_str(linking_verb.span);
-
+ let linking_verb = &chunk[idx];
if let Some(prev_word) = &chunk[0..idx].last_word() {
- if !prev_word
- .kind
- .as_word()
- .unwrap()
- .is_some_and(|m| m.is_nominal())
- {
- output.push(Lint {
- span: linking_verb.span,
- lint_kind: LintKind::Miscellaneous,
- message: format!(
- "Linking verbs like “{}” must be preceded by a noun or pronoun.",
- linking_verb_text
- ),
- ..Default::default()
- })
+ if let Some(metadata) = prev_word.kind.as_word().unwrap() {
+ if !metadata.is_nominal() {
+ let linking_verb_text = document.get_span_content(&linking_verb.span);
+
+ output.push(Lint {
+ span: linking_verb.span,
+ lint_kind: LintKind::Miscellaneous,
+ message: format!(
+ "Linking verbs like “{}” must be preceded by a noun or pronoun.",
+ linking_verb_text.to_string()
+ ),
+ ..Default::default()
+ })
+ }
}
}
}
diff --git a/harper-core/src/linting/lint_group.rs b/harper-core/src/linting/lint_group.rs
index 9eeba6f89..8e46b9fe6 100644
--- a/harper-core/src/linting/lint_group.rs
+++ b/harper-core/src/linting/lint_group.rs
@@ -379,7 +379,7 @@ impl Linter for LintGroup {
continue;
};
- let chunk_chars = document.get_span_content(chunk_span);
+ let chunk_chars = document.get_span_content(&chunk_span);
let config_hash = self.hasher_builder.hash_one(&self.config);
let key = (chunk_chars.into(), config_hash);
diff --git a/harper-core/src/linting/matcher.rs b/harper-core/src/linting/matcher.rs
index 7016af0c4..b39559327 100644
--- a/harper-core/src/linting/matcher.rs
+++ b/harper-core/src/linting/matcher.rs
@@ -15,7 +15,7 @@ impl PatternToken {
if token.kind.is_word() {
Self {
kind: token.kind.with_default_data(),
- content: Some(document.get_span_content(token.span).into()),
+ content: Some(document.get_span_content(&token.span).into()),
}
} else {
Self {
@@ -250,7 +250,7 @@ impl Linter for Matcher {
break;
};
- let t_pattern = PatternToken::from_token(token, document);
+ let t_pattern = PatternToken::from_token(token.clone(), document);
if t_pattern != *pattern {
break;
diff --git a/harper-core/src/linting/merge_words.rs b/harper-core/src/linting/merge_words.rs
index 7e945a9fc..108ff2106 100644
--- a/harper-core/src/linting/merge_words.rs
+++ b/harper-core/src/linting/merge_words.rs
@@ -35,8 +35,8 @@ impl Linter for MergeWords {
continue;
}
- let a_chars = document.get_span_content(a.span);
- let b_chars = document.get_span_content(b.span);
+ let a_chars = document.get_span_content(&a.span);
+ let b_chars = document.get_span_content(&b.span);
if (a_chars.len() == 1 && a_chars[0].is_uppercase())
|| (b_chars.len() == 1 && b_chars[0].is_uppercase())
diff --git a/harper-core/src/linting/modal_of.rs b/harper-core/src/linting/modal_of.rs
index 7281efa55..308e4c5d8 100644
--- a/harper-core/src/linting/modal_of.rs
+++ b/harper-core/src/linting/modal_of.rs
@@ -87,7 +87,7 @@ impl PatternLinter for ModalOf {
if w3_text.as_str() != "of" {
return None;
}
- let w1_kind = matched_toks.first().unwrap().kind;
+ let w1_kind = &matched_toks.first().unwrap().kind;
// the might of something, great might of something
if w1_kind.is_adjective() || w1_kind.is_determiner() {
return None;
diff --git a/harper-core/src/linting/no_oxford_comma.rs b/harper-core/src/linting/no_oxford_comma.rs
index be58c6228..74634478a 100644
--- a/harper-core/src/linting/no_oxford_comma.rs
+++ b/harper-core/src/linting/no_oxford_comma.rs
@@ -29,7 +29,7 @@ impl NoOxfordComma {
fn match_to_lint(&self, matched_toks: &[Token], _source: &[char]) -> Option<Lint> {
let last_comma_index = matched_toks.last_comma_index()?;
- let offender = matched_toks[last_comma_index];
+ let offender = &matched_toks[last_comma_index];
Some(Lint {
span: offender.span,
diff --git a/harper-core/src/linting/number_suffix_capitalization.rs b/harper-core/src/linting/number_suffix_capitalization.rs
index cc3dda170..d4d4205e5 100644
--- a/harper-core/src/linting/number_suffix_capitalization.rs
+++ b/harper-core/src/linting/number_suffix_capitalization.rs
@@ -18,7 +18,7 @@ impl Linter for NumberSuffixCapitalization {
let suffix_span = Span::new_with_len(number_tok.span.end, 2)
.pulled_by(2)
.unwrap();
- let chars = document.get_span_content(suffix_span);
+ let chars = document.get_span_content(&suffix_span);
if chars.iter().any(|c| !c.is_lowercase()) {
output.push(Lint {
diff --git a/harper-core/src/linting/oxford_comma.rs b/harper-core/src/linting/oxford_comma.rs
index ec2769d30..2962f4284 100644
--- a/harper-core/src/linting/oxford_comma.rs
+++ b/harper-core/src/linting/oxford_comma.rs
@@ -42,7 +42,7 @@ impl Default for OxfordComma {
impl OxfordComma {
fn match_to_lint(&self, matched_toks: &[Token], _source: &[char]) -> Option<Lint> {
let conj_index = matched_toks.last_conjunction_index()?;
- let offender = matched_toks[conj_index - 2];
+ let offender = &matched_toks[conj_index - 2];
Some(Lint {
span: offender.span,
@@ -60,7 +60,10 @@ impl Linter for OxfordComma {
for sentence in document.iter_sentences() {
let mut tok_cursor = 0;
- let mut words = sentence.iter_words().filter_map(|v| v.kind.expect_word());
+ let mut words = sentence
+ .iter_words()
+ .filter_map(|v| v.kind.as_word())
+ .flatten();
if let (Some(first), Some(second)) = (words.next(), words.next()) {
if first.preposition && second.is_likely_homograph() {
diff --git a/harper-core/src/linting/repeated_words.rs b/harper-core/src/linting/repeated_words.rs
index 6627ff241..09a60ce6b 100644
--- a/harper-core/src/linting/repeated_words.rs
+++ b/harper-core/src/linting/repeated_words.rs
@@ -39,8 +39,8 @@ impl Linter for RepeatedWords {
let mut iter = chunk.iter_word_indices().zip(chunk.iter_words()).peekable();
while let (Some((idx_a, tok_a)), Some((idx_b, tok_b))) = (iter.next(), iter.peek()) {
- let word_a = document.get_span_content(tok_a.span);
- let word_b = document.get_span_content(tok_b.span);
+ let word_a = document.get_span_content(&tok_a.span);
+ let word_b = document.get_span_content(&tok_b.span);
if (tok_a.kind.is_preposition()
|| tok_a.kind.is_conjunction()
@@ -58,7 +58,7 @@ impl Linter for RepeatedWords {
span: Span::new(tok_a.span.start, tok_b.span.end),
lint_kind: LintKind::Repetition,
suggestions: vec![Suggestion::ReplaceWith(
- document.get_span_content(tok_a.span).to_vec(),
+ document.get_span_content(&tok_a.span).to_vec(),
)],
message: "Did you mean to repeat this word?".to_string(),
..Default::default()
diff --git a/harper-core/src/linting/sentence_capitalization.rs b/harper-core/src/linting/sentence_capitalization.rs
index 650d7255e..826c5e0d3 100644
--- a/harper-core/src/linting/sentence_capitalization.rs
+++ b/harper-core/src/linting/sentence_capitalization.rs
@@ -38,7 +38,7 @@ impl Linter for SentenceCapitalization {
continue;
}
- let letters = document.get_span_content(first_word.span);
+ let letters = document.get_span_content(&first_word.span);
if let Some(first_letter) = letters.first() {
if first_letter.is_alphabetic() && !first_letter.is_uppercase() {
@@ -71,7 +71,7 @@ fn is_full_sentence(toks: &[Token]) -> bool {
let mut has_verb = false;
for tok in toks {
- if let TokenKind::Word(Some(metadata)) = tok.kind {
+ if let TokenKind::Word(Some(metadata)) = &tok.kind {
if metadata.is_nominal() {
has_nominal = true;
}
diff --git a/harper-core/src/linting/spell_check.rs b/harper-core/src/linting/spell_check.rs
index 1940326c9..bdf32c325 100644
--- a/harper-core/src/linting/spell_check.rs
+++ b/harper-core/src/linting/spell_check.rs
@@ -56,7 +56,7 @@ impl<T: Dictionary> Linter for SpellCheck<T> {
let mut lints = Vec::new();
for word in document.iter_words() {
- let word_chars = document.get_span_content(word.span);
+ let word_chars = document.get_span_content(&word.span);
if self.dictionary.contains_exact_word(word_chars)
|| self.dictionary.contains_exact_word(&word_chars.to_lower())
{
@@ -91,7 +91,7 @@ impl<T: Dictionary> Linter for SpellCheck<T> {
} else {
format!(
"Did you mean to spell “{}” this way?",
- document.get_span_content_str(word.span)
+ document.get_span_content_str(&word.span)
)
};
diff --git a/harper-core/src/linting/spelled_numbers.rs b/harper-core/src/linting/spelled_numbers.rs
index 558851aab..4a6b1a3d1 100644
--- a/harper-core/src/linting/spelled_numbers.rs
+++ b/harper-core/src/linting/spelled_numbers.rs
@@ -15,11 +15,11 @@ impl Linter for SpelledNumbers {
value,
suffix: None,
..
- } = number_tok.kind.number().unwrap()
+ } = number_tok.kind.as_number().unwrap()
else {
continue;
};
- let value: f64 = value.into();
+ let value: f64 = (*value).into();
if (value - value.floor()).abs() < f64::EPSILON && value < 10. {
lints.push(Lint {
diff --git a/harper-core/src/linting/wordpress_dotcom.rs b/harper-core/src/linting/wordpress_dotcom.rs
index 33ab889a9..e99005ee3 100644
--- a/harper-core/src/linting/wordpress_dotcom.rs
+++ b/harper-core/src/linting/wordpress_dotcom.rs
@@ -13,7 +13,7 @@ impl Linter for WordPressDotcom {
let mut lints = Vec::new();
for hostname in document.iter_hostnames() {
- let text = document.get_span_content(hostname.span);
+ let text = document.get_span_content(&hostname.span);
if correct.as_slice() != text && text.to_lower() == correct_lower {
lints.push(Lint {
diff --git a/harper-core/src/linting/wrong_quotes.rs b/harper-core/src/linting/wrong_quotes.rs
index 50ae3a43b..b18878c8e 100644
--- a/harper-core/src/linting/wrong_quotes.rs
+++ b/harper-core/src/linting/wrong_quotes.rs
@@ -19,13 +19,13 @@ impl Linter for WrongQuotes {
}
}
-fn lint_quote(document: &Document, quote_idx: usize, quote_token: Token) -> Option<Lint> {
+fn lint_quote(document: &Document, quote_idx: usize, quote_token: &Token) -> Option<Lint> {
let quote = quote_token.kind.as_quote().unwrap();
let twin_loc = quote.twin_loc?;
let is_left = twin_loc > quote_idx;
- let quote_char = *document.get_span_content(quote_token.span).first()?;
+ let quote_char = *document.get_span_content(&quote_token.span).first()?;
let should_be = if is_left { '“' } else { '”' };
diff --git a/harper-core/src/parsers/isolate_english.rs b/harper-core/src/parsers/isolate_english.rs
index 49e50d465..73a523c4f 100644
--- a/harper-core/src/parsers/isolate_english.rs
+++ b/harper-core/src/parsers/isolate_english.rs
@@ -26,7 +26,7 @@ impl<D: Dictionary> Parser for IsolateEnglish<D> {
for chunk in tokens.iter_chunks() {
if chunk.len() < 5 || is_likely_english(chunk, source, &self.dict) {
- english_tokens.extend(chunk);
+ english_tokens.extend_from_slice(chunk);
}
}
diff --git a/harper-core/src/parsers/markdown.rs b/harper-core/src/parsers/markdown.rs
index 02c24af32..d16fad959 100644
--- a/harper-core/src/parsers/markdown.rs
+++ b/harper-core/src/parsers/markdown.rs
@@ -324,7 +324,7 @@ mod tests {
let tokens = Markdown::default().parse_str(source);
assert_eq!(
- tokens.iter().map(|t| t.kind).collect::<Vec<_>>(),
+ tokens.iter().map(|t| t.kind.clone()).collect::<Vec<_>>(),
vec![
TokenKind::Unlintable,
TokenKind::Space(1),
@@ -342,7 +342,7 @@ mod tests {
let tokens = Markdown::default().parse_str(source);
- let token_kinds = tokens.iter().map(|t| t.kind).collect::<Vec<_>>();
+ let token_kinds = tokens.iter().map(|t| t.kind.clone()).collect::<Vec<_>>();
assert!(matches!(
token_kinds.as_slice(),
@@ -362,7 +362,7 @@ mod tests {
let tokens = Markdown::default().parse_str(source);
- let token_kinds = tokens.iter().map(|t| t.kind).collect::<Vec<_>>();
+ let token_kinds = tokens.iter().map(|t| t.kind.clone()).collect::<Vec<_>>();
dbg!(&token_kinds);
@@ -378,7 +378,7 @@ mod tests {
let tokens = Markdown::default().parse_str(source);
- let token_kinds = tokens.iter().map(|t| t.kind).collect::<Vec<_>>();
+ let token_kinds = tokens.iter().map(|t| t.kind.clone()).collect::<Vec<_>>();
dbg!(&token_kinds);
@@ -391,7 +391,7 @@ mod tests {
let tokens = Markdown::default().parse_str(source);
- let token_kinds = tokens.iter().map(|t| t.kind).collect::<Vec<_>>();
+ let token_kinds = tokens.iter().map(|t| t.kind.clone()).collect::<Vec<_>>();
dbg!(&token_kinds);
@@ -421,7 +421,7 @@ mod tests {
fn normal_wikilink() {
let source = r"[[Wikilink]]";
let tokens = Markdown::default().parse_str(source);
- let token_kinds = tokens.iter().map(|t| t.kind).collect::<Vec<_>>();
+ let token_kinds = tokens.iter().map(|t| t.kind.clone()).collect::<Vec<_>>();
dbg!(&token_kinds);
@@ -443,7 +443,7 @@ mod tests {
});
let source = r"[elijah-potter/harper](https://github.com/elijah-potter/harper)";
let tokens = parser.parse_str(source);
- let token_kinds = tokens.iter().map(|t| t.kind).collect::<Vec<_>>();
+ let token_kinds = tokens.iter().map(|t| t.kind.clone()).collect::<Vec<_>>();
dbg!(&token_kinds);
@@ -460,7 +460,7 @@ mod tests {
let token_kinds = parser
.parse_str(source)
.iter()
- .map(|t| t.kind)
+ .map(|t| t.kind.clone())
.collect::<Vec<_>>();
assert!(matches!(token_kinds.as_slice(), &[TokenKind::Unlintable]));
@@ -476,7 +476,7 @@ mod tests {
let token_kinds = parser
.parse_str(source)
.iter()
- .map(|t| t.kind)
+ .map(|t| t.kind.clone())
.collect::<Vec<_>>();
assert!(matches!(token_kinds.as_slice(), &[TokenKind::Unlintable]));
@@ -488,7 +488,7 @@ mod tests {
let token_kinds = parser
.parse_str(source)
.iter()
- .map(|t| t.kind)
+ .map(|t| t.kind.clone())
.collect::<Vec<_>>();
dbg!(&token_kinds);
@@ -518,7 +518,7 @@ Paragraph.
"#;
let parser = Markdown::new(MarkdownOptions::default());
let tokens = parser.parse_str(source);
- let token_kinds = tokens.iter().map(|t| t.kind).collect::<Vec<_>>();
+ let token_kinds = tokens.iter().map(|t| t.kind.clone()).collect::<Vec<_>>();
dbg!(&token_kinds);
diff --git a/harper-core/src/patterns/any_pattern.rs b/harper-core/src/patterns/any_pattern.rs
index 04312ff59..d7cb454b4 100644
--- a/harper-core/src/patterns/any_pattern.rs
+++ b/harper-core/src/patterns/any_pattern.rs
@@ -1,10 +1,12 @@
+use crate::Token;
+
use super::Pattern;
/// A [`Pattern`] that will match any single token.
pub struct AnyPattern;
impl Pattern for AnyPattern {
- fn matches(&self, tokens: &[crate::Token], _source: &[char]) -> usize {
+ fn matches(&self, tokens: &[Token], _source: &[char]) -> usize {
if tokens.is_empty() { 0 } else { 1 }
}
}
diff --git a/harper-core/src/patterns/implies_quantity.rs b/harper-core/src/patterns/implies_quantity.rs
index fd30ec844..be2ef7b25 100644
--- a/harper-core/src/patterns/implies_quantity.rs
+++ b/harper-core/src/patterns/implies_quantity.rs
@@ -14,7 +14,7 @@ impl ImpliesQuantity {
pub fn implies_plurality(tokens: &[Token], source: &[char]) -> Option<bool> {
let token = tokens.first()?;
- match token.kind {
+ match &token.kind {
TokenKind::Word(Some(word_metadata)) => {
if word_metadata.determiner {
return Some(false);
diff --git a/harper-core/src/patterns/split_compound_word.rs b/harper-core/src/patterns/split_compound_word.rs
index be34c452a..de5666749 100644
--- a/harper-core/src/patterns/split_compound_word.rs
+++ b/harper-core/src/patterns/split_compound_word.rs
@@ -10,13 +10,13 @@ use super::{Pattern, SequencePattern};
pub struct SplitCompoundWord {
inner: SequencePattern,
dict: Arc<FstDictionary>,
- predicate: Box<dyn Fn(WordMetadata) -> bool + Send + Sync>,
+ predicate: Box<dyn Fn(&WordMetadata) -> bool + Send + Sync>,
}
impl SplitCompoundWord {
/// Create a new instance of the linter which will only look for compound words that fit the
/// provided predicate.
- pub fn new(predicate: impl Fn(WordMetadata) -> bool + Send + Sync + 'static) -> Self {
+ pub fn new(predicate: impl Fn(&WordMetadata) -> bool + Send + Sync + 'static) -> Self {
Self {
inner: SequencePattern::default()
.then_any_word()
@@ -27,11 +27,11 @@ impl SplitCompoundWord {
}
}
- /// The merged word from the dictionary that this pattern would match on if it was split.
+ /// Get the merged word from the dictionary that this pattern would match on if it was split.
pub fn get_merged_word(
&self,
- word_a: Token,
- word_b: Token,
+ word_a: &Token,
+ word_b: &Token,
source: &[char],
) -> Option<CharString> {
let a_chars: CharString = word_a.span.get_content(source).into();
@@ -64,8 +64,8 @@ impl Pattern for SplitCompoundWord {
return 0;
}
- let a = tokens[0];
- let b = tokens[2];
+ let a = &tokens[0];
+ let b = &tokens[2];
if self.get_merged_word(a, b, source).is_some() {
return inner_match;
diff --git a/harper-core/src/patterns/token_kind_pattern_group.rs b/harper-core/src/patterns/token_kind_pattern_group.rs
index 7a539959d..bfcf178bb 100644
--- a/harper-core/src/patterns/token_kind_pattern_group.rs
+++ b/harper-core/src/patterns/token_kind_pattern_group.rs
@@ -10,7 +10,7 @@ pub struct TokenKindPatternGroup {
impl Pattern for TokenKindPatternGroup {
fn matches(&self, tokens: &[Token], source: &[char]) -> usize {
- let Some(first_kind) = &tokens.first().map(|t| t.kind) else {
+ let Some(first_kind) = tokens.first().map(|t| &t.kind) else {
return 0;
};
diff --git a/harper-core/src/spell/dictionary.rs b/harper-core/src/spell/dictionary.rs
index 4254893a7..42fb11ade 100644
--- a/harper-core/src/spell/dictionary.rs
+++ b/harper-core/src/spell/dictionary.rs
@@ -32,11 +32,11 @@ pub trait Dictionary: Send + Sync {
) -> 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<WordMetadata>;
+ fn get_word_metadata(&self, word: &[char]) -> Option<&WordMetadata>;
/// Get the associated [`WordMetadata`] 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<WordMetadata>;
+ fn get_word_metadata_str(&self, word: &str) -> Option<&WordMetadata>;
/// 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.rs
index 75afcbc7d..e637eeb3c 100644
--- a/harper-core/src/spell/fst_dictionary.rs
+++ b/harper-core/src/spell/fst_dictionary.rs
@@ -137,11 +137,11 @@ impl Dictionary for FstDictionary {
self.full_dict.contains_word_str(word)
}
- fn get_word_metadata(&self, word: &[char]) -> Option<WordMetadata> {
+ fn get_word_metadata(&self, word: &[char]) -> Option<&WordMetadata> {
self.full_dict.get_word_metadata(word)
}
- fn get_word_metadata_str(&self, word: &str) -> Option<WordMetadata> {
+ fn get_word_metadata_str(&self, word: &str) -> Option<&WordMetadata> {
self.full_dict.get_word_metadata_str(word)
}
@@ -181,7 +181,7 @@ impl Dictionary for FstDictionary {
merged.push(FuzzyMatchResult {
word,
edit_distance,
- metadata: *metadata,
+ metadata,
})
}
diff --git a/harper-core/src/spell/hunspell/attribute_list.rs b/harper-core/src/spell/hunspell/attribute_list.rs
index a97b5da4c..d84f2ffc8 100644
--- a/harper-core/src/spell/hunspell/attribute_list.rs
+++ b/harper-core/src/spell/hunspell/attribute_list.rs
@@ -53,7 +53,7 @@ impl AttributeList {
if let Some(val) = new_words.get_mut(&replaced) {
val.append(&expansion.adds_metadata);
} else {
- new_words.insert(replaced, expansion.adds_metadata);
+ new_words.insert(replaced, expansion.adds_metadata.clone());
}
}
}
diff --git a/harper-core/src/spell/merged_dictionary.rs b/harper-core/src/spell/merged_dictionary.rs
index 2149c385a..ce04ac54c 100644
--- a/harper-core/src/spell/merged_dictionary.rs
+++ b/harper-core/src/spell/merged_dictionary.rs
@@ -10,6 +10,9 @@ use crate::{CharString, WordMetadata};
/// A simple wrapper over [`Dictionary`] that allows
/// one to merge multiple dictionaries without copying.
+///
+/// In cases where more than one dictionary contains a word, data in the first
+/// dictionary inserted will be returned.
#[derive(Clone)]
pub struct MergedDictionary {
children: Vec<Arc<dyn Dictionary>>,
@@ -90,22 +93,14 @@ impl Dictionary for MergedDictionary {
false
}
- fn get_word_metadata(&self, word: &[char]) -> Option<WordMetadata> {
- let mut found_anything = false;
- let mut found_metadata = WordMetadata::default();
-
+ fn get_word_metadata(&self, word: &[char]) -> Option<&WordMetadata> {
for child in &self.children {
if let Some(found_item) = child.get_word_metadata(word) {
- found_metadata.append(&found_item);
- found_anything = true;
+ return Some(found_item);
}
}
- if found_anything {
- Some(found_metadata)
- } else {
- None
- }
+ None
}
fn words_iter(&self) -> Box<dyn Iterator<Item = &'_ [char]> + Send + '_> {
@@ -130,7 +125,7 @@ impl Dictionary for MergedDictionary {
self.contains_word(&chars)
}
- fn get_word_metadata_str(&self, word: &str) -> Option<WordMetadata> {
+ fn get_word_metadata_str(&self, word: &str) -> Option<&WordMetadata> {
let chars: CharString = word.chars().collect();
self.get_word_metadata(&chars)
}
diff --git a/harper-core/src/spell/mod.rs b/harper-core/src/spell/mod.rs
index 6ea5d784d..c53364c22 100644
--- a/harper-core/src/spell/mod.rs
+++ b/harper-core/src/spell/mod.rs
@@ -17,7 +17,7 @@ mod mutable_dictionary;
pub struct FuzzyMatchResult<'a> {
pub word: &'a [char],
pub edit_distance: u8,
- pub metadata: WordMetadata,
+ pub metadata: &'a WordMetadata,
}
impl PartialOrd for FuzzyMatchResult<'_> {
diff --git a/harper-core/src/spell/mutable_dictionary.rs b/harper-core/src/spell/mutable_dictionary.rs
index 734c9974e..5a35f1e09 100644
--- a/harper-core/src/spell/mutable_dictionary.rs
+++ b/harper-core/src/spell/mutable_dictionary.rs
@@ -163,11 +163,11 @@ impl Default for MutableDictionary {
}
impl Dictionary for MutableDictionary {
- fn get_word_metadata(&self, word: &[char]) -> Option<WordMetadata> {
+ fn get_word_metadata(&self, word: &[char]) -> Option<&WordMetadata> {
let normalized = seq_to_normalized(word);
let correct_caps = self.get_correct_capitalization_of(&normalized)?;
- self.word_map.get(correct_caps).cloned()
+ self.word_map.get(correct_caps)
}
fn contains_word(&self, word: &[char]) -> bool {
@@ -182,7 +182,7 @@ impl Dictionary for MutableDictionary {
self.contains_word(&chars)
}
- fn get_word_metadata_str(&self, word: &str) -> Option<WordMetadata> {
+ fn get_word_metadata_str(&self, word: &str) -> Option<&WordMetadata> {
let chars: CharString = word.chars().collect();
self.get_word_metadata(&chars)
}
diff --git a/harper-core/src/title_case.rs b/harper-core/src/title_case.rs
index e6dcca712..b4f623fc7 100644
--- a/harper-core/src/title_case.rs
+++ b/harper-core/src/title_case.rs
@@ -1,3 +1,5 @@
+use std::borrow::Cow;
+
use crate::Lrc;
use crate::Token;
use crate::TokenKind;
@@ -50,7 +52,7 @@ pub fn make_title_case(toks: &[Token], source: &[char], dict: &impl Dictionary)
}
};
- let should_capitalize = should_capitalize_token(&word, source, dict)
+ let should_capitalize = should_capitalize_token(word, source, dict)
|| index == 0
|| word_likes.peek().is_none();
@@ -71,8 +73,8 @@ pub fn make_title_case(toks: &[Token], source: &[char], dict: &impl Dictionary)
/// Determines whether a token should be capitalized.
/// Is not responsible for capitalization requirements that are dependent on token position.
fn should_capitalize_token(tok: &Token, source: &[char], dict: &impl Dictionary) -> bool {
- match tok.kind {
- TokenKind::Word(Some(mut metadata)) => {
+ match &tok.kind {
+ TokenKind::Word(Some(metadata)) => {
// Only specific conjunctions are not capitalized.
lazy_static! {
static ref SPECIAL_CONJUNCTIONS: HashSet<Vec<char>> =
@@ -85,7 +87,11 @@ fn should_capitalize_token(tok: &Token, source: &[char], dict: &impl Dictionary)
let chars = tok.span.get_content(source);
let chars_lower = chars.to_lower();
- metadata = metadata.or(&dict.get_word_metadata(&chars_lower).unwrap_or_default());
+ let mut metadata = Cow::Borrowed(metadata);
+
+ if let Some(metadata_lower) = dict.get_word_metadata(&chars_lower) {
+ metadata = Cow::Owned(metadata.clone().or(metadata_lower));
+ }
let is_short_preposition = metadata.preposition && tok.span.len() <= 4;
diff --git a/harper-core/src/token.rs b/harper-core/src/token.rs
index 8d4e86005..25896c7a1 100644
--- a/harper-core/src/token.rs
+++ b/harper-core/src/token.rs
@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
use crate::{FatToken, Span, TokenKind};
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Default)]
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct Token {
pub span: Span,
pub kind: TokenKind,
@@ -19,7 +19,7 @@ impl Token {
FatToken {
content,
- kind: self.kind,
+ kind: self.kind.clone(),
}
}
}
diff --git a/harper-core/src/token_kind.rs b/harper-core/src/token_kind.rs
index 7ffdb74c4..2e1ab766f 100644
--- a/harper-core/src/token_kind.rs
+++ b/harper-core/src/token_kind.rs
@@ -3,9 +3,7 @@ use serde::{Deserialize, Serialize};
use crate::{ConjunctionData, NounData, Number, PronounData, Punctuation, Quote, WordMetadata};
-#[derive(
- Debug, Is, Clone, Copy, Serialize, Deserialize, Default, PartialOrd, Hash, Eq, PartialEq,
-)]
+#[derive(Debug, Is, Clone, Serialize, Deserialize, Default, PartialOrd, Hash, Eq, PartialEq)]
#[serde(tag = "kind", content = "value")]
pub enum TokenKind {
/// `None` if the word does not exist in the dictionary.
@@ -229,7 +227,7 @@ impl TokenKind {
TokenKind::Number(..) => TokenKind::Number(Default::default()),
TokenKind::Space(_) => TokenKind::Space(Default::default()),
TokenKind::Newline(_) => TokenKind::Newline(Default::default()),
- _ => *self,
+ _ => self.clone(),
}
}
}
diff --git a/harper-core/src/token_string_ext.rs b/harper-core/src/token_string_ext.rs
index 76d7ed18b..4682af8a0 100644
--- a/harper-core/src/token_string_ext.rs
+++ b/harper-core/src/token_string_ext.rs
@@ -5,15 +5,15 @@ use paste::paste;
macro_rules! create_decl_for {
($thing:ident) => {
paste! {
- fn [< first_ $thing >](&self) -> Option<Token>;
+ fn [< first_ $thing >](&self) -> Option<&Token>;
- fn [< last_ $thing >](&self) -> Option<Token>;
+ fn [< last_ $thing >](&self) -> Option<&Token>;
fn [< last_ $thing _index >](&self) -> Option<usize>;
fn [<iter_ $thing _indices>](&self) -> impl Iterator<Item = usize> + '_;
- fn [<iter_ $thing s>](&self) -> impl Iterator<Item = Token> + '_;
+ fn [<iter_ $thing s>](&self) -> impl Iterator<Item = &Token> + '_;
}
};
}
@@ -21,12 +21,12 @@ macro_rules! create_decl_for {
macro_rules! create_fns_for {
($thing:ident) => {
paste! {
- fn [< first_ $thing >](&self) -> Option<Token> {
- self.iter().find(|v| v.kind.[<is_ $thing>]()).copied()
+ fn [< first_ $thing >](&self) -> Option<&Token> {
+ self.iter().find(|v| v.kind.[<is_ $thing>]())
}
- fn [< last_ $thing >](&self) -> Option<Token> {
- self.iter().rev().find(|v| v.kind.[<is_ $thing>]()).copied()
+ fn [< last_ $thing >](&self) -> Option<&Token> {
+ self.iter().rev().find(|v| v.kind.[<is_ $thing>]())
}
fn [< last_ $thing _index >](&self) -> Option<usize> {
@@ -40,8 +40,8 @@ macro_rules! create_fns_for {
.map(|(i, _)| i)
}
- fn [<iter_ $thing s>](&self) -> impl Iterator<Item = Token> + '_ {
- self.[<iter_ $thing _indices>]().map(|i| self[i])
+ fn [<iter_ $thing s>](&self) -> impl Iterator<Item = &Token> + '_ {
+ self.[<iter_ $thing _indices>]().map(|i| &self[i])
}
}
};
@@ -49,8 +49,8 @@ macro_rules! create_fns_for {
/// Extension methods for [`Token`] sequences that make them easier to wrangle and query.
pub trait TokenStringExt {
- fn first_sentence_word(&self) -> Option<Token>;
- fn first_non_whitespace(&self) -> Option<Token>;
+ fn first_sentence_word(&self) -> Option<&Token>;
+ fn first_non_whitespace(&self) -> Option<&Token>;
/// Grab the span that represents the beginning of the first element and the
/// end of the last element.
fn span(&self) -> Option<Span>;
@@ -76,7 +76,7 @@ pub trait TokenStringExt {
create_decl_for!(comma);
fn iter_linking_verb_indices(&self) -> impl Iterator<Item = usize> + '_;
- fn iter_linking_verbs(&self) -> impl Iterator<Item = Token> + '_;
+ fn iter_linking_verbs(&self) -> impl Iterator<Item = &Token> + '_;
/// Iterate over chunks.
///
@@ -118,18 +118,18 @@ impl TokenStringExt for [Token] {
create_fns_for!(likely_homograph);
create_fns_for!(comma);
- fn first_non_whitespace(&self) -> Option<Token> {
- self.iter().find(|t| !t.kind.is_whitespace()).copied()
+ fn first_non_whitespace(&self) -> Option<&Token> {
+ self.iter().find(|t| !t.kind.is_whitespace())
}
- fn first_sentence_word(&self) -> Option<Token> {
+ fn first_sentence_word(&self) -> Option<&Token> {
let (w_idx, word) = self.iter().find_position(|v| v.kind.is_word())?;
let Some(u_idx) = self.iter().position(|v| v.kind.is_unlintable()) else {
- return Some(*word);
+ return Some(word);
};
- if w_idx < u_idx { Some(*word) } else { None }
+ if w_idx < u_idx { Some(word) } else { None }
}
fn span(&self) -> Option<Span> {
@@ -147,7 +147,7 @@ impl TokenStringExt for [Token] {
fn iter_linking_verb_indices(&self) -> impl Iterator<Item = usize> + '_ {
self.iter_word_indices().filter(|idx| {
- let word = self[*idx];
+ let word = &self[*idx];
let Some(Some(meta)) = word.kind.as_word() else {
return false;
};
@@ -156,8 +156,8 @@ impl TokenStringExt for [Token] {
})
}
- fn iter_linking_verbs(&self) -> impl Iterator<Item = Token> + '_ {
- self.iter_linking_verb_indices().map(|idx| self[idx])
+ fn iter_linking_verbs(&self) -> impl Iterator<Item = &Token> + '_ {
+ self.iter_linking_verb_indices().map(|idx| &self[idx])
}
fn iter_chunks(&self) -> impl Iterator<Item = &'_ [Token]> + '_ {
diff --git a/harper-core/src/word_metadata.rs b/harper-core/src/word_metadata.rs
index 79c458b27..3bc1f9862 100644
--- a/harper-core/src/word_metadata.rs
+++ b/harper-core/src/word_metadata.rs
@@ -2,7 +2,7 @@ use is_macro::Is;
use paste::paste;
use serde::{Deserialize, Serialize};
-#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, PartialOrd, Hash)]
+#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, PartialOrd, Hash)]
pub struct WordMetadata {
pub noun: Option<NounData>,
pub pronoun: Option<PronounData>,
diff --git a/harper-typst/tests/tests.rs b/harper-typst/tests/tests.rs
index d6044d00d..bf15bb94a 100644
--- a/harper-typst/tests/tests.rs
+++ b/harper-typst/tests/tests.rs
@@ -9,7 +9,7 @@ fn number() {
let source = "12 is larger than 11, but much less than 11!";
let document = Document::new_curated(source, &Typst);
- let token_kinds = document.tokens().map(|t| t.kind).collect_vec();
+ let token_kinds = document.tokens().map(|t| t.kind.clone()).collect_vec();
dbg!(&token_kinds);
assert!(matches!(
@@ -57,7 +57,7 @@ fn math_unlintable() {
let source = "$12 > 11$, $12 << 11!$";
let document = Document::new_curated(source, &Typst);
- let token_kinds = document.tokens().map(|t| t.kind).collect_vec();
+ let token_kinds = document.tokens().map(|t| t.kind.clone()).collect_vec();
dbg!(&token_kinds);
assert!(matches!(
@@ -79,7 +79,7 @@ fn dict_parsing() {
)"#;
let document = Document::new_curated(source, &Typst);
- let token_kinds = document.tokens().map(|t| t.kind).collect_vec();
+ let token_kinds = document.tokens().map(|t| t.kind.clone()).collect_vec();
dbg!(&token_kinds);
let charslice = source.chars().collect_vec();
@@ -103,7 +103,7 @@ fn str_parsing() {
let source = r#"#let ident = "This is a string""#;
let document = Document::new_curated(source, &Typst);
- let token_kinds = document.tokens().map(|t| t.kind).collect_vec();
+ let token_kinds = document.tokens().map(|t| t.kind.clone()).collect_vec();
dbg!(&token_kinds);
assert!(matches!(
@@ -126,7 +126,7 @@ fn non_adjacent_spaces_not_condensed() {
let source = r#"#authors_slice.join(", ", last: ", and ") bob"#;
let document = Document::new_curated(source, &Typst);
- let token_kinds = document.tokens().map(|t| t.kind).collect_vec();
+ let token_kinds = document.tokens().map(|t| t.kind.clone()).collect_vec();
dbg!(&token_kinds);
assert!(matches!(
@@ -152,7 +152,7 @@ fn header_parsing() {
Paragraph";
let document = Document::new_curated(source, &Typst);
- let token_kinds = document.tokens().map(|t| t.kind).collect_vec();
+ let token_kinds = document.tokens().map(|t| t.kind.clone()).collect_vec();
dbg!(&token_kinds);
let charslice = source.chars().collect_vec();
@@ -177,7 +177,7 @@ fn parbreak() {
Paragraph";
let document = Document::new_curated(source, &Typst);
- let token_kinds = document.tokens().map(|t| t.kind).collect_vec();
+ let token_kinds = document.tokens().map(|t| t.kind.clone()).collect_vec();
dbg!(&token_kinds);
assert!(matches!(
@@ -197,7 +197,7 @@ fn label_ref_unlintable() {
Paragraph @label";
let document = Document::new_curated(source, &Typst);
- let token_kinds = document.tokens().map(|t| t.kind).collect_vec();
+ let token_kinds = document.tokens().map(|t| t.kind.clone()).collect_vec();
dbg!(&token_kinds);
assert!(matches!(
@@ -219,7 +219,7 @@ fn sentence() {
let source = "This is a sentence, it is not interesting.";
let document = Document::new_curated(source, &Typst);
- let token_kinds = document.tokens().map(|t| t.kind).collect_vec();
+ let token_kinds = document.tokens().map(|t| t.kind.clone()).collect_vec();
dbg!(&token_kinds);
assert!(matches!(
@@ -252,7 +252,7 @@ fn smart_apostrophe_newline() {
writing";
let document = Document::new_curated(source, &Typst);
- let token_kinds = document.tokens().map(|t| t.kind).collect_vec();
+ let token_kinds = document.tokens().map(|t| t.kind.clone()).collect_vec();
dbg!(&token_kinds);
let charslice = source.chars().collect_vec();
@@ -282,7 +282,7 @@ newlines
not paragraph breaks";
let document = Document::new_curated(source, &Typst);
- let token_kinds = document.tokens().map(|t| t.kind).collect_vec();
+ let token_kinds = document.tokens().map(|t| t.kind.clone()).collect_vec();
dbg!(&token_kinds);
assert!(matches!(
@@ -311,7 +311,7 @@ fn parbreaks_in_list() {
- p3";
let document = Document::new_curated(source, &Typst);
- let token_kinds = document.tokens().map(|t| t.kind).collect_vec();
+ let token_kinds = document.tokens().map(|t| t.kind.clone()).collect_vec();
dbg!(&token_kinds);
assert!(matches!(
@@ -340,7 +340,7 @@ fn do_not_lint_rgb() {
let source = r#"#color.rgb("ffffff")"#;
let document = Document::new_curated(source, &Typst);
- let token_kinds = document.tokens().map(|t| t.kind).collect_vec();
+ let token_kinds = document.tokens().map(|t| t.kind.clone()).collect_vec();
dbg!(&token_kinds);
assert!(matches!(