silens_scan/scanner_builder.rs
1use std::{error::Error, fmt, sync::Arc};
2
3use crate::{
4 compiled_rule::CompiledRuleSet,
5 rule::{Rule, RuleError, RuleId, RuleSpec},
6 scanner::Scanner,
7};
8
9/// Error returned when a [`Scanner`] cannot be compiled from its configured
10/// rules.
11///
12/// Scanner construction is a separate phase from scanning. All validation and
13/// matcher compilation happen in [`ScannerBuilder::build`], allowing
14/// [`Scanner::scan`](crate::Scanner::scan) to remain deterministic and free of
15/// rule-construction errors.
16#[derive(Debug)]
17pub enum ScannerBuildError {
18 /// A built-in [`RuleSpec`] could not be converted into an owned [`Rule`].
19 Rule(RuleError),
20
21 /// A rule uses an empty identifier.
22 ///
23 /// Rule identifiers are part of the stable machine-readable finding
24 /// contract and therefore cannot be empty.
25 EmptyRuleId,
26
27 /// A literal, prefix, or suffix matcher is empty.
28 ///
29 /// Empty matchers are rejected because they either match every source
30 /// position or otherwise have no useful detection semantics.
31 EmptyMatcher {
32 /// Identifier of the invalid rule.
33 rule_id: RuleId,
34 },
35
36 /// The configured rule count exceeds the capacity of the internal compact
37 /// rule index.
38 ///
39 /// The exact internal integer representation is deliberately not part of
40 /// the public API and may change after layout and benchmark measurements.
41 TooManyRules,
42
43 /// The shared multi-pattern automaton could not be built.
44 AutomatonBuild(aho_corasick::BuildError),
45}
46
47impl fmt::Display for ScannerBuildError {
48 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
49 match self {
50 Self::Rule(error) => write!(formatter, "could not construct rule: {error}"),
51 Self::EmptyRuleId => formatter.write_str("rule identifier cannot be empty"),
52 Self::EmptyMatcher { rule_id } => {
53 write!(formatter, "rule `{rule_id}` uses an empty matcher")
54 }
55 Self::TooManyRules => {
56 formatter.write_str("configured rule count exceeds the scanner limit")
57 }
58 Self::AutomatonBuild(error) => {
59 write!(
60 formatter,
61 "could not compile multi-pattern matcher: {error}"
62 )
63 }
64 }
65 }
66}
67
68impl Error for ScannerBuildError {
69 fn source(&self) -> Option<&(dyn Error + 'static)> {
70 match self {
71 Self::Rule(error) => Some(error),
72 Self::AutomatonBuild(error) => Some(error),
73 Self::EmptyRuleId | Self::EmptyMatcher { .. } | Self::TooManyRules => None,
74 }
75 }
76}
77
78impl From<RuleError> for ScannerBuildError {
79 fn from(error: RuleError) -> Self {
80 Self::Rule(error)
81 }
82}
83
84/// Builder used to configure and compile an immutable [`Scanner`].
85///
86/// A new builder starts with no rules. Built-in rule specifications and custom
87/// owned rules can be combined in any order. Calling [`build`](Self::build)
88/// converts built-ins into owned rules, validates the full configuration, and
89/// compiles the private execution plan.
90///
91/// # Examples
92///
93/// ```
94/// use silens_scan::{Rule, Scanner, Severity};
95///
96/// let scanner = Scanner::builder()
97/// .rule(Rule::literal(
98/// "example.exact-token",
99/// "internal_exact_token",
100/// Severity::High,
101/// ))
102/// .rule(Rule::prefix(
103/// "example.internal-token",
104/// "internal_live_",
105/// Severity::Critical,
106/// ))
107/// .build()?;
108///
109/// assert_eq!(scanner.rules_count(), 2);
110/// # Ok::<(), silens_scan::ScannerBuildError>(())
111/// ```
112#[derive(Debug, Default)]
113pub struct ScannerBuilder {
114 rules: Vec<Rule>,
115 builtin_rules: Vec<RuleSpec>,
116}
117
118impl ScannerBuilder {
119 /// Creates an empty scanner builder.
120 #[must_use]
121 pub const fn new() -> Self {
122 Self {
123 rules: Vec::new(),
124 builtin_rules: Vec::new(),
125 }
126 }
127
128 /// Adds one built-in rule specification.
129 ///
130 /// The specification is converted into an owned [`Rule`] during
131 /// [`build`](Self::build).
132 #[must_use]
133 pub fn builtin(mut self, rule: RuleSpec) -> Self {
134 self.builtin_rules.push(rule);
135 self
136 }
137
138 /// Adds multiple built-in rule specifications.
139 #[must_use]
140 pub fn builtins<I>(mut self, rules: I) -> Self
141 where
142 I: IntoIterator<Item = RuleSpec>,
143 {
144 self.builtin_rules.extend(rules);
145 self
146 }
147
148 /// Adds one custom owned rule.
149 #[must_use]
150 pub fn rule(mut self, rule: Rule) -> Self {
151 self.rules.push(rule);
152 self
153 }
154
155 /// Adds multiple custom owned rules.
156 #[must_use]
157 pub fn rules<I>(mut self, rules: I) -> Self
158 where
159 I: IntoIterator<Item = Rule>,
160 {
161 self.rules.extend(rules);
162 self
163 }
164
165 /// Validates and compiles the configured rules into an immutable scanner.
166 ///
167 /// Compilation performs all work that should not occur in the scan hot
168 /// path, including:
169 ///
170 /// - conversion of static built-in specifications into owned rules;
171 /// - validation of rule identifiers and matcher values;
172 /// - construction of the shared multi-pattern automaton;
173 /// - grouping of suffix and regular-expression matchers;
174 /// - construction of the immutable rule metadata table.
175 ///
176 /// The returned scanner can be reused for any number of input strings.
177 ///
178 /// # Errors
179 ///
180 /// Returns [`ScannerBuildError`] when a rule is invalid or the private
181 /// execution plan cannot be compiled.
182 pub fn build(mut self) -> Result<Scanner, ScannerBuildError> {
183 self.rules.reserve(self.builtin_rules.len());
184
185 for specification in self.builtin_rules {
186 self.rules.push(specification.to_rule()?);
187 }
188
189 let rules = CompiledRuleSet::compile(self.rules)?;
190 Ok(Scanner::new(Arc::new(rules)))
191 }
192}