refactor: compile reusable detector registry

This commit is contained in:
Dandaedre 2026-09-29 15:15:51 +02:00
parent 43ede9c717
commit 10d607d423
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
5 changed files with 179 additions and 85 deletions

View File

@ -3,9 +3,7 @@
use std::{path::PathBuf, process::ExitCode};
use clap::{Parser, Subcommand};
use john_slop::{
ConfigLoader, ConfigName, ConfigOverrides, InputOverrides, analyze_source, read_inputs,
};
use john_slop::{ConfigLoader, ConfigName, ConfigOverrides, Detector, InputOverrides, read_inputs};
use miette::{IntoDiagnostic, Result, WrapErr};
/// Inspect files, directories, or ZIP-based documents for low-care signals.
@ -98,6 +96,7 @@ fn run(cli: &Cli) -> Result<bool> {
}
let config = loader.load()?;
let detector = Detector::new(&config).into_diagnostic()?;
let mut threshold_reached = false;
for path in &cli.paths {
@ -108,7 +107,7 @@ fn run(cli: &Cli) -> Result<bool> {
let document = document
.into_diagnostic()
.wrap_err("failed to read an input document")?;
let analysis = analyze_source(&config, &document.content);
let analysis = detector.analyze(&document.content);
println!(
"{}: confidence {}, {} finding(s)",
document.source,

View File

@ -1,103 +1,182 @@
//! All detection function & modules
//!
#[cfg(test)]
use regex::{Regex, RegexBuilder};
#[cfg(test)]
use std::sync::LazyLock;
//! Compiled, reusable registry of configured detection rules.
use regex::Regex;
use crate::{
config::Config,
model::{Analysis, Category, Confidence, Finding, RuleId},
replacement,
Analysis, Category, Confidence, Config, ConfigValidationError, Finding, HeuristicRule,
MatcherType, RuleId, replacement,
};
/// A tiny “search‑engine” that knows a *set* of Unicode code‑points.
/// It returns the **byte** offset of every match (so the positions are
/// deterministic even if you run the search in parallel).
#[cfg(test)]
static HYPHEN_REGEX: LazyLock<Regex> = LazyLock::new(|| {
// All the Unicode characters that look like a hyphen.
// (U+002D, U+2010, U+2011, U+2012, U+2013, U+2014, U+2015, …)
let pattern = r"[\u002D\u2010\u2011\u2012\u2013\u2014\u2015\u2212\uFE58\uFE63\uFF0D]";
RegexBuilder::new(pattern)
.unicode(true) // enable Unicode semantics
.build()
.expect("regex build failed")
});
/// Find *all* occurrences of the characters in `re` inside `text`.
/// Returns a vector of `(byte_start, byte_end, matched_char)` tuples.
#[cfg(test)]
fn find_all(re: &Regex, text: &str) -> Vec<(usize, usize, char)> {
re.find_iter(text)
.map(|m| (m.start(), m.end(), text[m.range()].chars().next().unwrap()))
.collect()
/// A validated heuristic definition paired with its reusable matcher.
#[derive(Debug, Clone)]
pub struct Rule {
definition: HeuristicRule,
matcher: CompiledMatcher,
}
/// Analyze text using the proof-of-concept Unicode punctuation rule.
pub fn analyze(config: &Config, source: &str) -> Analysis {
let findings = replacement::plan(config, source)
.into_iter()
.map(|edit| Finding {
rule_id: RuleId::from_static("typography-non-ascii-hyphen"),
category: Category::Typography,
message: "configured non-ASCII character has an ASCII replacement".to_owned(),
help: Some("Review the punctuation or replace it with an ASCII hyphen.".to_owned()),
byte_span: edit.byte_span.clone(),
matched_text: source[edit.byte_span.clone()].to_owned(),
weight: 10.0,
fix: Some(edit),
})
.collect::<Vec<_>>();
let score = u8::try_from(findings.len().saturating_mul(10)).unwrap_or(u8::MAX);
impl Rule {
/// Return this rule's stable identifier.
pub fn id(&self) -> &str {
&self.definition.id
}
Analysis {
findings,
confidence: Confidence::from_score(score),
/// Return this rule's evidence family.
pub const fn category(&self) -> Category {
self.definition.category
}
/// Return whether this rule is enabled in the resolved configuration.
pub const fn is_enabled(&self) -> bool {
self.definition.enabled
}
/// Return the literal, regex source, or replacement-catalog sentinel.
pub fn pattern(&self) -> &str {
match &self.matcher {
CompiledMatcher::ExactPhrase(pattern) => pattern,
CompiledMatcher::Regex(regex) => regex.as_str(),
CompiledMatcher::Replacement => "configured-replacements",
}
}
}
// If you have many different “special” characters you can keep a
// `Vec<(Regex, &'static str)>` and run the search in parallel with `rayon`.
/// Matcher compiled once when the detector registry is built.
#[derive(Debug, Clone)]
enum CompiledMatcher {
ExactPhrase(String),
Regex(Regex),
Replacement,
}
/// Reusable detection engine built from one resolved configuration snapshot.
#[derive(Debug, Clone)]
pub struct Detector {
config: Config,
rules: Vec<Rule>,
}
impl Detector {
/// Validate a resolved configuration and compile every reusable matcher.
pub fn new(config: &Config) -> Result<Self, DetectorBuildError> {
config
.validate()
.map_err(|error| DetectorBuildError::InvalidConfig(Box::new(error)))?;
let rules = config
.rules
.iter()
.cloned()
.map(Rule::compile)
.collect::<Result<Vec<_>, _>>()?;
Ok(Self {
config: config.clone(),
rules,
})
}
/// Return the compiled registry in deterministic configuration order.
pub fn rules(&self) -> &[Rule] {
&self.rules
}
/// Analyze text with the compiled registry.
///
/// Exact and regex execution is introduced in the next engine task. This
/// method initially preserves the replacement-backed detector behavior.
pub fn analyze(&self, source: &str) -> Analysis {
let Some(rule) = self
.rules
.iter()
.find(|rule| rule.is_enabled() && matches!(rule.matcher, CompiledMatcher::Replacement))
else {
return Analysis::default();
};
let findings = replacement::plan(&self.config, source)
.into_iter()
.map(|edit| Finding {
rule_id: RuleId::new(rule.id()),
category: rule.category(),
message: rule.definition.message.clone(),
help: Some(rule.definition.help.clone()),
byte_span: edit.byte_span.clone(),
matched_text: source[edit.byte_span.clone()].to_owned(),
weight: rule.definition.weight,
fix: Some(edit),
})
.collect::<Vec<_>>();
let score = u8::try_from(findings.len().saturating_mul(10)).unwrap_or(u8::MAX);
Analysis {
findings,
confidence: Confidence::from_score(score),
}
}
}
impl Rule {
fn compile(definition: HeuristicRule) -> Result<Self, DetectorBuildError> {
let matcher = match definition.matcher {
MatcherType::ExactPhrase => CompiledMatcher::ExactPhrase(definition.pattern.clone()),
MatcherType::Regex => {
let regex = Regex::new(&definition.pattern).map_err(|source| {
DetectorBuildError::InvalidRegex {
id: definition.id.clone(),
source,
}
})?;
CompiledMatcher::Regex(regex)
}
MatcherType::Replacement => CompiledMatcher::Replacement,
};
Ok(Self {
definition,
matcher,
})
}
}
/// Failure while constructing a reusable detector registry.
#[derive(Debug, thiserror::Error)]
pub enum DetectorBuildError {
/// The resolved configuration was not semantically valid.
#[error("cannot build detector from invalid configuration")]
InvalidConfig(#[source] Box<ConfigValidationError>),
/// A configured regular expression could not be compiled.
#[error("failed to compile matcher for rule `{id}`")]
InvalidRegex {
/// Stable rule identifier.
id: String,
/// Regex compiler failure.
#[source]
source: regex::Error,
},
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_finds_all_hyphens() {
let s = "a‑b—c‑—d‑";
// The string contains U+2011, U+2014, U+2011, U+2014, and U+2011 in
// that order. Each matched code point occupies three UTF-8 bytes.
let mut results = find_all(&HYPHEN_REGEX, s);
fn registry_is_built_from_the_validated_configuration() {
let config = Config::embedded();
let detector = Detector::new(&config).unwrap();
// sort to make the assertion deterministic
results.sort_by_key(|r| r.0);
assert_eq!(detector.rules().len(), config.rules.len());
assert_eq!(detector.rules()[0].id(), config.rules[0].id);
assert_eq!(detector.rules()[0].pattern(), config.rules[0].pattern);
assert_eq!(
results,
vec![
(1, 4, '‑'),
(5, 8, '—'),
(9, 12, '‑'),
(12, 15, '—'),
(16, 19, '‑')
]
detector
.rules()
.iter()
.filter(|rule| rule.is_enabled())
.count(),
config.rules.iter().filter(|rule| rule.enabled).count()
);
}
#[test]
fn regex_offsets_are_utf8_byte_offsets() {
// U+1D306 is one grapheme cluster and occupies four bytes in UTF-8.
let s = "a𝌆b";
let symbol_regex = Regex::new(r"\u{1D306}").unwrap();
let matched = symbol_regex.find(s).unwrap();
assert_eq!(matched.range(), 1..5);
}
#[test]
fn analysis_returns_explainable_findings_and_ignores_ascii_hyphens() {
let analysis = analyze(&Config::embedded(), "ordinary-word and suspicious—dash");
fn replacement_rule_preserves_explainable_findings() {
let detector = Detector::new(&Config::embedded()).unwrap();
let analysis = detector.analyze("ordinary-word and suspicious—dash");
assert_eq!(analysis.findings.len(), 1);
assert_eq!(
@ -108,4 +187,12 @@ mod tests {
assert_eq!(analysis.findings[0].fix.as_ref().unwrap().replacement, "-");
assert_eq!(analysis.confidence.score(), 10);
}
#[test]
fn compiled_regex_uses_utf8_byte_offsets() {
let regex = Regex::new(r"\u{1D306}").unwrap();
let matched = regex.find("a𝌆b").unwrap();
assert_eq!(matched.range(), 1..5);
}
}

View File

@ -18,6 +18,7 @@ pub use config::{
HeuristicRule, InputLimits, InputOverrides, MatcherType, ReplacementRule, RuleScope,
ThresholdOverrides,
};
pub use detector::{Detector, DetectorBuildError, Rule};
pub use error::{InputError, InputResult};
pub use input::{Document, Documents};
pub use model::{Analysis, Category, Confidence, Finding, RuleId, SourceId, TextEdit};
@ -29,7 +30,9 @@ pub fn load_config() -> Result<Config, ConfigError> {
/// Analyze a UTF-8 source snapshot with the resolved configuration.
pub fn analyze_source(config: &Config, source: &str) -> Analysis {
detector::analyze(config, source)
Detector::new(config)
.expect("validated configuration must build a detector")
.analyze(source)
}
/// Plan safe ASCII replacements without modifying the source.

View File

@ -9,6 +9,11 @@ use serde::{Deserialize, Serialize};
pub struct RuleId(String);
impl RuleId {
/// Construct a rule identifier from validated configuration text.
pub fn new(value: impl Into<String>) -> Self {
Self(value.into())
}
/// Construct a rule identifier from a static, trusted value.
pub fn from_static(value: &'static str) -> Self {
Self(value.to_owned())
@ -155,7 +160,7 @@ mod tests {
#[test]
fn rule_id_has_stable_text_and_ordering() {
let first = RuleId::from_static("alpha-rule");
let first = RuleId::new("alpha-rule");
let second = RuleId::from_static("beta-rule");
assert_eq!(first.as_str(), "alpha-rule");

View File

@ -107,7 +107,7 @@ configuration is explainable, and all precedence/validation tests pass.
## Milestone 3 — Heuristic detection engine
- [ ] Define a `Rule`/`Detector` interface and a registry built entirely from the
- [x] Define a `Rule`/`Detector` interface and a registry built entirely from the
validated heuristic config. Compile reusable matchers once.
- [ ] Implement exact phrase and regex rules with precise byte spans, match text,
category, weight, message, help, and stable rule ID.