Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat(core): create linter for time unit expansion
Elijah Potter228a71dca674
diff --git a/harper-core/src/linting/expand_time_shorthands.rs b/harper-core/src/linting/expand_time_shorthands.rsnew file mode 100644index 000000000..4b67bfc22--- /dev/null+++ b/harper-core/src/linting/expand_time_shorthands.rs@@ -0,0 +1,179 @@+use std::sync::Arc;++use super::{Lint, LintKind, PatternLinter};+use crate::linting::Suggestion;+use crate::patterns::{EitherPattern, ImpliesQuantity, Pattern, SequencePattern, WordSet};+use crate::Token;++pub struct ExpandTimeShorthands {+ pattern: Box<dyn Pattern>,+}++impl ExpandTimeShorthands {+ pub fn new() -> Self {+ let hotwords = Arc::new(WordSet::all(&[+ "hr", "hrs", "min", "mins", "sec", "secs", "ms", "msec", "msecs",+ ]));++ Self {+ pattern: Box::new(+ SequencePattern::default()+ .then(Box::new(ImpliesQuantity))+ .then(Box::new(EitherPattern::new(vec![+ Box::new(SequencePattern::default().then(Box::new(hotwords.clone()))),+ Box::new(+ SequencePattern::default()+ .then_whitespace()+ .then(Box::new(hotwords.clone())),+ ),+ Box::new(+ SequencePattern::default()+ .then_hyphen()+ .then(Box::new(hotwords.clone())),+ ),+ ]))),+ ),+ }+ }++ fn get_replacement(abbreviation: &str, plural: Option<bool>) -> Option<&'static str> {+ dbg!(abbreviation, plural);++ let is_plural = plural.unwrap_or(matches!(abbreviation, "hrs" | "mins" | "secs" | "msecs"));+ match abbreviation {+ "hr" | "hrs" => Some(if is_plural { "hours" } else { "hour" }),+ "min" | "mins" => Some(if is_plural { "minutes" } else { "minute" }),+ "sec" | "secs" => Some(if is_plural { "seconds" } else { "second" }),+ "ms" | "msec" | "msecs" => Some(if is_plural {+ "milliseconds"+ } else {+ "millisecond"+ }),+ _ => None,+ }+ }+}++impl Default for ExpandTimeShorthands {+ fn default() -> Self {+ Self::new()+ }+}++impl PatternLinter for ExpandTimeShorthands {+ fn pattern(&self) -> &dyn Pattern {+ self.pattern.as_ref()+ }++ fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {+ let offending_span = matched_tokens.last()?.span;+ let implies_plural = ImpliesQuantity::implies_plurality(matched_tokens, source);++ let offending_text = offending_span.get_content(source);++ let replacement =+ Self::get_replacement(&offending_text.iter().collect::<String>(), implies_plural)?;++ let mut replacement_chars = Vec::new();++ // If there isn't spacing, insert a space+ if matched_tokens.len() == 2 {+ replacement_chars.push(' ');+ }++ replacement_chars.extend(replacement.chars());++ if replacement_chars == offending_text {+ return None;+ }++ Some(Lint {+ span: offending_span,+ lint_kind: LintKind::WordChoice,+ suggestions: vec![Suggestion::ReplaceWith(replacement_chars)],+ message: format!("Did you mean `{}`?", replacement),+ priority: 31,+ })+ }++ fn description(&self) -> &str {+ "Expands time-related abbreviations (`hr`, `hrs`, `min`, `mins`, `sec`, `secs`, `ms`, `msec`, `msecs`) to their full forms (`hour`, `hours`, `minute`, `minutes`, `second`, `seconds`, `millisecond`, `milliseconds`)."+ }+}++#[cfg(test)]+mod tests {+ use crate::linting::tests::assert_suggestion_result;++ use super::ExpandTimeShorthands;++ #[test]+ fn detects_singular_hour() {+ assert_suggestion_result("5 hr", ExpandTimeShorthands::new(), "5 hours");+ }++ #[test]+ fn detects_singular_minute() {+ assert_suggestion_result("10 min", ExpandTimeShorthands::new(), "10 minutes");+ }++ #[test]+ fn detects_singular_second() {+ assert_suggestion_result("30 sec", ExpandTimeShorthands::new(), "30 seconds");+ }++ #[test]+ fn detects_plural_hours() {+ assert_suggestion_result("5 hrs", ExpandTimeShorthands::new(), "5 hours");+ }++ #[test]+ fn detects_plural_minutes() {+ assert_suggestion_result("10 mins", ExpandTimeShorthands::new(), "10 minutes");+ }++ #[test]+ fn detects_plural_seconds() {+ assert_suggestion_result("30 secs", ExpandTimeShorthands::new(), "30 seconds");+ }++ #[test]+ fn detects_millisecond() {+ assert_suggestion_result("5 ms", ExpandTimeShorthands::new(), "5 milliseconds");+ }++ #[test]+ fn detects_milliseconds() {+ assert_suggestion_result("10 msecs", ExpandTimeShorthands::new(), "10 milliseconds");+ }++ #[test]+ fn handles_punctuation_hour() {+ assert_suggestion_result("5 hr.", ExpandTimeShorthands::new(), "5 hours.");+ }++ #[test]+ fn handles_punctuation_minute() {+ assert_suggestion_result("10 min,", ExpandTimeShorthands::new(), "10 minutes,");+ }++ #[test]+ fn handles_punctuation_second() {+ assert_suggestion_result("30 sec!", ExpandTimeShorthands::new(), "30 seconds!");+ }++ #[test]+ fn handles_adjacent_number_hour() {+ assert_suggestion_result("5hr", ExpandTimeShorthands::new(), "5 hours");+ }++ #[test]+ fn handles_adjacent_number_minute() {+ assert_suggestion_result("10-min", ExpandTimeShorthands::new(), "10-minutes");+ }++ #[test]+ fn handles_adjacent_number_second() {+ assert_suggestion_result("30sec", ExpandTimeShorthands::new(), "30 seconds");+ }+}diff --git a/harper-core/src/linting/lint_group.rs b/harper-core/src/linting/lint_group.rsindex c807871fb..1c46c2aa2 100644--- a/harper-core/src/linting/lint_group.rs+++ b/harper-core/src/linting/lint_group.rs@@ -15,6 +15,7 @@ use super::correct_number_suffix::CorrectNumberSuffix;use super::despite_of::DespiteOf;use super::dot_initialisms::DotInitialisms;use super::ellipsis_length::EllipsisLength;+use super::expand_time_shorthands::ExpandTimeShorthands;use super::hereby::Hereby;use super::hop_hope::HopHope;use super::hyphenate_number_day::HyphenateNumberDay;@@ -235,6 +236,7 @@ impl LintGroup {insert_struct_rule!(LetsConfusion, true);insert_struct_rule!(DespiteOf, true);insert_struct_rule!(ChockFull, true);+ insert_struct_rule!(ExpandTimeShorthands, true);out.add("SpellCheck", Box::new(SpellCheck::new(dictionary)));out.config.set_rule_enabled("SpellCheck", true);diff --git a/harper-core/src/linting/matcher.rs b/harper-core/src/linting/matcher.rsindex 9407f8632..6cd773759 100644--- a/harper-core/src/linting/matcher.rs+++ b/harper-core/src/linting/matcher.rs@@ -117,14 +117,7 @@ impl Matcher {triggers.extend(pt! {"dep" => "dependency","deps" => "dependencies",- "hr" => "hour",- "hrs" => "hours","min" => "minimum",- "min" => "minute",- "mins" => "minutes",- "ms" => "milliseconds",- "sec" => "second",- "secs" => "seconds","stdin" => "standard input","stdout" => "standard output","w/" => "with",diff --git a/harper-core/src/linting/mod.rs b/harper-core/src/linting/mod.rsindex 2ada8a398..e04df095b 100644--- a/harper-core/src/linting/mod.rs+++ b/harper-core/src/linting/mod.rs@@ -16,6 +16,7 @@ mod dashes;mod despite_of;mod dot_initialisms;mod ellipsis_length;+mod expand_time_shorthands;mod hereby;mod hop_hope;mod hyphenate_number_day;@@ -73,6 +74,7 @@ pub use currency_placement::CurrencyPlacement;pub use despite_of::DespiteOf;pub use dot_initialisms::DotInitialisms;pub use ellipsis_length::EllipsisLength;+pub use expand_time_shorthands::ExpandTimeShorthands;pub use hereby::Hereby;pub use hop_hope::HopHope;pub use hyphenate_number_day::HyphenateNumberDay;diff --git a/harper-core/src/patterns/implies_quantity.rs b/harper-core/src/patterns/implies_quantity.rsnew file mode 100644index 000000000..6e0ce52e3--- /dev/null+++ b/harper-core/src/patterns/implies_quantity.rs@@ -0,0 +1,64 @@+use crate::{Token, TokenKind};++use super::Pattern;++/// This struct does two things.+///+/// First, it acts as a pattern that looks for phrases that describe a quantity of a noun+/// that may or may not succeed it.+///+/// Second, it determines the implied plurality of that quantity.implies+pub struct ImpliesQuantity;++impl ImpliesQuantity {+ pub fn implies_plurality(tokens: &[Token], source: &[char]) -> Option<bool> {+ let token = tokens.first()?;++ match token.kind {+ TokenKind::Word(Some(word_metadata)) => {+ if word_metadata.article {+ return Some(false);+ }++ let source = token.span.get_content(source);++ match source {+ ['a'] => Some(false),+ ['a', 'n'] => Some(false),+ ['m', 'a', 'n', 'y'] => Some(true),+ _ => None,+ }+ }+ TokenKind::Number(number) => Some((number.value.abs() - 1.).abs() > f64::EPSILON),+ _ => None,+ }+ }+}++impl Pattern for ImpliesQuantity {+ fn matches(&self, tokens: &[Token], source: &[char]) -> usize {+ if Self::implies_plurality(tokens, source).is_some() {+ 1+ } else {+ 0+ }+ }+}++#[cfg(test)]+mod tests {+ use crate::{+ patterns::{DocPattern, ImpliesQuantity},+ Document, Span,+ };++ #[test]+ fn number_implies() {+ let doc = Document::new_plain_english_curated("There are 60 minutes in an hour.");++ assert_eq!(+ ImpliesQuantity.find_all_matches_in_doc(&doc),+ vec![Span::new(4, 5), Span::new(10, 11)]+ )+ }+}diff --git a/harper-core/src/patterns/mod.rs b/harper-core/src/patterns/mod.rsindex ba5ba36e4..43b9e2a18 100644--- a/harper-core/src/patterns/mod.rs+++ b/harper-core/src/patterns/mod.rs@@ -15,6 +15,7 @@ mod any_pattern;mod consumes_remaining_pattern;mod either_pattern;mod exact_phrase;+mod implies_quantity;mod indefinite_article;mod invert;mod is_not_title_case;@@ -38,6 +39,7 @@ use blanket::blanket;pub use consumes_remaining_pattern::ConsumesRemainingPattern;pub use either_pattern::EitherPattern;pub use exact_phrase::ExactPhrase;+pub use implies_quantity::ImpliesQuantity;pub use indefinite_article::IndefiniteArticle;pub use invert::Invert;pub use is_not_title_case::IsNotTitleCase;