ctb_build_support/
format_id_codegen.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Build-time code generator for `src/utilities/format_id.generated.rs` from
21//! the system graph in `assets/data/graph/`.
22
23use crate::global_graph_layout::FORMAT_REGION_START;
24use crate::graph_index::BuildGraphIndex;
25use crate::license_consts::DEFAULT_AGPL_HEADER;
26use crate::shorthand::DcShorthand;
27use anyhow::{Context, Result, bail, ensure};
28use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
29use std::fs;
30use std::path::Path;
31
32#[derive(Debug, Clone)]
33struct FormatRecord {
34    dc_id: u128,
35    short_id: u32,
36    ident: String,
37    label: String,
38    category: String,
39    nicknames: Vec<String>,
40    title: Option<String>,
41    implies_shorts: Vec<u32>,
42}
43
44/// Validates that an identifier is a valid non-empty Rust identifier.
45fn is_valid_rust_ident(ident: &str) -> bool {
46    if ident.is_empty() {
47        return false;
48    }
49    let mut chars = ident.chars();
50    let Some(first) = chars.next() else {
51        return false;
52    };
53    if !first.is_ascii_alphabetic() && first != '_' {
54        return false;
55    }
56    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
57}
58
59/// Converts a format category name (such as `base_alphabet` or `v:lineEndings`) into a
60/// `PascalCase` Rust enum variant name for `FormatCategory`.
61fn category_to_variant(category: &str) -> String {
62    let base = category
63        .strip_prefix("v.")
64        .or_else(|| category.strip_prefix("v:"))
65        .unwrap_or(category);
66    let mut out = String::new();
67    let mut capitalize_next = true;
68    for ch in base.chars() {
69        if ch == '_' || ch == '-' || ch == '.' || ch == ':' {
70            capitalize_next = true;
71        } else if capitalize_next {
72            out.extend(ch.to_uppercase());
73            capitalize_next = false;
74        } else {
75            out.push(ch);
76        }
77    }
78    if out.is_empty() {
79        "Other".to_string()
80    } else {
81        out
82    }
83}
84
85fn to_snake_case(s: &str) -> String {
86    let mut res = String::new();
87    let mut prev_is_upper = false;
88    for (i, c) in s.chars().enumerate() {
89        if c.is_uppercase() {
90            if i > 0 && !prev_is_upper {
91                res.push('_');
92            }
93            res.push(c.to_ascii_lowercase());
94            prev_is_upper = true;
95        } else {
96            res.push(c);
97            prev_is_upper = false;
98        }
99    }
100    res
101}
102
103fn to_screaming_snake_case(s: &str) -> String {
104    to_snake_case(s).to_ascii_uppercase()
105}
106
107/// Generates the contents of `format_id.generated.rs` from a [`BuildGraphIndex`].
108///
109/// # Errors
110/// Returns an error if the graph is missing required ontology Dcs or contains duplicate/invalid formats.
111#[expect(
112    clippy::too_many_lines,
113    reason = "Code generator for FormatId enum with all variants and mappings"
114)]
115pub fn generate_format_id_code_from_index(
116    index: &BuildGraphIndex,
117) -> Result<String> {
118    let sh_name = index.require_ident("CanonicalName")?;
119    let sh_nick = index.require_ident("Nickname")?;
120    let sh_formal_alias = index.require_ident("FormalAlias")?;
121    let sh_subtype = index.framing().is_subtype_of;
122    let sh_begin_group = index.require_ident("BeginAssociativityGroup")?;
123    let sh_end_group = index.require_ident("EndAssociativityGroup")?;
124    let sh_type_union = index.require_ident("TypeUnion")?;
125
126    let mut records = Vec::new();
127    let mut seen_idents = HashSet::new();
128    let mut seen_shorts = HashSet::new();
129    let mut seen_dcs = HashSet::new();
130
131    for short_id in index.all_format_short_ids()? {
132        let fid_usize = usize::try_from(short_id).with_context(|| {
133            format!("Format short ID {short_id} exceeds usize::MAX")
134        })?;
135        let subj = DcShorthand::Format(fid_usize);
136        let dc_id = FORMAT_REGION_START.saturating_add(u128::from(short_id));
137
138        let ident = index
139            .ident_for_shorthand(subj)
140            .with_context(|| {
141                format!(
142                    "Format f{short_id} has no @ident(\"...\") in system graph"
143                )
144            })?
145            .trim()
146            .to_string();
147        ensure!(
148            is_valid_rust_ident(&ident),
149            "Format f{short_id} has invalid Rust identifier '{ident}'"
150        );
151
152        // Reason for fallback: subjects returned by all_format_short_ids have a CanonicalName.
153        let label = index
154            .single_property_string(subj, sh_name)
155            .unwrap_or_default()
156            .trim()
157            .to_string();
158        ensure!(
159            !label.is_empty(),
160            "Format f{short_id} ({ident}) has empty CanonicalName"
161        );
162
163        // Reason for fallback: formats without an explicit script default to "other".
164        let script = index.subject_script(subj).unwrap_or_default();
165        let category = script
166            .strip_prefix(".Formats:")
167            .or_else(|| script.strip_prefix("Formats:"))
168            .map_or_else(|| "other".to_string(), |s| s.trim().to_string());
169
170        let nicknames: Vec<String> = index
171            .multi_property_strings_preferred_first(subj, sh_nick)
172            .into_iter()
173            .map(|s| s.trim().to_string())
174            .filter(|s| !s.is_empty())
175            .collect();
176
177        let title = index
178            .multi_property_strings_preferred_first(subj, sh_formal_alias)
179            .into_iter()
180            .map(|s| s.trim().to_string())
181            .find(|s| !s.is_empty());
182
183        let mut implies_shorts: Vec<u32> = Vec::new();
184        for &obj in index.direct_objects(sh_subtype, subj) {
185            match obj {
186                DcShorthand::Format(target_fid) => {
187                    if let Ok(target_sid) = u32::try_from(target_fid) {
188                        if !implies_shorts.contains(&target_sid) {
189                            implies_shorts.push(target_sid);
190                        }
191                    }
192                }
193                DcShorthand::Long(expr_node_id) => {
194                    if let Some(tokens) = index.node_tokens(expr_node_id) {
195                        let is_pure_format_conjunction = !tokens.is_empty()
196                            && tokens.iter().all(|&tok| {
197                                tok == sh_begin_group
198                                    || tok == sh_end_group
199                                    || tok == sh_type_union
200                                    || matches!(tok, DcShorthand::Format(_))
201                            });
202                        if is_pure_format_conjunction {
203                            for &tok in tokens {
204                                if let DcShorthand::Format(target_fid) = tok {
205                                    if let Ok(target_sid) =
206                                        u32::try_from(target_fid)
207                                    {
208                                        if !implies_shorts.contains(&target_sid)
209                                        {
210                                            implies_shorts.push(target_sid);
211                                        }
212                                    }
213                                }
214                            }
215                        }
216                    }
217                }
218                DcShorthand::Unicode(_)
219                | DcShorthand::Short(_)
220                | DcShorthand::Local(_) => {}
221            }
222        }
223
224        if !seen_idents.insert(ident.clone()) {
225            bail!("Duplicate FormatId variant '{ident}' on f{short_id}");
226        }
227        if !seen_shorts.insert(short_id) {
228            bail!("Duplicate Format short ID {short_id}");
229        }
230        if !seen_dcs.insert(dc_id) {
231            bail!("Duplicate Format Dc ID {dc_id}");
232        }
233
234        records.push(FormatRecord {
235            dc_id,
236            short_id,
237            ident,
238            label,
239            category,
240            nicknames,
241            title,
242            implies_shorts,
243        });
244    }
245
246    records.sort_by_key(|r| r.short_id);
247
248    // Collect distinct categories dynamically
249    let mut category_variants: BTreeSet<String> = BTreeSet::new();
250    let mut cat_to_variant: HashMap<String, String> = HashMap::new();
251    for r in &records {
252        let variant = category_to_variant(&r.category);
253        cat_to_variant.insert(r.category.clone(), variant.clone());
254        category_variants.insert(variant);
255    }
256    category_variants.insert("Other".to_string());
257
258    let mut out = String::new();
259    out.push_str(DEFAULT_AGPL_HEADER);
260    out.push_str("\n\n");
261    out.push_str(
262        "//! @generated by ctb-formats-dcdata::updater from format category data tables.\n",
263    );
264    out.push_str("//! Do not edit by hand.\n\n");
265    out.push_str("#[allow(\n");
266    out.push_str("    unused_imports,\n");
267    out.push_str("    clippy::wildcard_imports,\n");
268    out.push_str("    reason = \"Standard workspace module prelude\"\n");
269    out.push_str(")]\n");
270    out.push_str(
271        "use crate::dc_char::DcChar;\nuse serde::{Serialize, Deserialize};\n\n",
272    );
273    out.push_str(
274        "/// High-level category of file formats for domain filtering and score boosting.\n",
275    );
276    out.push_str(
277        "#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]\n",
278    );
279    out.push_str("pub enum FormatCategory {\n");
280    for cat_var in &category_variants {
281        out.push_str(&format!("    {cat_var},\n"));
282    }
283    out.push_str("}\n\n");
284
285    out.push_str(
286        "/// Standardized format identifier enum derived from formats category tables.\n",
287    );
288    out.push_str("#[expect(\n");
289    out.push_str("    non_camel_case_types,\n");
290    out.push_str("    reason = \"Language and format variants use underscores to reflect canonical format abbreviations\"\n");
291    out.push_str(")]\n");
292    out.push_str(
293        "#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]\n",
294    );
295    out.push_str("pub enum FormatId {\n");
296
297    for r in &records {
298        let escaped_label = r.label.replace('\n', " ").replace('"', "\\\"");
299        out.push_str(&format!(
300            "    /// {} (Short {}, Category: {})\n",
301            escaped_label, r.short_id, r.category
302        ));
303        out.push_str(&format!("    {},\n", r.ident));
304    }
305    if !seen_idents.contains("Unknown") {
306        out.push_str("    /// Unrecognized format.\n");
307        out.push_str("    Unknown,\n");
308    }
309    out.push_str("}\n\n");
310
311    out.push_str("impl FormatId {\n");
312    out.push_str(
313        "    /// Returns the primary format category for this format ID.\n",
314    );
315    out.push_str("    #[must_use]\n");
316    out.push_str("    pub fn category(&self) -> FormatCategory {\n");
317    out.push_str("        match self {\n");
318
319    let mut grouped_by_cat: BTreeMap<String, Vec<&str>> = BTreeMap::new();
320    for r in &records {
321        if let Some(var) = cat_to_variant.get(&r.category) {
322            grouped_by_cat
323                .entry(var.clone())
324                .or_default()
325                .push(&r.ident);
326        }
327    }
328    for (var, idents) in grouped_by_cat {
329        out.push_str("            ");
330        out.push_str(
331            &idents
332                .iter()
333                .map(|s| format!("Self::{s}"))
334                .collect::<Vec<_>>()
335                .join("\n            | "),
336        );
337        out.push_str(&format!(" => FormatCategory::{var},\n"));
338    }
339    out.push_str("            _ => FormatCategory::Other,\n");
340    out.push_str("        }\n");
341    out.push_str("    }\n\n");
342
343    out.push_str(
344        "    /// Looks up a `FormatId` variant from its identifier name or nickname.\n",
345    );
346    out.push_str("    #[must_use]\n");
347    out.push_str("    pub fn from_ident(ident: &str) -> Option<Self> {\n");
348    out.push_str("        let trimmed = ident.trim();\n");
349    out.push_str("        match trimmed.to_ascii_lowercase().as_str() {\n");
350    for r in &records {
351        let lower = r.ident.to_ascii_lowercase();
352        let mut patterns = vec![format!("\"{lower}\"")];
353        let snake = to_snake_case(&r.ident);
354        if snake != lower && !patterns.contains(&format!("\"{snake}\"")) {
355            patterns.push(format!("\"{snake}\""));
356        }
357        for nick in &r.nicknames {
358            let nick_lower = nick.trim().to_ascii_lowercase();
359            if !nick_lower.is_empty()
360                && !patterns.contains(&format!("\"{nick_lower}\""))
361            {
362                patterns.push(format!("\"{nick_lower}\""));
363            }
364        }
365        out.push_str(&format!(
366            "            {} => Some(Self::{}),\n",
367            patterns.join(" | "),
368            r.ident
369        ));
370    }
371    if !seen_idents.contains("Unknown") {
372        out.push_str("            \"unknown\" => Some(Self::Unknown),\n");
373    }
374    out.push_str("            _ => None,\n");
375    out.push_str("        }\n");
376    out.push_str("    }\n\n");
377
378    out.push_str(
379        "    /// Returns the canonical Rust identifier string for this format.\n",
380    );
381    out.push_str("    #[must_use]\n");
382    out.push_str("    pub const fn ident(&self) -> &'static str {\n");
383    out.push_str("        match self {\n");
384    for r in &records {
385        out.push_str(&format!(
386            "            Self::{} => \"{}\",\n",
387            r.ident, r.ident
388        ));
389    }
390    if !seen_idents.contains("Unknown") {
391        out.push_str("            Self::Unknown => \"Unknown\",\n");
392    }
393    out.push_str("        }\n");
394    out.push_str("    }\n\n");
395
396    out.push_str(
397        "    /// Returns the canonical human-readable title (\"true name\") for this format if defined.\n",
398    );
399    out.push_str("    #[must_use]\n");
400    out.push_str("    pub const fn title(&self) -> Option<&'static str> {\n");
401    out.push_str("        match self {\n");
402    for r in &records {
403        if let Some(t) = &r.title {
404            let escaped = t.replace('\\', "\\\\").replace('"', "\\\"");
405            out.push_str(&format!(
406                "            Self::{} => Some(\"{}\"),\n",
407                r.ident, escaped
408            ));
409        }
410    }
411    out.push_str("            _ => None,\n");
412    out.push_str("        }\n");
413    out.push_str("    }\n\n");
414
415    let short_to_ident: HashMap<u32, String> = records
416        .iter()
417        .map(|r| (r.short_id, r.ident.clone()))
418        .collect();
419    let direct_implies: HashMap<u32, Vec<u32>> = records
420        .iter()
421        .map(|r| (r.short_id, r.implies_shorts.clone()))
422        .collect();
423
424    let mut transitive_implies: HashMap<u32, Vec<String>> = HashMap::new();
425    for r in &records {
426        let mut seen = HashSet::new();
427        let mut queue = r.implies_shorts.clone();
428        let mut implied_idents = Vec::new();
429        while let Some(short_id) = queue.pop() {
430            if short_id != r.short_id && seen.insert(short_id) {
431                if let Some(ident) = short_to_ident.get(&short_id) {
432                    implied_idents.push(ident.clone());
433                }
434                if let Some(next_shorts) = direct_implies.get(&short_id) {
435                    for &next in next_shorts {
436                        if !seen.contains(&next) {
437                            queue.push(next);
438                        }
439                    }
440                }
441            }
442        }
443        implied_idents.sort();
444        implied_idents.dedup();
445        if !implied_idents.is_empty() {
446            transitive_implies.insert(r.short_id, implied_idents);
447        }
448    }
449
450    out.push_str(
451        "    /// Returns the slice of formats directly and transitively implied by this format,\n",
452    );
453    out.push_str(
454        "    /// as declared by `@implies(...)` directives in format tables.\n",
455    );
456    out.push_str("    #[must_use]\n");
457    out.push_str("    pub const fn implies(&self) -> &'static [Self] {\n");
458    out.push_str("        match self {\n");
459    for r in &records {
460        if let Some(implied) = transitive_implies.get(&r.short_id) {
461            if !implied.is_empty() {
462                out.push_str(&format!("            Self::{} => &[", r.ident));
463                for (i, id) in implied.iter().enumerate() {
464                    if i > 0 {
465                        out.push_str(", ");
466                    }
467                    out.push_str(&format!("Self::{id}"));
468                }
469                out.push_str("],\n");
470            }
471        }
472    }
473    out.push_str("            _ => &[],\n");
474    out.push_str("        }\n");
475    out.push_str("    }\n\n");
476
477    // NOTE: Do NOT add `short_id()` or `from_short_id()` integer methods here!
478    // There is no such thing as a "short format ID". Bare integers are confusing
479    // because they look identical to short Dc IDs. Format IDs must always use
480    // the `FormatId` enum, `FormatId::shorthand()` ("f<N>"), or `FormatId::ident()`.
481
482    out.push_str(
483        "    /// Returns the format shorthand string (e.g. \"f0\", \"f405\").\n",
484    );
485    out.push_str("    #[must_use]\n");
486    out.push_str("    pub const fn shorthand(&self) -> &'static str {\n");
487    out.push_str("        match self {\n");
488    for r in &records {
489        out.push_str(&format!(
490            "            Self::{} => \"f{}\",\n",
491            r.ident, r.short_id
492        ));
493    }
494    if !seen_idents.contains("Unknown") {
495        out.push_str("            Self::Unknown => \"unknown\",\n");
496    }
497    out.push_str("        }\n");
498    out.push_str("    }\n\n");
499
500    out.push_str(
501        "    /// Looks up a `FormatId` from its format shorthand string (e.g. \"f405\").\n",
502    );
503    out.push_str("    #[must_use]\n");
504    out.push_str(
505        "    pub fn from_shorthand(shorthand: &str) -> Option<Self> {\n",
506    );
507    out.push_str("        let trimmed = shorthand.trim();\n");
508    out.push_str("        match trimmed {\n");
509    for r in &records {
510        out.push_str(&format!(
511            "            \"f{}\" => Some(Self::{}),\n",
512            r.short_id, r.ident
513        ));
514    }
515    out.push_str("            _ => None,\n");
516    out.push_str("        }\n");
517    out.push_str("    }\n\n");
518
519    out.push_str(
520        "    /// Returns the Global Document Character ID if known.\n",
521    );
522    out.push_str("    #[must_use]\n");
523    out.push_str("    pub const fn dc_id(&self) -> Option<u128> {\n");
524    out.push_str("        match self {\n");
525    for r in &records {
526        out.push_str(&format!(
527            "            Self::{} => Some({}_u128),\n",
528            r.ident, r.dc_id
529        ));
530    }
531    if !seen_idents.contains("Unknown") {
532        out.push_str("            Self::Unknown => None,\n");
533    }
534    out.push_str("        }\n");
535    out.push_str("    }\n\n");
536
537    out.push_str(
538        "    /// Returns the format character as a `DcChar`, if known.\n",
539    );
540    out.push_str("    #[must_use]\n");
541    out.push_str("    pub const fn dc_char(&self) -> Option<DcChar> {\n");
542    out.push_str("        match self {\n");
543    out.push_str("            Self::Unknown => None,\n");
544    out.push_str("            _ => if let Some(dc) = self.dc_id() {\n");
545    out.push_str("                Some(DcChar::from_u128(dc))\n");
546    out.push_str("            } else {\n");
547    out.push_str("                None\n");
548    out.push_str("            }\n");
549    out.push_str("        }\n");
550    out.push_str("    }\n\n");
551
552    out.push_str(
553        "    /// Looks up a `FormatId` from its Global Document Character ID.\n",
554    );
555    out.push_str("    #[must_use]\n");
556    out.push_str("    pub const fn from_dc_id(id: u128) -> Option<Self> {\n");
557    out.push_str("        match id {\n");
558    for r in &records {
559        out.push_str(&format!(
560            "            {}_u128 => Some(Self::{}),\n",
561            r.dc_id, r.ident
562        ));
563    }
564    out.push_str("            _ => None,\n");
565    out.push_str("        }\n");
566    out.push_str("    }\n");
567    out.push_str("}\n\n");
568
569    // Generate individual format DcChar constants
570    for r in &records {
571        let screaming = to_screaming_snake_case(&r.ident);
572        let escaped_label = r.label.replace('\n', " ").replace('"', "\\\"");
573        out.push_str(&format!(
574            "/// DcChar constant for Format `{}` (Short f{}, Category: {}): {}\n",
575            r.ident, r.short_id, r.category, escaped_label
576        ));
577        out.push_str(&format!(
578            "pub const DC_{screaming}: DcChar = DcChar::from_format({});\n",
579            r.short_id
580        ));
581    }
582
583    Ok(out)
584}
585
586/// Generates the contents of `format_id.generated.rs` from the system graph in `graph_dir`.
587///
588/// # Errors
589/// Returns an error if `graph_dir` cannot be read or contains invalid data.
590pub fn generate_format_id_code(graph_dir: &Path) -> Result<String> {
591    let index = BuildGraphIndex::from_graph_dir(graph_dir)?;
592    generate_format_id_code_from_index(&index)
593}
594
595/// Generates `src/utilities/format_id.generated.rs` if its contents have changed.
596///
597/// # Errors
598/// Returns an error if reading the system graph or writing the generated file fails.
599pub fn generate_format_id_file(base_dir: &Path) -> Result<bool> {
600    let repo_root = crate::find_repository_root_from(base_dir)?;
601    let graph_dir = repo_root.join("assets").join("data").join("graph");
602    let out_file = repo_root
603        .join("src")
604        .join("utilities")
605        .join("format_id.generated.rs");
606
607    ensure!(
608        graph_dir.is_dir(),
609        "Could not locate system graph directory at {}",
610        graph_dir.display()
611    );
612
613    let code = generate_format_id_code(&graph_dir)?;
614
615    if let Ok(existing) = fs::read_to_string(&out_file) {
616        if existing == code {
617            return Ok(false);
618        }
619    }
620
621    fs::write(&out_file, code)
622        .with_context(|| format!("Failed to write {}", out_file.display()))?;
623    Ok(true)
624}