Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat(core): allow scope config in Weir rules (#3382)
Elijah Potter0f00de8f061d
diff --git a/harper-core/default_config.json b/harper-core/default_config.jsonindex 7312d7246..53390138f 100644--- a/harper-core/default_config.json+++ b/harper-core/default_config.json@@ -1589,6 +1589,13 @@"label": "Intro Cue Comma Before Thanks"}},+ {+ "Bool": {+ "name": "IncludingButNotLimitedToPunctuation",+ "state": true,+ "label": "Including But Not Limited To Punctuation"+ }+ },{"Bool": {"name": "MercedesBenzHyphen",diff --git a/harper-core/src/linting/lint_group/mod.rs b/harper-core/src/linting/lint_group/mod.rsindex 53005dc70..58bc676d9 100644--- a/harper-core/src/linting/lint_group/mod.rs+++ b/harper-core/src/linting/lint_group/mod.rs@@ -264,7 +264,7 @@ use super::wrong_apostrophe::WrongApostrophe;use super::{ExprLinter, Lint};use super::{HtmlDescriptionLinter, Linter};use crate::linting::dashes::Dashes;-use crate::linting::expr_linter::Chunk;+use crate::linting::expr_linter::{Chunk, Sentence};use crate::linting::open_compounds::OpenCompounds;use crate::linting::{be_adjective_confusions, closed_compounds, initialisms, phrase_set_corrections, weir_rules,@@ -285,6 +285,8 @@ pub struct LintGroup {linters: BTreeMap<String, Box<dyn Linter>>,/// We use a binary map here so the ordering is stable.chunk_expr_linters: BTreeMap<String, Box<dyn ExprLinter<Unit = Chunk>>>,+ /// We use a binary map here so the ordering is stable.+ sentence_expr_linters: BTreeMap<String, Box<dyn ExprLinter<Unit = Sentence>>>,/// Since [`ExprLinter`]s operate on a chunk-basis, we can store a/// mapping of `Chunk -> Lint` and only rerun the expr linters/// when a chunk changes.@@ -293,6 +295,8 @@ pub struct LintGroup {/// of the key.#[expect(clippy::complexity)]chunk_expr_cache: LruCache<(u64, u64), Lrc<BTreeMap<String, Vec<Lint>>>>,+ #[expect(clippy::complexity)]+ sentence_expr_cache: LruCache<(u64, u64), Lrc<BTreeMap<String, Vec<Lint>>>>,hasher_builder: RandomState,clashing_linter_names: Option<Vec<String>>,}@@ -305,7 +309,9 @@ impl LintGroup {config: FlatConfig::default(),linters: BTreeMap::new(),chunk_expr_linters: BTreeMap::new(),+ sentence_expr_linters: BTreeMap::new(),chunk_expr_cache: LruCache::new(NonZero::new(1000).unwrap()),+ sentence_expr_cache: LruCache::new(NonZero::new(1000).unwrap()),hasher_builder: RandomState::default(),clashing_linter_names: None,}@@ -315,6 +321,7 @@ impl LintGroup {pub fn contains_key(&self, name: impl AsRef<str>) -> bool {self.linters.contains_key(name.as_ref())|| self.chunk_expr_linters.contains_key(name.as_ref())+ || self.sentence_expr_linters.contains_key(name.as_ref())}/// Add a [`Linter`] to the group, returning whether the operation was successful.@@ -358,6 +365,27 @@ impl LintGroup {}}+ /// Add a sentence-based [`ExprLinter`] to the group, returning whether the operation was successful.+ /// If it returns `false`, it is because a linter with that key already existed in the group.+ pub fn add_sentence_expr_linter(+ &mut self,+ name: impl AsRef<str>,+ linter: impl ExprLinter<Unit = Sentence> + 'static,+ ) -> bool {+ if self.contains_key(&name) {+ if self.clashing_linter_names.is_none() {+ self.clashing_linter_names = Some(vec![name.as_ref().to_string()]);+ } else if let Some(clashing_names) = &mut self.clashing_linter_names {+ clashing_names.push(name.as_ref().to_string());+ }+ false+ } else {+ self.sentence_expr_linters+ .insert(name.as_ref().to_string(), Box::new(linter) as _);+ true+ }+ }+/// Merge the contents of another [`LintGroup`] into this one.pub fn merge_from(&mut self, other: LintGroup) {self.config.merge_from(other.config);@@ -384,12 +412,27 @@ impl LintGroup {}}self.chunk_expr_linters.extend(other.chunk_expr_linters);++ if let Some((conflicting_key, _)) = other+ .sentence_expr_linters+ .iter()+ .find(|(k, _)| self.contains_key(k))+ {+ if self.clashing_linter_names.is_none() {+ self.clashing_linter_names = Some(vec![conflicting_key.clone()]);+ } else if let Some(clashing_names) = &mut self.clashing_linter_names {+ clashing_names.push(conflicting_key.clone());+ }+ }+ self.sentence_expr_linters+ .extend(other.sentence_expr_linters);}pub fn iter_keys(&self) -> impl Iterator<Item = &str> {self.linters.keys().chain(self.chunk_expr_linters.keys())+ .chain(self.sentence_expr_linters.keys()).map(|v| v.as_str())}@@ -416,6 +459,11 @@ impl LintGroup {.iter().map(|(key, value)| (key.as_str(), ExprLinter::description(value))),)+ .chain(+ self.sentence_expr_linters+ .iter()+ .map(|(key, value)| (key.as_str(), ExprLinter::description(value))),+ ).collect()}@@ -429,6 +477,11 @@ impl LintGroup {.iter().map(|(key, value)| (key.as_str(), value.description_html())),)+ .chain(+ self.sentence_expr_linters+ .iter()+ .map(|(key, value)| (key.as_str(), value.description_html())),+ ).collect()}@@ -858,6 +911,53 @@ impl LintGroup {}}+ // Sentence Expr linters+ for sentence in document.iter_sentences() {+ let Some(sentence_span) = sentence.span() else {+ continue;+ };++ let sentence_chars = document.get_span_content(&sentence_span);+ let config_hash = self.hasher_builder.hash_one(&self.config);+ let char_hash = self.hasher_builder.hash_one(sentence_chars);+ let cache_key = (char_hash, config_hash);++ let sentence_results = if let Some(hit) = self.sentence_expr_cache.get(&cache_key) {+ hit.clone()+ } else {+ let mut pattern_lints = BTreeMap::new();++ for (key, linter) in &mut self.sentence_expr_linters {+ if self.config.is_rule_enabled(key) {+ let lints =+ run_on_chunk(linter, sentence, document.get_source()).map(|mut l| {+ l.span.pull_by(sentence_span.start);+ l+ });++ pattern_lints.insert(key.clone(), lints.collect());+ }+ }++ let pattern_lints = Lrc::new(pattern_lints);++ self.sentence_expr_cache+ .put(cache_key, pattern_lints.clone());+ pattern_lints+ };++ for (key, vec) in sentence_results.iter() {+ results+ .entry(key.to_owned())+ .or_default()+ .extend(vec.iter().cloned().map(|mut lint| {+ // Bring the spans back into document-space+ lint.span.push_by(sentence_span.start);+ lint+ }));+ }+ }+results}}@@ -889,6 +989,7 @@ mod tests {use crate::linting::LintKind;use crate::linting::tests::{assert_no_lints, assert_suggestion_result};use crate::spell::{FstDictionary, MutableDictionary};+ use crate::weir::WeirLinter;use crate::{Dialect, Document, linting::Linter};fn test_group() -> LintGroup {@@ -956,6 +1057,31 @@ mod tests {assert_suggestion_result("This is ok.", test_group(), "This is okay.");}+ #[test]+ fn weir_linter_uses_configured_sentence_scope() {+ let source = r#"+ expr main one**two+ let message "Use three."+ let description "Test sentence-scoped Weir."+ let kind "Miscellaneous"+ let becomes "three"+ let strategy "Exact"+ let scope "Sentence"+ "#;++ let mut group = LintGroup::empty();+ group.add_sentence_expr_linter(+ "TestSentenceWeir",+ WeirLinter::new(source)+ .unwrap()+ .into_sentence_linter()+ .unwrap_or_else(|_| unreachable!()),+ );+ group.config.set_rule_enabled("TestSentenceWeir", true);++ assert_suggestion_result("one, two.", group, "three.");+ }+#[test]fn can_get_all_descriptions() {let group =diff --git a/harper-core/src/linting/mod.rs b/harper-core/src/linting/mod.rsindex 09c2386a9..8a1b58d0f 100644--- a/harper-core/src/linting/mod.rs+++ b/harper-core/src/linting/mod.rs@@ -273,7 +273,7 @@ mod worth_to_do;mod would_never_have;mod wrong_apostrophe;-pub use expr_linter::{Chunk, ExprLinter};+pub use expr_linter::{Chunk, ExprLinter, Sentence};pub use initialism_linter::InitialismLinter;pub use lint::Lint;pub use lint_group::{diff --git a/harper-core/src/linting/weir_rules/IncludingButNotLimitedToPunctuation.weir b/harper-core/src/linting/weir_rules/IncludingButNotLimitedToPunctuation.weirnew file mode 100644index 000000000..ec4c97196--- /dev/null+++ b/harper-core/src/linting/weir_rules/IncludingButNotLimitedToPunctuation.weir@@ -0,0 +1,36 @@+expr wordBefore [NOUN, VERB, ADJ, ADV, PRON, PROPN]+expr phraseMissingAfterIncluding (including but not limited to)+expr phraseWithAfterIncluding [@phraseMissingAfterIncluding, (including, but not limited to)]+expr parentheticalMissing [(@wordBefore @phraseMissingAfterIncluding), (, @phraseMissingAfterIncluding)]+expr parentheticalWithAfterIncluding [(@wordBefore @phraseWithAfterIncluding), (, @phraseWithAfterIncluding)]++expr missingLeading <(@wordBefore @phraseWithAfterIncluding), ( )>+expr missingAfterIncluding <<(@parentheticalMissing), (including *)>, ( )>+expr missingAfterTo <<(@parentheticalWithAfterIncluding *), (to *)>, ( )>++expr main [@missingLeading, @missingAfterIncluding, @missingAfterTo]++let message "Add punctuation around `including, but not limited to,`."+let description "Adds the conventional commas around `including, but not limited to,` when used parenthetically."+let kind "Punctuation"+let becomes ", "+let strategy "Exact"+let scope "Sentence"++test "There are many activities including but not limited to running, jumping, and swimming." "There are many activities, including, but not limited to, running, jumping, and swimming."+test "The policy covers services including but not limited to hosting and support." "The policy covers services, including, but not limited to, hosting and support."+test "We reviewed data including but not limited to logs." "We reviewed data, including, but not limited to, logs."+test "The package includes tools including but not limited to a formatter." "The package includes tools, including, but not limited to, a formatter."+test "Eligible expenses including but not limited to meals are reimbursed." "Eligible expenses, including, but not limited to, meals are reimbursed."+test "There are many activities including, but not limited to, running." "There are many activities, including, but not limited to, running."+test "The policy covers services, including but not limited to hosting." "The policy covers services, including, but not limited to, hosting."+test "We reviewed data, including, but not limited to logs." "We reviewed data, including, but not limited to, logs."+test "The package includes tools including, but not limited to support." "The package includes tools, including, but not limited to, support."+test "Eligible expenses, including but not limited to meals are reimbursed." "Eligible expenses, including, but not limited to, meals are reimbursed."++allows "There are many activities, including, but not limited to, running, jumping, and swimming."+allows "The policy covers services, including, but not limited to, hosting and support."+allows "We reviewed data, including, but not limited to, logs."+allows "Including but not limited to examples can be awkward at the start of a sentence."+allows "This sentence is including the phrase but not the parenthetical construction."+allows "The list is not limited to running."diff --git a/harper-core/src/linting/weir_rules/mod.rs b/harper-core/src/linting/weir_rules/mod.rsindex b2ae0f02f..7c76d80d4 100644--- a/harper-core/src/linting/weir_rules/mod.rs+++ b/harper-core/src/linting/weir_rules/mod.rs@@ -8,7 +8,11 @@ macro_rules! generate_boilerplate {{$(- group.add_chunk_expr_linter(stringify!($name), WeirLinter::new(include_str!(concat!(env!("WEIR_RULE_DIR"), "/", stringify!($name), ".weir"))).unwrap());+ let linter = WeirLinter::new(include_str!(concat!(env!("WEIR_RULE_DIR"), "/", stringify!($name), ".weir"))).unwrap();+ match linter.into_sentence_linter() {+ Ok(linter) => group.add_sentence_expr_linter(stringify!($name), linter),+ Err(linter) => group.add_chunk_expr_linter(stringify!($name), linter.into_chunk_linter().unwrap_or_else(|_| unreachable!())),+ };)+}diff --git a/harper-core/src/weir/error.rs b/harper-core/src/weir/error.rsindex c60650a3b..0e29cd0e0 100644--- a/harper-core/src/weir/error.rs+++ b/harper-core/src/weir/error.rs@@ -18,6 +18,8 @@ pub enum Error {InvalidLintKind,#[error("Invalid Replacement Strategy")]InvalidReplacementStrategy,+ #[error("Invalid Scope")]+ InvalidScope,#[error("Expected a variable type other than the one provided.")]ExpectedDifferentVariableType,#[error("Unable to resolve expression reference {0}")]diff --git a/harper-core/src/weir/mod.rs b/harper-core/src/weir/mod.rsindex a3e0a6a7a..716c5b337 100644--- a/harper-core/src/weir/mod.rs+++ b/harper-core/src/weir/mod.rs@@ -16,8 +16,8 @@ use is_macro::Is;use parsing::{parse_expr_str, parse_str};use strum_macros::{AsRefStr, EnumString};-use crate::expr::Expr;-use crate::linting::{Chunk, ExprLinter, Lint, LintKind, Linter, Suggestion};+use crate::expr::{Expr, ExprExt};+use crate::linting::{Chunk, ExprLinter, Lint, LintKind, Linter, Sentence, Suggestion};use crate::parsers::Markdown;use crate::spell::FstDictionary;use crate::{Document, Lrc, Token, TokenStringExt};@@ -35,6 +35,12 @@ enum ReplacementStrategy {Exact,}+#[derive(Debug, Clone, Copy, PartialEq, Eq, EnumString)]+enum WeirScope {+ Chunk,+ Sentence,+}+#[derive(Debug, Clone, PartialEq, Eq)]pub struct TestResult {pub expected: String,@@ -48,9 +54,14 @@ pub struct WeirLinter {strategy: ReplacementStrategy,replacements: Vec<String>,lint_kind: LintKind,+ scope: WeirScope,ast: Arc<Ast>,}+struct ChunkWeirLinter(WeirLinter);++struct SentenceWeirLinter(WeirLinter);+impl WeirLinter {pub fn new(weir_code: &str) -> Result<WeirLinter, Error> {let ast = parse_str(weir_code, true)?;@@ -61,6 +72,7 @@ impl WeirLinter {let lint_kind_name = "kind";let replacement_name = "becomes";let replacement_strat_name = "strategy";+ let scope_name = "scope";let resolved = resolve_exprs(&ast)?;@@ -124,11 +136,22 @@ impl WeirLinter {LintKind::Miscellaneous};+ let scope_var = ast.get_variable_value(scope_name);+ let scope = if let Some(scope) = scope_var {+ let str = scope+ .as_string()+ .ok_or(Error::ExpectedDifferentVariableType)?;+ WeirScope::from_str(str).ok().ok_or(Error::InvalidScope)?+ } else {+ WeirScope::Chunk+ };+let linter = WeirLinter {strategy: replacement_strat,ast,expr: expr.clone(),lint_kind,+ scope,description,message,replacements,@@ -137,6 +160,48 @@ impl WeirLinter {Ok(linter)}+ pub fn into_chunk_linter(self) -> Result<impl ExprLinter<Unit = Chunk>, Self> {+ if self.scope == WeirScope::Chunk {+ Ok(ChunkWeirLinter(self))+ } else {+ Err(self)+ }+ }++ pub fn into_sentence_linter(self) -> Result<impl ExprLinter<Unit = Sentence>, Self> {+ if self.scope == WeirScope::Sentence {+ Ok(SentenceWeirLinter(self))+ } else {+ Err(self)+ }+ }++ fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {+ let span = matched_tokens.span()?;+ let orig = span.get_content(source);++ let suggestions = match self.strategy {+ ReplacementStrategy::MatchCase => self+ .replacements+ .iter()+ .map(|s| Suggestion::replace_with_match_case(s.chars().collect(), orig))+ .collect(),+ ReplacementStrategy::Exact => self+ .replacements+ .iter()+ .map(|r| Suggestion::ReplaceWith(r.chars().collect()))+ .collect(),+ };++ Some(Lint {+ span,+ lint_kind: self.lint_kind,+ suggestions,+ message: self.message.to_owned(),+ priority: 31,+ })+ }+/// Counts the total number of tests defined.pub fn count_tests(&self) -> usize {self.ast.iter_tests().count()@@ -265,41 +330,62 @@ impl WeirLinter {}}-impl ExprLinter for WeirLinter {+impl Linter for WeirLinter {+ fn lint(&mut self, document: &Document) -> Vec<Lint> {+ let source = document.get_source();+ let mut lints = Vec::new();+ let units: Box<dyn Iterator<Item = &[Token]> + '_> = match self.scope {+ WeirScope::Chunk => Box::new(document.iter_chunks()),+ WeirScope::Sentence => Box::new(document.iter_sentences()),+ };++ for unit in units {+ lints.extend(+ self.expr+ .iter_matches(unit, source)+ .filter_map(|match_span| {+ self.match_to_lint(&unit[match_span.start..match_span.end], source)+ }),+ );+ }++ lints+ }++ fn description(&self) -> &str {+ &self.description+ }+}++impl ExprLinter for ChunkWeirLinter {type Unit = Chunk;fn expr(&self) -> &dyn Expr {- &self.expr+ &self.0.expr}fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {- let span = matched_tokens.span()?;- let orig = span.get_content(source);+ self.0.match_to_lint(matched_tokens, source)+ }- let suggestions = match self.strategy {- ReplacementStrategy::MatchCase => self- .replacements- .iter()- .map(|s| Suggestion::replace_with_match_case(s.chars().collect(), orig))- .collect(),- ReplacementStrategy::Exact => self- .replacements- .iter()- .map(|r| Suggestion::ReplaceWith(r.chars().collect()))- .collect(),- };+ fn description(&self) -> &str {+ &self.0.description+ }+}- Some(Lint {- span,- lint_kind: self.lint_kind,- suggestions,- message: self.message.to_owned(),- priority: 31,- })+impl ExprLinter for SentenceWeirLinter {+ type Unit = Sentence;++ fn expr(&self) -> &dyn Expr {+ &self.0.expr+ }++ fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {+ self.0.match_to_lint(matched_tokens, source)}fn description(&self) -> &str {- &self.description+ &self.0.description}}@@ -403,6 +489,73 @@ pub mod tests {assert_eq!(4, linter.count_tests());}+ #[test]+ fn scope_defaults_to_chunk() {+ let source = r#"+ expr main one**two+ let message "Use three."+ let description "Test chunk-scoped Weir."+ let kind "Miscellaneous"+ let becomes "three"+ let strategy "Exact"++ allows "one, two."+ "#;++ let mut linter = WeirLinter::new(source).unwrap();++ assert_passes_all(&mut linter);++ let linter = WeirLinter::new(source).unwrap();+ let linter = match linter.into_sentence_linter() {+ Ok(_) => panic!("default-scoped Weir rule should not convert to sentence linter"),+ Err(linter) => linter,+ };+ assert!(linter.into_chunk_linter().is_ok());+ }++ #[test]+ fn sentence_scope_can_match_across_chunks() {+ let source = r#"+ expr main one**two+ let message "Use three."+ let description "Test sentence-scoped Weir."+ let kind "Miscellaneous"+ let becomes "three"+ let strategy "Exact"+ let scope "Sentence"++ test "one, two." "three."+ "#;++ let mut linter = WeirLinter::new(source).unwrap();++ assert_passes_all(&mut linter);++ assert!(+ WeirLinter::new(source)+ .unwrap()+ .into_sentence_linter()+ .is_ok()+ );+ }++ #[test]+ fn invalid_scope_errors() {+ let source = r#"+ expr main one+ let message ""+ let description ""+ let kind "Miscellaneous"+ let becomes ""+ let scope "Paragraph"+ "#;++ let res = WeirLinter::new(source);++ assert_eq!(res.err(), Some(Error::InvalidScope));+ }+#[test]fn fails_on_unresolved_expr() {let source = r#"diff --git a/harper-core/src/weirpack/mod.rs b/harper-core/src/weirpack/mod.rsindex dd75b3242..d51631d06 100644--- a/harper-core/src/weirpack/mod.rs+++ b/harper-core/src/weirpack/mod.rs@@ -72,7 +72,15 @@ impl Weirpack {for (name, rule) in &self.rules {let linter = WeirLinter::new(rule)?;- group.add_chunk_expr_linter(name, linter);+ match linter.into_sentence_linter() {+ Ok(linter) => group.add_sentence_expr_linter(name, linter),+ Err(linter) => group.add_chunk_expr_linter(+ name,+ linter+ .into_chunk_linter()+ .unwrap_or_else(|_| unreachable!()),+ ),+ };group.config.set_rule_enabled(name, true);}diff --git a/packages/web/src/routes/docs/weir/+page.md b/packages/web/src/routes/docs/weir/+page.mdindex 15ebaa115..b3623399d 100644--- a/packages/web/src/routes/docs/weir/+page.md+++ b/packages/web/src/routes/docs/weir/+page.md@@ -247,6 +247,23 @@ let becomes "Google Workspace"let strategy "Exact"```+## Matching Scope++By default, Weir rules run on chunks, which are usually clauses split by commas and sentence-ending punctuation.+If a rule needs to match across a comma within the same sentence, set its scope to `Sentence`.++```plaintext+expr main one**two+let message "Use three."+let description "Replaces a phrase that can span a comma."+let kind "Miscellaneous"+let becomes "three"+let scope "Sentence"+```++The supported values are `Chunk` and `Sentence`.+The setting is optional; omitting it is the same as `let scope "Chunk"`.+## Adding TestsThe Weir language supports the inclusion of tests directly in the file.