use std::path::Path;
use anyhow::{Context, Result};
use serde::Deserialize;
const BUILTINS: &[(&str, &str)] = &[
("cnmi-rules", include_str!("../profiles/cnmi-rules.toml")),
(
"cnmi-statutes",
include_str!("../profiles/cnmi-statutes.toml"),
),
(
"connecticut-practice-book",
include_str!("../profiles/connecticut-practice-book.toml"),
),
("guam-gca", include_str!("../profiles/guam-gca.toml")),
("guam-rules", include_str!("../profiles/guam-rules.toml")),
(
"kentucky-krs",
include_str!("../profiles/kentucky-krs.toml"),
),
("maine-rules", include_str!("../profiles/maine-rules.toml")),
(
"north-carolina-appellate-rules",
include_str!("../profiles/north-carolina-appellate-rules.toml"),
),
(
"north-carolina-general-practice-rules",
include_str!("../profiles/north-carolina-general-practice-rules.toml"),
),
(
"north-dakota-century-code",
include_str!("../profiles/north-dakota-century-code.toml"),
),
("pr-rules", include_str!("../profiles/pr-rules.toml")),
(
"wyoming-statutes",
include_str!("../profiles/wyoming-statutes.toml"),
),
];
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Profile {
pub name: String,
pub jurisdiction: String,
pub kind: String,
pub citation_template: String,
#[serde(default)]
pub draft: bool,
#[serde(default = "default_language")]
pub language: String,
pub heading_patterns: Vec<String>,
#[serde(default)]
pub history_patterns: Vec<String>,
#[serde(default)]
pub date_formats: Vec<String>,
#[serde(default)]
pub skip_patterns: Vec<String>,
#[serde(default)]
pub skip_block_patterns: Vec<String>,
#[serde(default)]
pub stop_patterns: Vec<String>,
#[serde(default)]
pub empty_doc_patterns: Vec<String>,
#[serde(default)]
pub adoption_patterns: Vec<String>,
#[serde(default)]
pub adoption_date: Option<String>,
#[serde(default)]
pub title_patterns: Vec<String>,
#[serde(default)]
pub expected_gaps: Vec<String>,
#[serde(default = "default_true")]
pub monotonic_numbers: bool,
#[serde(default)]
pub toc_restart: bool,
#[serde(default = "default_true")]
pub heading_x0_cluster: bool,
#[serde(default)]
pub heading_style: Option<HeadingStyle>,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HeadingStyle {
#[serde(default)]
pub bold: Option<bool>,
#[serde(default)]
pub centered: Option<bool>,
#[serde(default)]
pub min_size: Option<f32>,
#[serde(default)]
pub max_size: Option<f32>,
}
fn default_language() -> String {
"en".to_string()
}
fn default_true() -> bool {
true
}
impl Profile {
pub fn from_toml(src: &str) -> Result<Self> {
let p: Profile = toml::from_str(src).context("invalid profile TOML")?;
p.validate()?;
Ok(p)
}
pub fn from_path(path: &Path) -> Result<Self> {
let src = std::fs::read_to_string(path)
.with_context(|| format!("reading profile {}", path.display()))?;
Self::from_toml(&src)
}
pub fn builtin(name: &str) -> Result<Self> {
let src = BUILTINS
.iter()
.find(|(n, _)| *n == name)
.map(|(_, s)| *s)
.with_context(|| {
format!(
"no built-in profile {name:?} (known: {})",
builtin_names().join(", ")
)
})?;
Self::from_toml(src)
}
fn validate(&self) -> Result<()> {
anyhow::ensure!(
!self.jurisdiction.is_empty(),
"profile: jurisdiction must not be empty"
);
anyhow::ensure!(
self.kind == "rule" || self.kind == "statute",
"profile: kind must be \"rule\" or \"statute\", got {:?}",
self.kind
);
anyhow::ensure!(
!self.language.is_empty(),
"profile: language must not be empty"
);
self.validate_template()?;
anyhow::ensure!(
!self.heading_patterns.is_empty(),
"profile: at least one heading pattern is required"
);
for pat in &self.heading_patterns {
let re =
regex::Regex::new(pat).with_context(|| format!("invalid profile regex {pat:?}"))?;
anyhow::ensure!(
re.capture_names().flatten().any(|n| n == "num"),
"profile: heading pattern {pat:?} lacks the required (?P<num>…) capture"
);
}
for pat in self
.history_patterns
.iter()
.chain(&self.skip_patterns)
.chain(&self.skip_block_patterns)
.chain(&self.stop_patterns)
.chain(&self.empty_doc_patterns)
.chain(&self.adoption_patterns)
.chain(&self.title_patterns)
{
regex::Regex::new(pat).with_context(|| format!("invalid profile regex {pat:?}"))?;
}
for pat in &self.title_patterns {
let re = regex::Regex::new(pat).expect("validated above");
anyhow::ensure!(
re.capture_names().flatten().any(|n| n == "title"),
"profile: title pattern {pat:?} lacks the required (?P<title>…) capture"
);
}
if let Some(date) = &self.adoption_date {
chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d").with_context(|| {
format!("profile: adoption_date {date:?} is not a YYYY-MM-DD date")
})?;
}
crate::structure::dates::DateScanner::new(&self.date_formats)
.context("profile: date_formats")?;
Ok(())
}
fn validate_template(&self) -> Result<()> {
anyhow::ensure!(
self.citation_template.contains("{num}"),
"profile: citation_template must contain {{num}}"
);
let placeholder = regex::Regex::new(r"\{([a-zA-Z_]+)\}").expect("static regex");
for cap in placeholder.captures_iter(&self.citation_template) {
let name = &cap[1];
match name {
"num" => {}
"title" => {
let heading_has_title = self.heading_patterns.iter().any(|p| {
regex::Regex::new(p)
.map(|re| re.capture_names().flatten().any(|n| n == "title"))
.unwrap_or(false)
});
anyhow::ensure!(
!self.title_patterns.is_empty() || heading_has_title,
"profile: citation_template uses {{title}} but the profile declares \
no title_patterns and no heading pattern captures (?P<title>…)"
);
}
other => anyhow::bail!(
"profile: citation_template has unknown placeholder {{{other}}} \
(only {{num}} and {{title}} exist)"
),
}
}
Ok(())
}
}
pub fn builtin_names() -> Vec<&'static str> {
BUILTINS.iter().map(|(n, _)| *n).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builtin_cnmi_rules_parses() {
let p = Profile::builtin("cnmi-rules").expect("built-in must parse");
assert_eq!(p.jurisdiction, "northern_mariana_islands");
assert_eq!(p.kind, "rule");
assert_eq!(p.language, "en");
assert!(p.citation_template.contains("{num}"));
assert!(!p.draft, "template signed off 2026-07-03");
assert!(p.monotonic_numbers && p.heading_x0_cluster);
}
#[test]
fn builtin_cnmi_statutes_parses() {
let p = Profile::builtin("cnmi-statutes").expect("built-in must parse");
assert_eq!(p.jurisdiction, "northern_mariana_islands");
assert_eq!(p.kind, "statute");
assert!(p.citation_template.contains("{title}"));
assert!(
!p.title_patterns.is_empty(),
"{{title}} needs a title source"
);
assert!(!p.draft, "template signed off 2026-07-03");
}
#[test]
fn unknown_builtin_errors() {
assert!(Profile::builtin("nope").is_err());
}
#[test]
fn every_builtin_parses_and_is_signed_off() {
for name in builtin_names() {
let p = Profile::builtin(name).unwrap_or_else(|e| panic!("{name}: {e:#}"));
assert_eq!(p.name, name, "profile name must match the builtin key");
assert!(
!p.draft,
"{name}: wave-1 templates were signed off 2026-07-03"
);
}
}
#[test]
fn wave1_builtins_carry_the_signed_off_templates() {
let expected = [
("cnmi-statutes", "{title} CMC § {num}"),
("cnmi-rules", "NMI R. Civ. P. {num}"),
("guam-gca", "{title} GCA § {num}"),
("guam-rules", "Guam R. Civ. P. {num}"),
("maine-rules", "M.R. Civ. P. {num}"),
("connecticut-practice-book", "Conn. Practice Book § {num}"),
("kentucky-krs", "KRS {num}"),
("pr-rules", "32 L.P.R.A. Ap. V, R. {num}"),
("north-dakota-century-code", "N.D. Cent. Code § {num}"),
("wyoming-statutes", "Wyo. Stat. § {num}"),
("north-carolina-appellate-rules", "N.C. R. App. P. {num}"),
(
"north-carolina-general-practice-rules",
"N.C. Gen. R. Prac. Super. & Dist. Ct. {num}",
),
];
for (name, template) in expected {
let p = Profile::builtin(name).expect(name);
assert_eq!(p.citation_template, template, "{name}");
}
}
#[test]
fn builtin_north_dakota_century_code_parses() {
let p = Profile::builtin("north-dakota-century-code").expect("built-in must parse");
assert_eq!(p.jurisdiction, "north_dakota");
assert_eq!(p.kind, "statute");
assert_eq!(p.citation_template, "N.D. Cent. Code § {num}");
assert!(!p.draft);
assert!(!p.citation_template.contains("{title}"));
}
#[test]
fn builtin_north_dakota_recognizes_repealed_chapter_stubs() {
let p = Profile::builtin("north-dakota-century-code").unwrap();
assert!(!p.empty_doc_patterns.is_empty());
let re = regex::Regex::new(&p.empty_doc_patterns[0]).unwrap();
for marker in [
"[Repealed by S.L. 1947, ch. 1, § 18]",
"[Repealed by omission from this code]",
"[Superseded by North Dakota Rules of Civil Procedure, Rule 16]",
"[Expired under S.L. 2017, ch. 341, § 22]",
"[Referred and disapproved at election of June 28, 1950]",
"[Unconstitutional - Scott v. Donnelly, 133 N.W.2d 418]",
"[Title 26 was repealed and replaced by S.L. 1983,",
"[Each section of this chapter has been repealed or omitted as not of a general or permanent",
] {
assert!(re.is_match(marker), "must match {marker:?}");
}
assert!(!re.is_match("Repealed by S.L. 1985, ch. 103, § 10."));
}
#[test]
fn builtin_wyoming_statutes_parses() {
let p = Profile::builtin("wyoming-statutes").expect("built-in must parse");
assert_eq!(p.jurisdiction, "wyoming");
assert_eq!(p.kind, "statute");
assert_eq!(p.citation_template, "Wyo. Stat. § {num}");
assert!(!p.draft);
assert!(!p.citation_template.contains("{title}"));
}
#[test]
fn builtin_north_carolina_appellate_rules_parses() {
let p = Profile::builtin("north-carolina-appellate-rules").expect("built-in must parse");
assert_eq!(p.jurisdiction, "north_carolina");
assert_eq!(p.kind, "rule");
assert_eq!(p.citation_template, "N.C. R. App. P. {num}");
assert!(!p.draft);
assert!(p.toc_restart, "consolidated TOC mirrors the headings");
assert!(!p.stop_patterns.is_empty(), "appendixes must not attach");
}
#[test]
fn builtin_north_carolina_general_practice_rules_parses() {
let p =
Profile::builtin("north-carolina-general-practice-rules").expect("built-in must parse");
assert_eq!(p.jurisdiction, "north_carolina");
assert_eq!(p.kind, "rule");
assert_eq!(
p.citation_template,
"N.C. Gen. R. Prac. Super. & Dist. Ct. {num}"
);
assert!(!p.draft);
assert!(p.toc_restart, "consolidated TOC mirrors the headings");
assert!(!p.stop_patterns.is_empty(), "forms must not attach");
}
#[test]
fn pr_rules_is_spanish() {
let p = Profile::builtin("pr-rules").unwrap();
assert_eq!(p.language, "es");
assert_eq!(p.jurisdiction, "puerto_rico");
assert_eq!(p.kind, "rule");
}
fn minimal() -> String {
r#"
name = "x"
jurisdiction = "guam"
kind = "rule"
citation_template = "X {num}"
heading_patterns = ['^RULE (?P<num>\d+)']
"#
.to_string()
}
#[test]
fn minimal_profile_gets_defaults() {
let p = Profile::from_toml(&minimal()).unwrap();
assert_eq!(p.language, "en");
assert!(p.monotonic_numbers);
assert!(p.heading_x0_cluster);
assert!(p.heading_style.is_none());
assert!(p.adoption_date.is_none());
}
#[test]
fn missing_routing_keys_rejected() {
let err = Profile::from_toml(&minimal().replace("\"rule\"", "\"regulation\"")).unwrap_err();
assert!(err.to_string().contains("kind"));
}
#[test]
fn bad_regex_rejected() {
let err = Profile::from_toml(&minimal().replace(r"^RULE (?P<num>\d+)", "(")).unwrap_err();
assert!(err.to_string().contains("invalid profile regex"));
}
#[test]
fn heading_pattern_without_num_capture_rejected() {
let err = Profile::from_toml(&minimal().replace(r"(?P<num>\d+)", r"\d+")).unwrap_err();
assert!(err.to_string().contains("(?P<num>"));
}
#[test]
fn unknown_template_placeholder_rejected() {
let err =
Profile::from_toml(&minimal().replace("X {num}", "X {num} {volume}")).unwrap_err();
assert!(err.to_string().contains("{volume}"));
}
#[test]
fn title_placeholder_requires_a_title_source() {
let err = Profile::from_toml(&minimal().replace("X {num}", "{title} X {num}")).unwrap_err();
assert!(err.to_string().contains("{title}"));
let src = format!(
"{}\ntitle_patterns = ['^TITLE (?P<title>\\d+)']",
minimal().replace("X {num}", "{title} X {num}")
);
Profile::from_toml(&src).expect("title_patterns satisfies {title}");
}
#[test]
fn title_pattern_must_capture_title() {
let src = format!("{}\ntitle_patterns = ['^TITLE \\d+']", minimal());
let err = Profile::from_toml(&src).unwrap_err();
assert!(err.to_string().contains("(?P<title>"));
}
#[test]
fn bad_empty_doc_regex_rejected() {
let src = format!("{}\nempty_doc_patterns = ['(']", minimal());
let err = Profile::from_toml(&src).unwrap_err();
assert!(err.to_string().contains("invalid profile regex"));
}
#[test]
fn malformed_adoption_date_rejected() {
let src = format!("{}\nadoption_date = \"Feb 13, 2002\"", minimal());
let err = Profile::from_toml(&src).unwrap_err();
assert!(err.to_string().contains("YYYY-MM-DD"));
}
#[test]
fn unsupported_date_format_rejected() {
let src = format!("{}\ndate_formats = [\"%H:%M\"]", minimal());
let err = Profile::from_toml(&src).unwrap_err();
assert!(format!("{err:#}").contains("unsupported strftime specifier"));
}
#[test]
fn heading_style_parses() {
let src = format!(
"{}\n[heading_style]\nbold = true\nmin_size = 10.5",
minimal()
);
let p = Profile::from_toml(&src).unwrap();
let style = p.heading_style.expect("style table");
assert_eq!(style.bold, Some(true));
assert_eq!(style.min_size, Some(10.5));
assert!(style.centered.is_none());
}
}