Skip to main content

sbol_rulegen/
lib.rs

1//! Build-time code generator that turns a versioned SBOL validation
2//! `rules.toml` into Rust rule-catalog source.
3//!
4//! The `sbol2` and `sbol3` crates each call [`generate`] from their `build.rs`,
5//! pointing at their own `rules.toml`. This keeps one generator, one set of
6//! catalog invariants, and one emitted shape across both data-model versions.
7//!
8//! Cold-compile cost on a fresh `target/` dir is roughly 30s because of the
9//! `toml`+`serde` dep stack. Subsequent builds reuse the cached deps; a caller
10//! re-runs the script only when its `rules.toml`, `build.rs`, or policies
11//! directory changes (the caller emits the `cargo:rerun-if-changed` directives).
12//!
13//! Outputs into `out_dir`:
14//!   - `rule_catalog.rs`: `VALIDATION_RULE_STATUSES` slice literal, sorted by
15//!     rule id for diff stability.
16//!   - `rule_spec_meta.rs`: the `VALIDATION_RULE_SPEC_*` constants sourced from
17//!     the TOML `[meta]` block.
18//!
19//! Failures (TOML parse error, unknown enum variant, missing required field,
20//! missing policy ADR) panic with a message that names the offending rule id
21//! and field, so a build failure points straight at the bad entry.
22
23use std::fs;
24use std::path::Path;
25
26use serde::Deserialize;
27
28#[derive(Debug, Deserialize)]
29#[serde(deny_unknown_fields)]
30struct Catalog {
31    meta: Meta,
32    #[serde(default, rename = "rule")]
33    rules: Vec<RawRule>,
34}
35
36#[derive(Debug, Deserialize)]
37#[serde(deny_unknown_fields)]
38struct Meta {
39    spec_version: String,
40    spec_path: String,
41    spec_canonical_url: String,
42    spec_pdf_sha256: String,
43}
44
45#[derive(Debug, Deserialize)]
46#[serde(deny_unknown_fields)]
47struct RawRule {
48    id: String,
49    status: String,
50    normative_severity: String,
51    spec_section: String,
52    note: String,
53    #[serde(default)]
54    blocker: Option<String>,
55    #[serde(default)]
56    validator_function: Option<String>,
57    /// Optional per-rule coverage tag. When set, overrides the
58    /// default inferred from `status`/`blocker`.
59    #[serde(default)]
60    coverage_kind: Option<String>,
61    /// Optional validation family. Absent means `Always`.
62    #[serde(default)]
63    gate: Option<String>,
64}
65
66/// Generates `rule_catalog.rs` and `rule_spec_meta.rs` into `out_dir` from the
67/// `rules.toml` at `rules_toml`.
68///
69/// When `policies_dir` is `Some`, every rule whose blocker is `Policy` must
70/// have a matching `<rule-id>.md` ADR file in that directory; a missing ADR
71/// panics. Pass `None` to skip the check (for example when building from a
72/// packaged crates.io tarball, where the workspace policies directory is
73/// absent).
74///
75/// Panics on any catalog error, naming the offending rule and field.
76pub fn generate(rules_toml: &Path, out_dir: &Path, policies_dir: Option<&Path>) {
77    let text = match fs::read_to_string(rules_toml) {
78        Ok(t) => t,
79        Err(err) => panic!("failed to read {}: {err}", rules_toml.display()),
80    };
81    let catalog: Catalog = match toml::from_str(&text) {
82        Ok(c) => c,
83        Err(err) => panic!("failed to parse {}: {err}", rules_toml.display()),
84    };
85
86    let mut rules = catalog.rules;
87    rules.sort_by(|a, b| a.id.cmp(&b.id));
88    for rule in &rules {
89        validate_status(&rule.id, &rule.status);
90        validate_severity(&rule.id, &rule.normative_severity);
91        validate_blocker(&rule.id, &rule.status, rule.blocker.as_deref());
92        validate_coverage_kind(&rule.id, rule.coverage_kind.as_deref());
93        validate_gate(&rule.id, rule.gate.as_deref());
94        if let Some(policies_dir) = policies_dir
95            && rule.blocker.as_deref() == Some("Policy")
96        {
97            let adr_path = policies_dir.join(format!("{}.md", rule.id));
98            if !adr_path.exists() {
99                panic!(
100                    "rule {}: blocker = \"Policy\" requires {}/{}.md (not found at {})",
101                    rule.id,
102                    policies_dir.display(),
103                    rule.id,
104                    adr_path.display()
105                );
106            }
107        }
108    }
109
110    write_rule_catalog(&out_dir.join("rule_catalog.rs"), &rules);
111    write_spec_meta(&out_dir.join("rule_spec_meta.rs"), &catalog.meta);
112}
113
114const VALID_STATUSES: &[&str] = &[
115    "Error",
116    "Warning",
117    "Configurable",
118    "MachineUncheckable",
119    "Unimplemented",
120];
121
122fn validate_status(rule_id: &str, status: &str) -> &'static str {
123    for valid in VALID_STATUSES {
124        if status == *valid {
125            return valid;
126        }
127    }
128    panic!("rule {rule_id}: invalid status `{status}` (expected one of {VALID_STATUSES:?})");
129}
130
131fn validate_severity(rule_id: &str, severity: &str) {
132    match severity {
133        "MUST" | "SHOULD" | "MAY" => {}
134        other => panic!(
135            "rule {rule_id}: invalid normative_severity `{other}` (expected MUST, SHOULD, or MAY)"
136        ),
137    }
138}
139
140fn validate_coverage_kind(rule_id: &str, coverage_kind: Option<&str>) {
141    if let Some(value) = coverage_kind {
142        match value {
143            "OntologyKnownTermsOnly"
144            | "LocalReferencesOnly"
145            | "LexicalShapeOnly"
146            | "PolicyDefaultUndecided" => {}
147            other => panic!(
148                "rule {rule_id}: invalid coverage_kind `{other}` (expected \
149                 OntologyKnownTermsOnly, LocalReferencesOnly, LexicalShapeOnly, \
150                 or PolicyDefaultUndecided)"
151            ),
152        }
153    }
154}
155
156fn validate_gate(rule_id: &str, gate: Option<&str>) {
157    if let Some(value) = gate {
158        match value {
159            "Always" | "Compliant" | "Complete" | "BestPractice" => {}
160            other => panic!(
161                "rule {rule_id}: invalid gate `{other}` (expected Always, Compliant, \
162                 Complete, or BestPractice)"
163            ),
164        }
165    }
166}
167
168fn validate_blocker(rule_id: &str, status: &str, blocker: Option<&str>) {
169    // `Error` and `Warning` are unconditional algorithms with no blocker.
170    // Every other status carries a blocker that names the configuration
171    // axis (Configurable), the spec context (MachineUncheckable), or
172    // what's needed to implement (Unimplemented).
173    let needs_blocker = !matches!(status, "Error" | "Warning");
174    match (needs_blocker, blocker) {
175        (true, None) => {
176            panic!("rule {rule_id}: status `{status}` requires a `blocker = \"...\"` entry")
177        }
178        (false, Some(b)) => panic!(
179            "rule {rule_id}: status `{status}` must not have a `blocker` entry (found `{b}`)"
180        ),
181        (true, Some(b)) => match b {
182            "Ontology" | "Resolver" | "StrictDatatype" | "Policy" | "External" => {}
183            other => panic!(
184                "rule {rule_id}: invalid blocker `{other}` (expected Ontology, Resolver, \
185                 StrictDatatype, Policy, or External)"
186            ),
187        },
188        (false, None) => {}
189    }
190}
191
192fn write_rule_catalog(path: &Path, rules: &[RawRule]) {
193    use std::fmt::Write;
194    let mut buf = String::new();
195    buf.push_str(
196        "// Generated by sbol-rulegen from rules.toml. Do not edit by hand.\n\
197         const VALIDATION_RULE_STATUSES: &[ValidationRuleStatus] = &[\n",
198    );
199    for rule in rules {
200        let status = validate_status(&rule.id, &rule.status);
201        let severity = match rule.normative_severity.as_str() {
202            "MUST" => "Must",
203            "SHOULD" => "Should",
204            "MAY" => "May",
205            other => panic!("rule {}: invalid severity `{other}`", rule.id),
206        };
207        writeln!(buf, "    ValidationRuleStatus::new(").unwrap();
208        writeln!(buf, "        {},", rust_string_literal(&rule.id)).unwrap();
209        writeln!(buf, "        RuleStatus::{status},").unwrap();
210        writeln!(buf, "        NormativeSeverity::{severity},").unwrap();
211        writeln!(buf, "        {},", rust_string_literal(&rule.spec_section)).unwrap();
212        writeln!(buf, "        {},", rust_string_literal(&rule.note)).unwrap();
213        match rule.blocker.as_deref() {
214            Some(b) => writeln!(buf, "        Some(super::Blocker::{b}),").unwrap(),
215            None => writeln!(buf, "        None,").unwrap(),
216        }
217        match rule.validator_function.as_deref() {
218            Some(fn_name) => {
219                writeln!(buf, "        Some({}),", rust_string_literal(fn_name)).unwrap()
220            }
221            None => writeln!(buf, "        None,").unwrap(),
222        }
223        match rule.coverage_kind.as_deref() {
224            Some(kind) => writeln!(buf, "        Some(super::CoverageKind::{kind}),").unwrap(),
225            None => writeln!(buf, "        None,").unwrap(),
226        }
227        let gate = rule.gate.as_deref().unwrap_or("Always");
228        writeln!(buf, "        super::ValidationGate::{gate},").unwrap();
229        writeln!(buf, "    ),").unwrap();
230    }
231    buf.push_str("];\n");
232    fs::write(path, buf).unwrap_or_else(|err| panic!("write {}: {err}", path.display()));
233}
234
235fn write_spec_meta(path: &Path, meta: &Meta) {
236    use std::fmt::Write;
237    let mut buf = String::new();
238    buf.push_str("// Generated by sbol-rulegen from rules.toml. Do not edit by hand.\n");
239    writeln!(
240        buf,
241        "pub const VALIDATION_RULE_SPEC_VERSION: &str = {};",
242        rust_string_literal(&meta.spec_version)
243    )
244    .unwrap();
245    writeln!(
246        buf,
247        "pub const VALIDATION_RULE_SPEC_PATH: &str = {};",
248        rust_string_literal(&meta.spec_path)
249    )
250    .unwrap();
251    writeln!(
252        buf,
253        "pub const VALIDATION_RULE_SPEC_CANONICAL_URL: &str = {};",
254        rust_string_literal(&meta.spec_canonical_url)
255    )
256    .unwrap();
257    writeln!(
258        buf,
259        "pub const VALIDATION_RULE_SPEC_PDF_SHA256: &str = {};",
260        rust_string_literal(&meta.spec_pdf_sha256)
261    )
262    .unwrap();
263    fs::write(path, buf).unwrap_or_else(|err| panic!("write {}: {err}", path.display()));
264}
265
266fn rust_string_literal(value: &str) -> String {
267    let mut out = String::with_capacity(value.len() + 2);
268    out.push('"');
269    for ch in value.chars() {
270        match ch {
271            '\\' => out.push_str("\\\\"),
272            '"' => out.push_str("\\\""),
273            '\n' => out.push_str("\\n"),
274            '\r' => out.push_str("\\r"),
275            '\t' => out.push_str("\\t"),
276            c if (c as u32) < 0x20 => {
277                use std::fmt::Write;
278                write!(out, "\\u{{{:x}}}", c as u32).unwrap();
279            }
280            c => out.push(c),
281        }
282    }
283    out.push('"');
284    out
285}