Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat(core): can now handle international positioning
Elijah Potter6b6370586260
diff --git a/harper-core/src/currency.rs b/harper-core/src/currency.rsindex affeb0685..7f7532ee8 100644--- a/harper-core/src/currency.rs+++ b/harper-core/src/currency.rs@@ -1,10 +1,14 @@use is_macro::Is;use serde::{Deserialize, Serialize};+use crate::NumberSuffix;+#[derive(Debug, Is, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Hash)]pub enum Currency {// $Dollar,+ // ¢+ Cent,// €Euro,// ₽@@ -27,6 +31,7 @@ impl Currency {pub fn from_char(c: char) -> Option<Self> {let cur = match c {'$' => Self::Dollar,+ '¢' => Self::Cent,'€' => Self::Euro,'₽' => Self::Ruble,'₺' => Self::Lira,@@ -44,6 +49,7 @@ impl Currency {pub fn to_char(&self) -> char {match self {Self::Dollar => '$',+ Self::Cent => '¢',Self::Euro => '€',Self::Ruble => '₽',Self::Lira => '₺',@@ -54,4 +60,28 @@ impl Currency {Self::Kip => '₭',}}++ /// Format an amount of the specific currency.+ pub fn format_amount(&self, value: f64, suffix: Option<NumberSuffix>) -> String {+ let c = self.to_char();++ let mut amount = value.to_string();++ if let Some(suffix) = suffix {+ amount.extend(suffix.to_chars());+ }++ match self {+ Currency::Dollar => format!("{}{amount}", c),+ Currency::Cent => format!("{amount}{}", c),+ Currency::Euro => format!("{}{amount}", c),+ Currency::Ruble => format!("{amount} {}", c),+ Currency::Lira => format!("{amount} {}", c),+ Currency::Pound => format!("{}{amount}", c),+ Currency::Yen => format!("{} {amount}", c),+ Currency::Baht => format!("{amount} {}", c),+ Currency::Won => format!("{} {amount}", c),+ Currency::Kip => format!("{}{amount}", c),+ }+ }}diff --git a/harper-core/src/document.rs b/harper-core/src/document.rsindex a3f1da1bd..8e10d07c2 100644--- a/harper-core/src/document.rs+++ b/harper-core/src/document.rs@@ -510,6 +510,7 @@ impl TokenStringExt for Document {create_fns_on_doc!(paragraph_break);create_fns_on_doc!(chunk_terminator);create_fns_on_doc!(punctuation);+ create_fns_on_doc!(currency);create_fns_on_doc!(likely_homograph);fn first_sentence_word(&self) -> Option<Token> {diff --git a/harper-core/src/linting/currency_placement.rs b/harper-core/src/linting/currency_placement.rsindex 7b86a0497..e80dc7f59 100644--- a/harper-core/src/linting/currency_placement.rs+++ b/harper-core/src/linting/currency_placement.rs@@ -1,81 +1,76 @@-use crate::{- patterns::{EitherPattern, Pattern, SequencePattern},- Punctuation, Token, TokenKind, TokenStringExt,-};+use itertools::Itertools;-use super::{Lint, LintKind, PatternLinter, Suggestion};+use crate::{remove_overlaps, Document, Token, TokenStringExt};-static DESCRIPTION: &str =- "Currency symbols should always come before the quantity being described.";+use super::{Lint, LintKind, Linter, Suggestion};-pub struct CurrencyPlacement {- pattern: Box<dyn Pattern>,-}+#[derive(Debug, Default)]+pub struct CurrencyPlacement {}++impl Linter for CurrencyPlacement {+ fn lint(&mut self, document: &Document) -> Vec<Lint> {+ let mut lints = Vec::new();++ for chunk in document.iter_chunks() {+ for (a, b) in chunk.iter().tuple_windows() {+ lints.extend(generate_lint_for_tokens(*a, *b, document));+ }-impl Default for CurrencyPlacement {- fn default() -> Self {- let currency_pat = Box::new(|t: &Token, _source: &[char]| {- matches!(t.kind, TokenKind::Punctuation(Punctuation::Currency(..)))- });-- let pattern = EitherPattern::new(vec![- Box::new(- SequencePattern::default()- .then_number()- .then_whitespace()- .then(currency_pat.clone()),- ),- Box::new(SequencePattern::default().then_number().then(currency_pat)),- ]);-- Self {- pattern: Box::new(pattern),+ for (a, b, c) in chunk.iter().tuple_windows() {+ if !b.kind.is_whitespace() {+ continue;+ }++ lints.extend(generate_lint_for_tokens(*a, *c, document));+ }}++ remove_overlaps(&mut lints);++ lints}-}-impl PatternLinter for CurrencyPlacement {- fn pattern(&self) -> &dyn Pattern {- self.pattern.as_ref()+ fn description(&self) -> &str {+ "The location of currency symbols varies by country. The rule looks for and corrects improper positioning."}+}- fn match_to_lint(&self, matched_tokens: &[Token], _source: &[char]) -> Lint {- let currency_tok = matched_tokens.first_punctuation().unwrap();- let currency = currency_tok- .kind- .as_punctuation()- .unwrap()- .expect_currency();+// 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];- // We can unwrap like this thanks to the pattern.- let number_tok = matched_tokens.first_number().unwrap();- let (value, suffix) = number_tok.kind.expect_number();+ let punct = matched_tokens+ .first_punctuation()?+ .kind+ .expect_punctuation();+ let currency = punct.as_currency()?;- let mut fix = vec![currency.to_char()];+ let (value, suffix) = matched_tokens.first_number()?.kind.expect_number();- fix.extend(value.to_string().chars());+ let span = matched_tokens.span().unwrap();- if let Some(suffix) = suffix {- fix.extend(suffix.to_chars());- }+ let correct: Vec<_> = currency+ .format_amount(value.into(), suffix)+ .chars()+ .collect();+ let actual = document.get_span_content(span);- Lint {- span: matched_tokens.span().unwrap(),+ if correct != actual {+ Some(Lint {+ span,lint_kind: LintKind::Formatting,- suggestions: vec![Suggestion::ReplaceWith(fix)],- message: DESCRIPTION.to_string(),+ suggestions: vec![Suggestion::ReplaceWith(correct)],+ message: "The position of the currency symbol matters.".to_string(),priority: 63,- }- }-- fn description(&self) -> &'static str {- DESCRIPTION+ })+ } else {+ None}}#[cfg(test)]mod tests {- use crate::linting::tests::assert_suggestion_result;+ use crate::linting::tests::{assert_lint_count, assert_suggestion_result};use super::CurrencyPlacement;@@ -88,6 +83,11 @@ mod tests {);}+ #[test]+ fn blog_title_allows_correct() {+ assert_lint_count("The Best $25 I Ever Spent", CurrencyPlacement::default(), 0);+ }+#[test]fn blog_title() {assert_suggestion_result(@@ -97,6 +97,15 @@ mod tests {);}+ #[test]+ fn blog_title_cents() {+ assert_suggestion_result(+ "The Best ¢25 I Ever Spent",+ CurrencyPlacement::default(),+ "The Best 25¢ I Ever Spent",+ );+ }+#[test]fn blog_title_with_space() {assert_suggestion_result(diff --git a/harper-core/src/token.rs b/harper-core/src/token.rsindex f5e66c0ec..06ab11ce9 100644--- a/harper-core/src/token.rs+++ b/harper-core/src/token.rs@@ -93,6 +93,7 @@ pub trait TokenStringExt {create_decl_for!(paragraph_break);create_decl_for!(chunk_terminator);create_decl_for!(punctuation);+ create_decl_for!(currency);create_decl_for!(likely_homograph);fn iter_linking_verb_indices(&self) -> impl Iterator<Item = usize> + '_;@@ -133,6 +134,7 @@ impl TokenStringExt for [Token] {create_fns_for!(sentence_terminator);create_fns_for!(paragraph_break);create_fns_for!(chunk_terminator);+ create_fns_for!(currency);create_fns_for!(likely_homograph);fn first_non_whitespace(&self) -> Option<Token> {diff --git a/harper-core/src/token_kind.rs b/harper-core/src/token_kind.rsindex c3145849d..93df3a300 100644--- a/harper-core/src/token_kind.rs+++ b/harper-core/src/token_kind.rs@@ -103,6 +103,10 @@ impl TokenKind {}}+ pub fn is_currency(&self) -> bool {+ matches!(self, TokenKind::Punctuation(Punctuation::Currency(..)))+ }+pub fn is_article(&self) -> bool {matches!(self, TokenKind::Word(WordMetadata { article: true, .. }))}