Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat(core): create rule to add accent to cliche (#3494)
Elijah Potterdf18ff1cbc2b
diff --git a/AGENTS.md b/AGENTS.mdindex 64af60e3c..7e7a4beaa 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -222,6 +222,7 @@ When asked to write a new rule, keep these guidelines in mind:- You should include at least 15 total tests, covering a wide variety of cases. Cover false-positives, false negatives, true positives, and if relevant, true negatives.- You should run any and all tests to ensure that you do no break existing behavior and that your new rule runs the way you expect.- After adding a new rule, update `harper-core/default_config.json` so it is enabled in the curated default config.+- Built-in Weir rules can be grouped by putting related `.weir` files in a directory under `harper-core/src/linting/weir_rules`; the directory name becomes the single public rule name.- If the rule is related to a closed compound noun, see if you can just add an entry to the existing closed compound linter.Unless you are specifically requested to write the rule in a specific way, choose the language (Rust or Weir) and methodology that fits the task.diff --git a/harper-core/build.rs b/harper-core/build.rsindex 3246b7d63..df200a1b2 100644--- a/harper-core/build.rs+++ b/harper-core/build.rs@@ -1,43 +1,152 @@-use std::{env, fs, path::PathBuf};+use std::{env, fs, path::Path};++#[derive(Debug)]+struct StandaloneRule {+ name: String,+ relative_path: String,+}++#[derive(Debug)]+struct GroupedRule {+ public_name: String,+ children: Vec<StandaloneRule>,+}++/// Convert a Weir rule path to an `include_str!`-friendly relative path.+fn path_as_weir_relative(path: &Path, root: &Path) -> String {+ path.strip_prefix(root)+ .unwrap()+ .to_string_lossy()+ .replace('\\', "/")+}++/// Top-level `RuleName.weir` files are public as `RuleName`.+fn rule_name_from_path(path: &Path) -> String {+ path.file_stem().unwrap().to_string_lossy().to_string()+}++/// Grouped child rules use their relative path as a private name.+fn rule_name_from_relative_path(path: &Path, root: &Path) -> String {+ let mut relative = path_as_weir_relative(path, root);+ relative.truncate(relative.len() - ".weir".len());+ relative+}++/// Recursively collect child `.weir` files for a grouped rule directory.+fn collect_weir_files(dir: &Path, group_root: &Path, weir_root: &Path) -> Vec<StandaloneRule> {+ println!("cargo:rerun-if-changed={}", dir.display());++ let mut entries = fs::read_dir(dir)+ .unwrap()+ .filter_map(Result::ok)+ .collect::<Vec<_>>();++ entries.sort_by_key(|entry| entry.path());++ let mut rules = Vec::new();++ for entry in entries {+ let path = entry.path();+ let file_type = entry.file_type().unwrap();++ if file_type.is_dir() {+ rules.extend(collect_weir_files(&path, group_root, weir_root));+ } else if file_type.is_file() && path.extension().is_some_and(|ext| ext == "weir") {+ println!("cargo:rerun-if-changed={}", path.display());++ rules.push(StandaloneRule {+ name: rule_name_from_relative_path(&path, group_root),+ relative_path: path_as_weir_relative(&path, weir_root),+ });+ }+ }++ rules+}++/// Render a string as an escaped Rust string literal for generated source.+fn rust_string_literal(value: &str) -> String {+ format!("{value:?}")+}fn main() {- let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());+ let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));let weir_rule_dir = manifest_dir.join("./src/linting/weir_rules");- let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());+ let out_dir = Path::new(&env::var("OUT_DIR").unwrap()).to_path_buf();let dest = out_dir.join("weir_rules_generated_list.rs");- let mut files: Vec<PathBuf> = fs::read_dir(&weir_rule_dir)+ let mut entries = fs::read_dir(&weir_rule_dir).unwrap().filter_map(Result::ok)- .filter(|e| e.file_type().unwrap().is_file())- .map(|e| e.path().to_path_buf())- .collect();+ .collect::<Vec<_>>();++ entries.sort_by_key(|entry| entry.path());++ let mut standalone_rules = Vec::new();+ let mut grouped_rules = Vec::new();++ // Watch the root for top-level `.weir` files and group directories.+ println!("cargo:rerun-if-changed={}", weir_rule_dir.display());- files.sort();+ for entry in entries {+ let path = entry.path();+ let file_type = entry.file_type().unwrap();++ if file_type.is_dir() {+ let public_name = entry.file_name().to_string_lossy().to_string();+ let children = collect_weir_files(&path, &path, &weir_rule_dir);++ if !children.is_empty() {+ grouped_rules.push(GroupedRule {+ public_name,+ children,+ });+ }+ } else if file_type.is_file() && path.extension().is_some_and(|ext| ext == "weir") {+ println!("cargo:rerun-if-changed={}", path.display());++ standalone_rules.push(StandaloneRule {+ name: rule_name_from_path(&path),+ relative_path: path_as_weir_relative(&path, &weir_rule_dir),+ });+ }+ }let mut code = String::new();- code.push_str("generate_boilerplate!{[");+ code.push_str("generate_boilerplate! {\n");+ code.push_str(" standalone: [\n");+ for rule in standalone_rules {+ code.push_str(&format!(+ " ({}, {}),\n",+ rust_string_literal(&rule.name),+ rust_string_literal(&rule.relative_path)+ ));+ }+ code.push_str(" ],\n");++ code.push_str(" groups: [\n");+ for group in grouped_rules {+ code.push_str(&format!(+ " ({}, [\n",+ rust_string_literal(&group.public_name)+ ));- for file in files {- if file- .file_name()- .unwrap()- .to_string_lossy()- .ends_with(".weir")- {+ for child in group.children {code.push_str(&format!(- "{},\n",- file.file_stem().unwrap().to_str().unwrap()+ " ({}, {}),\n",+ rust_string_literal(&child.name),+ rust_string_literal(&child.relative_path)));}- }- code.push_str("]}");+ code.push_str(" ]),\n");+ }+ code.push_str(" ],\n");+ code.push_str("}\n");fs::write(&dest, code).unwrap();- println!("cargo:rerun-if-changed={}", weir_rule_dir.display());println!("cargo:rerun-if-changed=build.rs");println!("cargo:rustc-env=WEIR_RULE_DIR={}", weir_rule_dir.display());println!("cargo:rustc-env=WEIR_RULE_LIST={}", dest.display());diff --git a/harper-core/default_config.json b/harper-core/default_config.jsonindex cb90d3b1d..577bb4683 100644--- a/harper-core/default_config.json+++ b/harper-core/default_config.json@@ -2420,6 +2420,13 @@"label": "Case In Point"}},+ {+ "Bool": {+ "name": "ClicheAccent",+ "state": true,+ "label": "Cliche Accent"+ }+ },{"Bool": {"name": "DoNotWant",diff --git a/harper-core/src/linting/weir_rules/ClicheAccent/Plural.weir b/harper-core/src/linting/weir_rules/ClicheAccent/Plural.weirnew file mode 100644index 000000000..812dffe64--- /dev/null+++ b/harper-core/src/linting/weir_rules/ClicheAccent/Plural.weir@@ -0,0 +1,19 @@+expr main cliches++let message "Did you mean `clichés`?"+let description "Adds the accent to the standard plural spelling of `clichés`."+let kind "Spelling"+let becomes "clichés"++test "Avoid tired cliches." "Avoid tired clichés."+test "These cliches weaken the argument." "These clichés weaken the argument."+test "The essay repeats old cliches." "The essay repeats old clichés."+test "Movie cliches can still be fun." "Movie clichés can still be fun."+test "Readers notice cliches quickly." "Readers notice clichés quickly."+test "CLICHES should be revised." "CLICHÉS should be revised."+test "Some CLICHES are hard to avoid." "Some CLICHÉS are hard to avoid."+allows "Clichés are sometimes useful shorthand."+allows "Those clichés were intentional."+allows "CLICHÉS should already be accented."+allows "Clichy is a commune in France."+allows "The uncluttered sentence is not a stereotype."diff --git a/harper-core/src/linting/weir_rules/ClicheAccent/Singular.weir b/harper-core/src/linting/weir_rules/ClicheAccent/Singular.weirnew file mode 100644index 000000000..29d53c714--- /dev/null+++ b/harper-core/src/linting/weir_rules/ClicheAccent/Singular.weir@@ -0,0 +1,22 @@+expr main cliche++let message "Did you mean `cliché`?"+let description "Adds the accent to the standard spelling of `cliché`."+let kind "Spelling"+let becomes "cliché"++test "That ending is a cliche." "That ending is a cliché."+test "It felt like a tired cliche." "It felt like a tired cliché."+test "Avoid that cliche in the introduction." "Avoid that cliché in the introduction."+test "The phrase has become a cliche." "The phrase has become a cliché."+test "Calling it innovative is a cliche by now." "Calling it innovative is a cliché by now."+test "This is another cliche, unfortunately." "This is another cliché, unfortunately."+test "The plot twist was cliche-ridden." "The plot twist was cliché-ridden."+test "Cliche examples can distract readers." "Cliché examples can distract readers."+test "CLICHE headlines are easy to spot." "CLICHÉ headlines are easy to spot."+test "A CLICHE? Not ideal." "A CLICHÉ? Not ideal."+allows "That ending is a cliché."+allows "The cliché-ridden plot bored me."+allows "Clichés are sometimes useful shorthand."+allows "Clichy is a commune in France."+allows "The uncluttered sentence is not a stereotype."diff --git a/harper-core/src/linting/weir_rules/mod.rs b/harper-core/src/linting/weir_rules/mod.rsindex 7c76d80d4..338ae75ea 100644--- a/harper-core/src/linting/weir_rules/mod.rs+++ b/harper-core/src/linting/weir_rules/mod.rs@@ -2,40 +2,80 @@ use super::LintGroup;use crate::weir::WeirLinter;macro_rules! generate_boilerplate {- ([$($name:ident),+ $(,)?]) => {+ (+ standalone: [$(($standalone_name:literal, $standalone_path:literal)),* $(,)?],+ groups: [$(($group_name:literal, [$(($child_name:literal, $child_path:literal)),* $(,)?])),* $(,)?],+ ) => {pub fn lint_group() -> LintGroup {let mut group = LintGroup::default();+ // Standalone `.weir` files remain one public Harper rule each.+ $(+ add_weir_linter(+ &mut group,+ $standalone_name,+ include_str!(concat!(env!("WEIR_RULE_DIR"), "/", $standalone_path)),+ );+ )*++ $({+ // A directory under `weir_rules` is exposed as a single public rule.+ // Its children are regular Weir rules inside an inner LintGroup, so they+ // run independently while the outer configuration only sees `$group_name`.+ let mut grouped_rule = LintGroup::default();+$(- 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!())),- };- )++ add_weir_linter(+ &mut grouped_rule,+ $child_name,+ include_str!(concat!(env!("WEIR_RULE_DIR"), "/", $child_path)),+ );+ )*++ grouped_rule.set_all_rules_to(Some(true));+ group.add($group_name, grouped_rule);}+ )*group.set_all_rules_to(Some(true));group}+ /// Add a Weir rule using its declared chunk/sentence scope.+ fn add_weir_linter(group: &mut LintGroup, name: &str, weir_code: &str) {+ let linter = WeirLinter::new(weir_code).unwrap();+ 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!()),+ ),+ };+ }+#[cfg(test)]mod tests {- use paste::paste;use crate::weir::tests::assert_passes_all;use crate::weir::WeirLinter;- $(- paste! {- #[test]- fn [<run_tests_for_ $name:snake>](){- let mut linter = WeirLinter::new(include_str!(concat!(env!("WEIR_RULE_DIR"), "/", stringify!($name), ".weir"))).unwrap();- assert_passes_all(&mut linter);- }- }- )++ #[test]+ fn run_tests_for_weir_rules() {+ $(+ let mut linter = WeirLinter::new(+ include_str!(concat!(env!("WEIR_RULE_DIR"), "/", $standalone_path)),+ ).unwrap();+ assert_passes_all(&mut linter);+ )*++ $($(+ let mut linter = WeirLinter::new(+ include_str!(concat!(env!("WEIR_RULE_DIR"), "/", $child_path)),+ ).unwrap();+ assert_passes_all(&mut linter);+ )*)*+ }}};}diff --git a/packages/web/src/routes/docs/contributors/author-a-rule/+page.md b/packages/web/src/routes/docs/contributors/author-a-rule/+page.mdindex bdb8bc5d1..13f2103bd 100644--- a/packages/web/src/routes/docs/contributors/author-a-rule/+page.md+++ b/packages/web/src/routes/docs/contributors/author-a-rule/+page.md@@ -122,7 +122,12 @@ Similarly, if you just want Harper to enforce proper capitalization of a multi-t},```-If neither of those work for the rule you have in mind, continue on to the next section.+If your rule is a good fit for Weir, add it under `harper-core/src/linting/weir_rules`.+A top-level file, such as `RuleName.weir`, is loaded as one public rule named `RuleName`.+If several related Weir rules should share one setting and one rules-catalog entry, put them in a directory instead.+For example, `RuleName/Singular.weir` and `RuleName/Plural.weir` run as separate child rules, but Harper exposes them together as one public rule named `RuleName`.++If none of those work for the rule you have in mind, continue on to the next section.## Create Your Rule's Module@@ -178,7 +183,7 @@ Otherwise, use `insert_struct_rule`.## Update `default_config.json`-Whenever you add a new rule, update `harper-core/src/linting/lint_group/default_config.json` too.+Whenever you add a new rule, update `harper-core/default_config.json` too.That file defines the curated default configuration shown throughout Harper, so a new rule will notappear in the default setup until it is added there as well.See also [`StructuredConfig`](https://docs.rs/harper-core/latest/harper_core/linting/lint_group/struct.StructuredConfig.html).