1use 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 #[serde(default)]
60 coverage_kind: Option<String>,
61 #[serde(default)]
63 gate: Option<String>,
64}
65
66pub 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 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}