ctb_formats_dcdata/support/
format.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//! Schema validator for Formats registry category files (`src/formats/dcdata/data/categories/formats/*.csv`).
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use crate::dc_def::{DcDefn, FormatDetails};
30use crate::format_spec::{parse_format_expr, validate_format_expr};
31use crate::report::ValidationReport;
32use crate::shared::{
33    BidiClass, GeneralCategory, split_comma_separated_items,
34    validate_extensions_field, validate_mime_field, validate_rust_identifier,
35    validate_support_level,
36};
37use crate::syntax::parse_dc_syntax;
38use include_dir::Dir;
39use std::collections::{HashMap, HashSet};
40
41pub use ctb_storage_minimal::global_graph_layout::{
42    FORMAT_REGION_END, FORMAT_REGION_START,
43};
44
45/// Parses and validates a single format category CSV file.
46pub fn validate_formats_category_file(
47    csv_bytes: &[u8],
48    file_path: &str,
49    valid_variant_names: &HashSet<String>,
50    report: &mut ValidationReport,
51) -> Vec<DcDefn> {
52    let vec_bytes = csv_bytes.to_vec();
53    let table = match csv_tools::parse_csv_reader(
54        &vec_bytes,
55        csv_tools::CsvParseOptions {
56            has_header: true,
57            flexible: true,
58            ..Default::default()
59        },
60    ) {
61        Ok(t) => t,
62        Err(e) => {
63            report.add_error(
64                file_path,
65                None,
66                None,
67                format!("Failed to parse CSV file: {e}"),
68                Some("Verify CSV syntax and RFC4180 quotes"),
69            );
70            return Vec::new();
71        }
72    };
73
74    let mut rows = Vec::new();
75
76    if let Some(header) = table.header() {
77        if header.len() != 17 {
78            report.add_error(
79                file_path,
80                Some(1),
81                None,
82                format!(
83                    "CSV header has {} columns, expected 17 columns",
84                    header.len()
85                ),
86                Some("Ensure CSV header has exactly 17 columns matching schema.csv"),
87            );
88        }
89    }
90
91    for i in 0..table.row_count() {
92        let line_no = i.saturating_add(2);
93
94        if let Some(row_slice) = table.row(i) {
95            if row_slice.iter().all(|s| s.trim().is_empty()) {
96                continue;
97            }
98            if row_slice.len() != 17 {
99                report.add_error(
100                    file_path,
101                    Some(line_no),
102                    None,
103                    format!(
104                        "Row has {} columns, expected 17 columns (mismatched field count)",
105                        row_slice.len()
106                    ),
107                    Some("Check for unquoted commas, missing commas, or extra columns to avoid misaligned data"),
108                );
109            }
110        }
111
112        let get_str = |col: usize| -> String {
113            match table.cell(i, col) {
114                Some(s) => s.trim().to_string(),
115                None => String::new(),
116            }
117        };
118
119        let dc_str = get_str(0);
120        let short_str = get_str(1);
121        let ident = get_str(2);
122        let label = get_str(3);
123        let category = get_str(4);
124        let base_format_raw = get_str(5);
125        let extensions = get_str(6);
126        let mime = get_str(7);
127        let uti = get_str(8);
128        let apple_type = get_str(9);
129        let nicknames = get_str(10);
130        let import_support = get_str(11);
131        let export_support = get_str(12);
132        let tests = get_str(13);
133        let variant_types = get_str(14);
134        let comments = get_str(15);
135        let references = get_str(16);
136
137        if dc_str.is_empty() && short_str.is_empty() && label.is_empty() {
138            continue;
139        }
140
141        let short_id = if let Ok(v) =
142            ctb_storage_minimal::shorthand::parse_format_shorthand(&short_str)
143        {
144            v
145        } else {
146            report.add_error(
147                file_path,
148                Some(line_no),
149                Some("Short"),
150                format!("Invalid Short format ID integer: '{short_str}'"),
151                Some("Must be a non-negative integer or lowercase 'f<digits>'"),
152            );
153            continue;
154        };
155
156        let dc_id = if let Ok(v) = dc_str.parse::<u128>() {
157            v
158        } else {
159            report.add_error(
160                file_path,
161                Some(line_no),
162                Some("Dc"),
163                format!("Invalid Global Dc ID integer: '{dc_str}'"),
164                Some("Must be an integer within format region"),
165            );
166            continue;
167        };
168
169        let Ok(short_id_u128) = u128::try_from(short_id) else {
170            report.add_error(
171                file_path,
172                Some(line_no),
173                Some("Short"),
174                format!("Short ID {short_id} exceeds u128 range"),
175                Some("Short IDs must fit within numeric limits"),
176            );
177            continue;
178        };
179
180        let expected_dc = FORMAT_REGION_START.saturating_add(short_id_u128);
181        if dc_id != expected_dc {
182            report.add_error(
183                file_path,
184                Some(line_no),
185                Some("Dc"),
186                format!(
187                    "Global Dc ID ({dc_id}) does not match FORMAT_REGION_START + Short ID ({expected_dc})"
188                ),
189                Some("Ensure Dc ID is offset from Short ID by 2228224"),
190            );
191        }
192
193        if !(FORMAT_REGION_START..=FORMAT_REGION_END).contains(&dc_id) {
194            report.add_error(
195                file_path,
196                Some(line_no),
197                Some("Dc"),
198                format!(
199                    "Dc ID {dc_id} is out of the Formats region bounds ({FORMAT_REGION_START}..={FORMAT_REGION_END})"
200                ),
201                Some("Verify region boundaries"),
202            );
203        }
204
205        let is_deprecated = ident.starts_with('!') || label.starts_with('!');
206        let clean_ident = if let Some(stripped) = ident.strip_prefix('!') {
207            stripped.trim()
208        } else {
209            ident.as_str()
210        };
211        let clean_label = if let Some(stripped) = label.strip_prefix('!') {
212            stripped.trim()
213        } else {
214            label.as_str()
215        };
216
217        if clean_label.is_empty() {
218            report.add_error(
219                file_path,
220                Some(line_no),
221                Some("Label"),
222                "Format must have a Label",
223                Some("Provide a human-readable display label for the format"),
224            );
225        }
226
227        if !ident.is_empty() {
228            if let Err(e) = validate_rust_identifier(clean_ident) {
229                report.add_error(
230                    file_path,
231                    Some(line_no),
232                    Some("Ident"),
233                    format!("Invalid Rust identifier '{ident}': {e}"),
234                    Some("Identifiers must match [a-zA-Z_][a-zA-Z0-9_]* (optionally prefixed with '!' for deprecated formats) and not clash with keywords"),
235                );
236            }
237        }
238
239        if category.is_empty() {
240            report.add_error(
241                file_path,
242                Some(line_no),
243                Some("Category"),
244                "Category column cannot be empty",
245                Some("Specify the format category (e.g. document, encoding, compression)"),
246            );
247        }
248
249        if let Err(e) = validate_mime_field(&mime) {
250            report.add_error(
251                file_path,
252                Some(line_no),
253                Some("MIME"),
254                format!("Invalid MIME field '{mime}': {e}"),
255                Some("Format as 'type/subtype' (e.g. 'text/plain')"),
256            );
257        }
258
259        if let Err(e) = validate_extensions_field(&extensions) {
260            report.add_error(
261                file_path,
262                Some(line_no),
263                Some("Extensions"),
264                format!("Invalid Extensions field '{extensions}': {e}"),
265                Some("Extensions must start with '.' or regexes enclosed in '~...~'"),
266            );
267        }
268
269        if !apple_type.is_empty() && apple_type.chars().count() != 4 {
270            report.add_warning(
271                file_path,
272                Some(line_no),
273                Some("Apple Type code"),
274                format!("Apple Type code '{apple_type}' is not 4 characters"),
275                Some("Classic Mac OSTypes are usually 4 bytes/characters"),
276            );
277        }
278
279        if let Err(e) = validate_support_level(&import_support) {
280            report.add_error(
281                file_path,
282                Some(line_no),
283                Some("Import support"),
284                format!("Invalid Import support value: {e}"),
285                Some("Use space-separated '<general> <dc>' (e.g. '3 1' or '2 0') in -1..=5, or leave blank"),
286            );
287        }
288
289        if let Err(e) = validate_support_level(&export_support) {
290            report.add_error(
291                file_path,
292                Some(line_no),
293                Some("Export support"),
294                format!("Invalid Export support value: {e}"),
295                Some("Use space-separated '<general> <dc>' (e.g. '3 1' or '2 0') in -1..=5, or leave blank"),
296            );
297        }
298
299        if let Err(e) = validate_support_level(&tests) {
300            report.add_error(
301                file_path,
302                Some(line_no),
303                Some("Tests"),
304                format!("Invalid Tests support value: {e}"),
305                Some("Use space-separated '<general> <dc>' (e.g. '1 1' or '2 0') in -1..=5, or leave blank"),
306            );
307        }
308
309        if !variant_types.is_empty() {
310            for v in variant_types.split(',') {
311                let v_trimmed = v.trim();
312                if v_trimmed.is_empty() {
313                    continue;
314                }
315                if !valid_variant_names.contains(v_trimmed) {
316                    report.add_error(
317                        file_path,
318                        Some(line_no),
319                        Some("Variant Types"),
320                        format!(
321                            "Variant Type '{v_trimmed}' is not among registered 'v.*' category files"
322                        ),
323                        Some("Ensure Variant Types reference existing 'v.*' category file stems (e.g. lineEndings, unicodePua)"),
324                    );
325                }
326            }
327        }
328
329        let parsed = crate::column_spec::parse_aliases_or_base_column(
330            &base_format_raw,
331            file_path,
332            line_no,
333            report,
334            true,
335        );
336        let implies = if parsed.implies.is_empty() {
337            None
338        } else {
339            Some(parsed.implies.join(", "))
340        };
341        let based_on = if parsed.based_on.is_empty() {
342            None
343        } else {
344            Some(parsed.based_on.join(", "))
345        };
346        let chain = None;
347        let format_spec_raw = parsed.format_spec_raw;
348        let syntax_raw = parsed.syntax_raw;
349        let decompositions = parsed.decompositions;
350        let format_spec = if let Some(raw_spec) = &format_spec_raw {
351            match parse_format_expr(raw_spec) {
352                Ok(expr) => {
353                    if let Err(e) = validate_format_expr(&expr) {
354                        report.add_error(
355                            file_path,
356                            Some(line_no),
357                            Some("Base/Related Format (format_spec)"),
358                            format!("Semantic validation failed for format spec '{raw_spec}': {e}"),
359                            Some("Check format IDs and registered named types in expression"),
360                        );
361                    }
362                    Some(expr)
363                }
364                Err(e) => {
365                    report.add_error(
366                        file_path,
367                        Some(line_no),
368                        Some("Base/Related Format (format_spec)"),
369                        format!("Failed to parse format specification DSL rule '{raw_spec}': {e}"),
370                        Some("Verify format specification DSL syntax (@chain(...))"),
371                    );
372                    None
373                }
374            }
375        } else {
376            None
377        };
378        let syntax = if let Some(raw_syntax) = &syntax_raw {
379            match parse_dc_syntax(raw_syntax) {
380                Ok(rule) => Some(rule),
381                Err(e) => {
382                    report.add_error(
383                        file_path,
384                        Some(line_no),
385                        Some("Base/Related Format (syntax)"),
386                        format!("Failed to parse Format syntax DSL rule: {e}"),
387                        Some("Verify syntax DSL grammar"),
388                    );
389                    None
390                }
391            }
392        } else {
393            None
394        };
395
396        let formatted_category = if category.starts_with("format_") {
397            category.clone()
398        } else {
399            format!("format_{category}")
400        };
401
402        let mut all_nicknames = if nicknames.is_empty() {
403            Vec::new()
404        } else {
405            split_comma_separated_items(&nicknames)
406        };
407        for nick in &parsed.nicknames {
408            if !nick.is_empty() && !all_nicknames.contains(nick) {
409                all_nicknames.push(nick.clone());
410            }
411        }
412        let merged_nicknames = if all_nicknames.is_empty() {
413            None
414        } else {
415            Some(all_nicknames.join(", "))
416        };
417
418        let format_details = FormatDetails {
419            implies,
420            based_on,
421            chain,
422            format_spec,
423            extensions: if extensions.is_empty() {
424                None
425            } else {
426                Some(extensions)
427            },
428            mime: if mime.is_empty() { None } else { Some(mime) },
429            uti: if uti.is_empty() { None } else { Some(uti) },
430            apple_type: if apple_type.is_empty() {
431                None
432            } else {
433                Some(apple_type)
434            },
435            nicknames: merged_nicknames,
436            import_support: if import_support.is_empty() {
437                None
438            } else {
439                Some(import_support)
440            },
441            export_support: if export_support.is_empty() {
442                None
443            } else {
444                Some(export_support)
445            },
446            tests: if tests.is_empty() { None } else { Some(tests) },
447            variant_types: if variant_types.is_empty() {
448                None
449            } else {
450                Some(variant_types)
451            },
452            title: parsed.title.clone(),
453            default_line_ending: parsed.default_line_ending,
454            vary_as: parsed.vary_as,
455            varies: parsed.varies,
456        };
457
458        let aliases = all_nicknames;
459        let cross_references: Vec<String> = if references.is_empty() {
460            Vec::new()
461        } else {
462            split_comma_separated_items(&references)
463        };
464
465        if parsed.stable_ident && clean_ident.is_empty() {
466            report.add_error(
467                file_path,
468                Some(line_no),
469                Some("Ident"),
470                "Format has '@stable_ident()' but is missing an Ident".to_string(),
471                Some("Provide a valid Rust-friendly Ident in the Ident column"),
472            );
473        }
474
475        if !crate::syntax::is_transformation_format_category(&category) {
476            for decomp in &decompositions {
477                // Reason for fallback: untagged decomposition strings contain payload from index 0.
478                let payload = decomp
479                    .find('>')
480                    .and_then(|idx| decomp.get(idx.saturating_add(1)..))
481                    .unwrap_or(decomp)
482                    .trim();
483                let Some(first_tok) = payload.split_whitespace().next() else {
484                    continue;
485                };
486                let is_exec_decomp = first_tok
487                    .parse::<crate::DcShorthand>()
488                    .ok()
489                    .and_then(|sh| sh.to_global_id().ok())
490                    .is_some_and(|gid| {
491                        use crate::syntax::DcRole;
492                        [
493                            DcRole::BeginWasmProgram,
494                            DcRole::BeginModule,
495                            DcRole::BeginStagerModule,
496                            DcRole::BeginRoutineDecl,
497                            DcRole::BeginRoutine,
498                            DcRole::DeclareConst,
499                            DcRole::DeclarePub,
500                            DcRole::BeginPositionalStructDecl,
501                            DcRole::DeclareBrandType,
502                            DcRole::BeginNamedStructDecl,
503                            DcRole::BeginEnumDecl,
504                        ]
505                        .into_iter()
506                        .any(|role| role.matches_canonical(gid))
507                    });
508                if is_exec_decomp {
509                    report.add_error(
510                        file_path,
511                        Some(line_no),
512                        Some("Base/Related Format (decomposition)"),
513                        format!(
514                            "Executable implementation decomposition '{decomp}' cannot be attached directly to non-transformation format f{short_id} ('{clean_label}', category '{category}')"
515                        ),
516                        Some(
517                            "Only document transformations (.Formats:transformation) may own direct implementations; implement format converters as verbs/transformations referencing the format instead",
518                        ),
519                    );
520                }
521            }
522        }
523
524        rows.push(DcDefn {
525            dc_id,
526            short_id: Some(short_id),
527            ident: if clean_ident.is_empty() {
528                None
529            } else {
530                Some(clean_ident.to_string())
531            },
532            stable_ident: parsed.stable_ident,
533            title: parsed.title,
534            name: clean_label.to_string(),
535            category: formatted_category,
536            combining_class: 0,
537            bidi_class: BidiClass::BN,
538            casing_partner: None,
539            general_category: GeneralCategory::NonUnicodeControl,
540            script: format!(".Formats:{category}"),
541            is_deprecated,
542            decompositions,
543            aliases,
544            formal_aliases: Vec::new(),
545            cross_references,
546            annotations: parsed.annotations,
547            implies: parsed.implies,
548            based_on: parsed.based_on,
549            os_associations: parsed.os_associations,
550            magic_names: parsed.magic_names,
551            syntax,
552            closes: parsed.closes,
553            description: comments,
554            format: Some(format_details),
555            source_file: file_path.to_string(),
556            line_number: line_no,
557        });
558    }
559
560    rows
561}
562
563/// Validates a sequence of format category files.
564pub fn validate_format_files_data<'a, I>(
565    files: I,
566    category_dir_label: &str,
567    known_scripts: Option<&HashSet<String>>,
568    report: &mut ValidationReport,
569) -> Vec<DcDefn>
570where
571    I: IntoIterator<Item = (&'a str, &'a [u8])> + Clone,
572{
573    let mut variant_categories = HashSet::new();
574
575    // First pass: discover all category file names (including "v.*" variant category files and standard categories)
576    for (path_str, _) in files.clone() {
577        if path_str.ends_with(".csv") {
578            let path = std::path::Path::new(path_str);
579            let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
580                continue;
581            };
582            variant_categories.insert(stem.to_string());
583            if let Some(variant_name) = stem.strip_prefix("v.") {
584                variant_categories.insert(variant_name.to_string());
585            }
586        }
587    }
588
589    let mut all_rows = Vec::new();
590    let mut short_id_map: HashMap<usize, (String, usize)> = HashMap::new();
591    let mut ident_map: HashMap<String, (String, usize)> = HashMap::new();
592
593    for (path_str, contents) in files {
594        if !path_str.ends_with(".csv")
595            || path_str.ends_with("schema.csv")
596            || path_str.ends_with(".generated.csv")
597        {
598            continue;
599        }
600
601        let rows = validate_formats_category_file(
602            contents,
603            path_str,
604            &variant_categories,
605            report,
606        );
607
608        for row in rows {
609            if let Some(scripts) = known_scripts {
610                if !scripts.contains(&row.script) {
611                    report.add_error(
612                        &row.source_file,
613                        Some(row.line_number),
614                        Some("Script"),
615                        format!("Unknown format script '{}'", row.script),
616                        Some("Ensure format category is registered in README.scripts.csv"),
617                    );
618                }
619            }
620
621            if let Some(short_id) = row.short_id {
622                if let Some((prev_file, prev_line)) =
623                    short_id_map.get(&short_id)
624                {
625                    report.add_error(
626                        &row.source_file,
627                        Some(row.line_number),
628                        Some("Short"),
629                        format!(
630                            "Duplicate Short Format ID {short_id} already defined in {prev_file}:{prev_line}",
631                        ),
632                        Some("Assign a unique Short ID to each format"),
633                    );
634                } else {
635                    short_id_map.insert(
636                        short_id,
637                        (row.source_file.clone(), row.line_number),
638                    );
639                }
640            }
641
642            if let Some(ident) = &row.ident {
643                if let Some((prev_file, prev_line)) = ident_map.get(ident) {
644                    report.add_error(
645                        &row.source_file,
646                        Some(row.line_number),
647                        Some("Ident"),
648                        format!(
649                            "Duplicate Format Ident '{ident}' already defined in {prev_file}:{prev_line}"
650                        ),
651                        Some("Assign a unique Rust-friendly Ident to each format"),
652                    );
653                } else {
654                    ident_map.insert(
655                        ident.clone(),
656                        (row.source_file.clone(), row.line_number),
657                    );
658                }
659            }
660
661            all_rows.push(row);
662        }
663    }
664
665    // Validate that Short Format IDs in the legacy contiguous region form a contiguous sequence starting from 0 with no gaps/holes
666    let known_fmt_ids: HashSet<usize> =
667        all_rows.iter().filter_map(|r| r.short_id).collect();
668    if let Some(&max_id) = known_fmt_ids.iter().max() {
669        // Reason for fallback: PREEXISTING_CONTIGUOUS_FORMAT_MAX is a small u32 constant that always fits in usize.
670        let legacy_limit = max_id.min(
671            usize::try_from(crate::updater::PREEXISTING_CONTIGUOUS_FORMAT_MAX)
672                .unwrap_or(0),
673        );
674        let mut missing_ids = Vec::new();
675        for id in 0..=legacy_limit {
676            if !known_fmt_ids.contains(&id) {
677                missing_ids.push(id);
678            }
679        }
680        if !missing_ids.is_empty() {
681            let missing_str = if missing_ids.len() <= 10 {
682                missing_ids
683                    .iter()
684                    .map(std::string::ToString::to_string)
685                    .collect::<Vec<_>>()
686                    .join(", ")
687            } else {
688                format!(
689                    "{} (and {} more)",
690                    missing_ids
691                        .iter()
692                        .take(10)
693                        .map(std::string::ToString::to_string)
694                        .collect::<Vec<_>>()
695                        .join(", "),
696                    missing_ids.len().saturating_sub(10)
697                )
698            };
699            report.add_error(
700                category_dir_label,
701                None,
702                Some("Short"),
703                format!(
704                    "Format Short IDs have gaps/holes. Missing {} ID(s): [{missing_str}] in range 0..={legacy_limit}",
705                    missing_ids.len()
706                ),
707                Some("Ensure Format Short IDs are contiguous with no missing numbers"),
708            );
709        }
710    }
711
712    // Validate format syntax definitions
713    let known_syntax_targets: HashSet<crate::syntax::CharTarget> = all_rows
714        .iter()
715        .filter(|r| r.syntax.is_some())
716        .filter_map(|r| r.short_id)
717        .filter_map(|sid| {
718            ctb_utilities::format_id::FormatId::from_shorthand(&format!(
719                "f{sid}"
720            ))
721        })
722        .map(crate::syntax::CharTarget::Format)
723        .collect();
724    let empty_dcs = HashSet::new();
725    let empty_named_types = HashSet::new();
726    let format_registry =
727        crate::syntax::build_format_validation_registry(&all_rows);
728
729    for row in &all_rows {
730        if let (Some(syntax_rule), Some(Ok(self_id))) =
731            (&row.syntax, row.short_id.map(u32::try_from))
732        {
733            crate::syntax::validator::validate_dc_syntax(
734                syntax_rule,
735                self_id,
736                &empty_dcs,
737                &known_fmt_ids,
738                &empty_named_types,
739                known_scripts,
740                &known_syntax_targets,
741                Some(&format_registry),
742                report,
743                &row.source_file,
744                row.line_number,
745            );
746        }
747    }
748
749    // Validate format variant declarations and dependencies
750    let mut declared_vary_as: HashSet<String> = HashSet::new();
751    let mut variant_format_short_ids: HashSet<usize> = HashSet::new();
752    let mut variant_format_dc_ids: HashSet<u128> = HashSet::new();
753
754    for row in &all_rows {
755        if row.script == ".Formats:format_variant" {
756            if let Some(short_id) = row.short_id {
757                variant_format_short_ids.insert(short_id);
758            }
759            variant_format_dc_ids.insert(row.dc_id);
760            if let Some(details) = &row.format {
761                if let Some(vary_as) = &details.vary_as {
762                    declared_vary_as.insert(vary_as.clone());
763                }
764            }
765        }
766    }
767
768    for row in &all_rows {
769        if let Some(details) = &row.format {
770            if details.vary_as.is_some()
771                && row.script != ".Formats:format_variant"
772            {
773                report.add_error(
774                    &row.source_file,
775                    Some(row.line_number),
776                    Some("Base/Related Format (vary_as)"),
777                    format!(
778                        "Directive '@vary_as' is only permitted on formats in '.Formats:format_variant' (found in '{}')",
779                        row.script
780                    ),
781                    Some("Move the format to 'format_variant.csv' or remove '@vary_as'"),
782                );
783            }
784
785            for target in &details.varies {
786                let is_variant = match target {
787                    ctb_storage_minimal::shorthand::DcShorthand::Format(
788                        sid,
789                    ) => variant_format_short_ids.contains(sid),
790                    ctb_storage_minimal::shorthand::DcShorthand::Short(sid) => {
791                        // Reason for fallback: out-of-range integer IDs cannot match format IDs
792                        usize::try_from(*sid).is_ok_and(|s| {
793                            variant_format_short_ids.contains(&s)
794                        })
795                    }
796                    ctb_storage_minimal::shorthand::DcShorthand::Long(dc) => {
797                        variant_format_dc_ids.contains(dc)
798                    }
799                    ctb_storage_minimal::shorthand::DcShorthand::Unicode(
800                        dc,
801                    ) => {
802                        let dc_u128 = u128::from(*dc);
803                        variant_format_dc_ids.contains(&dc_u128)
804                    }
805                    ctb_storage_minimal::shorthand::DcShorthand::Local(_) => {
806                        false
807                    }
808                };
809
810                if !is_variant {
811                    report.add_error(
812                        &row.source_file,
813                        Some(row.line_number),
814                        Some("Base/Related Format (varies)"),
815                        format!(
816                            "Directive '@varies({target})' references non-variant format or character. Only formats in '.Formats:format_variant' are permitted in '@varies'"
817                        ),
818                        Some("Ensure the target is defined in 'src/formats/dcdata/data-src/categories/formats/format_variant.csv'"),
819                    );
820                }
821            }
822        }
823
824        if let Some(variant_name) = row.script.strip_prefix(".Formats:v:") {
825            if !declared_vary_as.contains(variant_name) {
826                report.add_error(
827                    &row.source_file,
828                    Some(row.line_number),
829                    Some("Script"),
830                    format!(
831                        "Script '{}' is not defined by any declared '@vary_as(\"{variant_name}\")' in .Formats:format_variant",
832                        row.script
833                    ),
834                    Some("Add a format in 'format_variant.csv' with the corresponding '@vary_as' directive"),
835                );
836            }
837        }
838    }
839
840    all_rows
841}
842
843/// Discovers all format category files from an embedded directory and validates uniqueness across files.
844pub fn validate_all_format_files(
845    formats_dir: &Dir,
846    known_scripts: Option<&HashSet<String>>,
847    report: &mut ValidationReport,
848) -> Vec<DcDefn> {
849    let mut files = Vec::new();
850    for f in formats_dir.files() {
851        if let Some(path_str) = f.path().to_str() {
852            files.push((path_str, f.contents()));
853        }
854    }
855    validate_format_files_data(
856        files,
857        "src/formats/dcdata/data-src/categories/formats/",
858        known_scripts,
859        report,
860    )
861}
862
863/// Discovers all format category files from an on-disk directory and validates uniqueness across files.
864pub fn validate_all_format_files_from_disk(
865    formats_dir: &std::path::Path,
866    known_scripts: Option<&HashSet<String>>,
867    report: &mut ValidationReport,
868) -> Vec<DcDefn> {
869    let Ok(entries) = std::fs::read_dir(formats_dir) else {
870        report.add_error(
871            &formats_dir.display().to_string(),
872            None,
873            None,
874            format!(
875                "Could not read Formats directory at {}",
876                formats_dir.display()
877            ),
878            None,
879        );
880        return Vec::new();
881    };
882
883    let mut paths = Vec::new();
884    for entry in entries.flatten() {
885        let p = entry.path();
886        if p.is_file() {
887            let Some(file_name) = p.file_name().and_then(|n| n.to_str()) else {
888                continue;
889            };
890            if file_name.ends_with(".csv")
891                && file_name != "schema.csv"
892                && !file_name.ends_with(".generated.csv")
893            {
894                paths.push(p);
895            }
896        }
897    }
898    paths.sort();
899
900    let mut file_data = Vec::new();
901    for p in &paths {
902        let Some(file_name) = p.file_name().and_then(|n| n.to_str()) else {
903            continue;
904        };
905        if let Ok(bytes) = std::fs::read(p) {
906            file_data.push((file_name.to_string(), bytes));
907        } else {
908            report.add_error(
909                &p.display().to_string(),
910                None,
911                None,
912                format!("Failed to read file {}", p.display()),
913                None,
914            );
915        }
916    }
917
918    let files_iter: Vec<(&str, &[u8])> = file_data
919        .iter()
920        .map(|(name, bytes)| (name.as_str(), bytes.as_slice()))
921        .collect();
922
923    let mut defns = validate_format_files_data(
924        files_iter,
925        &formats_dir.display().to_string(),
926        known_scripts,
927        report,
928    );
929    if let Some(data_src_dir) = formats_dir.parent().and_then(std::path::Path::parent)
930        && let Ok((staged_impls, _)) = crate::wat::load_staged_dc_impls(data_src_dir)
931    {
932        for staged in staged_impls {
933            if let ctb_storage_minimal::shorthand::DcShorthand::Format(fid) =
934                staged.target
935                && let Some(fdefn) = defns
936                    .iter_mut()
937                    .find(|d| d.format.is_some() && d.short_id == Some(fid))
938            {
939                let entry = staged.to_decomposition_entry();
940                if !fdefn.decompositions.contains(&entry) {
941                    fdefn.decompositions.push(entry);
942                }
943            }
944        }
945    }
946    defns
947}
948
949#[cfg(test)]
950#[allow(
951    clippy::panic,
952    clippy::expect_used,
953    clippy::unwrap_used,
954    clippy::unwrap_in_result,
955    clippy::panic_in_result_fn,
956    clippy::indexing_slicing,
957    clippy::arithmetic_side_effects,
958    reason = "Standard repository test boilerplate"
959)]
960mod tests {
961    use super::*;
962
963    #[crate::ctb_test]
964    fn test_format_label_required() {
965        let mut report = ValidationReport::new();
966        let valid_variants = HashSet::new();
967
968        // Row with blank label but present ident
969        let csv_data = b"Dc,Short,Ident (Rust-friendly),Label,Category,Base,Ext,MIME,UTI,Apple,Nick,Imp,Exp,Tests,Var,Comments,Ref\n2228224,0,MyFormat,,document,,,,,,,,,,,, \n";
970        validate_formats_category_file(
971            csv_data,
972            "test/formats/test.csv",
973            &valid_variants,
974            &mut report,
975        );
976
977        assert!(report.has_errors());
978        assert!(report.format_report().contains("Format must have a Label"));
979    }
980
981    #[crate::ctb_test]
982    fn test_deprecated_format_ident_allowed() {
983        let mut report = ValidationReport::new();
984        let valid_variants = HashSet::new();
985
986        let csv_data = b"Dc,Short,Ident (Rust-friendly),Label,Category,Base,Ext,MIME,UTI,Apple,Nick,Imp,Exp,Tests,Var,Comments,Ref\n2228224,0,!Gregorian,Gregorian calendar,calendar,,,,,,,,,,,, \n";
987        let rows = validate_formats_category_file(
988            csv_data,
989            "test/formats/calendar.csv",
990            &valid_variants,
991            &mut report,
992        );
993
994        assert!(
995            !report.has_errors(),
996            "Unexpected errors: {}",
997            report.format_report()
998        );
999        assert_eq!(rows.len(), 1);
1000        assert!(rows[0].is_deprecated);
1001        assert_eq!(rows[0].ident.as_deref(), Some("Gregorian"));
1002        assert_eq!(rows[0].name, "Gregorian calendar");
1003    }
1004
1005    #[crate::ctb_test]
1006    fn test_deprecated_format_invalid_ident_fails() {
1007        let mut report = ValidationReport::new();
1008        let valid_variants = HashSet::new();
1009
1010        let csv_data = b"Dc,Short,Ident (Rust-friendly),Label,Category,Base,Ext,MIME,UTI,Apple,Nick,Imp,Exp,Tests,Var,Comments,Ref\n2228224,0,!123Invalid,Invalid ident format,calendar,,,,,,,,,,,, \n";
1011        validate_formats_category_file(
1012            csv_data,
1013            "test/formats/calendar.csv",
1014            &valid_variants,
1015            &mut report,
1016        );
1017
1018        assert!(report.has_errors());
1019        assert!(
1020            report
1021                .format_report()
1022                .contains("Invalid Rust identifier '!123Invalid'")
1023        );
1024    }
1025
1026    #[crate::ctb_test]
1027    fn test_format_spec_chain_directive_parsed() {
1028        let mut report = ValidationReport::new();
1029        let valid_variants = HashSet::new();
1030
1031        let csv_data = b"Dc,Short,Ident (Rust-friendly),Label,Category,\"Base/Related Format/Category, Chain (@), or Syntax (:)\",Ext,MIME,UTI,Apple,Nick,Imp,Exp,Tests,Var,Comments,Ref\n2228224,0,TestMojibake,Test Mojibake,encoding,\"@chain(((f15 > f542) ! f0) > f0)\",,,,,,,,,,, \n";
1032        let rows = validate_formats_category_file(
1033            csv_data,
1034            "test/formats/encoding.csv",
1035            &valid_variants,
1036            &mut report,
1037        );
1038
1039        assert!(
1040            !report.has_errors(),
1041            "Unexpected errors: {}",
1042            report.format_report()
1043        );
1044        assert_eq!(rows.len(), 1);
1045        let details = rows[0].format.as_ref().unwrap();
1046        assert!(details.format_spec.is_some());
1047        let spec_str = format!("{}", details.format_spec.as_ref().unwrap());
1048        assert_eq!(spec_str, "((f15 > f542) ! f0) > f0");
1049    }
1050
1051    #[crate::ctb_test]
1052    fn test_format_spec_chain_invalid_syntax_reports_error() {
1053        let mut report = ValidationReport::new();
1054        let valid_variants = HashSet::new();
1055
1056        // Ambiguous unparenthesized mixing of & and | inside @chain(...)
1057        let csv_data = b"Dc,Short,Ident (Rust-friendly),Label,Category,\"Base/Related Format/Category, Chain (@), or Syntax (:)\",Ext,MIME,UTI,Apple,Nick,Imp,Exp,Tests,Var,Comments,Ref\n2228224,0,TestBadChain,Test Bad Chain,encoding,\"@chain(f15 & f542 | f0)\",,,,,,,,,,, \n";
1058        validate_formats_category_file(
1059            csv_data,
1060            "test/formats/encoding.csv",
1061            &valid_variants,
1062            &mut report,
1063        );
1064
1065        assert!(report.has_errors());
1066        let err = report.format_report();
1067        assert!(err.contains("Failed to parse format specification DSL rule"));
1068    }
1069
1070    #[crate::ctb_test]
1071    fn test_legacy_chain_syntax_reports_error() {
1072        let mut report = ValidationReport::new();
1073        let valid_variants = HashSet::new();
1074
1075        let csv_data = b"Dc,Short,Ident (Rust-friendly),Label,Category,\"Base/Related Format/Category, Chain (@), or Syntax (:)\",Ext,MIME,UTI,Apple,Nick,Imp,Exp,Tests,Var,Comments,Ref\n2228224,0,TestOldChain,Test Old Chain,encoding,\"=f15 > f0\",,,,,,,,,,, \n";
1076        validate_formats_category_file(
1077            csv_data,
1078            "test/formats/encoding.csv",
1079            &valid_variants,
1080            &mut report,
1081        );
1082
1083        assert!(report.has_errors());
1084        let err = report.format_report();
1085        assert!(err.contains("Legacy chain syntax '=' is deprecated"));
1086    }
1087
1088    #[crate::ctb_test]
1089    fn test_format_variant_rules_validation() {
1090        let mut report = ValidationReport::new();
1091
1092        // 1. Valid scenario: format_variant file with @vary_as and a number format using @varies
1093        let fv_csv = b"Dc,Short,Ident (Rust-friendly),Label,Category,\"Base/Related Format/Category, Chain (@), or Syntax (:)\",Ext,MIME,UTI,Apple,Nick,Imp,Exp,Tests,Var,Comments,Ref\n2228224,0,Base,Base radix,format_variant,\"@vary_as(\"\"radix\"\")\",,,,,,,,,,, \n";
1094        let num_csv = b"Dc,Short,Ident (Rust-friendly),Label,Category,\"Base/Related Format/Category, Chain (@), or Syntax (:)\",Ext,MIME,UTI,Apple,Nick,Imp,Exp,Tests,Var,Comments,Ref\n2228225,1,BaseNNumeral,Base N Numeral,number,\"@varies(f0)\",,,,,,,,,,, \n";
1095
1096        let files = vec![
1097            ("format_variant.csv", &fv_csv[..]),
1098            ("number.csv", &num_csv[..]),
1099        ];
1100        let _ = validate_format_files_data(
1101            files,
1102            "test/formats/",
1103            None,
1104            &mut report,
1105        );
1106        assert!(
1107            !report.has_errors(),
1108            "Unexpected errors: {}",
1109            report.format_report()
1110        );
1111
1112        // 2. Invalid @varies target (referencing non-variant format f1)
1113        let mut err_report = ValidationReport::new();
1114        let num_bad_csv = b"Dc,Short,Ident (Rust-friendly),Label,Category,\"Base/Related Format/Category, Chain (@), or Syntax (:)\",Ext,MIME,UTI,Apple,Nick,Imp,Exp,Tests,Var,Comments,Ref\n2228225,1,BaseNNumeral,Base N Numeral,number,\"@varies(f1)\",,,,,,,,,,, \n";
1115        let files_bad_varies = vec![
1116            ("format_variant.csv", &fv_csv[..]),
1117            ("number.csv", &num_bad_csv[..]),
1118        ];
1119        let _ = validate_format_files_data(
1120            files_bad_varies,
1121            "test/formats/",
1122            None,
1123            &mut err_report,
1124        );
1125        assert!(err_report.has_errors());
1126        assert!(
1127            err_report
1128                .format_report()
1129                .contains("references non-variant format or character")
1130        );
1131
1132        // 3. Invalid @vary_as placement outside .Formats:format_variant
1133        let mut err_vary_as = ValidationReport::new();
1134        let num_bad_vary_as = b"Dc,Short,Ident (Rust-friendly),Label,Category,\"Base/Related Format/Category, Chain (@), or Syntax (:)\",Ext,MIME,UTI,Apple,Nick,Imp,Exp,Tests,Var,Comments,Ref\n2228225,1,BaseNNumeral,Base N Numeral,number,\"@vary_as(\"\"radix\"\")\",,,,,,,,,,, \n";
1135        let files_bad_vary_as = vec![("number.csv", &num_bad_vary_as[..])];
1136        let _ = validate_format_files_data(
1137            files_bad_vary_as,
1138            "test/formats/",
1139            None,
1140            &mut err_vary_as,
1141        );
1142        assert!(err_vary_as.has_errors());
1143        assert!(err_vary_as.format_report().contains(
1144            "only permitted on formats in '.Formats:format_variant'"
1145        ));
1146
1147        // 4. Variant script .Formats:v:case without matching @vary_as("case") in format_variant
1148        let mut err_unregistered_v = ValidationReport::new();
1149        let v_case_csv = b"Dc,Short,Ident (Rust-friendly),Label,Category,\"Base/Related Format/Category, Chain (@), or Syntax (:)\",Ext,MIME,UTI,Apple,Nick,Imp,Exp,Tests,Var,Comments,Ref\n2228225,1,CaseInsensitive,Case Insensitive,v:case,,,,,,,,,,,, \n";
1150        let files_unregistered_v = vec![
1151            ("format_variant.csv", &fv_csv[..]),
1152            ("v.case.csv", &v_case_csv[..]),
1153        ];
1154        let _ = validate_format_files_data(
1155            files_unregistered_v,
1156            "test/formats/",
1157            None,
1158            &mut err_unregistered_v,
1159        );
1160        assert!(err_unregistered_v.has_errors());
1161        assert!(err_unregistered_v.format_report().contains("is not defined by any declared '@vary_as(\"case\")' in .Formats:format_variant"));
1162    }
1163}