ctb_formats_dcdata/support/
validation.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//! Comprehensive table validators for Document Characters (Dcs), Formats, and
21//! Global Graph Layout datasets.
22
23#[allow(
24    unused_imports,
25    clippy::wildcard_imports,
26    reason = "Standard workspace module prelude"
27)]
28use crate::utilities::*;
29
30use std::collections::{HashMap, HashSet};
31use std::path::Path;
32
33use include_dir::Dir;
34
35use crate::dc::{SHORT_DC_REGION_END, SHORT_DC_REGION_START};
36use crate::dc_def::DcDefn;
37use crate::format::validate_all_format_files_from_disk;
38use crate::layout::validate_layout_table;
39use crate::report::ValidationReport;
40use crate::shared::{
41    BidiClass, GeneralCategory, validate_bidi_class, validate_combining_class,
42    validate_cross_table_uniqueness, validate_general_category,
43};
44use crate::syntax::{
45    CharTarget, DcSyntaxRule, FormatValidationRegistry,
46    build_format_validation_registry, normalize_syntax_pattern,
47    parse_dc_syntax, parse_target_token, validate_dc_syntax,
48};
49use ctb_storage_minimal::shorthand::parse_unicode_shorthand;
50
51/// Runs comprehensive validation across all repository data tables.
52pub fn validate_all_data_tables() -> ValidationReport {
53    validate_all_data_tables_embedded()
54}
55
56/// Runs validation across all repository data tables located in the repository.
57pub fn validate_all_data_tables_embedded() -> ValidationReport {
58    match crate::find_repository_root() {
59        Ok(repo_root) => validate_all_data_tables_from_repo(&repo_root),
60        Err(e) => {
61            let mut report = ValidationReport::new();
62            report.add_error(
63                "src/formats/dcdata/data-src",
64                None,
65                None,
66                format!("Could not locate repository root: {e}"),
67                None,
68            );
69            report
70        }
71    }
72}
73
74/// Runs validation directly against live files in a repository directory.
75pub fn validate_all_data_tables_from_repo(
76    repo_root: &Path,
77) -> ValidationReport {
78    validate_all_data_tables_from_repo_with_options(repo_root, true)
79}
80
81/// Runs validation directly against live files in a repository directory, optionally
82/// checking on-disk `assets/data/graph/*.ctbnodes` synchronization (`check_ledger_sync`).
83pub fn validate_all_data_tables_from_repo_with_options(
84    repo_root: &Path,
85    check_ledger_sync: bool,
86) -> ValidationReport {
87    let mut report = ValidationReport::new();
88
89    if let Err(error) = crate::updater::validate_category_allocations(repo_root)
90    {
91        report.add_error(
92            "src/formats/dcdata/data-src",
93            None,
94            None,
95            format!("Invalid block reservations or ID assignments: {error:#}"),
96            Some("Check block ranges, allocation high-water marks, and category IDs"),
97        );
98    }
99
100    // 1. Validate Global Graph Layout table
101    let layout_path =
102        repo_root.join("src/storage/minimal/data/global-graph-layout.csv");
103    if let Ok(bytes) = std::fs::read(&layout_path) {
104        validate_layout_table(
105            &bytes,
106            "storage/minimal/data/global-graph-layout.csv",
107            &mut report,
108        );
109    } else {
110        report.add_error(
111            "storage/minimal/data/global-graph-layout.csv",
112            None,
113            None,
114            "Could not locate global-graph-layout.csv on disk",
115            Some("Ensure file exists in storage/minimal/data/"),
116        );
117    }
118
119    // 2. Validate Scripts Registry table
120    let scripts_path =
121        repo_root.join("src/formats/dcdata/data-src/README.scripts.csv");
122    let Ok(bytes) = std::fs::read(&scripts_path) else {
123        report.add_error(
124            "src/formats/dcdata/data-src/README.scripts.csv",
125            None,
126            None,
127            "Could not locate README.scripts.csv on disk",
128            Some("Ensure file exists in src/formats/dcdata/data-src/"),
129        );
130        return report;
131    };
132    let known_scripts = validate_scripts_table(
133        &bytes,
134        "src/formats/dcdata/data-src/README.scripts.csv",
135        &mut report,
136    );
137    if report.has_errors() && known_scripts.is_empty() {
138        return report;
139    }
140
141    // 3. Validate Formats category files
142    let formats_dir =
143        repo_root.join("src/formats/dcdata/data-src/categories/formats");
144    let format_rows = validate_all_format_files_from_disk(
145        &formats_dir,
146        Some(&known_scripts),
147        &mut report,
148    );
149    let known_format_ids: HashSet<usize> =
150        format_rows.iter().filter_map(|r| r.short_id).collect();
151    let known_format_with_syntax: HashSet<usize> = format_rows
152        .iter()
153        .filter(|r| r.syntax.is_some())
154        .filter_map(|r| r.short_id)
155        .collect();
156
157    // 4. Validate Decompositions table
158    let decomp_path =
159        repo_root.join("src/formats/dcdata/data-src/README-decompositions.csv");
160    let known_decomp_tags = if let Ok(bytes) = std::fs::read(&decomp_path) {
161        validate_decompositions_table(
162            &bytes,
163            "src/formats/dcdata/data-src/README-decompositions.csv",
164            &mut report,
165        )
166    } else {
167        report.add_error(
168            "src/formats/dcdata/data-src/README-decompositions.csv",
169            None,
170            None,
171            "Could not locate README-decompositions.csv on disk",
172            Some("Ensure file exists in src/formats/dcdata/data-src/"),
173        );
174        HashSet::new()
175    };
176
177    let named_types_path =
178        repo_root.join("src/formats/dcdata/data-src/README-named-types.csv");
179    let named_types_bytes_opt = std::fs::read(&named_types_path).ok();
180    // Reason for fallback: optional named types file defaults to empty set if not present on disk
181    let known_named_types = named_types_bytes_opt
182        .as_ref()
183        .map(|b| extract_named_type_names(b))
184        .unwrap_or_default();
185
186    let format_registry = build_format_validation_registry(&format_rows);
187
188    // 5. Validate Document Characters category files
189    let dc_dir = repo_root.join("src/formats/dcdata/data-src/categories");
190    let dc_rows = validate_all_dc_files_from_disk(
191        &dc_dir,
192        &known_format_ids,
193        Some(&known_decomp_tags),
194        Some(&known_named_types),
195        Some(&known_scripts),
196        Some(&known_format_with_syntax),
197        Some(&format_registry),
198        &mut report,
199    );
200
201    // 6. Validate Cross-Table Name / Label Uniqueness
202    let dc_names: Vec<(usize, &str, &str)> = dc_rows
203        .iter()
204        .filter_map(|r| {
205            r.short_id
206                .map(|sid| (sid, r.name.as_str(), r.source_file.as_str()))
207        })
208        .collect();
209
210    let format_labels: Vec<(usize, &str, &str)> = format_rows
211        .iter()
212        .filter_map(|r| {
213            r.short_id
214                .map(|sid| (sid, r.name.as_str(), r.source_file.as_str()))
215        })
216        .collect();
217
218    validate_cross_table_uniqueness(&dc_names, &format_labels, &mut report);
219
220    // 7. Validate Named Types table
221    let known_dc_ids: HashSet<u32> = dc_rows
222        .iter()
223        .filter_map(|r| r.short_id)
224        .filter_map(|id| u32::try_from(id).ok())
225        .collect();
226
227    let mut known_syntax_targets: HashSet<CharTarget> = dc_rows
228        .iter()
229        .filter(|r| r.syntax.is_some())
230        .filter_map(|r| r.short_id)
231        .filter_map(|id| u32::try_from(id).ok())
232        .map(CharTarget::Dc)
233        .collect();
234    for &fid in &known_format_with_syntax {
235        if let Some(format_id) =
236            ctb_utilities::format_id::FormatId::from_shorthand(&format!(
237                "f{fid}"
238            ))
239        {
240            known_syntax_targets.insert(CharTarget::Format(format_id));
241        }
242    }
243
244    if let Some(bytes) = named_types_bytes_opt {
245        validate_named_types_table(
246            &bytes,
247            "src/formats/dcdata/data-src/README-named-types.csv",
248            &known_dc_ids,
249            &known_format_ids,
250            Some(&known_scripts),
251            Some(&known_syntax_targets),
252            Some(&format_registry),
253            &mut report,
254        );
255    } else {
256        report.add_error(
257            "src/formats/dcdata/data-src/README-named-types.csv",
258            None,
259            None,
260            "Could not locate README-named-types.csv on disk",
261            Some("Ensure file exists in src/formats/dcdata/data-src/"),
262        );
263    }
264
265    // 8. Validate StageL 3 PSR-4 files, `: @dc` ledger bindings, and Gate 4 `.WASM` boundaries
266    crate::support::stagel_dc_alloc::validate_stagel_and_system_graph_in_repo_with_options(
267        repo_root,
268        &repo_root.join("src/formats/dcdata/data-src"),
269        &known_dc_ids,
270        &known_format_ids,
271        Some(&format_registry),
272        check_ledger_sync,
273        &mut report,
274    );
275
276    report
277}
278
279/// Validates the README.scripts.csv registry table, verifying schema, uniqueness,
280/// and block increment sizes (`TBD` or a positive integer multiple of 16),
281/// and returning the set of valid script identifiers.
282pub fn validate_scripts_table(
283    csv_bytes: &[u8],
284    file_path: &str,
285    report: &mut ValidationReport,
286) -> HashSet<String> {
287    parse_scripts_block_sizes_with_report(csv_bytes, file_path, report)
288        .into_keys()
289        .collect()
290}
291
292/// Validates and parses the `README.scripts.csv` registry table into a map from
293/// script name to its optional block increment size (`None` when `"TBD"`, or
294/// `Some(size)` where `size` is a positive multiple of 16).
295pub fn parse_scripts_block_sizes_with_report(
296    csv_bytes: &[u8],
297    file_path: &str,
298    report: &mut ValidationReport,
299) -> HashMap<String, Option<u32>> {
300    let vec_bytes = csv_bytes.to_vec();
301    let table = match csv_tools::parse_csv_reader(
302        &vec_bytes,
303        csv_tools::CsvParseOptions {
304            has_header: true,
305            flexible: true,
306            ..Default::default()
307        },
308    ) {
309        Ok(t) => t,
310        Err(e) => {
311            report.add_error(
312                file_path,
313                None,
314                None,
315                format!("Failed to parse CSV: {e}"),
316                Some("Verify CSV syntax and formatting"),
317            );
318            return HashMap::new();
319        }
320    };
321
322    let mut valid_scripts = HashMap::new();
323    for i in 0..table.row_count() {
324        let line_no = i.saturating_add(2);
325        let Some(row) = table.row(i) else {
326            continue;
327        };
328
329        if row.is_empty() {
330            report.add_error(
331                file_path,
332                Some(line_no),
333                None,
334                "Empty row in scripts registry".to_string(),
335                Some("Specify script name and block increment size"),
336            );
337            continue;
338        }
339
340        #[expect(
341            clippy::expect_used,
342            reason = "Row is guaranteed non-empty by the is_empty() check above"
343        )]
344        let script = row.first().expect("row is non-empty").trim();
345        // Reason for fallback: a missing second CSV column is treated as empty so the validation check below reports a missing block increment size.
346        let raw_block_size = row.get(1).map_or("", |s| s.trim());
347
348        let parsed_block_size = if raw_block_size.is_empty() {
349            report.add_error(
350                file_path,
351                Some(line_no),
352                Some("Block increment size"),
353                format!("Script '{script}' is missing a Block increment size"),
354                Some("Specify 'TBD' or a positive integer multiple of 16 (e.g. 16, 32, 64, 128, 256)"),
355            );
356            None
357        } else if raw_block_size == "TBD" {
358            None
359        } else {
360            match raw_block_size.parse::<u32>() {
361                Ok(size) if size > 0 && size.is_multiple_of(16) => Some(size),
362                Ok(size) => {
363                    report.add_error(
364                        file_path,
365                        Some(line_no),
366                        Some("Block increment size"),
367                        format!(
368                            "Block increment size {size} for script '{script}' must be a positive multiple of 16"
369                        ),
370                        Some("Use a multiple of 16 so blocks align to 0..F hexadecimal boundaries"),
371                    );
372                    None
373                }
374                Err(_) => {
375                    report.add_error(
376                        file_path,
377                        Some(line_no),
378                        Some("Block increment size"),
379                        format!(
380                            "Invalid Block increment size '{raw_block_size}' for script '{script}'"
381                        ),
382                        Some("Specify 'TBD' or a positive integer multiple of 16"),
383                    );
384                    None
385                }
386            }
387        };
388
389        if script.is_empty() {
390            report.add_error(
391                file_path,
392                Some(line_no),
393                Some("Script"),
394                "Script identifier cannot be empty".to_string(),
395                Some("Specify a script name"),
396            );
397        } else if !script.starts_with('.')
398            && !ctb_formats_unicode::is_valid_unicode_script(script)
399        {
400            report.add_error(
401                file_path,
402                Some(line_no),
403                Some("Script"),
404                format!(
405                    "Script '{script}' must start with a full stop '.' or be a valid Unicode script"
406                ),
407                Some("Prefix Dc-specific script name with '.'"),
408            );
409        } else if valid_scripts
410            .insert(script.to_string(), parsed_block_size)
411            .is_some()
412        {
413            report.add_error(
414                file_path,
415                Some(line_no),
416                Some("Script"),
417                format!("Duplicate script '{script}'"),
418                Some("Ensure each script is defined uniquely"),
419            );
420        }
421    }
422
423    valid_scripts
424}
425
426/// Loads and validates the known scripts table from embedded assets.
427///
428/// Returns `None` if the file could not be found or if validation failed.
429pub fn load_embedded_known_scripts(
430    report: &mut ValidationReport,
431) -> Option<HashSet<String>> {
432    let Some(scripts_bytes) = crate::get_dc_data_file("README.scripts.csv")
433    else {
434        report.add_error(
435            "data/README.scripts.csv",
436            None,
437            None,
438            "Could not locate embedded README.scripts.csv",
439            None,
440        );
441        return None;
442    };
443    let scripts = validate_scripts_table(
444        &scripts_bytes,
445        "data/README.scripts.csv",
446        report,
447    );
448    if report.has_errors() && scripts.is_empty() {
449        None
450    } else {
451        Some(scripts)
452    }
453}
454
455/// Validates the README-decompositions.csv table, verifying schema and uniqueness,
456/// and returning the set of valid decomposition tags.
457pub fn validate_decompositions_table(
458    csv_bytes: &[u8],
459    file_path: &str,
460    report: &mut ValidationReport,
461) -> HashSet<String> {
462    let vec_bytes = csv_bytes.to_vec();
463    let table = match csv_tools::parse_csv_reader(
464        &vec_bytes,
465        csv_tools::CsvParseOptions {
466            has_header: true,
467            flexible: true,
468            ..Default::default()
469        },
470    ) {
471        Ok(t) => t,
472        Err(e) => {
473            report.add_error(
474                file_path,
475                None,
476                None,
477                format!("Failed to parse CSV: {e}"),
478                Some("Verify CSV syntax and formatting"),
479            );
480            return HashSet::new();
481        }
482    };
483
484    let mut valid_tags = HashSet::new();
485    for i in 0..table.row_count() {
486        let line_no = i.saturating_add(2);
487        let Some(row) = table.row(i) else {
488            continue;
489        };
490
491        let (Some(raw_tag), Some(raw_desc)) = (row.first(), row.get(1)) else {
492            report.add_error(
493                file_path,
494                Some(line_no),
495                None,
496                format!("Row has {} columns, expected at least 2", row.len()),
497                Some(
498                    "Ensure row has 'Decomposition' and 'Description' columns",
499                ),
500            );
501            continue;
502        };
503        let (tag, desc) = (raw_tag.trim(), raw_desc.trim());
504
505        if tag.is_empty() {
506            report.add_error(
507                file_path,
508                Some(line_no),
509                Some("Decomposition"),
510                "Decomposition tag cannot be empty".to_string(),
511                Some("Specify a tag name for the decomposition"),
512            );
513        } else if !tag.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
514            report.add_error(
515                file_path,
516                Some(line_no),
517                Some("Decomposition"),
518                format!("Invalid characters in decomposition tag '{tag}'"),
519                Some("Decomposition tags must be alphanumeric"),
520            );
521        } else if !valid_tags.insert(tag.to_string()) {
522            report.add_error(
523                file_path,
524                Some(line_no),
525                Some("Decomposition"),
526                format!("Duplicate decomposition tag '{tag}'"),
527                Some("Ensure each decomposition tag is defined uniquely"),
528            );
529        }
530
531        if desc.is_empty() {
532            report.add_error(
533                file_path,
534                Some(line_no),
535                Some("Description"),
536                "Decomposition description cannot be empty".to_string(),
537                Some("Provide a description explaining the decomposition semantics"),
538            );
539        }
540    }
541
542    valid_tags
543}
544
545/// Extracts the set of named type identifiers from the README-named-types.csv table.
546pub fn extract_named_type_names(csv_bytes: &[u8]) -> HashSet<String> {
547    let vec_bytes = csv_bytes.to_vec();
548    let Ok(table) = csv_tools::parse_csv_reader(
549        &vec_bytes,
550        csv_tools::CsvParseOptions {
551            has_header: true,
552            flexible: true,
553            ..Default::default()
554        },
555    ) else {
556        return HashSet::new();
557    };
558
559    let mut names = HashSet::new();
560    for i in 0..table.row_count() {
561        if let Some(row) = table.row(i) {
562            if let Some(name) = row.first() {
563                let trimmed = name.trim();
564                if !trimmed.is_empty() {
565                    names.insert(trimmed.to_string());
566                }
567            }
568        }
569    }
570    names
571}
572
573/// Validates the README-named-types.csv table, verifying syntax declarations
574/// for each named type, and returning the set of valid named type names.
575pub fn validate_named_types_table(
576    csv_bytes: &[u8],
577    file_path: &str,
578    known_dc_ids: &HashSet<u32>,
579    known_format_ids: &HashSet<usize>,
580    known_scripts: Option<&HashSet<String>>,
581    known_syntax_targets: Option<&HashSet<CharTarget>>,
582    format_registry: Option<&FormatValidationRegistry>,
583    report: &mut ValidationReport,
584) -> HashSet<String> {
585    let all_known_names = extract_named_type_names(csv_bytes);
586    let vec_bytes = csv_bytes.to_vec();
587    let table = match csv_tools::parse_csv_reader(
588        &vec_bytes,
589        csv_tools::CsvParseOptions {
590            has_header: true,
591            flexible: true,
592            ..Default::default()
593        },
594    ) {
595        Ok(t) => t,
596        Err(e) => {
597            report.add_error(
598                file_path,
599                None,
600                None,
601                format!("Failed to parse CSV: {e}"),
602                Some("Verify CSV syntax and formatting"),
603            );
604            return HashSet::new();
605        }
606    };
607
608    let default_syntax_targets = HashSet::new();
609    // Reason for fallback: optional known syntax targets registry defaults to empty set when omitted
610    let syntax_targets =
611        known_syntax_targets.unwrap_or(&default_syntax_targets);
612
613    let mut seen_names = HashSet::new();
614    for i in 0..table.row_count() {
615        let line_no = i.saturating_add(2);
616        let Some(row) = table.row(i) else {
617            continue;
618        };
619
620        let (Some(raw_name), Some(raw_syntax)) = (row.first(), row.get(1))
621        else {
622            report.add_error(
623                file_path,
624                Some(line_no),
625                None,
626                format!("Row has {} columns, expected at least 2", row.len()),
627                Some("Ensure row has 'Named type' and 'Syntax' columns"),
628            );
629            continue;
630        };
631        let (name, syntax) = (raw_name.trim(), raw_syntax.trim());
632
633        if name.is_empty() {
634            report.add_error(
635                file_path,
636                Some(line_no),
637                Some("Named type"),
638                "Named type cannot be empty".to_string(),
639                Some("Specify a name for the named type construct"),
640            );
641        } else if !seen_names.insert(name.to_string()) {
642            report.add_error(
643                file_path,
644                Some(line_no),
645                Some("Named type"),
646                format!("Duplicate named type '{name}'"),
647                Some("Ensure each named type is defined uniquely"),
648            );
649        }
650
651        if syntax.is_empty() {
652            report.add_error(
653                file_path,
654                Some(line_no),
655                Some("Syntax"),
656                "Syntax rule cannot be empty".to_string(),
657                Some("Provide a Dc syntax declaration for the named type"),
658            );
659        } else {
660            match parse_dc_syntax(syntax) {
661                Ok(rule) => {
662                    validate_dc_syntax(
663                        &rule,
664                        0,
665                        known_dc_ids,
666                        known_format_ids,
667                        &all_known_names,
668                        known_scripts,
669                        syntax_targets,
670                        format_registry,
671                        report,
672                        file_path,
673                        line_no,
674                    );
675                }
676                Err(e) => {
677                    report.add_error(
678                        file_path,
679                        Some(line_no),
680                        Some("Syntax"),
681                        format!("Failed to parse syntax DSL rule: {e}"),
682                        Some("Verify syntax DSL grammar"),
683                    );
684                }
685            }
686        }
687    }
688
689    seen_names
690}
691
692/// Parses the composite Aliases/cross-reference/decomposition/syntax column and
693/// validates all spacing, delimiter, and formatting conventions in a single pass.
694///
695/// Ensures:
696/// - No leading or trailing whitespace in the cell.
697/// - Every comma is followed by exactly one space (no missing space, no
698///   multiple spaces).
699/// - No whitespace before a comma.
700/// - No empty elements or misplaced commas (leading/trailing/consecutive
701///   commas).
702/// - Decompositions (`<tag>...`):
703///   - No whitespace inside the tag brackets (e.g. `< approx>`, `<approx >`).
704///   - No whitespace immediately following the closing `>` (e.g. `<approx> 0`
705///     has extra space before 0).
706///   - Tokens in decomposition payload are separated by single spaces.
707/// - Cross-references (`>...`):
708///   - No whitespace immediately following `>` (e.g. `> 32` has extra space
709///     before 32).
710/// - Plain aliases and syntax declarations:
711///   - No multiple consecutive spaces.
712pub fn parse_dc_aliases_column(
713    raw: &str,
714    file_path: &str,
715    line_no: usize,
716    report: &mut ValidationReport,
717) -> (Vec<String>, Vec<String>, Vec<String>, Option<String>) {
718    let parsed = crate::column_spec::parse_aliases_or_base_column(
719        raw, file_path, line_no, report, false,
720    );
721    (
722        parsed.aliases,
723        parsed.cross_references,
724        parsed.decompositions,
725        parsed.syntax_raw,
726    )
727}
728
729/// Splits the composite aliases/cross-reference/decomposition/syntax column.
730pub fn split_dc_aliases_column(
731    raw: &str,
732) -> (Vec<String>, Vec<String>, Vec<String>, Option<String>) {
733    let mut dummy_report = ValidationReport::default();
734    parse_dc_aliases_column(raw, "", 0, &mut dummy_report)
735}
736
737/// Validates spacing and formatting conventions in the Aliases column.
738pub fn validate_dc_aliases_spacing(
739    raw: &str,
740    file_path: &str,
741    line_no: usize,
742    report: &mut ValidationReport,
743) {
744    let _ = parse_dc_aliases_column(raw, file_path, line_no, report);
745}
746
747/// Derives a [`DcSyntaxRule`] for a `.EM Routines` entry from the parameter
748/// signature in its `Name` column (e.g. `void lang.say([string] text)` ->
749/// `:~ 258 [string $text] 259`).
750pub fn derive_el_routine_syntax(name: &str) -> Result<Option<DcSyntaxRule>> {
751    let trimmed = name.trim();
752    let Some(open_idx) = trimmed.find('(') else {
753        return Ok(Some(parse_dc_syntax(":~")?));
754    };
755    let Some(close_idx) = trimmed.rfind(')') else {
756        bail!("Routine signature '{trimmed}' has '(' without matching ')'");
757    };
758    ensure!(
759        open_idx < close_idx,
760        "Mismatched parentheses in routine signature '{trimmed}'"
761    );
762    let params_raw = trimmed
763        .get(open_idx.saturating_add(1)..close_idx)
764        .context("Invalid parameter slice bounds")?
765        .trim();
766    if params_raw.is_empty() {
767        return Ok(Some(parse_dc_syntax(":~")?));
768    }
769
770    let mut params = Vec::new();
771    let mut current = String::new();
772    let mut depth_p = 0usize;
773    let mut depth_b = 0usize;
774    for ch in params_raw.chars() {
775        match ch {
776            '(' => {
777                depth_p = depth_p.saturating_add(1);
778                current.push(ch);
779            }
780            ')' => {
781                depth_p = depth_p.saturating_sub(1);
782                current.push(ch);
783            }
784            '[' => {
785                depth_b = depth_b.saturating_add(1);
786                current.push(ch);
787            }
788            ']' => {
789                depth_b = depth_b.saturating_sub(1);
790                current.push(ch);
791            }
792            ',' if depth_p == 0 && depth_b == 0 => {
793                params.push(current.trim().to_string());
794                current.clear();
795            }
796            _ => current.push(ch),
797        }
798    }
799    if !current.trim().is_empty() {
800        params.push(current.trim().to_string());
801    }
802
803    let mut rule_parts = vec![":~".to_string()];
804    for param in params {
805        let mut alt_branches = Vec::new();
806        let mut branch_cur = String::new();
807        let mut dp = 0usize;
808        let mut db = 0usize;
809        for ch in param.chars() {
810            match ch {
811                '(' => {
812                    dp = dp.saturating_add(1);
813                    branch_cur.push(ch);
814                }
815                ')' => {
816                    dp = dp.saturating_sub(1);
817                    branch_cur.push(ch);
818                }
819                '[' => {
820                    db = db.saturating_add(1);
821                    branch_cur.push(ch);
822                }
823                ']' => {
824                    db = db.saturating_sub(1);
825                    branch_cur.push(ch);
826                }
827                '|' if dp == 0 && db == 0 => {
828                    alt_branches.push(branch_cur.trim().to_string());
829                    branch_cur.clear();
830                }
831                _ => branch_cur.push(ch),
832            }
833        }
834        if !branch_cur.trim().is_empty() {
835            alt_branches.push(branch_cur.trim().to_string());
836        }
837
838        let mut converted_branches = Vec::new();
839        for branch in &alt_branches {
840            let b = branch.trim();
841            ensure!(
842                b.starts_with('['),
843                "Routine parameter '{b}' in '{trimmed}' must start with a bracketed type '[type]'"
844            );
845            let mut close_b_idx = None;
846            let mut b_depth = 0usize;
847            for (i, c) in b.char_indices() {
848                match c {
849                    '[' => b_depth = b_depth.saturating_add(1),
850                    ']' => {
851                        b_depth = b_depth.saturating_sub(1);
852                        if b_depth == 0 {
853                            close_b_idx = Some(i);
854                            break;
855                        }
856                    }
857                    _ => {}
858                }
859            }
860            let Some(end_bracket) = close_b_idx else {
861                bail!("Unclosed '[' in routine parameter '{b}' in '{trimmed}'");
862            };
863            let type_content = b
864                .get(1..end_bracket)
865                .context("Invalid bracket slice")?
866                .trim();
867            let param_name = b
868                .get(end_bracket.saturating_add(1)..)
869                .context("Invalid parameter name slice bounds")?
870                .trim();
871            ensure!(
872                !type_content.is_empty(),
873                "Empty type in routine parameter '{b}' in '{trimmed}'"
874            );
875            if param_name.is_empty() {
876                converted_branches.push(format!("[{type_content}]"));
877            } else {
878                let clean_var = param_name.trim_start_matches('$');
879                converted_branches
880                    .push(format!("[{type_content} ${clean_var}]"));
881            }
882        }
883
884        if converted_branches.len() == 1 {
885            if let Some(single) = converted_branches.first() {
886                rule_parts.push(format!("258 {single} 259"));
887            }
888        } else {
889            rule_parts
890                .push(format!("258 ({}) 259", converted_branches.join(" | ")));
891        }
892    }
893
894    let raw_rule = rule_parts.join(" ");
895    Ok(Some(parse_dc_syntax(&raw_rule)?))
896}
897
898/// Parses and validates a single Dc category CSV file.
899pub fn validate_dc_category_file(
900    csv_bytes: &[u8],
901    file_path: &str,
902    report: &mut ValidationReport,
903) -> Vec<DcDefn> {
904    let vec_bytes = csv_bytes.to_vec();
905    let table = match csv_tools::parse_csv_reader(
906        &vec_bytes,
907        csv_tools::CsvParseOptions {
908            has_header: true,
909            flexible: true,
910            ..Default::default()
911        },
912    ) {
913        Ok(t) => t,
914        Err(e) => {
915            report.add_error(
916                file_path,
917                None,
918                None,
919                format!("Failed to parse CSV: {e}"),
920                Some("Verify CSV syntax and formatting"),
921            );
922            return Vec::new();
923        }
924    };
925
926    let mut rows = Vec::new();
927    let is_generated_csv = file_path.ends_with(".generated.csv");
928    let expected_cols = if is_generated_csv { 19 } else { 10 };
929
930    if let Some(header) = table.header() {
931        if header.len() != expected_cols {
932            report.add_error(
933                file_path,
934                Some(1),
935                None,
936                format!(
937                    "CSV header has {} columns, expected {} columns",
938                    header.len(),
939                    expected_cols
940                ),
941                Some("Ensure CSV header matches schema"),
942            );
943        }
944    }
945
946    let Some(category) = std::path::Path::new(file_path)
947        .file_stem()
948        .and_then(|s| s.to_str())
949    else {
950        report.add_error(
951            file_path,
952            None,
953            None,
954            format!("Invalid category file path: unable to determine category name from '{file_path}'"),
955            Some("Ensure category files have a valid filename stem (e.g. 'latin.csv')"),
956        );
957        return Vec::new();
958    };
959    let category = category.to_string();
960
961    for i in 0..table.row_count() {
962        let line_no = i.saturating_add(2);
963        let row_opt = table.row(i);
964        let Some(row) = row_opt else {
965            continue;
966        };
967
968        if row.len() != expected_cols {
969            report.add_error(
970                file_path,
971                Some(line_no),
972                None,
973                format!("Row has {} columns, expected {}", row.len(), expected_cols),
974                Some("Each row in Dc categories must have columns matching schema"),
975            );
976        }
977
978        // Reason for fallback: out-of-bounds column indices on malformed rows default to empty string so schema validation can report all diagnostics without indexing panics
979        let get_str = |idx: usize| -> String {
980            row.get(idx).map_or(String::new(), |s| s.trim().to_string())
981        };
982
983        let dc_str = get_str(0);
984        let short_str = get_str(1);
985        let raw_name = get_str(2);
986        let combining_str = get_str(3);
987        let bidi_str = get_str(4);
988        let casing_str = get_str(5);
989        let general_cat_str = get_str(6);
990        let script = get_str(7);
991        let raw_aliases_untrimmed = get_str(8);
992        let description = get_str(9);
993
994        if dc_str.is_empty() && short_str.is_empty() && raw_name.is_empty() {
995            continue;
996        }
997
998        let is_generated_csv = file_path.ends_with(".generated.csv");
999        let (dc_id, is_unicode_char) = if dc_str.starts_with('u') {
1000            match parse_unicode_shorthand(&dc_str) {
1001                Ok(cp) => (u128::from(cp), true),
1002                Err(err) => {
1003                    let err_msg = err.to_string();
1004                    if err_msg.contains("exceeds maximum") {
1005                        // Reason for fallback: starts_with('u') confirmed above, strip 'u' prefix for error message
1006                        let hex_part = dc_str.strip_prefix('u').unwrap_or("");
1007                        report.add_error(
1008                            file_path,
1009                            Some(line_no),
1010                            Some("Dc"),
1011                            format!("Unicode codepoint 'u{hex_part}' exceeds maximum Unicode 0x10FFFF"),
1012                            Some("Ensure codepoint is within 0x0..=0x10FFFF"),
1013                        );
1014                    } else if dc_str.strip_prefix('u').is_some_and(|h| {
1015                        !h.is_empty()
1016                            && h.chars().all(|c| c.is_ascii_hexdigit())
1017                    }) {
1018                        report.add_error(
1019                            file_path,
1020                            Some(line_no),
1021                            Some("Dc"),
1022                            format!(
1023                                "Invalid hex in Unicode reference: '{dc_str}'"
1024                            ),
1025                            Some("Must be 'u' followed by valid lowercase hex"),
1026                        );
1027                    } else {
1028                        report.add_error(
1029                            file_path,
1030                            Some(line_no),
1031                            Some("Dc"),
1032                            format!("Invalid Unicode notation '{dc_str}': must be 'u' followed by 1..=6 lowercase hex digits (e.g. u0020, u0b)"),
1033                            Some("Only lowercase u<hex> is permitted for Unicode characters in category tables"),
1034                        );
1035                    }
1036                    continue;
1037                }
1038            }
1039        } else if let Ok(v) = dc_str.parse::<u128>() {
1040            if v <= 1_114_111 {
1041                if is_generated_csv {
1042                    (v, true)
1043                } else {
1044                    report.add_error(
1045                        file_path,
1046                        Some(line_no),
1047                        Some("Dc"),
1048                        format!("Unicode character must use 'u<hex>' format in category tables, found decimal integer: '{dc_str}'"),
1049                        Some("Use 'u<hex>' (e.g. u0a, u85) for Unicode characters in category CSVs"),
1050                    );
1051                    continue;
1052                }
1053            } else {
1054                (v, false)
1055            }
1056        } else {
1057            report.add_error(
1058                file_path,
1059                Some(line_no),
1060                Some("Dc"),
1061                format!("Invalid Global Dc ID integer or Unicode reference: '{dc_str}'"),
1062                Some("Must be an integer within Document Character region or 'u<hex>' for Unicode characters"),
1063            );
1064            continue;
1065        };
1066
1067        let short_id = if is_unicode_char {
1068            if short_str.is_empty()
1069                || short_str.starts_with("308")
1070                || parse_unicode_shorthand(&short_str).is_ok()
1071            {
1072                None
1073            } else {
1074                report.add_error(
1075                    file_path,
1076                    Some(line_no),
1077                    Some("Short"),
1078                    format!("Invalid Short ID for Unicode character: '{short_str}'"),
1079                    Some("Short ID for Unicode characters must be blank, lowercase 'u<hex>', or start with 308 (case-sensitive per README.shorthand.md)"),
1080                );
1081                None
1082            }
1083        } else {
1084            let parsed_short = if let Ok(v) = short_str.parse::<u32>() {
1085                v
1086            } else {
1087                report.add_error(
1088                    file_path,
1089                    Some(line_no),
1090                    Some("Short"),
1091                    format!("Invalid Short Dc ID integer: '{short_str}'"),
1092                    Some("Must be a non-negative integer"),
1093                );
1094                continue;
1095            };
1096
1097            let expected_dc =
1098                SHORT_DC_REGION_START.saturating_add(u128::from(parsed_short));
1099            if dc_id != expected_dc {
1100                report.add_error(
1101                    file_path,
1102                    Some(line_no),
1103                    Some("Dc"),
1104                    format!(
1105                        "Global Dc ID ({dc_id}) does not match SHORT_DC_REGION_START + Short ID ({expected_dc})"
1106                    ),
1107                    Some("Ensure Dc ID is offset from Short ID by 1114112"),
1108                );
1109            }
1110
1111            if !(SHORT_DC_REGION_START..=SHORT_DC_REGION_END).contains(&dc_id) {
1112                report.add_error(
1113                    file_path,
1114                    Some(line_no),
1115                    Some("Dc"),
1116                    format!(
1117                        "Dc ID {dc_id} is out of the Document Characters region bounds ({SHORT_DC_REGION_START}..={SHORT_DC_REGION_END})"
1118                    ),
1119                    Some("Verify region boundaries"),
1120                );
1121            }
1122
1123            let Ok(short_id_usize) = usize::try_from(parsed_short) else {
1124                report.add_error(
1125                    file_path,
1126                    Some(line_no),
1127                    Some("Short"),
1128                    format!("Short ID {parsed_short} exceeds usize limits"),
1129                    Some("Ensure Short ID fits in machine usize"),
1130                );
1131                continue;
1132            };
1133
1134            Some(short_id_usize)
1135        };
1136
1137        let (name, is_deprecated) = if is_unicode_char {
1138            #[expect(
1139                clippy::expect_used,
1140                reason = "is_unicode_char guarantees dc_id was constructed from a u32 <= 0x10_FFFF"
1141            )]
1142            let cp = u32::try_from(dc_id)
1143                .expect("dc_id fits in u32 for unicode chars");
1144            // Reason for fallback: characters without standard Unicode names use raw name from CSV category definition
1145            let uni_name = ctb_formats_unicode::get_unicode_name(cp)
1146                .unwrap_or_else(|| {
1147                    if let Some(stripped) = raw_name.strip_prefix('!') {
1148                        stripped.trim().to_string()
1149                    } else {
1150                        raw_name.trim().to_string()
1151                    }
1152                });
1153            let dep = ctb_formats_unicode::is_deprecated_unicode(cp);
1154            (uni_name, dep)
1155        } else {
1156            let dep = raw_name.starts_with('!');
1157            let n = if let Some(stripped) = raw_name.strip_prefix('!') {
1158                stripped.trim().to_string()
1159            } else {
1160                raw_name.trim().to_string()
1161            };
1162            (n, dep)
1163        };
1164
1165        let (combining_class, bidi_class, general_category, script) =
1166            if is_unicode_char {
1167                #[expect(
1168                    clippy::expect_used,
1169                    reason = "is_unicode_char guarantees dc_id was constructed from a u32 <= 0x10_FFFF"
1170                )]
1171                let cp = u32::try_from(dc_id)
1172                    .expect("dc_id fits in u32 for unicode chars");
1173                let cc = ctb_formats_unicode::combining_class(cp);
1174                // Reason for fallback: unassigned Unicode codepoints default to Boundary Neutral bidi class
1175                let bc = validate_bidi_class(
1176                    ctb_formats_unicode::bidi_class_code(cp),
1177                )
1178                .unwrap_or(BidiClass::BN);
1179                // Reason for fallback: unassigned Unicode codepoints default to NonUnicodeControl general category
1180                let gc = validate_general_category(
1181                    ctb_formats_unicode::general_category_code(cp),
1182                )
1183                .unwrap_or(GeneralCategory::NonUnicodeControl);
1184                // Reason for fallback: unassigned Unicode codepoints default to Common script
1185                let sc = ctb_formats_unicode::script_name(cp)
1186                    .unwrap_or("Common")
1187                    .to_string();
1188                (cc, bc, gc, sc)
1189            } else {
1190                let cc = match validate_combining_class(&combining_str) {
1191                    Ok(val) => val,
1192                    Err(e) => {
1193                        report.add_error(
1194                            file_path,
1195                            Some(line_no),
1196                            Some("◌"),
1197                            format!("Invalid combining class: {e}"),
1198                            Some("Must be integer 0..=254"),
1199                        );
1200                        0
1201                    }
1202                };
1203                let bc = match validate_bidi_class(&bidi_str) {
1204                    Ok(b) => b,
1205                    Err(e) => {
1206                        report.add_error(
1207                        file_path,
1208                        Some(line_no),
1209                        Some("⇆"),
1210                        format!("Invalid Bidi Class: {e}"),
1211                        Some("Use standard Unicode Bidi class abbreviation (e.g. BN, L, ON)"),
1212                    );
1213                        BidiClass::BN
1214                    }
1215                };
1216                let gc = match validate_general_category(&general_cat_str) {
1217                    Ok(cat) => cat,
1218                    Err(e) => {
1219                        report.add_error(
1220                            file_path,
1221                            Some(line_no),
1222                            Some("Type"),
1223                            format!("Invalid General Category: {e}"),
1224                            Some("Use standard Unicode category or '!Cx'"),
1225                        );
1226                        GeneralCategory::NonUnicodeControl
1227                    }
1228                };
1229                let sc = script.trim().to_string();
1230                (cc, bc, gc, sc)
1231            };
1232
1233        let casing_partner = if casing_str.is_empty() {
1234            None
1235        } else if let Ok(v) = casing_str.parse::<u32>() {
1236            Some(v)
1237        } else {
1238            report.add_error(
1239                file_path,
1240                Some(line_no),
1241                Some("Aa"),
1242                format!("Invalid Casing partner ID integer: '{casing_str}'"),
1243                Some("Must be a short Dc ID integer if present"),
1244            );
1245            None
1246        };
1247
1248        let parsed_col = crate::column_spec::parse_aliases_or_base_column(
1249            &raw_aliases_untrimmed,
1250            file_path,
1251            line_no,
1252            report,
1253            false,
1254        );
1255        let aliases = parsed_col.aliases;
1256        let cross_references = parsed_col.cross_references;
1257        let decompositions = parsed_col.decompositions;
1258        let raw_dc_syntax = parsed_col.syntax_raw;
1259        let formal_aliases = parsed_col
1260            .formal_aliases
1261            .into_iter()
1262            .map(|f| (f.kind, f.alias))
1263            .collect();
1264        let annotations = parsed_col.annotations;
1265
1266        let dc_syntax =
1267            if matches!(script.as_str(), ".EM Routines" | ".EL Routines") {
1268                if raw_dc_syntax.is_some() {
1269                    report.add_error(
1270                    file_path,
1271                    Some(line_no),
1272                    Some("Aliases (syntax)"),
1273                    "Redundant explicit syntax rule on '.EM Routines' Document Character (syntax is derived automatically from the parameter declaration in Name)"
1274                        .to_string(),
1275                    Some("Remove explicit ':...' syntax rule from Aliases and declare parameter types in Name"),
1276                );
1277                }
1278                match derive_el_routine_syntax(&name) {
1279                    Ok(rule) => rule,
1280                    Err(e) => {
1281                        report.add_error(
1282                        file_path,
1283                        Some(line_no),
1284                        Some("Name (!=deprecated)"),
1285                        format!("Failed to derive '.EM Routines' parameter syntax from Name '{name}': {e}"),
1286                        Some("Specify parameters in the form 'retType routine.name([type] paramName, ...)'"),
1287                    );
1288                        None
1289                    }
1290                }
1291            } else if let Some(raw_syn) = &raw_dc_syntax {
1292            match parse_dc_syntax(raw_syn) {
1293                Ok(rule) => Some(rule),
1294                Err(e) => {
1295                    report.add_error(
1296                        file_path,
1297                        Some(line_no),
1298                        Some("Aliases (syntax)"),
1299                        format!("Failed to parse Dc syntax DSL rule: {e}"),
1300                        Some("Verify Dc syntax DSL grammar"),
1301                    );
1302                    None
1303                }
1304            }
1305        } else {
1306            None
1307        };
1308
1309        let (row_category, format_details) = if let Some(fmt_cat) = script
1310            .strip_prefix(".Formats:")
1311            .or_else(|| script.strip_prefix("Formats:"))
1312        {
1313            let cat_trimmed = fmt_cat.trim();
1314            if cat_trimmed.is_empty() {
1315                report.add_error(
1316                    file_path,
1317                    Some(line_no),
1318                    Some("Script"),
1319                    "Format script '.Formats:' is missing category name (e.g. '.Formats:calendar')".to_string(),
1320                    Some("Specify category name after '.Formats:'"),
1321                );
1322            }
1323            let formatted_cat = if cat_trimmed.starts_with("format_") {
1324                cat_trimmed.to_string()
1325            } else {
1326                format!("format_{cat_trimmed}")
1327            };
1328            (
1329                formatted_cat,
1330                Some(crate::dc_def::FormatDetails {
1331                    implies: None,
1332                    based_on: None,
1333                    chain: None,
1334                    format_spec: None,
1335                    extensions: None,
1336                    mime: None,
1337                    uti: None,
1338                    apple_type: None,
1339                    nicknames: if parsed_col.nicknames.is_empty() {
1340                        None
1341                    } else {
1342                        Some(parsed_col.nicknames.join(", "))
1343                    },
1344                    import_support: None,
1345                    export_support: None,
1346                    tests: None,
1347                    variant_types: None,
1348                    title: parsed_col.title.clone(),
1349                    default_line_ending: parsed_col.default_line_ending.clone(),
1350                    vary_as: parsed_col.vary_as.clone(),
1351                    varies: parsed_col.varies.clone(),
1352                }),
1353            )
1354        } else {
1355            (category.clone(), None)
1356        };
1357
1358        if parsed_col.stable_ident && parsed_col.rust_ident.is_none() {
1359            report.add_error(
1360                file_path,
1361                Some(line_no),
1362                Some("Aliases"),
1363                "Document Character has '@stable_ident()' but is missing an '@ident(\"...\")' declaration".to_string(),
1364                Some("Add an '@ident(\"...\")' declaration before marking it with '@stable_ident()'"),
1365            );
1366        }
1367
1368        rows.push(DcDefn {
1369            dc_id,
1370            short_id,
1371            ident: parsed_col.rust_ident,
1372            stable_ident: parsed_col.stable_ident,
1373            title: parsed_col.title,
1374            name,
1375            category: row_category,
1376            combining_class,
1377            bidi_class,
1378            casing_partner,
1379            general_category,
1380            script,
1381            is_deprecated,
1382            decompositions,
1383            aliases,
1384            formal_aliases,
1385            cross_references,
1386            annotations,
1387            implies: parsed_col.implies,
1388            based_on: parsed_col.based_on,
1389            os_associations: parsed_col.os_associations,
1390            magic_names: parsed_col.magic_names,
1391            syntax: dc_syntax,
1392            closes: parsed_col.closes,
1393            description,
1394            format: format_details,
1395            source_file: file_path.to_string(),
1396            line_number: line_no,
1397        });
1398    }
1399
1400    rows
1401}
1402
1403/// Validates target references strictly (Dc short IDs, lowercase Unicode `uXXXX`, Formats `fXX`).
1404fn collect_format_ids_from_expr(
1405    expr: &crate::format_spec::FormatExpr,
1406    ids: &mut Vec<usize>,
1407) {
1408    match expr {
1409        crate::format_spec::FormatExpr::Dc(
1410            ctb_storage_minimal::shorthand::DcShorthand::Format(fmt_id),
1411        ) => {
1412            ids.push(*fmt_id);
1413        }
1414        crate::format_spec::FormatExpr::Convert(l, r)
1415        | crate::format_spec::FormatExpr::Transmute(l, r)
1416        | crate::format_spec::FormatExpr::Transform(l, r) => {
1417            collect_format_ids_from_expr(l, ids);
1418            collect_format_ids_from_expr(r, ids);
1419        }
1420        crate::format_spec::FormatExpr::Union(children)
1421        | crate::format_spec::FormatExpr::Intersection(children) => {
1422            for child in children {
1423                collect_format_ids_from_expr(child, ids);
1424            }
1425        }
1426        crate::format_spec::FormatExpr::Apply { target, params } => {
1427            collect_format_ids_from_expr(target, ids);
1428            for p in params {
1429                match &p.value {
1430                    crate::format_spec::ParamValue::Dc(
1431                        ctb_storage_minimal::shorthand::DcShorthand::Format(
1432                            fmt_id,
1433                        ),
1434                    ) => {
1435                        ids.push(*fmt_id);
1436                    }
1437                    crate::format_spec::ParamValue::Expr(sub) => {
1438                        collect_format_ids_from_expr(sub, ids);
1439                    }
1440                    _ => {}
1441                }
1442            }
1443        }
1444        _ => {}
1445    }
1446}
1447
1448fn validate_target_token(
1449    token: &str,
1450    source_file: &str,
1451    line_no: usize,
1452    col_name: &str,
1453    known_dc_ids: &HashSet<u32>,
1454    deprecated_dc_ids: Option<&HashSet<u32>>,
1455    tag_name: Option<&str>,
1456    known_format_ids: &HashSet<usize>,
1457    deprecated_format_ids: Option<&HashSet<usize>>,
1458    report: &mut ValidationReport,
1459) {
1460    let trimmed = token.trim();
1461    if trimmed.contains('(') && trimmed.ends_with(')') {
1462        if let Ok(expr) = crate::format_spec::parse_format_expr(trimmed) {
1463            if let Err(e) = crate::format_spec::validate_format_expr(&expr) {
1464                report.add_error(
1465                    source_file,
1466                    Some(line_no),
1467                    Some(col_name),
1468                    format!("Invalid format specification in '{trimmed}': {e}"),
1469                    Some("Ensure valid format specification syntax and parameters"),
1470                );
1471            }
1472            let mut fmt_ids = Vec::new();
1473            collect_format_ids_from_expr(&expr, &mut fmt_ids);
1474            for fmt_id in fmt_ids {
1475                if !known_format_ids.contains(&fmt_id) {
1476                    report.add_error(
1477                        source_file,
1478                        Some(line_no),
1479                        Some(col_name),
1480                        format!(
1481                            "Referenced Format ID 'f{fmt_id}' does not exist in formats registry"
1482                        ),
1483                        Some(
1484                            "Ensure referenced format ID is defined in formats category files",
1485                        ),
1486                    );
1487                } else if let (Some(dep_fmts), Some(tag)) =
1488                    (deprecated_format_ids, tag_name)
1489                {
1490                    if dep_fmts.contains(&fmt_id) {
1491                        report.add_error(
1492                            source_file,
1493                            Some(line_no),
1494                            Some(col_name),
1495                            format!(
1496                                "Canonical equivalency or approximate relationship '<{tag}>' references deprecated Format ID 'f{fmt_id}'"
1497                            ),
1498                            Some("Canonical equivalencies and approximations must target active, non-deprecated Formats"),
1499                        );
1500                    }
1501                }
1502            }
1503            return;
1504        }
1505        // If it failed to parse as format spec, fall through to single token validation
1506    }
1507
1508    let clean = token
1509        .trim()
1510        .trim_matches(|c| c == '(' || c == ')' || c == '>' || c == '<');
1511    if clean.is_empty() {
1512        return;
1513    }
1514
1515    let Some(target) = parse_target_token(clean) else {
1516        report.add_error(
1517            source_file,
1518            Some(line_no),
1519            Some(col_name),
1520            format!(
1521                "Invalid target reference token '{clean}': must be a Short Dc ID (e.g. 240), format ID (e.g. f80), or lowercase Unicode hex (e.g. u12ab)"
1522            ),
1523            Some("Use canonical format IDs (f80), lowercase Unicode hex (u0020), or Short Dc IDs (240)"),
1524        );
1525        return;
1526    };
1527
1528    match target {
1529        CharTarget::Format(fmt_id) => {
1530            let short_id = fmt_id
1531                .dc_id()
1532                .and_then(|dc| {
1533                    dc.checked_sub(
1534                        ctb_storage_minimal::global_graph_layout::FORMAT_REGION_START,
1535                    )
1536                })
1537                .and_then(|v| usize::try_from(v).ok());
1538            if short_id.is_none_or(|id| !known_format_ids.contains(&id)) {
1539                let shorthand = fmt_id.shorthand();
1540                report.add_error(
1541                    source_file,
1542                    Some(line_no),
1543                    Some(col_name),
1544                    format!("Referenced Format ID '{shorthand}' does not exist in formats registry"),
1545                    Some("Ensure referenced format ID is defined in formats category files"),
1546                );
1547            } else if let (Some(dep_fmts), Some(tag)) =
1548                (deprecated_format_ids, tag_name)
1549            {
1550                if short_id.is_some_and(|id| dep_fmts.contains(&id)) {
1551                    let shorthand = fmt_id.shorthand();
1552                    report.add_error(
1553                        source_file,
1554                        Some(line_no),
1555                        Some(col_name),
1556                        format!(
1557                            "Canonical equivalency or approximate relationship '<{tag}>' references deprecated Format ID '{shorthand}'"
1558                        ),
1559                        Some("Canonical equivalencies and approximations must target active, non-deprecated Formats"),
1560                    );
1561                }
1562            }
1563        }
1564        CharTarget::FormatRegionEnd => {
1565            report.add_error(
1566                source_file,
1567                Some(line_no),
1568                Some(col_name),
1569                format!(
1570                    "Referenced Format ID 'f{}' does not exist in formats registry",
1571                    ctb_storage_minimal::shorthand::MAX_FORMAT_ID
1572                ),
1573                Some("Ensure referenced format ID is defined in formats category files"),
1574            );
1575        }
1576        CharTarget::Unicode(cp) => {
1577            if !ctb_formats_unicode::is_assigned_unicode(cp) {
1578                report.add_error(
1579                    source_file,
1580                    Some(line_no),
1581                    Some(col_name),
1582                    format!(
1583                        "Referenced Unicode codepoint 'u{cp:04x}' (U+{cp:04X}) is not an assigned Unicode character"
1584                    ),
1585                    Some("Ensure referenced Unicode character exists in Unicode standard"),
1586                );
1587            } else if let Some(tag) = tag_name {
1588                if ctb_formats_unicode::is_deprecated_unicode(cp) {
1589                    report.add_error(
1590                        source_file,
1591                        Some(line_no),
1592                        Some(col_name),
1593                        format!(
1594                            "Canonical equivalency or approximate relationship '<{tag}>' references deprecated Unicode character 'u{cp:04x}' (U+{cp:04X})"
1595                        ),
1596                        Some("Canonical equivalencies and approximations must target active, non-deprecated Unicode characters"),
1597                    );
1598                }
1599            }
1600        }
1601        CharTarget::Dc(target_dc) => {
1602            if !known_dc_ids.contains(&target_dc) {
1603                report.add_error(
1604                    source_file,
1605                    Some(line_no),
1606                    Some(col_name),
1607                    format!("Referenced Dc ID '{target_dc}' does not exist in Document Characters registry"),
1608                    Some("Ensure referenced Dc ID is defined in a Dc category file"),
1609                );
1610            } else if let (Some(dep_ids), Some(tag)) =
1611                (deprecated_dc_ids, tag_name)
1612            {
1613                if dep_ids.contains(&target_dc) {
1614                    report.add_error(
1615                        source_file,
1616                        Some(line_no),
1617                        Some(col_name),
1618                        format!(
1619                            "Canonical equivalency or approximate relationship '<{tag}>' references deprecated Dc ID '{target_dc}'"
1620                        ),
1621                        Some("Canonical equivalencies and approximations must target active, non-deprecated Document Characters"),
1622                    );
1623                }
1624            }
1625        }
1626    }
1627}
1628
1629/// Validates a sequence of Dc category files.
1630pub fn validate_dc_files_data<'a, I>(
1631    files: I,
1632    category_dir_label: &str,
1633    known_format_ids: &HashSet<usize>,
1634    known_decomp_tags: Option<&HashSet<String>>,
1635    known_named_types: Option<&HashSet<String>>,
1636    known_scripts: Option<&HashSet<String>>,
1637    known_format_with_syntax: Option<&HashSet<usize>>,
1638    format_registry: Option<&FormatValidationRegistry>,
1639    report: &mut ValidationReport,
1640) -> Vec<DcDefn>
1641where
1642    I: IntoIterator<Item = (&'a str, &'a [u8])>,
1643{
1644    let mut all_rows = Vec::new();
1645    let mut short_id_map: HashMap<usize, (String, usize)> = HashMap::new();
1646    let mut dc_id_map: HashMap<u128, (String, usize)> = HashMap::new();
1647
1648    for (path_str, contents) in files {
1649        if !path_str.ends_with(".csv")
1650            || path_str.ends_with("schema.csv")
1651            || path_str.ends_with(".generated.csv")
1652        {
1653            continue;
1654        }
1655
1656        let rows = validate_dc_category_file(contents, path_str, report);
1657
1658        for row in rows {
1659            if let Some(scripts) = known_scripts {
1660                let is_valid = if row.short_id.is_some() {
1661                    scripts.contains(&row.script)
1662                } else if row.script.starts_with('.') {
1663                    scripts.contains(&row.script)
1664                } else {
1665                    ctb_formats_unicode::is_valid_unicode_script(&row.script)
1666                };
1667                if !is_valid {
1668                    report.add_error(
1669                        &row.source_file,
1670                        Some(row.line_number),
1671                        Some("Script"),
1672                        format!("Unknown script '{}'", row.script),
1673                        Some("Ensure script is registered in README.scripts.csv"),
1674                    );
1675                }
1676            }
1677
1678            if let Some(short_id) = row.short_id {
1679                if let Some((prev_file, prev_line)) =
1680                    short_id_map.get(&short_id)
1681                {
1682                    report.add_error(
1683                        &row.source_file,
1684                        Some(row.line_number),
1685                        Some("Short"),
1686                        format!(
1687                            "Duplicate Short Dc ID {short_id} already defined in {prev_file}:{prev_line}",
1688                        ),
1689                        Some("Assign a unique Short ID to each Document Character"),
1690                    );
1691                } else {
1692                    short_id_map.insert(
1693                        short_id,
1694                        (row.source_file.clone(), row.line_number),
1695                    );
1696                }
1697            }
1698
1699            if let Some((prev_file, prev_line)) = dc_id_map.get(&row.dc_id) {
1700                report.add_error(
1701                    &row.source_file,
1702                    Some(row.line_number),
1703                    Some("Dc"),
1704                    format!(
1705                        "Duplicate Dc ID {} already defined in {prev_file}:{prev_line}",
1706                        row.dc_id
1707                    ),
1708                    Some("Ensure each character has a unique Dc ID"),
1709                );
1710            } else {
1711                dc_id_map.insert(
1712                    row.dc_id,
1713                    (row.source_file.clone(), row.line_number),
1714                );
1715            }
1716
1717            all_rows.push(row);
1718        }
1719    }
1720
1721    let known_dc_ids: HashSet<u32> = all_rows
1722        .iter()
1723        .filter_map(|r| r.short_id)
1724        .filter_map(|id| u32::try_from(id).ok())
1725        .collect();
1726
1727    let deprecated_dc_ids: HashSet<u32> = all_rows
1728        .iter()
1729        .filter(|r| r.is_deprecated)
1730        .filter_map(|r| r.short_id)
1731        .filter_map(|id| u32::try_from(id).ok())
1732        .collect();
1733
1734    // Reason for fallback: when format_registry is not provided, no formats are considered deprecated.
1735    let deprecated_format_ids: HashSet<usize> = format_registry
1736        .map(|reg| {
1737            reg.formats_by_id
1738                .values()
1739                .filter(|f| f.is_deprecated)
1740                .map(|f| f.short_id)
1741                .collect()
1742        })
1743        .unwrap_or_default();
1744
1745    let mut known_syntax_targets: HashSet<CharTarget> = all_rows
1746        .iter()
1747        .filter(|r| r.syntax.is_some())
1748        .filter_map(|r| r.short_id)
1749        .filter_map(|id| u32::try_from(id).ok())
1750        .map(CharTarget::Dc)
1751        .collect();
1752    if let Some(fmts_with_syntax) = known_format_with_syntax {
1753        for &fid in fmts_with_syntax {
1754            if let Some(format_id) =
1755                ctb_utilities::format_id::FormatId::from_shorthand(&format!(
1756                    "f{fid}"
1757                ))
1758            {
1759                known_syntax_targets.insert(CharTarget::Format(format_id));
1760            }
1761        }
1762    }
1763
1764    // Validate that Short Dc IDs in the legacy contiguous region form a contiguous sequence starting from 0 with no gaps/holes
1765    if let Some(&max_id) = known_dc_ids.iter().max() {
1766        let legacy_limit = max_id.min(crate::updater::PREEXISTING_CONTIGUOUS_DC_MAX);
1767        let mut missing_ids = Vec::new();
1768        for id in 0..=legacy_limit {
1769            if !known_dc_ids.contains(&id) {
1770                missing_ids.push(id);
1771            }
1772        }
1773        if !missing_ids.is_empty() {
1774            let missing_str = if missing_ids.len() <= 10 {
1775                missing_ids
1776                    .iter()
1777                    .map(std::string::ToString::to_string)
1778                    .collect::<Vec<_>>()
1779                    .join(", ")
1780            } else {
1781                format!(
1782                    "{} (and {} more)",
1783                    missing_ids
1784                        .iter()
1785                        .take(10)
1786                        .map(std::string::ToString::to_string)
1787                        .collect::<Vec<_>>()
1788                        .join(", "),
1789                    missing_ids.len().saturating_sub(10)
1790                )
1791            };
1792            report.add_error(
1793                category_dir_label,
1794                None,
1795                Some("Short"),
1796                format!(
1797                    "Document Character Short IDs have gaps/holes. Missing {} ID(s): [{missing_str}] in range 0..={legacy_limit}",
1798                    missing_ids.len()
1799                ),
1800                Some("Ensure Short Dc IDs are contiguous with no missing numbers"),
1801            );
1802        }
1803    }
1804
1805    let dc_lookup_by_short: HashMap<
1806        usize,
1807        (
1808            &Option<DcSyntaxRule>,
1809            &Option<ctb_storage_minimal::shorthand::DcShorthand>,
1810            &str,
1811            usize,
1812        ),
1813    > = all_rows
1814        .iter()
1815        .filter_map(|r| {
1816            r.short_id.map(|sid| {
1817                (
1818                    sid,
1819                    (
1820                        &r.syntax,
1821                        &r.closes,
1822                        r.source_file.as_str(),
1823                        r.line_number,
1824                    ),
1825                )
1826            })
1827        })
1828        .collect();
1829
1830    // Build equivalence connected components for normalizing equivalent opener targets
1831    let mut equiv_graph: HashMap<u128, HashSet<u128>> = HashMap::new();
1832    let mut equiv_sources: HashSet<u128> = HashSet::new();
1833    let mut equiv_targets: HashSet<u128> = HashSet::new();
1834    for r in &all_rows {
1835        for decomp in &r.decompositions {
1836            if let Some((tag_raw, payload)) = decomp.split_once('>') {
1837                if tag_raw.trim_start_matches('<').trim() == "equiv" {
1838                    let tokens: Vec<&str> =
1839                        payload.split_whitespace().collect();
1840                    if tokens.len() == 1 {
1841                        if let Some(&target_tok) = tokens.first() {
1842                            if let Ok(sh) = ctb_storage_minimal::shorthand::DcShorthand::parse(target_tok) {
1843                                if let Ok(target_gid) = sh.to_global_id() {
1844                                    equiv_graph.entry(r.dc_id).or_default().insert(target_gid);
1845                                    equiv_graph.entry(target_gid).or_default().insert(r.dc_id);
1846                                    equiv_sources.insert(r.dc_id);
1847                                    equiv_targets.insert(target_gid);
1848                                }
1849                            }
1850                        }
1851                    }
1852                }
1853            }
1854        }
1855    }
1856    if let Some(reg) = format_registry {
1857        for fmt_info in reg.formats_by_id.values() {
1858            if let Ok(fmt_sh) =
1859                ctb_storage_minimal::shorthand::DcShorthand::Format(
1860                    fmt_info.short_id,
1861                )
1862                .to_global_id()
1863            {
1864                for decomp in &fmt_info.decompositions {
1865                    if let Some((tag_raw, payload)) = decomp.split_once('>') {
1866                        if tag_raw.trim_start_matches('<').trim() == "equiv" {
1867                            let tokens: Vec<&str> =
1868                                payload.split_whitespace().collect();
1869                            if tokens.len() == 1 {
1870                                if let Some(&target_tok) = tokens.first() {
1871                                    if let Ok(sh) = ctb_storage_minimal::shorthand::DcShorthand::parse(target_tok) {
1872                                        if let Ok(target_gid) = sh.to_global_id() {
1873                                            equiv_graph.entry(fmt_sh).or_default().insert(target_gid);
1874                                            equiv_graph.entry(target_gid).or_default().insert(fmt_sh);
1875                                            equiv_sources.insert(fmt_sh);
1876                                            equiv_targets.insert(target_gid);
1877                                        }
1878                                    }
1879                                }
1880                            }
1881                        }
1882                    }
1883                }
1884            }
1885        }
1886    }
1887
1888    let is_dep = |token: u128| -> bool {
1889        let dc = DcChar::from_u128(token);
1890        if let Ok(sid) = dc.to_short() {
1891            deprecated_dc_ids.contains(&sid)
1892        } else if let Some(fid) =
1893            ctb_utilities::format_id::FormatId::from_dc_id(token)
1894        {
1895            fid.shorthand()
1896                .trim_start_matches('f')
1897                .parse::<usize>()
1898                .ok()
1899                .is_some_and(|id| deprecated_format_ids.contains(&id))
1900        } else {
1901            false
1902        }
1903    };
1904
1905    let mut canonical_map: HashMap<u128, u128> = HashMap::new();
1906    let mut visited_equiv: HashSet<u128> = HashSet::new();
1907    for &node in equiv_graph.keys() {
1908        if visited_equiv.contains(&node) {
1909            continue;
1910        }
1911        let mut component: Vec<u128> = Vec::new();
1912        let mut queue: Vec<u128> = vec![node];
1913        visited_equiv.insert(node);
1914        while let Some(curr) = queue.pop() {
1915            component.push(curr);
1916            if let Some(neighbors) = equiv_graph.get(&curr) {
1917                for &neighbor in neighbors {
1918                    if visited_equiv.insert(neighbor) {
1919                        queue.push(neighbor);
1920                    }
1921                }
1922            }
1923        }
1924
1925        let terminal_targets: Vec<u128> = component
1926            .iter()
1927            .copied()
1928            .filter(|m| {
1929                equiv_targets.contains(m)
1930                    && !equiv_sources.contains(m)
1931                    && !is_dep(*m)
1932            })
1933            .collect();
1934        let non_dep_targets: Vec<u128> = component
1935            .iter()
1936            .copied()
1937            .filter(|m| equiv_targets.contains(m) && !is_dep(*m))
1938            .collect();
1939        let non_dep_members: Vec<u128> =
1940            component.iter().copied().filter(|m| !is_dep(*m)).collect();
1941        let any_targets: Vec<u128> = component
1942            .iter()
1943            .copied()
1944            .filter(|m| equiv_targets.contains(m))
1945            .collect();
1946
1947        let canonical = terminal_targets
1948            .into_iter()
1949            .min()
1950            .or_else(|| non_dep_targets.into_iter().min())
1951            .or_else(|| non_dep_members.into_iter().min())
1952            .or_else(|| any_targets.into_iter().min())
1953            .or_else(|| component.iter().copied().min());
1954
1955        if let Some(canonical) = canonical {
1956            for member in component {
1957                canonical_map.insert(member, canonical);
1958            }
1959        }
1960    }
1961
1962    let are_openers_equivalent =
1963        |s: &ctb_storage_minimal::shorthand::DcShorthand,
1964         t: &ctb_storage_minimal::shorthand::DcShorthand|
1965         -> bool {
1966            if s == t {
1967                return true;
1968            }
1969            match (s.to_global_id(), t.to_global_id()) {
1970                (Ok(s_gid), Ok(t_gid)) => {
1971                    // Reason for fallback: tokens not in canonical_map are self-canonical.
1972                    let s_canon =
1973                        canonical_map.get(&s_gid).copied().unwrap_or(s_gid);
1974                    // Reason for fallback: token not in canonical_map is self-canonical.
1975                    let t_canon =
1976                        canonical_map.get(&t_gid).copied().unwrap_or(t_gid);
1977                    s_canon == t_canon
1978                }
1979                _ => false,
1980            }
1981        };
1982
1983    let mut opener_to_closer: HashMap<u32, u128> = HashMap::new();
1984    let mut closing_delimiters: HashMap<u32, crate::syntax::CharTarget> =
1985        HashMap::new();
1986    for row in &all_rows {
1987        let Some(short_id) = row.short_id.and_then(|id| u32::try_from(id).ok())
1988        else {
1989            continue;
1990        };
1991        let Some(closes) = &row.closes else {
1992            continue;
1993        };
1994        let closer_u128 = DcChar::from_short(short_id).to_u128();
1995        let opener_target = match closes {
1996            ctb_storage_minimal::shorthand::DcShorthand::Short(id) => {
1997                u32::try_from(*id).ok().map(|sid| {
1998                    opener_to_closer.insert(sid, closer_u128);
1999                    crate::syntax::CharTarget::Dc(sid)
2000                })
2001            }
2002            ctb_storage_minimal::shorthand::DcShorthand::Format(id) => {
2003                ctb_utilities::format_id::FormatId::from_shorthand(&format!(
2004                    "f{id}"
2005                ))
2006                .map(crate::syntax::CharTarget::Format)
2007            }
2008            ctb_storage_minimal::shorthand::DcShorthand::Unicode(cp) => {
2009                Some(crate::syntax::CharTarget::Unicode(*cp))
2010            }
2011            _ => None,
2012        };
2013        if let Some(target) = opener_target {
2014            closing_delimiters.insert(short_id, target);
2015        }
2016    }
2017    for row in &all_rows {
2018        if matches!(row.script.as_str(), ".EM Routines" | ".EL Routines") {
2019            continue;
2020        }
2021        let Some(short_id) = row.short_id.and_then(|id| u32::try_from(id).ok())
2022        else {
2023            continue;
2024        };
2025        let Some(rule) = &row.syntax else {
2026            continue;
2027        };
2028        if let Some(closer_u128) =
2029            crate::syntax::detect_container_closer(&rule.pattern)
2030        {
2031            if !opener_to_closer.contains_key(&short_id) {
2032                opener_to_closer.insert(short_id, closer_u128);
2033            }
2034            if let Ok(closer_sid) = DcChar::from_u128(closer_u128).to_short() {
2035                closing_delimiters
2036                    .entry(closer_sid)
2037                    .or_insert(crate::syntax::CharTarget::Dc(short_id));
2038            }
2039        }
2040    }
2041
2042    // Second pass: Validate cross-references, decompositions, and syntax rules
2043    for row in &all_rows {
2044        for xref in &row.cross_references {
2045            let target = if let Some(stripped) = xref.strip_prefix('>') {
2046                stripped
2047            } else {
2048                xref
2049            };
2050            validate_target_token(
2051                target,
2052                &row.source_file,
2053                row.line_number,
2054                "Aliases (cross-reference)",
2055                &known_dc_ids,
2056                None,
2057                None,
2058                known_format_ids,
2059                None,
2060                report,
2061            );
2062        }
2063
2064        for decomp in &row.decompositions {
2065            let Some((tag_raw, payload)) = decomp.split_once('>') else {
2066                continue;
2067            };
2068            let tag_inner = tag_raw.trim_start_matches('<').trim();
2069            let (tag_name, ctx_raw_opt) = match tag_inner.split_once('@') {
2070                Some((t, c)) => (t.trim(), Some(c.trim())),
2071                None => (tag_inner, None),
2072            };
2073            if let Some(tags) = known_decomp_tags {
2074                if !tags.contains(tag_name) {
2075                    report.add_error(
2076                        &row.source_file,
2077                        Some(row.line_number),
2078                        Some("Aliases (decomposition)"),
2079                        format!("Unknown decomposition tag '<{tag_name}>'"),
2080                        Some("Ensure decomposition tag is defined in README-decompositions.csv"),
2081                    );
2082                }
2083            }
2084            if let Some(ctx_raw) = ctx_raw_opt {
2085                if ctx_raw.is_empty() {
2086                    report.add_error(
2087                        &row.source_file,
2088                        Some(row.line_number),
2089                        Some("Aliases (decomposition)"),
2090                        format!("Empty @context qualifier in decomposition '<{tag_inner}>'"),
2091                        Some("Provide one or more Dc or Format shorthands after '@'"),
2092                    );
2093                } else {
2094                    for ctx_tok in ctx_raw.split_whitespace() {
2095                        validate_target_token(
2096                            ctx_tok,
2097                            &row.source_file,
2098                            row.line_number,
2099                            "Aliases (decomposition)",
2100                            &known_dc_ids,
2101                            None,
2102                            None,
2103                            known_format_ids,
2104                            None,
2105                            report,
2106                        );
2107                    }
2108                }
2109            }
2110            let enforce_deprecation =
2111                ctx_raw_opt.is_none() && (tag_name == "equiv" || tag_name == "approx");
2112            let tag_opt = if enforce_deprecation {
2113                Some(tag_name)
2114            } else {
2115                None
2116            };
2117            let dep_opt = if enforce_deprecation {
2118                Some(&deprecated_dc_ids)
2119            } else {
2120                None
2121            };
2122            let dep_fmt_opt = if enforce_deprecation {
2123                Some(&deprecated_format_ids)
2124            } else {
2125                None
2126            };
2127
2128            for token in payload.split_whitespace() {
2129                validate_target_token(
2130                    token,
2131                    &row.source_file,
2132                    row.line_number,
2133                    "Aliases (decomposition)",
2134                    &known_dc_ids,
2135                    dep_opt,
2136                    tag_opt,
2137                    known_format_ids,
2138                    dep_fmt_opt,
2139                    report,
2140                );
2141            }
2142
2143            if tag_name == "equiv" {
2144                let tokens: Vec<&str> = payload.split_whitespace().collect();
2145                if tokens.len() > 1 {
2146                    if row.syntax.is_some() || row.closes.is_some() {
2147                        report.add_error(
2148                            &row.source_file,
2149                            Some(row.line_number),
2150                            Some("Aliases (decomposition)"),
2151                            format!(
2152                                "Document Character has multi-token <equiv> decomposition '{payload}' but defines a syntax rule or @closes"
2153                            ),
2154                            Some("Multi-token decompositions cannot define single-token syntax rules or @closes"),
2155                        );
2156                    }
2157                } else if let Some(&target_token) = tokens.first() {
2158                    if let Ok(shorthand) =
2159                        ctb_storage_minimal::shorthand::DcShorthand::parse(
2160                            target_token,
2161                        )
2162                    {
2163                        match shorthand {
2164                            ctb_storage_minimal::shorthand::DcShorthand::Short(target_sid) => {
2165                                let sid_usize = usize::try_from(target_sid).ok();
2166                                if let Some((target_syntax, target_closes, _target_file, _target_line)) =
2167                                    sid_usize.and_then(|sid| dc_lookup_by_short.get(&sid))
2168                                {
2169                                    let s_has_syntax = row.syntax.is_some();
2170                                    let t_has_syntax = target_syntax.is_some();
2171                                    if s_has_syntax != t_has_syntax {
2172                                        report.add_error(
2173                                            &row.source_file,
2174                                            Some(row.line_number),
2175                                            Some("Aliases (decomposition)"),
2176                                            format!(
2177                                                "Document Character has <equiv> relationship with '{target_token}' but their syntax rules do not match: one defines a syntax rule and the other does not"
2178                                            ),
2179                                            Some("Ensure equivalent characters define identical syntax rules or omit them consistently"),
2180                                        );
2181                                    } else if let (Some(s_rule), Some(t_rule)) = (&row.syntax, target_syntax.as_ref()) {
2182                                        let s_self = row.short_id.and_then(|id| u32::try_from(id).ok());
2183                                        let t_self = u32::try_from(target_sid).ok();
2184                                        let s_norm = normalize_syntax_pattern(&s_rule.pattern, s_self, &canonical_map);
2185                                        let t_norm = normalize_syntax_pattern(&t_rule.pattern, t_self, &canonical_map);
2186                                        if s_norm != t_norm || s_rule.action != t_rule.action {
2187                                            report.add_error(
2188                                                &row.source_file,
2189                                                Some(row.line_number),
2190                                                Some("Aliases (decomposition)"),
2191                                                format!(
2192                                                    "Document Character has <equiv> relationship with '{target_token}' but their syntax rules differ: '{}' vs '{}'",
2193                                                    s_rule.raw, t_rule.raw
2194                                                ),
2195                                                Some("Ensure equivalent characters define identical syntax rules"),
2196                                            );
2197                                        }
2198                                    }
2199
2200                                    let s_has_closes = row.closes.is_some();
2201                                    let t_has_closes = target_closes.is_some();
2202                                    if s_has_closes != t_has_closes {
2203                                        report.add_error(
2204                                            &row.source_file,
2205                                            Some(row.line_number),
2206                                            Some("Aliases (decomposition)"),
2207                                            format!(
2208                                                "Document Character has <equiv> relationship with '{target_token}' but their @closes declarations do not match"
2209                                            ),
2210                                            Some("Ensure equivalent characters define identical @closes targets or omit them consistently"),
2211                                        );
2212                                    } else if let (Some(s_c), Some(t_c)) = (&row.closes, target_closes.as_ref()) {
2213                                        if !are_openers_equivalent(s_c, t_c) {
2214                                            report.add_error(
2215                                                &row.source_file,
2216                                                Some(row.line_number),
2217                                                Some("Aliases (decomposition)"),
2218                                                format!(
2219                                                    "Document Character has <equiv> relationship with '{target_token}' but their @closes targets differ: {s_c:?} vs {t_c:?}"
2220                                                ),
2221                                                Some("Ensure equivalent characters close the same construct"),
2222                                            );
2223                                        }
2224                                    }
2225                                }
2226                            }
2227                            ctb_storage_minimal::shorthand::DcShorthand::Unicode(_) => {
2228                                if row.syntax.is_some() || row.closes.is_some() {
2229                                    report.add_error(
2230                                        &row.source_file,
2231                                        Some(row.line_number),
2232                                        Some("Aliases (decomposition)"),
2233                                        format!(
2234                                            "Document Character has <equiv> relationship with Unicode codepoint '{target_token}' but defines a syntax rule or @closes"
2235                                        ),
2236                                        Some("Unicode codepoints cannot define syntax rules or @closes"),
2237                                    );
2238                                }
2239                            }
2240                            ctb_storage_minimal::shorthand::DcShorthand::Format(fmt_id) => {
2241                                if let Some(fmt_info) = format_registry.and_then(|r| r.formats_by_id.get(&fmt_id)) {
2242                                    if fmt_info.is_deprecated {
2243                                        let already_flagged = report.diagnostics.iter().any(|d| {
2244                                            d.file_path == row.source_file
2245                                                && d.row_number == Some(row.line_number)
2246                                                && d.message.contains("references deprecated Format ID")
2247                                        });
2248                                        if !already_flagged {
2249                                            report.add_error(
2250                                                &row.source_file,
2251                                                Some(row.line_number),
2252                                                Some("Aliases (decomposition)"),
2253                                                format!(
2254                                                    "Canonical equivalency relationship '<equiv>' references deprecated Format ID 'f{fmt_id}'"
2255                                                ),
2256                                                Some("Canonical equivalencies must target active, non-deprecated Formats"),
2257                                            );
2258                                        }
2259                                    }
2260
2261                                    let s_has_syntax = row.syntax.is_some();
2262                                    let t_has_syntax = fmt_info.syntax.is_some();
2263                                    if s_has_syntax != t_has_syntax {
2264                                        report.add_error(
2265                                            &row.source_file,
2266                                            Some(row.line_number),
2267                                            Some("Aliases (decomposition)"),
2268                                            format!(
2269                                                "Document Character has <equiv> relationship with Format '{target_token}' but their syntax rules do not match: one defines a syntax rule and the other does not"
2270                                            ),
2271                                            Some("Ensure equivalent characters define identical syntax rules or omit them consistently"),
2272                                        );
2273                                    } else if let (Some(s_rule), Some(t_rule)) = (&row.syntax, fmt_info.syntax.as_ref()) {
2274                                        let s_self = row.short_id.and_then(|id| u32::try_from(id).ok());
2275                                        let s_norm = normalize_syntax_pattern(&s_rule.pattern, s_self, &canonical_map);
2276                                        let t_norm = normalize_syntax_pattern(&t_rule.pattern, None, &canonical_map);
2277                                        if s_norm != t_norm || s_rule.action != t_rule.action {
2278                                            report.add_error(
2279                                                &row.source_file,
2280                                                Some(row.line_number),
2281                                                Some("Aliases (decomposition)"),
2282                                                format!(
2283                                                    "Document Character has <equiv> relationship with Format '{target_token}' but their syntax rules differ: '{}' vs '{}'",
2284                                                    s_rule.raw, t_rule.raw
2285                                                ),
2286                                                Some("Ensure equivalent characters define identical syntax rules"),
2287                                            );
2288                                        }
2289                                    }
2290
2291                                    let s_has_closes = row.closes.is_some();
2292                                    let t_has_closes = fmt_info.closes.is_some();
2293                                    if s_has_closes != t_has_closes {
2294                                        report.add_error(
2295                                            &row.source_file,
2296                                            Some(row.line_number),
2297                                            Some("Aliases (decomposition)"),
2298                                            format!(
2299                                                "Document Character has <equiv> relationship with Format '{target_token}' but their @closes declarations do not match"
2300                                            ),
2301                                            Some("Ensure equivalent characters define identical @closes targets or omit them consistently"),
2302                                        );
2303                                    } else if let (Some(s_c), Some(t_c)) = (&row.closes, fmt_info.closes.as_ref()) {
2304                                        if !are_openers_equivalent(s_c, t_c) {
2305                                            report.add_error(
2306                                                &row.source_file,
2307                                                Some(row.line_number),
2308                                                Some("Aliases (decomposition)"),
2309                                                format!(
2310                                                    "Document Character has <equiv> relationship with Format '{target_token}' but their @closes targets differ: {s_c:?} vs {t_c:?}"
2311                                                ),
2312                                                Some("Ensure equivalent characters close the same construct"),
2313                                            );
2314                                        }
2315                                    }
2316                                } else {
2317                                    let target_has_syntax = known_format_with_syntax
2318                                        .is_some_and(|set| set.contains(&fmt_id));
2319                                    if row.syntax.is_some() != target_has_syntax {
2320                                        report.add_error(
2321                                            &row.source_file,
2322                                            Some(row.line_number),
2323                                            Some("Aliases (decomposition)"),
2324                                            format!(
2325                                                "Document Character has <equiv> relationship with Format '{target_token}' but their syntax rules do not match: one defines a syntax rule and the other does not"
2326                                            ),
2327                                            Some("Ensure equivalent characters define identical syntax rules or omit them consistently"),
2328                                        );
2329                                    }
2330                                }
2331                            }
2332                            _ => {}
2333                        }
2334                    }
2335                }
2336            }
2337        }
2338
2339        if let Some(syntax_rule) = &row.syntax {
2340            let Some(short_id) = row.short_id else {
2341                report.add_error(
2342                    &row.source_file,
2343                    Some(row.line_number),
2344                    Some("Aliases"),
2345                    "Document Character syntax rule defined on an entry without a valid Short ID",
2346                    Some("Assign a Short ID to characters that define syntax rules"),
2347                );
2348                continue;
2349            };
2350
2351            let Ok(short_id_u32) = u32::try_from(short_id) else {
2352                report.add_error(
2353                    &row.source_file,
2354                    Some(row.line_number),
2355                    Some("Short"),
2356                    format!("Short ID {short_id} exceeds u32 limits for syntax rule validation"),
2357                    Some("Ensure Short ID fits in u32"),
2358                );
2359                continue;
2360            };
2361
2362            // Reason for fallback: when optional known_named_types set is None, start with empty set.
2363            let combined_named_types =
2364                known_named_types.cloned().unwrap_or_default();
2365
2366            validate_dc_syntax(
2367                syntax_rule,
2368                short_id_u32,
2369                &known_dc_ids,
2370                known_format_ids,
2371                &combined_named_types,
2372                known_scripts,
2373                &known_syntax_targets,
2374                format_registry,
2375                report,
2376                &row.source_file,
2377                row.line_number,
2378            );
2379
2380            let target = crate::syntax::CharTarget::Dc(short_id_u32);
2381            let closer = opener_to_closer.get(&short_id_u32).copied();
2382            let has_trailing = closer.is_some_and(|c| {
2383                !crate::syntax::extract_trailing_after_closer(
2384                    &syntax_rule.pattern,
2385                    c,
2386                )
2387                .is_empty()
2388            });
2389            let closing_opener = closing_delimiters.get(&short_id_u32).cloned();
2390            let shape = crate::syntax::classify_rule_framing_shape_with(
2391                &target,
2392                Some(syntax_rule),
2393                closer,
2394                has_trailing,
2395                closing_opener,
2396                |o| match o {
2397                    crate::syntax::CharTarget::Dc(sid) => {
2398                        opener_to_closer.get(sid).copied()
2399                    }
2400                    _ => None,
2401                },
2402                |t| match t {
2403                    crate::syntax::CharTarget::Dc(sid) => usize::try_from(*sid)
2404                        .ok()
2405                        .and_then(|s| dc_lookup_by_short.get(&s))
2406                        .and_then(|(syn, _, _, _)| syn.as_ref())
2407                        .is_some_and(crate::syntax::is_unary_prefix_rule),
2408                    _ => false,
2409                },
2410            );
2411            match shape {
2412                None | Some(crate::syntax::FramingShape::ValueConstraint) => {
2413                    report.add_error(
2414                        &row.source_file,
2415                        Some(row.line_number),
2416                        Some("Syntax"),
2417                        format!(
2418                            "Document Character Dc {short_id_u32} syntax rule '{}' does not conform to a valid framing shape (Paired, Closer, PrefixArity, PrefixAtomArity, PrefixVariableArity, or Infix)",
2419                            syntax_rule.raw
2420                        ),
2421                        Some("Ensure syntax rule starts with '~' (or defines a paired delimiter with @closes)"),
2422                    );
2423                }
2424                Some(ref valid_shape) => {
2425                    let is_equiv_alias = equiv_sources.contains(&row.dc_id);
2426                    if short_id_u32
2427                        > crate::syntax::MAX_LEGACY_FRAMING_SHORT_DC_ID
2428                        && !is_equiv_alias
2429                        && !valid_shape.is_allowed_for_new_dc()
2430                    {
2431                        report.add_error(
2432                            &row.source_file,
2433                            Some(row.line_number),
2434                            Some("Syntax"),
2435                            format!(
2436                                "New Document Character Dc {short_id_u32} (> {}) uses legacy non-deterministic framing shape {valid_shape:?} in syntax rule '{}'",
2437                                crate::syntax::MAX_LEGACY_FRAMING_SHORT_DC_ID,
2438                                syntax_rule.raw
2439                            ),
2440                            Some("New Document Characters with syntax rules must use deterministic Paired (@closes) or fixed-arity prefix (':~ <arg1> ... <argN>') framing"),
2441                        );
2442                    }
2443                }
2444            }
2445        }
2446
2447        for imp in &row.implies {
2448            let trimmed = imp.trim();
2449            if trimmed.starts_with('[') && trimmed.ends_with(']') {
2450                if let (Some(short_id), Ok(imp_rule)) =
2451                    (row.short_id, parse_dc_syntax(&format!(":{trimmed}")))
2452                {
2453                    if let Ok(short_id_u32) = u32::try_from(short_id) {
2454                        // Reason for fallback: when optional known_named_types set is None, start with empty set.
2455                        let combined_named_types =
2456                            known_named_types.cloned().unwrap_or_default();
2457                        validate_dc_syntax(
2458                            &imp_rule,
2459                            short_id_u32,
2460                            &known_dc_ids,
2461                            known_format_ids,
2462                            &combined_named_types,
2463                            known_scripts,
2464                            &known_syntax_targets,
2465                            format_registry,
2466                            report,
2467                            &row.source_file,
2468                            row.line_number,
2469                        );
2470                    }
2471                }
2472            }
2473        }
2474    }
2475
2476    all_rows
2477}
2478
2479/// Discovers and validates all Dc category files from an embedded directory.
2480pub fn validate_all_dc_files(
2481    dc_dir: &Dir,
2482    known_format_ids: &HashSet<usize>,
2483    known_decomp_tags: Option<&HashSet<String>>,
2484    known_named_types: Option<&HashSet<String>>,
2485    known_scripts: Option<&HashSet<String>>,
2486    known_format_with_syntax: Option<&HashSet<usize>>,
2487    format_registry: Option<&FormatValidationRegistry>,
2488    report: &mut ValidationReport,
2489) -> Vec<DcDefn> {
2490    let mut files = Vec::new();
2491    for f in dc_dir.files() {
2492        if let Some(path_str) = f.path().to_str() {
2493            files.push((path_str, f.contents()));
2494        }
2495    }
2496    validate_dc_files_data(
2497        files,
2498        "src/formats/dcdata/data-src/categories/",
2499        known_format_ids,
2500        known_decomp_tags,
2501        known_named_types,
2502        known_scripts,
2503        known_format_with_syntax,
2504        format_registry,
2505        report,
2506    )
2507}
2508
2509/// Discovers and validates all Dc category files from an on-disk directory.
2510pub fn validate_all_dc_files_from_disk(
2511    dc_dir: &std::path::Path,
2512    known_format_ids: &HashSet<usize>,
2513    known_decomp_tags: Option<&HashSet<String>>,
2514    known_named_types: Option<&HashSet<String>>,
2515    known_scripts: Option<&HashSet<String>>,
2516    known_format_with_syntax: Option<&HashSet<usize>>,
2517    format_registry: Option<&FormatValidationRegistry>,
2518    report: &mut ValidationReport,
2519) -> Vec<DcDefn> {
2520    let Ok(entries) = std::fs::read_dir(dc_dir) else {
2521        report.add_error(
2522            &dc_dir.display().to_string(),
2523            None,
2524            None,
2525            format!(
2526                "Could not read Dc categories directory at {}",
2527                dc_dir.display()
2528            ),
2529            None,
2530        );
2531        return Vec::new();
2532    };
2533
2534    let mut paths = Vec::new();
2535    for entry in entries.flatten() {
2536        let p = entry.path();
2537        if p.is_file() {
2538            let Some(file_name) = p.file_name().and_then(|n| n.to_str()) else {
2539                continue;
2540            };
2541            if file_name.ends_with(".csv")
2542                && file_name != "schema.csv"
2543                && !file_name.ends_with(".generated.csv")
2544            {
2545                paths.push(p);
2546            }
2547        }
2548    }
2549    paths.sort();
2550
2551    let mut file_data = Vec::new();
2552    for p in &paths {
2553        let Some(file_name) = p.file_name().and_then(|n| n.to_str()) else {
2554            continue;
2555        };
2556        if let Ok(bytes) = std::fs::read(p) {
2557            file_data.push((file_name.to_string(), bytes));
2558        } else {
2559            report.add_error(
2560                &p.display().to_string(),
2561                None,
2562                None,
2563                format!("Failed to read file {}", p.display()),
2564                None,
2565            );
2566        }
2567    }
2568
2569    let files_iter: Vec<(&str, &[u8])> = file_data
2570        .iter()
2571        .map(|(name, bytes)| (name.as_str(), bytes.as_slice()))
2572        .collect();
2573
2574    let mut defns = validate_dc_files_data(
2575        files_iter,
2576        &dc_dir.display().to_string(),
2577        known_format_ids,
2578        known_decomp_tags,
2579        known_named_types,
2580        known_scripts,
2581        known_format_with_syntax,
2582        format_registry,
2583        report,
2584    );
2585    if let Some(data_src_dir) = dc_dir.parent() {
2586        attach_staged_dc_impls_from_data_dir_with_known_formats(
2587            data_src_dir,
2588            &mut defns,
2589            Some(known_format_ids),
2590            format_registry,
2591            report,
2592        );
2593    }
2594    defns
2595}
2596
2597/// Attaches already-loaded [`crate::wat::StagedDcImpl`] entries to `dc_defns` and optional
2598/// `format_defns` (or validates format targets against `known_format_ids` when `format_defns` is
2599/// not supplied).
2600pub fn attach_staged_dc_impls_to_defns(
2601    staged_impls: &[crate::wat::StagedDcImpl],
2602    dc_defns: &mut [DcDefn],
2603    format_defns: Option<&mut [DcDefn]>,
2604    known_format_ids: Option<&HashSet<usize>>,
2605    report: &mut ValidationReport,
2606) {
2607    attach_staged_dc_impls_to_defns_with_registry(
2608        staged_impls,
2609        dc_defns,
2610        format_defns,
2611        known_format_ids,
2612        None,
2613        report,
2614    );
2615}
2616
2617/// Attaches already-loaded [`crate::wat::StagedDcImpl`] entries to `dc_defns` and optional
2618/// `format_defns`, enforcing that any `DcShorthand::Format(fid)` target belongs to
2619/// `.Formats:transformation`.
2620pub fn attach_staged_dc_impls_to_defns_with_registry(
2621    staged_impls: &[crate::wat::StagedDcImpl],
2622    dc_defns: &mut [DcDefn],
2623    mut format_defns: Option<&mut [DcDefn]>,
2624    known_format_ids: Option<&HashSet<usize>>,
2625    format_registry: Option<&FormatValidationRegistry>,
2626    report: &mut ValidationReport,
2627) {
2628    use ctb_storage_minimal::global_graph_layout::{
2629        SYSTEM_REGION_END, SYSTEM_REGION_START,
2630    };
2631    use ctb_storage_minimal::shorthand::DcShorthand;
2632
2633    let check_endpoint = |sh: DcShorthand,
2634                          role_label: &str,
2635                          rel_path: &str,
2636                          dc_slice: &[DcDefn],
2637                          fmt_slice: Option<&[DcDefn]>,
2638                          known_fids: Option<&HashSet<usize>>,
2639                          rep: &mut ValidationReport| {
2640        match sh {
2641            DcShorthand::Short(sid) => {
2642                let sid_usize = usize::try_from(sid).ok();
2643                if !dc_slice
2644                    .iter()
2645                    .any(|d| d.format.is_none() && d.short_id == sid_usize)
2646                {
2647                    rep.add_error(
2648                        rel_path,
2649                        None,
2650                        Some("@converts"),
2651                        format!(
2652                            "Standalone '@converts' {role_label} targets unknown Short Dc ID {sid}"
2653                        ),
2654                        Some("Ensure the Short Dc ID is defined in categories/*.csv"),
2655                    );
2656                }
2657            }
2658            DcShorthand::Format(fid) => {
2659                let exists = if let Some(fdefs) = fmt_slice {
2660                    fdefs
2661                        .iter()
2662                        .any(|d| d.format.is_some() && d.short_id == Some(fid))
2663                } else if let Some(fset) = known_fids {
2664                    fset.contains(&fid)
2665                } else {
2666                    true
2667                };
2668                if !exists {
2669                    rep.add_error(
2670                        rel_path,
2671                        None,
2672                        Some("@converts"),
2673                        format!(
2674                            "Standalone '@converts' {role_label} targets unknown Format Dc f{fid}"
2675                        ),
2676                        Some("Ensure the Format Dc is defined in categories/formats/*.csv"),
2677                    );
2678                }
2679            }
2680            DcShorthand::Long(nid) => {
2681                if !(SYSTEM_REGION_START..=SYSTEM_REGION_END).contains(&nid) {
2682                    rep.add_error(
2683                        rel_path,
2684                        None,
2685                        Some("@converts"),
2686                        format!(
2687                            "Standalone '@converts' {role_label} l{nid} is outside System region ({SYSTEM_REGION_START}..={SYSTEM_REGION_END})"
2688                        ),
2689                        None,
2690                    );
2691                }
2692            }
2693            other => {
2694                rep.add_error(
2695                    rel_path,
2696                    None,
2697                    Some("@converts"),
2698                    format!(
2699                        "Unsupported '@converts' {role_label} shorthand '{other}'"
2700                    ),
2701                    Some("Use a Short, Format, or System-block Long Dc shorthand"),
2702                );
2703            }
2704        }
2705    };
2706
2707    for staged in staged_impls {
2708        match staged.target {
2709            DcShorthand::Short(short_u32) => {
2710                let target_short = usize::try_from(short_u32).ok();
2711                if let Some(defn) = dc_defns
2712                    .iter_mut()
2713                    .find(|d| d.format.is_none() && d.short_id == target_short)
2714                {
2715                    let entry = staged.to_decomposition_entry();
2716                    if !defn.decompositions.contains(&entry) {
2717                        defn.decompositions.push(entry);
2718                    }
2719                } else {
2720                    report.add_error(
2721                        &staged.rel_path,
2722                        None,
2723                        Some("Short"),
2724                        format!(
2725                            "Staged implementation targets unknown Short Dc ID {short_u32}"
2726                        ),
2727                        Some("Ensure the target Short Dc ID is defined in a category CSV"),
2728                    );
2729                }
2730            }
2731            DcShorthand::Format(fid) => {
2732                if let Some(fmt_slice) = format_defns.as_deref_mut() {
2733                    if let Some(fdefn) = fmt_slice
2734                        .iter_mut()
2735                        .find(|d| d.format.is_some() && d.short_id == Some(fid))
2736                    {
2737                        if !crate::syntax::is_transformation_format_category(
2738                            &fdefn.category,
2739                        ) && !crate::syntax::is_transformation_format_category(
2740                            &fdefn.script,
2741                        ) {
2742                            report.add_error(
2743                                &staged.rel_path,
2744                                None,
2745                                Some("Format"),
2746                                format!(
2747                                    "Staged implementation '{}' cannot be attached directly to non-transformation format f{fid} ('{}', category '{}')",
2748                                    staged.rel_path, fdefn.name, fdefn.category
2749                                ),
2750                                Some(
2751                                    "Only document transformations (.Formats:transformation) may own direct implementations; implement format converters as verbs/transformations referencing the format instead",
2752                                ),
2753                            );
2754                        } else {
2755                            let entry = staged.to_decomposition_entry();
2756                            if !fdefn.decompositions.contains(&entry) {
2757                                fdefn.decompositions.push(entry);
2758                            }
2759                        }
2760                    } else {
2761                        report.add_error(
2762                            &staged.rel_path,
2763                            None,
2764                            Some("Short"),
2765                            format!(
2766                                "Staged implementation targets unknown Format Dc f{fid}"
2767                            ),
2768                            Some("Ensure the target Format Dc is defined in categories/formats/*.csv"),
2769                        );
2770                    }
2771                } else {
2772                    let exists =
2773                        known_format_ids.is_none_or(|fids| fids.contains(&fid));
2774                    if !exists {
2775                        report.add_error(
2776                            &staged.rel_path,
2777                            None,
2778                            Some("Short"),
2779                            format!(
2780                                "Staged implementation targets unknown Format Dc f{fid}"
2781                            ),
2782                            Some("Ensure the target Format Dc is defined in categories/formats/*.csv"),
2783                        );
2784                    } else if let Some(reg) = format_registry
2785                        && !reg.is_transformation_format(fid)
2786                    {
2787                        report.add_error(
2788                            &staged.rel_path,
2789                            None,
2790                            Some("Format"),
2791                            format!(
2792                                "Staged implementation '{}' cannot be attached directly to non-transformation format f{fid}",
2793                                staged.rel_path
2794                            ),
2795                            Some(
2796                                "Only document transformations (.Formats:transformation) may own direct implementations; implement format converters as verbs/transformations referencing the format instead",
2797                            ),
2798                        );
2799                    }
2800                }
2801            }
2802            DcShorthand::Long(entity_id) if staged.converts.is_some() => {
2803                if !(SYSTEM_REGION_START..=SYSTEM_REGION_END)
2804                    .contains(&entity_id)
2805                {
2806                    report.add_error(
2807                        &staged.rel_path,
2808                        None,
2809                        Some("@dc"),
2810                        format!(
2811                            "Standalone converter '@dc l{entity_id}' is outside System region ({SYSTEM_REGION_START}..={SYSTEM_REGION_END})"
2812                        ),
2813                        None,
2814                    );
2815                }
2816                if let Some((src_sh, dst_sh)) = staged.converts {
2817                    let fmt_ref = format_defns.as_deref().map(|s| &*s);
2818                    check_endpoint(
2819                        src_sh,
2820                        "source",
2821                        &staged.rel_path,
2822                        dc_defns,
2823                        fmt_ref,
2824                        known_format_ids,
2825                        report,
2826                    );
2827                    check_endpoint(
2828                        dst_sh,
2829                        "destination",
2830                        &staged.rel_path,
2831                        dc_defns,
2832                        fmt_ref,
2833                        known_format_ids,
2834                        report,
2835                    );
2836                }
2837            }
2838            other => {
2839                report.add_error(
2840                    &staged.rel_path,
2841                    None,
2842                    Some("wat"),
2843                    format!("Unsupported staged implementation target '{other}'"),
2844                    Some("Use a Short Dc stem (e.g. 1936_...), transformation Format stem (e.g. f1680_...), or '@dc l<id>' + '@converts(<src> <dst>)'"),
2845                );
2846            }
2847        }
2848    }
2849}
2850
2851/// Loads staged implementations from `data_src_dir` (`stage_0_impls/`, `stage_1_impls/`,
2852/// and `impls/`), validates each target Short Dc ID in `dc_defns`, and attaches its
2853/// `<semantic>...` / `<equiv>...` decomposition entry to the matching [`DcDefn`].
2854pub fn attach_staged_dc_impls_from_data_dir(
2855    data_src_dir: &Path,
2856    dc_defns: &mut [DcDefn],
2857    report: &mut ValidationReport,
2858) {
2859    attach_staged_dc_impls_from_data_dir_with_known_formats(
2860        data_src_dir,
2861        dc_defns,
2862        None,
2863        None,
2864        report,
2865    );
2866}
2867
2868fn attach_staged_dc_impls_from_data_dir_with_known_formats(
2869    data_src_dir: &Path,
2870    dc_defns: &mut [DcDefn],
2871    known_format_ids: Option<&HashSet<usize>>,
2872    format_registry: Option<&FormatValidationRegistry>,
2873    report: &mut ValidationReport,
2874) {
2875    match crate::wat::load_staged_dc_impls(data_src_dir) {
2876        Ok((staged_impls, _raw_files)) => {
2877            attach_staged_dc_impls_to_defns_with_registry(
2878                &staged_impls,
2879                dc_defns,
2880                None,
2881                known_format_ids,
2882                format_registry,
2883                report,
2884            );
2885        }
2886        Err(err) => {
2887            report.add_error(
2888                &data_src_dir.display().to_string(),
2889                None,
2890                Some("wat"),
2891                format!("Failed to load staged implementations: {err:#}"),
2892                Some("Fix syntax or filename errors in stage_0_impls/, stage_1_impls/, or impls/"),
2893            );
2894        }
2895    }
2896}
2897
2898#[cfg(test)]
2899#[allow(
2900    clippy::panic,
2901    clippy::expect_used,
2902    clippy::unwrap_used,
2903    clippy::unwrap_in_result,
2904    clippy::panic_in_result_fn,
2905    clippy::indexing_slicing,
2906    clippy::arithmetic_side_effects,
2907    reason = "Standard repository test boilerplate"
2908)]
2909mod tests {
2910    use super::*;
2911    use crate::format::validate_formats_category_file;
2912    use crate::shared::{
2913        SupportLevel, validate_extension_entry, validate_rust_identifier,
2914        validate_support_level,
2915    };
2916    use crate::syntax::{
2917        ActionArg, Quantifier, SubtypeConstraint, SyntaxPattern, SyntaxTerm,
2918    };
2919    use crate::updater::{
2920        UNIFIED_SCHEMA_HEADER, assign_and_update_dc_categories,
2921        assign_and_update_format_categories, generate_merged_csvs,
2922        read_csv_file, write_csv_file,
2923    };
2924
2925    #[crate::ctb_test]
2926    fn test_validate_all_data_tables_repository() {
2927        let report = validate_all_data_tables();
2928        assert!(
2929            !report.has_errors(),
2930            "Data table validation failed:\n{}",
2931            report.format_report()
2932        );
2933    }
2934
2935    #[crate::ctb_test]
2936    fn test_math_format_metadata() -> Result<()> {
2937        let repo_root = crate::find_repository_root()?;
2938        let report = validate_all_data_tables_from_repo(&repo_root);
2939        ensure!(
2940            !report.has_errors(),
2941            "Live data table validation failed:\n{}",
2942            report.format_report()
2943        );
2944
2945        let mut report = ValidationReport::new();
2946        let rows = validate_all_format_files_from_disk(
2947            &repo_root.join("src/formats/dcdata/data-src/categories/formats"),
2948            None,
2949            &mut report,
2950        );
2951        ensure!(!report.has_errors(), "{}", report.format_report());
2952
2953        for (short_id, ident, base) in [
2954            (505, "Point1D", "f504"),
2955            (506, "Point2D", "f504"),
2956            (507, "Point3D", "f504"),
2957            (509, "Vector1D", "f508"),
2958            (510, "Vector2D", "f508"),
2959            (511, "Vector3D", "f508"),
2960        ] {
2961            let row = rows
2962                .iter()
2963                .find(|row| row.short_id == Some(short_id))
2964                .context("Missing fixed-dimensional math format")?;
2965            assert_eq!(row.ident.as_deref(), Some(ident));
2966            let details =
2967                row.format.as_ref().context("Missing format details")?;
2968            assert_eq!(details.implies.as_deref(), Some(base));
2969            assert!(row.syntax.is_some());
2970            assert!(row.decompositions.is_empty());
2971        }
2972
2973        for short_id in 515..=524 {
2974            let row = rows
2975                .iter()
2976                .find(|row| row.short_id == Some(short_id))
2977                .context("Missing specialized math format")?;
2978            assert!(row.decompositions.iter().all(|decomposition| {
2979                !decomposition.starts_with("<semantic>")
2980            }));
2981            assert!(row.description.contains("metadata relationships"));
2982        }
2983        Ok(())
2984    }
2985
2986    #[crate::ctb_test]
2987    fn test_validate_rust_identifier() {
2988        validate_rust_identifier("Utf8").unwrap();
2989        validate_rust_identifier("_Valid123").unwrap();
2990        validate_rust_identifier("MyFormat").unwrap();
2991
2992        assert!(validate_rust_identifier("").is_err());
2993        assert!(validate_rust_identifier("123abc").is_err());
2994        assert!(validate_rust_identifier("bad-name").is_err());
2995        assert!(validate_rust_identifier("type").is_err());
2996        assert!(validate_rust_identifier("match").is_err());
2997    }
2998
2999    #[crate::ctb_test]
3000    fn test_validate_support_level() {
3001        // Blank or whitespace-only is valid (interpreted as 0 0)
3002        validate_support_level("").unwrap();
3003        validate_support_level("   ").unwrap();
3004        let empty_lvl = SupportLevel::parse("").unwrap();
3005        assert_eq!(empty_lvl.general, 0);
3006        assert_eq!(empty_lvl.dc, 0);
3007
3008        // Valid two-level specifications
3009        let s1 = SupportLevel::parse("3 1").unwrap();
3010        assert_eq!(s1.general, 3);
3011        assert_eq!(s1.dc, 1);
3012
3013        let s2 = SupportLevel::parse("2 0").unwrap();
3014        assert_eq!(s2.general, 2);
3015        assert_eq!(s2.dc, 0);
3016
3017        let s3 = SupportLevel::parse("-1 -1").unwrap();
3018        assert_eq!(s3.general, -1);
3019        assert_eq!(s3.dc, -1);
3020
3021        let s4 = SupportLevel::parse("5 4").unwrap();
3022        assert_eq!(s4.general, 5);
3023        assert_eq!(s4.dc, 4);
3024
3025        // Single values must fail validation
3026        assert!(validate_support_level("2").is_err());
3027        assert!(validate_support_level("0").is_err());
3028        assert!(validate_support_level("-1").is_err());
3029        assert!(validate_support_level("3").is_err());
3030
3031        // Invalid counts and out-of-range components
3032        assert!(validate_support_level("1 2 3").is_err());
3033        assert!(validate_support_level("6 1").is_err());
3034        assert!(validate_support_level("1 -2").is_err());
3035        assert!(validate_support_level("foo bar").is_err());
3036    }
3037
3038    #[crate::ctb_test]
3039    fn test_validate_extension_rules() {
3040        // Plain extensions must have leading dots
3041        validate_extension_entry(".txt").unwrap();
3042        validate_extension_entry(".tar.gz").unwrap();
3043        assert!(validate_extension_entry("txt").is_err());
3044
3045        // Regex patterns with ~...~
3046        validate_extension_entry(r"~^\._~").unwrap();
3047        validate_extension_entry(r"~/\.AppleDouble/~").unwrap();
3048        assert!(validate_extension_entry(r"~[invalid regex(+~").is_err());
3049
3050        // Case-sensitive prefix syntax
3051        validate_extension_entry("case:.Z").unwrap();
3052        validate_extension_entry("case:.C").unwrap();
3053        validate_extension_entry("case:.z").unwrap();
3054        assert!(validate_extension_entry("case:").is_err());
3055        assert!(validate_extension_entry("case:txt").is_err());
3056        assert!(validate_extension_entry("sensitive:.C").is_err());
3057    }
3058
3059    #[crate::ctb_test]
3060    fn test_split_dc_aliases_column() {
3061        let raw = "xon, resume transmission, >32, <equiv>240 239";
3062        let (aliases, xrefs, decomps, syntax) = split_dc_aliases_column(raw);
3063
3064        assert_eq!(aliases, vec!["xon", "resume transmission"]);
3065        assert_eq!(xrefs, vec![">32"]);
3066        assert_eq!(decomps, vec!["<equiv>240 239"]);
3067        assert!(syntax.is_none());
3068
3069        let raw_syntax = ":~ [^248 255]+ 248";
3070        let (aliases_s, xrefs_s, decomps_s, syntax_s) =
3071            split_dc_aliases_column(raw_syntax);
3072        assert!(aliases_s.is_empty());
3073        assert!(xrefs_s.is_empty());
3074        assert!(decomps_s.is_empty());
3075        assert_eq!(syntax_s.as_deref(), Some(":~ [^248 255]+ 248"));
3076    }
3077
3078    #[crate::ctb_test]
3079    fn test_cross_table_uniqueness() {
3080        let mut report = ValidationReport::new();
3081        let dc_names = vec![(10, "UniqueDc", "test/dc.csv")];
3082        let fmt_labels = vec![(20, "UniqueDc", "test/fmt.csv")];
3083
3084        validate_cross_table_uniqueness(&dc_names, &fmt_labels, &mut report);
3085        assert!(report.has_errors());
3086        assert!(report.format_report().contains("collides with Dc name"));
3087    }
3088
3089    #[crate::ctb_test]
3090    fn test_dc_gap_detection() {
3091        let mut report = ValidationReport::new();
3092        let _known_formats: HashSet<usize> = HashSet::new();
3093
3094        // Create a simulated in-memory category with gap: Short IDs 0 and 2 (missing 1)
3095        let csv_data = b"Dc,Short,Name (!=deprecated),comb,bidi,Aa,Type,Script,Aliases,Description,\n1114112,0,Null,0,BN,,Cc,,,, \n1114114,2,Two,0,BN,,Po,,,, \n";
3096        let rows = validate_dc_category_file(
3097            csv_data,
3098            "test/categories/test.csv",
3099            &mut report,
3100        );
3101        assert_eq!(rows.len(), 2);
3102
3103        // Run gap validation logic
3104        let known_dc_ids: HashSet<usize> =
3105            rows.iter().filter_map(|r| r.short_id).collect();
3106        if let Some(&max_id) = known_dc_ids.iter().max() {
3107            let mut missing_ids = Vec::new();
3108            for id in 0..=max_id {
3109                if !known_dc_ids.contains(&id) {
3110                    missing_ids.push(id);
3111                }
3112            }
3113            if !missing_ids.is_empty() {
3114                report.add_error(
3115                    "test/categories/",
3116                    None,
3117                    Some("Short"),
3118                    format!("Missing IDs: {missing_ids:?}"),
3119                    None,
3120                );
3121            }
3122        }
3123
3124        assert!(report.has_errors());
3125        assert!(report.format_report().contains("Missing IDs: [1]"));
3126    }
3127
3128    #[crate::ctb_test]
3129    fn test_end_to_end_assign_and_merge_cycle() {
3130        let temp_dir = tempfile::tempdir().unwrap();
3131        let repo = temp_dir.path();
3132
3133        let dc_cats = repo.join("src/formats/dcdata/data-src/categories");
3134        let fmt_cats =
3135            repo.join("src/formats/dcdata/data-src/categories/formats");
3136        std::fs::create_dir_all(&dc_cats).unwrap();
3137        std::fs::create_dir_all(&fmt_cats).unwrap();
3138
3139        // Write schema.csv files
3140        let dc_schema_header = vec![
3141            "Dc".to_string(),
3142            "Short".to_string(),
3143            "Name (!=deprecated)".to_string(),
3144            "◌".to_string(),
3145            "⇆".to_string(),
3146            "Aa".to_string(),
3147            "Type".to_string(),
3148            "Script".to_string(),
3149            "Aliases; >=xref, <=decompos., :=Dc syntax".to_string(),
3150            "Description".to_string(),
3151        ];
3152        write_csv_file(
3153            &repo.join("src/formats/dcdata/data-src/schema.csv"),
3154            &dc_schema_header,
3155            &[],
3156        )
3157        .unwrap();
3158
3159        let fmt_schema_header = vec![
3160            "Dc".to_string(),
3161            "Short".to_string(),
3162            "Ident (Rust-friendly)".to_string(),
3163            "Label".to_string(),
3164            "Category".to_string(),
3165            "BaseFormat".to_string(),
3166            "Extensions".to_string(),
3167            "MIME".to_string(),
3168            "UTI".to_string(),
3169            "Apple Type".to_string(),
3170            "Nicknames".to_string(),
3171            "Import".to_string(),
3172            "Export".to_string(),
3173            "Tests".to_string(),
3174            "Variants".to_string(),
3175            "Comments".to_string(),
3176            "References".to_string(),
3177        ];
3178        write_csv_file(
3179            &repo.join(
3180                "src/formats/dcdata/data-src/categories/formats/schema.csv",
3181            ),
3182            &fmt_schema_header,
3183            &[],
3184        )
3185        .unwrap();
3186
3187        // Write category files with AUTO IDs
3188        let dc_rows = vec![
3189            vec![
3190                "1114112".to_string(),
3191                "0".to_string(),
3192                "Null".to_string(),
3193                "0".to_string(),
3194                "BN".to_string(),
3195                String::new(),
3196                "Cc".to_string(),
3197                ".Controls".to_string(),
3198                String::new(),
3199                String::new(),
3200            ],
3201            vec![
3202                String::new(),
3203                "AUTO".to_string(),
3204                "CustomDc".to_string(),
3205                "0".to_string(),
3206                "BN".to_string(),
3207                String::new(),
3208                "Po".to_string(),
3209                ".Punctuation".to_string(),
3210                String::new(),
3211                String::new(),
3212            ],
3213        ];
3214        write_csv_file(
3215            &dc_cats.join("custom.csv"),
3216            &dc_schema_header,
3217            &dc_rows,
3218        )
3219        .unwrap();
3220
3221        let fmt_rows = vec![
3222            vec![
3223                "2228224".to_string(),
3224                "0".to_string(),
3225                "FormatZero".to_string(),
3226                "Format Zero".to_string(),
3227                "document".to_string(),
3228                String::new(),
3229                ".fz".to_string(),
3230                String::new(),
3231                String::new(),
3232                String::new(),
3233                String::new(),
3234                "3".to_string(),
3235                "3".to_string(),
3236                "1".to_string(),
3237                String::new(),
3238                String::new(),
3239                String::new(),
3240            ],
3241            vec![
3242                String::new(),
3243                "AUTO".to_string(),
3244                "FormatOne".to_string(),
3245                "Format One".to_string(),
3246                "document".to_string(),
3247                String::new(),
3248                ".fo".to_string(),
3249                String::new(),
3250                String::new(),
3251                String::new(),
3252                String::new(),
3253                "3".to_string(),
3254                "3".to_string(),
3255                "1".to_string(),
3256                String::new(),
3257                String::new(),
3258                String::new(),
3259            ],
3260        ];
3261        write_csv_file(
3262            &fmt_cats.join("doc.csv"),
3263            &fmt_schema_header,
3264            &fmt_rows,
3265        )
3266        .unwrap();
3267
3268        // Sparse fixtures must still reserve the complete legacy regions.
3269        let dc_stats = assign_and_update_dc_categories(repo).unwrap();
3270        assert_eq!(dc_stats.new_ids_assigned, 1);
3271        assert_eq!(dc_stats.max_short_id, 1936);
3272
3273        let fmt_stats = assign_and_update_format_categories(repo).unwrap();
3274        assert_eq!(fmt_stats.new_ids_assigned, 1);
3275        assert_eq!(fmt_stats.max_short_id, 656);
3276
3277        // Run merge generation
3278        let gen_stats = generate_merged_csvs(repo).unwrap();
3279        assert_eq!(gen_stats.dc_records_merged, 2);
3280        assert_eq!(gen_stats.format_records_merged, 2);
3281        assert!(gen_stats.unicode_records_merged > 0);
3282        assert!(gen_stats.total_records_merged >= 4);
3283
3284        let canonical_header: Vec<String> = UNIFIED_SCHEMA_HEADER
3285            .iter()
3286            .map(|s| (*s).to_string())
3287            .collect();
3288
3289        // Verify generated DcList.generated.csv contents and order
3290        let (dc_gen_hdr, dc_gen_rows) = read_csv_file(
3291            &repo.join("src/formats/dcdata/data-src/DcList.generated.csv"),
3292        )
3293        .unwrap();
3294        assert_eq!(dc_gen_hdr, canonical_header);
3295        assert_eq!(dc_gen_rows.len(), 2);
3296        assert_eq!(dc_gen_rows[0][0], "1114112");
3297        assert_eq!(dc_gen_rows[0][1], "0");
3298        assert_eq!(dc_gen_rows[1][0], "1116048");
3299        assert_eq!(dc_gen_rows[1][1], "1936");
3300
3301        // Verify generated formats.generated.csv contents and order
3302        let (fmt_gen_hdr, fmt_gen_rows) = read_csv_file(
3303            &repo.join("src/formats/dcdata/data-src/formats.generated.csv"),
3304        )
3305        .unwrap();
3306        assert_eq!(fmt_gen_hdr, canonical_header);
3307        assert_eq!(fmt_gen_rows.len(), 2);
3308        assert_eq!(fmt_gen_rows[0][0], "2228224");
3309        assert_eq!(fmt_gen_rows[0][1], "f0");
3310        assert_eq!(fmt_gen_rows[1][0], "2228880");
3311        assert_eq!(fmt_gen_rows[1][1], "f656");
3312
3313        // FIXME Readd this but not included in the binary.
3314        /*
3315                // Verify generated unicode.generated.csv
3316        let (uni_gen_hdr, uni_gen_rows) = read_csv_file(
3317            &repo.join("src/formats/dcdata/data-src/unicode.generated.csv"),
3318        )
3319        .unwrap();
3320        assert_eq!(uni_gen_hdr, canonical_header);
3321        assert_eq!(uni_gen_rows.len(), gen_stats.unicode_records_merged);
3322        assert_eq!(uni_gen_rows[0][0], "0");
3323        assert_eq!(uni_gen_rows[0][1], "u0");
3324
3325        // Verify generated all.generated.csv
3326        let (all_gen_hdr, all_gen_rows) = read_csv_file(
3327            &repo.join("src/formats/dcdata/data-src/all.generated.csv"),
3328        )
3329        .unwrap();
3330        assert_eq!(all_gen_hdr, canonical_header);
3331        assert_eq!(all_gen_rows.len(), gen_stats.total_records_merged);
3332
3333        */
3334        // Verify unicode and all tables are NOT generated
3335        let uni_csv_path =
3336            repo.join("src/formats/dcdata/data-src/unicode.generated.csv");
3337        assert!(!uni_csv_path.exists());
3338        let all_csv_path =
3339            repo.join("src/formats/dcdata/data-src/all.generated.csv");
3340        assert!(!all_csv_path.exists());
3341
3342        // Verify JSON files are NOT generated
3343        let dc_json_path =
3344            repo.join("src/formats/dcdata/data-src/DcList.generated.json");
3345        assert!(!dc_json_path.exists());
3346        let fmt_json_path =
3347            repo.join("src/formats/dcdata/data-src/formats.generated.json");
3348        assert!(!fmt_json_path.exists());
3349    }
3350
3351    #[crate::ctb_test]
3352    fn test_strict_target_token_rules() {
3353        // Valid Short Dc IDs
3354        assert_eq!(parse_target_token("246"), Some(CharTarget::Dc(246)));
3355        assert_eq!(parse_target_token("0"), Some(CharTarget::Dc(0)));
3356
3357        // Valid Format IDs
3358        assert_eq!(
3359            parse_target_token("f80"),
3360            Some(CharTarget::Format(
3361                ctb_utilities::format_id::FormatId::from_shorthand("f80")
3362                    .unwrap()
3363            ))
3364        );
3365        assert_eq!(
3366            parse_target_token("f0"),
3367            Some(CharTarget::Format(
3368                ctb_utilities::format_id::FormatId::from_shorthand("f0")
3369                    .unwrap()
3370            ))
3371        );
3372
3373        // Valid Unicode codepoints (lowercase hex only)
3374        assert_eq!(
3375            parse_target_token("u0020"),
3376            Some(CharTarget::Unicode(0x20))
3377        );
3378        assert_eq!(
3379            parse_target_token("u12ab"),
3380            Some(CharTarget::Unicode(0x12ab))
3381        );
3382        assert_eq!(parse_target_token("u0"), Some(CharTarget::Unicode(0)));
3383
3384        // Rejected format variants
3385        assert_eq!(parse_target_token("format 80"), None);
3386        assert_eq!(parse_target_token("format80"), None);
3387        assert_eq!(parse_target_token("F80"), None);
3388        assert_eq!(parse_target_token("fmt80"), None);
3389
3390        // Rejected Unicode variants (uppercase, U+, u+)
3391        assert_eq!(parse_target_token("U+12AB"), None);
3392        assert_eq!(parse_target_token("U+12ab"), None);
3393        assert_eq!(parse_target_token("u12AB"), None);
3394        assert_eq!(parse_target_token("u+0020"), None);
3395        assert_eq!(parse_target_token("U0020"), None);
3396        assert_eq!(parse_target_token("u1234567"), None); // Too long
3397    }
3398
3399    #[crate::ctb_test]
3400    fn test_dc_syntax_dsl_parser() {
3401        // Comment rule: :~ [^248 255]+ 248
3402        let rule1 = parse_dc_syntax(":~ [^248 255]+ 248").unwrap();
3403        assert!(rule1.action.is_none());
3404        if let SyntaxPattern::Sequence(elements) = &rule1.pattern {
3405            assert_eq!(elements.len(), 3);
3406            assert_eq!(elements[0].term, SyntaxTerm::SelfChar);
3407            assert_eq!(
3408                elements[1].term,
3409                SyntaxTerm::CharSet {
3410                    negated: true,
3411                    members: vec![CharTarget::Dc(248), CharTarget::Dc(255)],
3412                }
3413            );
3414            assert_eq!(elements[1].quantifier, Quantifier::OneOrMore);
3415            assert_eq!(
3416                elements[2].term,
3417                SyntaxTerm::CharRef(CharTarget::Dc(248))
3418            );
3419        } else {
3420            panic!("Expected sequence pattern");
3421        }
3422
3423        // Rule with macro expansion: :~ [260:] 259
3424        let rule2 = parse_dc_syntax(":~ [260:] 259").unwrap();
3425        if let SyntaxPattern::Sequence(elements) = &rule2.pattern {
3426            assert_eq!(elements.len(), 3);
3427            assert_eq!(
3428                elements[1].term,
3429                SyntaxTerm::RuleRef {
3430                    target: CharTarget::Dc(260)
3431                }
3432            );
3433            assert_eq!(elements[1].quantifier, Quantifier::ExactOne);
3434        } else {
3435            panic!("Expected sequence pattern");
3436        }
3437        assert!(parse_dc_syntax(":260:").is_err());
3438        assert!(parse_dc_syntax(":260 262 280: 263").is_err());
3439
3440        // Rule with named constructs and action invocation:
3441        // :[identifier $ident] ~ [value $val] : lang.assign($ident, $val)
3442        let rule3 = parse_dc_syntax(
3443            ":[identifier $ident] ~ [value $val] : lang.assign($ident, $val)",
3444        )
3445        .unwrap();
3446        assert!(rule3.action.is_some());
3447        let action = rule3.action.unwrap();
3448        assert_eq!(action.method, "lang.assign");
3449        assert_eq!(
3450            action.args,
3451            vec![
3452                ActionArg::Variable("ident".to_string()),
3453                ActionArg::Variable("val".to_string()),
3454            ]
3455        );
3456
3457        // Grouped alternation: :([statement] ~) | (~ ~)
3458        let rule4 = parse_dc_syntax(":([statement] ~) | (~ ~)").unwrap();
3459        if let SyntaxPattern::Alternation(branches) = &rule4.pattern {
3460            assert_eq!(branches.len(), 2);
3461        } else {
3462            panic!("Expected alternation pattern");
3463        }
3464
3465        // Parameterized named construct with nested pattern: :[list:([filename] | 513)]
3466        let expected_nested =
3467            parse_dc_syntax(":([filename] | 513)").unwrap().pattern;
3468        let rule5 = parse_dc_syntax(":[list:([filename] | 513)]").unwrap();
3469        if let SyntaxPattern::Sequence(elements) = &rule5.pattern {
3470            assert_eq!(elements.len(), 1);
3471            assert_eq!(
3472                elements[0].term,
3473                SyntaxTerm::NamedConstruct {
3474                    name: "list".to_string(),
3475                    subtype: Some(SubtypeConstraint::Pattern(Box::new(
3476                        expected_nested.clone()
3477                    ))),
3478                    capture_var: None,
3479                }
3480            );
3481        } else {
3482            panic!("Expected sequence pattern");
3483        }
3484
3485        // Parameterized named construct with capture variable: :[list:([filename] | 513) $path]
3486        let rule6 =
3487            parse_dc_syntax(":[list:([filename] | 513) $path]").unwrap();
3488        if let SyntaxPattern::Sequence(elements) = &rule6.pattern {
3489            assert_eq!(elements.len(), 1);
3490            assert_eq!(
3491                elements[0].term,
3492                SyntaxTerm::NamedConstruct {
3493                    name: "list".to_string(),
3494                    subtype: Some(SubtypeConstraint::Pattern(Box::new(
3495                        expected_nested
3496                    ))),
3497                    capture_var: Some("path".to_string()),
3498                }
3499            );
3500        } else {
3501            panic!("Expected sequence pattern");
3502        }
3503
3504        // Parenthesized alternation in negated character set: :[^(314 | 312)]
3505        let rule7 = parse_dc_syntax(":[^(314 | 312)]").unwrap();
3506        if let SyntaxPattern::Sequence(elements) = &rule7.pattern {
3507            assert_eq!(elements.len(), 1);
3508            assert_eq!(
3509                elements[0].term,
3510                SyntaxTerm::CharSet {
3511                    negated: true,
3512                    members: vec![CharTarget::Dc(314), CharTarget::Dc(312)],
3513                }
3514            );
3515        } else {
3516            panic!("Expected sequence pattern");
3517        }
3518
3519        // Bare pipe in negated character set must be an error
3520        let err_rule = parse_dc_syntax(":[^314 | 312]");
3521        assert!(err_rule.is_err());
3522        assert!(
3523            err_rule
3524                .unwrap_err()
3525                .to_string()
3526                .contains("enclosed in parentheses")
3527        );
3528
3529        // Parenthesized alternation in positive character set: :[(246 | 247)]
3530        let rule8 = parse_dc_syntax(":[(246 | 247)]").unwrap();
3531        if let SyntaxPattern::Sequence(elements) = &rule8.pattern {
3532            assert_eq!(elements.len(), 1);
3533            assert_eq!(
3534                elements[0].term,
3535                SyntaxTerm::CharSet {
3536                    negated: false,
3537                    members: vec![CharTarget::Dc(246), CharTarget::Dc(247)],
3538                }
3539            );
3540        } else {
3541            panic!("Expected sequence pattern");
3542        }
3543    }
3544
3545    #[crate::ctb_test]
3546    fn test_dc_syntax_validator_checks() {
3547        let mut report = ValidationReport::new();
3548        let known_dcs: HashSet<u32> =
3549            [246, 248, 255, 260].into_iter().collect();
3550        let known_fmts: HashSet<usize> = [80].into_iter().collect();
3551        let mut known_named_types: HashSet<String> = HashSet::new();
3552        known_named_types.insert("identifier".to_string());
3553        let mut known_scripts: HashSet<String> = HashSet::new();
3554        known_scripts.insert(".EM Types".to_string());
3555        let known_syntax_targets: HashSet<CharTarget> = HashSet::new();
3556
3557        // Valid rule
3558        let valid_rule = parse_dc_syntax(":~ [^248 255]+ 248").unwrap();
3559        validate_dc_syntax(
3560            &valid_rule,
3561            246,
3562            &known_dcs,
3563            &known_fmts,
3564            &known_named_types,
3565            Some(&known_scripts),
3566            &known_syntax_targets,
3567            None,
3568            &mut report,
3569            "test/syntax.csv",
3570            10,
3571        );
3572        assert!(!report.has_errors());
3573
3574        // Unknown Dc reference: 9999
3575        let invalid_rule = parse_dc_syntax(":~ 9999").unwrap();
3576        validate_dc_syntax(
3577            &invalid_rule,
3578            246,
3579            &known_dcs,
3580            &known_fmts,
3581            &known_named_types,
3582            Some(&known_scripts),
3583            &known_syntax_targets,
3584            None,
3585            &mut report,
3586            "test/syntax.csv",
3587            11,
3588        );
3589        assert!(report.has_errors());
3590        assert!(report.format_report().contains("Referenced Dc ID '9999'"));
3591
3592        // Unbound variable in action
3593        let mut report2 = ValidationReport::new();
3594        let unbound_action_rule = parse_dc_syntax(
3595            ":[identifier $ident] ~ : lang.assign($ident, $unbound)",
3596        )
3597        .unwrap();
3598        validate_dc_syntax(
3599            &unbound_action_rule,
3600            269,
3601            &known_dcs,
3602            &known_fmts,
3603            &known_named_types,
3604            Some(&known_scripts),
3605            &known_syntax_targets,
3606            None,
3607            &mut report2,
3608            "test/syntax.csv",
3609            12,
3610        );
3611        assert!(report2.has_errors());
3612        assert!(report2.format_report().contains("Variable '$unbound'"));
3613
3614        // Unknown named type construct: [unknown_type]
3615        let mut report3 = ValidationReport::new();
3616        let unknown_type_rule = parse_dc_syntax(":[unknown_type]").unwrap();
3617        validate_dc_syntax(
3618            &unknown_type_rule,
3619            246,
3620            &known_dcs,
3621            &known_fmts,
3622            &known_named_types,
3623            Some(&known_scripts),
3624            &known_syntax_targets,
3625            None,
3626            &mut report3,
3627            "test/syntax.csv",
3628            13,
3629        );
3630        assert!(report3.has_errors());
3631        assert!(
3632            report3
3633                .format_report()
3634                .contains("Unknown named type construct '[unknown_type]'")
3635        );
3636
3637        // Macro expansion of target without syntax: f80 has no syntax
3638        let mut report4 = ValidationReport::new();
3639        let macro_no_syntax_rule = parse_dc_syntax(":~ 511 [f80:]").unwrap();
3640        validate_dc_syntax(
3641            &macro_no_syntax_rule,
3642            246,
3643            &known_dcs,
3644            &known_fmts,
3645            &known_named_types,
3646            Some(&known_scripts),
3647            &known_syntax_targets,
3648            None,
3649            &mut report4,
3650            "test/syntax.csv",
3651            14,
3652        );
3653        assert!(report4.has_errors());
3654        assert!(report4.format_report().contains(
3655            "references target that does not define its own syntax rule"
3656        ));
3657
3658        // Unknown script in [script:...]: [script:Nonexistent]
3659        let mut report5 = ValidationReport::new();
3660        let unknown_script_rule =
3661            parse_dc_syntax(":[script:Nonexistent]").unwrap();
3662        validate_dc_syntax(
3663            &unknown_script_rule,
3664            246,
3665            &known_dcs,
3666            &known_fmts,
3667            &known_named_types,
3668            Some(&known_scripts),
3669            &known_syntax_targets,
3670            None,
3671            &mut report5,
3672            "test/syntax.csv",
3673            15,
3674        );
3675        assert!(report5.has_errors());
3676        assert!(
3677            report5
3678                .format_report()
3679                .contains("Unknown script '[script:Nonexistent]'")
3680        );
3681
3682        // [data] without subtype is valid
3683        let mut report6 = ValidationReport::new();
3684        let bare_data_rule = parse_dc_syntax(":[data]").unwrap();
3685        validate_dc_syntax(
3686            &bare_data_rule,
3687            246,
3688            &known_dcs,
3689            &known_fmts,
3690            &known_named_types,
3691            Some(&known_scripts),
3692            &known_syntax_targets,
3693            None,
3694            &mut report6,
3695            "test/syntax.csv",
3696            16,
3697        );
3698        assert!(!report6.has_errors());
3699
3700        // Setup format registry for [data:...] tests
3701        let mut fmt_registry = FormatValidationRegistry::new();
3702        fmt_registry.add_format(crate::syntax::FormatValidationInfo {
3703            short_id: 248,
3704            ident: Some("Sha256".to_string()),
3705            stable_ident: true,
3706            category: "hash".to_string(),
3707            nicknames: vec!["sha256".to_string()],
3708            has_import_support: true,
3709            has_export_support: true,
3710            ..Default::default()
3711        });
3712        fmt_registry.add_format(crate::syntax::FormatValidationInfo {
3713            short_id: 99,
3714            ident: Some("NoExport".to_string()),
3715            stable_ident: true,
3716            category: "archive".to_string(),
3717            nicknames: vec![],
3718            has_import_support: true,
3719            has_export_support: false,
3720            ..Default::default()
3721        });
3722        fmt_registry.add_format(crate::syntax::FormatValidationInfo {
3723            short_id: 207,
3724            ident: Some("U32".to_string()),
3725            stable_ident: false,
3726            category: "number".to_string(),
3727            nicknames: vec![],
3728            has_import_support: true,
3729            has_export_support: true,
3730            ..Default::default()
3731        });
3732        fmt_registry.add_format(crate::syntax::FormatValidationInfo {
3733            short_id: 351,
3734            ident: Some("Natural1".to_string()),
3735            stable_ident: true,
3736            category: "number_abstract".to_string(),
3737            nicknames: vec![],
3738            has_import_support: false,
3739            has_export_support: false,
3740            ..Default::default()
3741        });
3742
3743        // [data:hash] rejects category name
3744        let mut report_cat = ValidationReport::new();
3745        let cat_data_rule = parse_dc_syntax(":[data:hash]").unwrap();
3746        validate_dc_syntax(
3747            &cat_data_rule,
3748            246,
3749            &known_dcs,
3750            &known_fmts,
3751            &known_named_types,
3752            Some(&known_scripts),
3753            &known_syntax_targets,
3754            Some(&fmt_registry),
3755            &mut report_cat,
3756            "test/syntax.csv",
3757            17,
3758        );
3759        assert!(report_cat.has_errors());
3760        assert!(report_cat.format_report().contains("specifies a format category instead of a specific format identifier"));
3761
3762        // [data:checksum] rejects unknown format (not a specific format identifier)
3763        let mut report_checksum = ValidationReport::new();
3764        let checksum_data_rule = parse_dc_syntax(":[data:checksum]").unwrap();
3765        validate_dc_syntax(
3766            &checksum_data_rule,
3767            246,
3768            &known_dcs,
3769            &known_fmts,
3770            &known_named_types,
3771            Some(&known_scripts),
3772            &known_syntax_targets,
3773            Some(&fmt_registry),
3774            &mut report_checksum,
3775            "test/syntax.csv",
3776            17,
3777        );
3778        assert!(report_checksum.has_errors());
3779        assert!(report_checksum.format_report().contains(
3780            "Unknown format identifier 'checksum' in '[data:checksum]'"
3781        ));
3782
3783        // [data:f9999] rejects unknown format
3784        let mut report_unknown_fmt = ValidationReport::new();
3785        let unknown_fmt_rule = parse_dc_syntax(":[data:f9999]").unwrap();
3786        validate_dc_syntax(
3787            &unknown_fmt_rule,
3788            246,
3789            &known_dcs,
3790            &known_fmts,
3791            &known_named_types,
3792            Some(&known_scripts),
3793            &known_syntax_targets,
3794            Some(&fmt_registry),
3795            &mut report_unknown_fmt,
3796            "test/syntax.csv",
3797            18,
3798        );
3799        assert!(report_unknown_fmt.has_errors());
3800        assert!(
3801            report_unknown_fmt.format_report().contains(
3802                "Unknown format identifier 'f9999' in '[data:f9999]'"
3803            )
3804        );
3805
3806        // [data:NoExport] rejects format without both import and export
3807        let mut report_no_export = ValidationReport::new();
3808        let no_export_rule = parse_dc_syntax(":[data:NoExport]").unwrap();
3809        validate_dc_syntax(
3810            &no_export_rule,
3811            246,
3812            &known_dcs,
3813            &known_fmts,
3814            &known_named_types,
3815            Some(&known_scripts),
3816            &known_syntax_targets,
3817            Some(&fmt_registry),
3818            &mut report_no_export,
3819            "test/syntax.csv",
3820            19,
3821        );
3822        assert!(report_no_export.has_errors());
3823        assert!(
3824            report_no_export
3825                .format_report()
3826                .contains("must have both import and export support")
3827        );
3828
3829        // [data:Sha256] and [data:f248] succeed when format has both import and export
3830        let mut report_ok = ValidationReport::new();
3831        let ok_rule = parse_dc_syntax(":[data:Sha256] [data:f248]").unwrap();
3832        validate_dc_syntax(
3833            &ok_rule,
3834            246,
3835            &known_dcs,
3836            &known_fmts,
3837            &known_named_types,
3838            Some(&known_scripts),
3839            &known_syntax_targets,
3840            Some(&fmt_registry),
3841            &mut report_ok,
3842            "test/syntax.csv",
3843            20,
3844        );
3845        assert!(!report_ok.has_errors());
3846
3847        // [number:U32] rejects format identifier not marked @stable_ident(), while [number:f207] and [number:Natural1] succeed
3848        let mut report_unstable_num = ValidationReport::new();
3849        let unstable_num_rule = parse_dc_syntax(":[number:U32]").unwrap();
3850        validate_dc_syntax(
3851            &unstable_num_rule,
3852            246,
3853            &known_dcs,
3854            &known_fmts,
3855            &known_named_types,
3856            Some(&known_scripts),
3857            &known_syntax_targets,
3858            Some(&fmt_registry),
3859            &mut report_unstable_num,
3860            "test/syntax.csv",
3861            21,
3862        );
3863        assert!(report_unstable_num.has_errors());
3864        assert!(
3865            report_unstable_num.format_report().contains(
3866                "Format identifier 'U32' in '[number:U32]' is not marked '@stable_ident()'"
3867            )
3868        );
3869
3870        let mut report_stable_num = ValidationReport::new();
3871        let stable_num_rule = parse_dc_syntax(
3872            ":[number:Natural1] [number:f207] [number:Natural1&<(2^8)]",
3873        )
3874        .unwrap();
3875        validate_dc_syntax(
3876            &stable_num_rule,
3877            246,
3878            &known_dcs,
3879            &known_fmts,
3880            &known_named_types,
3881            Some(&known_scripts),
3882            &known_syntax_targets,
3883            Some(&fmt_registry),
3884            &mut report_stable_num,
3885            "test/syntax.csv",
3886            22,
3887        );
3888        assert!(
3889            !report_stable_num.has_errors(),
3890            "Unexpected errors: {}",
3891            report_stable_num.format_report()
3892        );
3893
3894        // Invalid [number:...] bound expressions or empty '&'-clauses must be rejected at parse time
3895        for invalid_num_syntax in [
3896            ":[number:<not_a_number]",
3897            ":[number:Natural1&]",
3898            ":[number:<(2^8 - 1)]",
3899        ] {
3900            assert!(
3901                parse_dc_syntax(invalid_num_syntax).is_err(),
3902                "Expected parse error for '{invalid_num_syntax}'"
3903            );
3904        }
3905    }
3906
3907    #[crate::ctb_test]
3908    fn test_redundant_quantifier_syntax_validation() {
3909        let known_dcs: HashSet<u32> =
3910            [246, 248, 255, 260, 262].into_iter().collect();
3911        let known_fmts: HashSet<usize> = [80].into_iter().collect();
3912        let mut known_named_types: HashSet<String> = HashSet::new();
3913        known_named_types.insert("identifier".to_string());
3914        let mut known_scripts: HashSet<String> = HashSet::new();
3915        known_scripts.insert(".EM Types".to_string());
3916        let mut known_syntax_targets: HashSet<CharTarget> = HashSet::new();
3917        known_syntax_targets.insert(CharTarget::Dc(262));
3918
3919        // Redundant quantifiers like [262:]{1} must produce validation errors
3920        let redundant_cases = [
3921            ":[262:]{1}",
3922            ":[262:]{1..1}",
3923            ":[262:]{1,1}",
3924            ":246{1}",
3925            ":~{1}",
3926            ":[identifier]{1}",
3927            ":(246 | 248){1}",
3928            ":[246 248]{1}",
3929        ];
3930
3931        for pattern in redundant_cases {
3932            let mut report = ValidationReport::new();
3933            let rule = parse_dc_syntax(pattern)
3934                .unwrap_or_else(|e| panic!("Failed to parse {pattern}: {e}"));
3935            validate_dc_syntax(
3936                &rule,
3937                246,
3938                &known_dcs,
3939                &known_fmts,
3940                &known_named_types,
3941                Some(&known_scripts),
3942                &known_syntax_targets,
3943                None,
3944                &mut report,
3945                "test/syntax.csv",
3946                1,
3947            );
3948            assert!(
3949                report.has_errors(),
3950                "Expected validation error for redundant quantifier in '{pattern}'"
3951            );
3952            assert!(
3953                report
3954                    .format_report()
3955                    .contains("Redundant quantifier '{1}'"),
3956                "Error report for '{pattern}' should mention redundant quantifier"
3957            );
3958        }
3959
3960        // Non-redundant quantifiers and unquantified elements must pass validation
3961        let valid_cases = [
3962            ":[262:]",
3963            ":246{2}",
3964            ":246{1..2}",
3965            ":[246]+",
3966            ":[246]*",
3967            ":[246]?",
3968            ":(246)+",
3969            ":~",
3970            ":[identifier]",
3971            ":(246 | 248)",
3972            ":[246 248]",
3973        ];
3974
3975        for pattern in valid_cases {
3976            let mut report = ValidationReport::new();
3977            let rule = parse_dc_syntax(pattern)
3978                .unwrap_or_else(|e| panic!("Failed to parse {pattern}: {e}"));
3979            validate_dc_syntax(
3980                &rule,
3981                246,
3982                &known_dcs,
3983                &known_fmts,
3984                &known_named_types,
3985                Some(&known_scripts),
3986                &known_syntax_targets,
3987                None,
3988                &mut report,
3989                "test/syntax.csv",
3990                1,
3991            );
3992            assert!(
3993                !report.has_errors(),
3994                "Expected no validation errors for valid pattern '{pattern}', got: {}",
3995                report.format_report()
3996            );
3997        }
3998    }
3999
4000    #[crate::ctb_test]
4001    fn test_column_count_mismatch_validation() {
4002        let mut report = ValidationReport::default();
4003
4004        // 1. Dc category with row having 9 columns instead of 10
4005        let invalid_dc_csv = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114112,0,Null,0,BN,,Cc,Controls,\n";
4006        validate_dc_category_file(
4007            invalid_dc_csv,
4008            "invalid_dc.csv",
4009            &mut report,
4010        );
4011        assert!(report.has_errors());
4012        assert!(
4013            report
4014                .format_report()
4015                .contains("Row has 9 columns, expected 10")
4016        );
4017
4018        // 2. Format category with row having 16 columns instead of 17
4019        let mut fmt_report = ValidationReport::default();
4020        let invalid_fmt_csv = b"Dc,Short,Ident (Rust-friendly),Label,Category,BaseFormat,Extensions,MIME,UTI,Apple Type,Nicknames,Import,Export,Tests,Variants,Comments,References\n2228224,0,FmtZero,Format Zero,document,,.fz,,,,3,3,1,,,\n";
4021        let valid_variants = HashSet::new();
4022        validate_formats_category_file(
4023            invalid_fmt_csv,
4024            "invalid_fmt.csv",
4025            &valid_variants,
4026            &mut fmt_report,
4027        );
4028        assert!(fmt_report.has_errors());
4029        assert!(
4030            fmt_report
4031                .format_report()
4032                .contains("Row has 16 columns, expected 17")
4033        );
4034
4035        // 3. Layout table with row having 4 columns instead of 5
4036        let mut layout_report = ValidationReport::default();
4037        let invalid_layout_csv = b"Partition Name,First ID,Last ID,Count,Description\n0,1114111,1114112,Unicode\n";
4038        validate_layout_table(
4039            invalid_layout_csv,
4040            "invalid_layout.csv",
4041            &mut layout_report,
4042        );
4043        assert!(layout_report.has_errors());
4044        assert!(
4045            layout_report
4046                .format_report()
4047                .contains("Row has 4 columns, expected 5")
4048        );
4049    }
4050
4051    #[crate::ctb_test]
4052    fn test_equiv_and_approx_deprecated_target_validation() {
4053        let known_formats: HashSet<usize> = HashSet::new();
4054
4055        // 1. <equiv> referencing deprecated Dc (Short ID 0 is !Null)
4056        let mut report_equiv_dc = ValidationReport::default();
4057        let csv_equiv_dc = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114112,0,!Null,0,BN,,Cc,Controls,,\n1114113,1,One,0,BN,,Po,Controls,<equiv>0,\n";
4058        validate_dc_files_data(
4059            [("test.csv", &csv_equiv_dc[..])],
4060            "test",
4061            &known_formats,
4062            None,
4063            None,
4064            None,
4065            None,
4066            None,
4067            &mut report_equiv_dc,
4068        );
4069        assert!(report_equiv_dc.has_errors());
4070        assert!(
4071            report_equiv_dc
4072                .format_report()
4073                .contains("references deprecated Dc ID '0'")
4074        );
4075
4076        // 2. <approx> referencing deprecated Dc (Short ID 0 is !Null)
4077        let mut report_approx_dc = ValidationReport::default();
4078        let csv_approx_dc = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114112,0,!Null,0,BN,,Cc,Controls,,\n1114113,1,One,0,BN,,Po,Controls,<approx>0,\n";
4079        validate_dc_files_data(
4080            [("test.csv", &csv_approx_dc[..])],
4081            "test",
4082            &known_formats,
4083            None,
4084            None,
4085            None,
4086            None,
4087            None,
4088            &mut report_approx_dc,
4089        );
4090        assert!(report_approx_dc.has_errors());
4091        assert!(
4092            report_approx_dc
4093                .format_report()
4094                .contains("references deprecated Dc ID '0'")
4095        );
4096
4097        // 3. <equiv> referencing deprecated Unicode codepoint (u17a3)
4098        let mut report_equiv_uni = ValidationReport::default();
4099        let csv_equiv_uni = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114112,0,Zero,0,BN,,Cc,Controls,,\n1114113,1,One,0,BN,,Po,Controls,<equiv>u17a3,\n";
4100        validate_dc_files_data(
4101            [("test.csv", &csv_equiv_uni[..])],
4102            "test",
4103            &known_formats,
4104            None,
4105            None,
4106            None,
4107            None,
4108            None,
4109            &mut report_equiv_uni,
4110        );
4111        assert!(report_equiv_uni.has_errors());
4112        assert!(report_equiv_uni.format_report().contains(
4113            "references deprecated Unicode character 'u17a3' (U+17A3)"
4114        ));
4115
4116        // 4. <approx> referencing deprecated Unicode codepoint (u0149)
4117        let mut report_approx_uni = ValidationReport::default();
4118        let csv_approx_uni = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114112,0,Zero,0,BN,,Cc,Controls,,\n1114113,1,One,0,BN,,Po,Controls,<approx>u0149,\n";
4119        validate_dc_files_data(
4120            [("test.csv", &csv_approx_uni[..])],
4121            "test",
4122            &known_formats,
4123            None,
4124            None,
4125            None,
4126            None,
4127            None,
4128            &mut report_approx_uni,
4129        );
4130        assert!(report_approx_uni.has_errors());
4131        assert!(report_approx_uni.format_report().contains(
4132            "references deprecated Unicode character 'u0149' (U+0149)"
4133        ));
4134
4135        // 5. Cross references and <ambiguous> may reference deprecated Dcs without error
4136        let mut report_allowed = ValidationReport::default();
4137        let csv_allowed = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114112,0,!Null,0,BN,,Cc,Controls,,\n1114113,1,One,0,BN,,Po,Controls,\">0, <ambiguous>0\",\n";
4138        validate_dc_files_data(
4139            [("test.csv", &csv_allowed[..])],
4140            "test",
4141            &known_formats,
4142            None,
4143            None,
4144            None,
4145            None,
4146            None,
4147            &mut report_allowed,
4148        );
4149        assert!(!report_allowed.has_errors());
4150
4151        // 6. Valid non-deprecated <equiv> and <approx> targets pass
4152        let mut report_valid = ValidationReport::default();
4153        let csv_valid = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114112,0,Zero,0,BN,,Cc,Controls,,\n1114113,1,One,0,BN,,Po,Controls,\"<equiv>u0020, <approx>0\",\n";
4154        validate_dc_files_data(
4155            [("test.csv", &csv_valid[..])],
4156            "test",
4157            &known_formats,
4158            None,
4159            None,
4160            None,
4161            None,
4162            None,
4163            &mut report_valid,
4164        );
4165        assert!(!report_valid.has_errors());
4166
4167        // 7. <equiv> referencing deprecated Format ID
4168        let mut report_equiv_fmt = ValidationReport::default();
4169        let mut fmt_registry = FormatValidationRegistry::new();
4170        fmt_registry.add_format(crate::syntax::FormatValidationInfo {
4171            short_id: 20,
4172            ident: Some("DeprecatedFormat".to_string()),
4173            category: "archive".to_string(),
4174            is_deprecated: true,
4175            ..Default::default()
4176        });
4177        let mut known_formats_with_20 = HashSet::new();
4178        known_formats_with_20.insert(20);
4179        let csv_equiv_fmt = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114112,0,Zero,0,BN,,Cc,Controls,,\n1114113,1,One,0,BN,,Po,Controls,<equiv>f20,\n";
4180        validate_dc_files_data(
4181            [("test.csv", &csv_equiv_fmt[..])],
4182            "test",
4183            &known_formats_with_20,
4184            None,
4185            None,
4186            None,
4187            None,
4188            Some(&fmt_registry),
4189            &mut report_equiv_fmt,
4190        );
4191        assert!(report_equiv_fmt.has_errors());
4192        assert!(
4193            report_equiv_fmt
4194                .format_report()
4195                .contains("references deprecated Format ID 'f20'")
4196        );
4197
4198        // 8. <approx> referencing deprecated Format ID
4199        let mut report_approx_fmt = ValidationReport::default();
4200        let csv_approx_fmt = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114112,0,Zero,0,BN,,Cc,Controls,,\n1114113,1,One,0,BN,,Po,Controls,<approx>f20,\n";
4201        validate_dc_files_data(
4202            [("test.csv", &csv_approx_fmt[..])],
4203            "test",
4204            &known_formats_with_20,
4205            None,
4206            None,
4207            None,
4208            None,
4209            Some(&fmt_registry),
4210            &mut report_approx_fmt,
4211        );
4212        assert!(report_approx_fmt.has_errors());
4213        assert!(
4214            report_approx_fmt
4215                .format_report()
4216                .contains("references deprecated Format ID 'f20'")
4217        );
4218    }
4219
4220    #[crate::ctb_test]
4221    fn test_decomposition_tag_validation() {
4222        let known_formats: HashSet<usize> = HashSet::new();
4223        let mut known_tags: HashSet<String> = HashSet::new();
4224        known_tags.insert("equiv".to_string());
4225        known_tags.insert("approx".to_string());
4226
4227        // Unknown decomposition tag <unknown_decomp>
4228        let mut report = ValidationReport::default();
4229        let csv_unknown_tag = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114112,0,Zero,0,BN,,Cc,Controls,,\n1114113,1,One,0,BN,,Po,Controls,<unknown_decomp>0,\n";
4230        validate_dc_files_data(
4231            [("test.csv", &csv_unknown_tag[..])],
4232            "test",
4233            &known_formats,
4234            Some(&known_tags),
4235            None,
4236            None,
4237            None,
4238            None,
4239            &mut report,
4240        );
4241        assert!(report.has_errors());
4242        assert!(
4243            report
4244                .format_report()
4245                .contains("Unknown decomposition tag '<unknown_decomp>'")
4246        );
4247
4248        // Valid decomposition tag <equiv>
4249        let mut report_valid = ValidationReport::default();
4250        let csv_valid = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114112,0,Zero,0,BN,,Cc,Controls,,\n1114113,1,One,0,BN,,Po,Controls,<equiv>0,\n";
4251        validate_dc_files_data(
4252            [("test.csv", &csv_valid[..])],
4253            "test",
4254            &known_formats,
4255            Some(&known_tags),
4256            None,
4257            None,
4258            None,
4259            None,
4260            &mut report_valid,
4261        );
4262        assert!(!report_valid.has_errors());
4263    }
4264
4265    #[crate::ctb_test]
4266    fn test_reject_uppercase_f_format_shorthand() {
4267        let mut report = ValidationReport::default();
4268        let invalid_csv = b"Dc,Short,Ident (Rust-friendly),Label,Category,BaseFormat,Extensions,MIME,UTI,Apple Type,Nicknames,Import,Export,Tests,Variants,Comments,References\n2228224,F0,FmtZero,Format Zero,document,,.fz,,,,3,3,1,,,\n";
4269        let valid_variants = HashSet::new();
4270        validate_formats_category_file(
4271            invalid_csv,
4272            "invalid_fmt.csv",
4273            &valid_variants,
4274            &mut report,
4275        );
4276        assert!(report.has_errors());
4277        assert!(
4278            report
4279                .format_report()
4280                .contains("Invalid Short format ID integer: 'F0'")
4281        );
4282    }
4283
4284    #[crate::ctb_test]
4285    fn test_dc_aliases_spacing_validation() {
4286        // 1. Contrived example with two spacing errors:
4287        //    "<approx> 0,<equiv>u15"
4288        //    - extra space before 0
4289        //    - missing space after ,
4290        let mut report_contrived = ValidationReport::default();
4291        validate_dc_aliases_spacing(
4292            "<approx> 0,<equiv>u15",
4293            "test/categories.csv",
4294            2,
4295            &mut report_contrived,
4296        );
4297        assert!(report_contrived.has_errors());
4298        assert_eq!(report_contrived.error_count(), 2);
4299        let report_text = report_contrived.format_report();
4300        assert!(
4301            report_text.contains("Extra space before '0' in decomposition")
4302        );
4303        assert!(
4304            report_text.contains("Missing space after ',' in Aliases column")
4305        );
4306
4307        // 2. Extra space before comma: "<approx>0 , <equiv>u15"
4308        let mut report_space_before_comma = ValidationReport::default();
4309        validate_dc_aliases_spacing(
4310            "<approx>0 , <equiv>u15",
4311            "test/categories.csv",
4312            2,
4313            &mut report_space_before_comma,
4314        );
4315        assert!(report_space_before_comma.has_errors());
4316        assert!(
4317            report_space_before_comma
4318                .format_report()
4319                .contains("Extra space before ','")
4320        );
4321
4322        // 3. Multiple spaces after comma: "<approx>0,  <equiv>u15"
4323        let mut report_multiple_spaces = ValidationReport::default();
4324        validate_dc_aliases_spacing(
4325            "<approx>0,  <equiv>u15",
4326            "test/categories.csv",
4327            2,
4328            &mut report_multiple_spaces,
4329        );
4330        assert!(report_multiple_spaces.has_errors());
4331        assert!(
4332            report_multiple_spaces
4333                .format_report()
4334                .contains("Multiple spaces after ','")
4335        );
4336
4337        // 4. Extra space after '>' in cross-reference: "> 32"
4338        let mut report_xref_space = ValidationReport::default();
4339        validate_dc_aliases_spacing(
4340            "> 32",
4341            "test/categories.csv",
4342            2,
4343            &mut report_xref_space,
4344        );
4345        assert!(report_xref_space.has_errors());
4346        assert!(
4347            report_xref_space
4348                .format_report()
4349                .contains("Extra space before '32' in cross-reference")
4350        );
4351
4352        // 5. Extra space inside tag name: "< approx>0"
4353        let mut report_tag_space = ValidationReport::default();
4354        validate_dc_aliases_spacing(
4355            "< approx>0",
4356            "test/categories.csv",
4357            2,
4358            &mut report_tag_space,
4359        );
4360        assert!(report_tag_space.has_errors());
4361        assert!(
4362            report_tag_space
4363                .format_report()
4364                .contains("Extra space after '<'")
4365        );
4366
4367        // 6. Cell leading and trailing whitespace
4368        let mut report_cell_ws = ValidationReport::default();
4369        validate_dc_aliases_spacing(
4370            " <approx>0",
4371            "test/categories.csv",
4372            2,
4373            &mut report_cell_ws,
4374        );
4375        assert!(report_cell_ws.has_errors());
4376        assert!(
4377            report_cell_ws
4378                .format_report()
4379                .contains("Cell has leading whitespace")
4380        );
4381
4382        // 7. Multiple spaces in alias name: "word  separator"
4383        let mut report_alias_spaces = ValidationReport::default();
4384        validate_dc_aliases_spacing(
4385            "word  separator",
4386            "test/categories.csv",
4387            2,
4388            &mut report_alias_spaces,
4389        );
4390        assert!(report_alias_spaces.has_errors());
4391        assert!(
4392            report_alias_spaces
4393                .format_report()
4394                .contains("Multiple consecutive spaces in alias")
4395        );
4396
4397        // 8. Correctly formatted aliases pass without any error
4398        let mut report_ok = ValidationReport::default();
4399        validate_dc_aliases_spacing(
4400            "<approx>0, <equiv>u15",
4401            "test/categories.csv",
4402            2,
4403            &mut report_ok,
4404        );
4405        validate_dc_aliases_spacing(
4406            "word separator, <equiv>u20, >32, <approx>u2d",
4407            "test/categories.csv",
4408            2,
4409            &mut report_ok,
4410        );
4411        validate_dc_aliases_spacing(
4412            "line feed, end of line, <equiv>240 239",
4413            "test/categories.csv",
4414            2,
4415            &mut report_ok,
4416        );
4417        validate_dc_aliases_spacing(
4418            ":~ [number]",
4419            "test/categories.csv",
4420            2,
4421            &mut report_ok,
4422        );
4423        assert!(!report_ok.has_errors());
4424    }
4425
4426    #[crate::ctb_test]
4427    fn test_equiv_syntax_parity_validation() {
4428        let known_formats: HashSet<usize> = HashSet::new();
4429        let mut known_named_types: HashSet<String> = HashSet::new();
4430        known_named_types.insert("string".to_string());
4431
4432        // 1. Matching syntax passes validation
4433        let mut report_ok = ValidationReport::default();
4434        let csv_ok = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114112,0,Base,0,BN,,Cc,Controls,:~ [string],\n1114113,1,Equiv,0,BN,,Po,Controls,\"<equiv>0, :~ [string]\",\n";
4435        validate_dc_files_data(
4436            [("test.csv", &csv_ok[..])],
4437            "test",
4438            &known_formats,
4439            None,
4440            Some(&known_named_types),
4441            None,
4442            None,
4443            None,
4444            &mut report_ok,
4445        );
4446        assert!(
4447            !report_ok.has_errors(),
4448            "Expected success but got: {}",
4449            report_ok.format_report()
4450        );
4451
4452        // 2. Mismatched syntax (one has rule, one has None) fails validation
4453        let mut report_missing = ValidationReport::default();
4454        let csv_missing = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114112,0,Base,0,BN,,Cc,Controls,:~ [string],\n1114113,1,Equiv,0,BN,,Po,Controls,<equiv>0,\n";
4455        validate_dc_files_data(
4456            [("test.csv", &csv_missing[..])],
4457            "test",
4458            &known_formats,
4459            None,
4460            Some(&known_named_types),
4461            None,
4462            None,
4463            None,
4464            &mut report_missing,
4465        );
4466        assert!(report_missing.has_errors());
4467        assert!(
4468            report_missing
4469                .format_report()
4470                .contains("their syntax rules do not match")
4471        );
4472
4473        // 3. Incompatible syntax rules fail validation
4474        let mut report_diff = ValidationReport::default();
4475        let csv_diff = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114112,0,Base,0,BN,,Cc,Controls,:~ [string],\n1114113,1,Equiv,0,BN,,Po,Controls,\"<equiv>0, :~ 0\",\n";
4476        validate_dc_files_data(
4477            [("test.csv", &csv_diff[..])],
4478            "test",
4479            &known_formats,
4480            None,
4481            Some(&known_named_types),
4482            None,
4483            None,
4484            None,
4485            &mut report_diff,
4486        );
4487        assert!(report_diff.has_errors());
4488        assert!(
4489            report_diff
4490                .format_report()
4491                .contains("their syntax rules differ")
4492        );
4493
4494        // 4. Mismatched @closes declarations fail validation
4495        let mut report_closes = ValidationReport::default();
4496        let csv_closes = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114112,0,Opener,0,BN,,Cc,Controls,,\n1114113,1,CloserA,0,BN,,Po,Controls,@closes(0),\n1114114,2,CloserB,0,BN,,Po,Controls,<equiv>1,\n";
4497        validate_dc_files_data(
4498            [("test.csv", &csv_closes[..])],
4499            "test",
4500            &known_formats,
4501            None,
4502            Some(&known_named_types),
4503            None,
4504            None,
4505            None,
4506            &mut report_closes,
4507        );
4508        assert!(report_closes.has_errors());
4509        assert!(
4510            report_closes
4511                .format_report()
4512                .contains("their @closes declarations do not match")
4513        );
4514
4515        // 5. Normalized equivalent opener targets in @closes succeed
4516        let mut report_norm_closes = ValidationReport::default();
4517        let csv_norm_closes = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114112,0,OpenerA,0,BN,,Cc,Controls,,\n1114113,1,OpenerAEquiv,0,BN,,Cc,Controls,<equiv>0,\n1114114,2,CloserA,0,BN,,Po,Controls,@closes(0),\n1114115,3,CloserB,0,BN,,Po,Controls,\"<equiv>2, @closes(1)\",\n";
4518        validate_dc_files_data(
4519            [("test.csv", &csv_norm_closes[..])],
4520            "test",
4521            &known_formats,
4522            None,
4523            Some(&known_named_types),
4524            None,
4525            None,
4526            None,
4527            &mut report_norm_closes,
4528        );
4529        assert!(
4530            !report_norm_closes.has_errors(),
4531            "Expected normalized @closes to pass: {}",
4532            report_norm_closes.format_report()
4533        );
4534
4535        // 6. Truly mismatched @closes targets still fail validation
4536        let mut report_mismatched_target = ValidationReport::default();
4537        let csv_mismatched_target = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114112,0,OpenerA,0,BN,,Cc,Controls,,\n1114113,1,OpenerB,0,BN,,Cc,Controls,,\n1114114,2,CloserA,0,BN,,Po,Controls,@closes(0),\n1114115,3,CloserB,0,BN,,Po,Controls,\"<equiv>2, @closes(1)\",\n";
4538        validate_dc_files_data(
4539            [("test.csv", &csv_mismatched_target[..])],
4540            "test",
4541            &known_formats,
4542            None,
4543            Some(&known_named_types),
4544            None,
4545            None,
4546            None,
4547            &mut report_mismatched_target,
4548        );
4549        assert!(report_mismatched_target.has_errors());
4550        assert!(
4551            report_mismatched_target
4552                .format_report()
4553                .contains("their @closes targets differ")
4554        );
4555
4556        // 7. Format ID <equiv> with matching syntax passes
4557        let mut report_fmt_ok = ValidationReport::default();
4558        let mut fmt_registry_syntax = FormatValidationRegistry::new();
4559        let string_syntax = parse_dc_syntax(":~ [string]").unwrap();
4560        fmt_registry_syntax.add_format(crate::syntax::FormatValidationInfo {
4561            short_id: 10,
4562            ident: Some("TestFormat".to_string()),
4563            category: "text".to_string(),
4564            syntax: Some(string_syntax.clone()),
4565            ..Default::default()
4566        });
4567        let known_formats_10 = HashSet::from([10]);
4568        let known_fmts_syntax_10 = HashSet::from([10]);
4569        let csv_fmt_ok = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114112,0,Zero,0,BN,,Cc,Controls,,\n1114113,1,One,0,BN,,Po,Controls,\"<equiv>f10, :~ [string]\",\n";
4570        validate_dc_files_data(
4571            [("test.csv", &csv_fmt_ok[..])],
4572            "test",
4573            &known_formats_10,
4574            None,
4575            Some(&known_named_types),
4576            None,
4577            Some(&known_fmts_syntax_10),
4578            Some(&fmt_registry_syntax),
4579            &mut report_fmt_ok,
4580        );
4581        assert!(
4582            !report_fmt_ok.has_errors(),
4583            "Expected format equiv to pass: {}",
4584            report_fmt_ok.format_report()
4585        );
4586
4587        // 8. Format ID <equiv> with mismatched syntax rules fails
4588        let mut report_fmt_diff = ValidationReport::default();
4589        let csv_fmt_diff = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114112,0,Zero,0,BN,,Cc,Controls,,\n1114113,1,One,0,BN,,Po,Controls,\"<equiv>f10, :~ 0\",\n";
4590        validate_dc_files_data(
4591            [("test.csv", &csv_fmt_diff[..])],
4592            "test",
4593            &known_formats_10,
4594            None,
4595            Some(&known_named_types),
4596            None,
4597            Some(&known_fmts_syntax_10),
4598            Some(&fmt_registry_syntax),
4599            &mut report_fmt_diff,
4600        );
4601        assert!(report_fmt_diff.has_errors());
4602        assert!(
4603            report_fmt_diff
4604                .format_report()
4605                .contains("their syntax rules differ")
4606        );
4607
4608        // 11. Redundant explicit syntax rule on .EM Routines fails validation
4609        let mut report_redundant_routine_syn = ValidationReport::default();
4610        let csv_redundant_routine_syn = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114368,256,void lang.say([string] text),0,BN,,!Cx,.EM Routines,\"@ident(\"\"LangSay\"\"), :~ 258 [string $text] 259\",\n";
4611        validate_dc_files_data(
4612            [("em.csv", &csv_redundant_routine_syn[..])],
4613            "test",
4614            &known_formats,
4615            None,
4616            Some(&known_named_types),
4617            None,
4618            None,
4619            None,
4620            &mut report_redundant_routine_syn,
4621        );
4622        assert!(report_redundant_routine_syn.has_errors());
4623        assert!(
4624            report_redundant_routine_syn
4625                .format_report()
4626                .contains("Redundant explicit syntax rule on '.EM Routines'")
4627        );
4628
4629        // 12. Derived syntax rule on .EM Routines from parameter declaration in Name
4630        let say_rule = derive_el_routine_syntax("void lang.say([string] text)")
4631            .unwrap()
4632            .unwrap();
4633        assert_eq!(say_rule.raw, ":~ 258 [string $text] 259");
4634        let assign_rule = derive_el_routine_syntax(
4635            "void lang.assign([identifier] identifier, [value] value)",
4636        )
4637        .unwrap()
4638        .unwrap();
4639        assert_eq!(
4640            assign_rule.raw,
4641            ":~ 258 [identifier $identifier] 259 258 [value $value] 259"
4642        );
4643        let invoke_rule = derive_el_routine_syntax(
4644            "void lang.invoke([Routine] routine | [Routine name] routineName)",
4645        )
4646        .unwrap()
4647        .unwrap();
4648        assert_eq!(
4649            invoke_rule.raw,
4650            ":~ 258 ([Routine $routine] | [Routine name $routineName]) 259"
4651        );
4652    }
4653
4654    #[crate::ctb_test]
4655    fn test_new_dc_framing_shape_validation() {
4656        let known_formats: HashSet<usize> = HashSet::new();
4657        let known_named_types: HashSet<String> = [
4658            "string".to_string(),
4659            "number".to_string(),
4660            "identifier".to_string(),
4661            "value".to_string(),
4662            "atom_dc".to_string(),
4663        ]
4664        .into_iter()
4665        .collect();
4666
4667        // 1. New Dc (> 634) with deterministic fixed-arity prefix rule passes
4668        let mut report_ok_prefix = ValidationReport::default();
4669        let csv_ok_prefix = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114747,635,NewFixedPrefix,0,BN,,!Cx,.Semantic,:~ [string] [number],\n";
4670        validate_dc_files_data(
4671            [("semantic.csv", &csv_ok_prefix[..])],
4672            "test",
4673            &known_formats,
4674            None,
4675            Some(&known_named_types),
4676            None,
4677            None,
4678            None,
4679            &mut report_ok_prefix,
4680        );
4681        assert!(
4682            !report_ok_prefix
4683                .diagnostics
4684                .iter()
4685                .any(|d| d.column_name.as_deref() == Some("Syntax")),
4686            "Expected new fixed-arity prefix Dc to have no syntax/framing errors: {}",
4687            report_ok_prefix.format_report()
4688        );
4689
4690        // 2. New Dc (> 634) with Paired (@closes) delimiter passes
4691        let mut report_ok_paired = ValidationReport::default();
4692        let csv_ok_paired = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114747,635,NewBeginBlock,0,BN,,Ps,.Semantic,:~ [^636]* 636,\n1114748,636,NewEndBlock,0,BN,,Pe,.Semantic,@closes(635),\n";
4693        validate_dc_files_data(
4694            [("semantic.csv", &csv_ok_paired[..])],
4695            "test",
4696            &known_formats,
4697            None,
4698            Some(&known_named_types),
4699            None,
4700            None,
4701            None,
4702            &mut report_ok_paired,
4703        );
4704        assert!(
4705            !report_ok_paired
4706                .diagnostics
4707                .iter()
4708                .any(|d| d.column_name.as_deref() == Some("Syntax")),
4709            "Expected new paired Dc with @closes to have no syntax/framing errors: {}",
4710            report_ok_paired.format_report()
4711        );
4712
4713        // 3. New Dc (> 634) with infix rule is rejected
4714        let mut report_err_infix = ValidationReport::default();
4715        let csv_err_infix = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114747,635,NewInfixOp,0,BN,,!Cx,.Semantic,:[identifier] ~ [value],\n";
4716        validate_dc_files_data(
4717            [("semantic.csv", &csv_err_infix[..])],
4718            "test",
4719            &known_formats,
4720            None,
4721            Some(&known_named_types),
4722            None,
4723            None,
4724            None,
4725            &mut report_err_infix,
4726        );
4727        assert!(report_err_infix.has_errors());
4728        assert!(
4729            report_err_infix
4730                .format_report()
4731                .contains("uses legacy non-deterministic framing shape Infix"),
4732            "Got: {}",
4733            report_err_infix.format_report()
4734        );
4735
4736        // 4. New Dc (> 634) with variable-arity prefix rule (without @closes) is rejected
4737        let mut report_err_var = ValidationReport::default();
4738        let csv_err_var = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114747,635,NewVarPrefix,0,BN,,!Cx,.Semantic,:~ [string]+,\n";
4739        validate_dc_files_data(
4740            [("semantic.csv", &csv_err_var[..])],
4741            "test",
4742            &known_formats,
4743            None,
4744            Some(&known_named_types),
4745            None,
4746            None,
4747            None,
4748            &mut report_err_var,
4749        );
4750        assert!(report_err_var.has_errors());
4751        assert!(
4752            report_err_var
4753                .format_report()
4754                .contains("uses legacy non-deterministic framing shape PrefixVariableArity"),
4755            "Got: {}",
4756            report_err_var.format_report()
4757        );
4758
4759        // 5. Dc with self-less rule is rejected
4760        let mut report_err_selfless = ValidationReport::default();
4761        let csv_err_selfless = b"Dc,Short,Name (!=deprecated),\xe2\x97\x8c,\xe2\x87\x86,Aa,Type,Script,Aliases,Description\n1114747,635,NewSelfless,0,BN,,!Cx,.Semantic,:[string],\n";
4762        validate_dc_files_data(
4763            [("semantic.csv", &csv_err_selfless[..])],
4764            "test",
4765            &known_formats,
4766            None,
4767            Some(&known_named_types),
4768            None,
4769            None,
4770            None,
4771            &mut report_err_selfless,
4772        );
4773        assert!(report_err_selfless.has_errors());
4774        assert!(
4775            report_err_selfless
4776                .format_report()
4777                .contains("does not conform to a valid framing shape"),
4778            "Got: {}",
4779            report_err_selfless.format_report()
4780        );
4781    }
4782
4783    #[crate::ctb_test]
4784    fn test_validate_scripts_table_block_sizes() {
4785        let mut report = ValidationReport::default();
4786        let valid_csv = b"Script,Block increment size,Comments\n.Controls,256,Core\n.Emoji,TBD,Deferred\nLatin,TBD,Deprecated short Latin Dcs\n.Formats:v:case,32,Small\n";
4787        let map = parse_scripts_block_sizes_with_report(
4788            valid_csv,
4789            "README.scripts.csv",
4790            &mut report,
4791        );
4792        assert!(
4793            !report.has_errors(),
4794            "Unexpected errors: {}",
4795            report.format_report()
4796        );
4797        assert_eq!(map.get(".Controls"), Some(&Some(256)));
4798        assert_eq!(map.get(".Emoji"), Some(&None));
4799        assert_eq!(map.get("Latin"), Some(&None));
4800        assert_eq!(map.get(".Formats:v:case"), Some(&Some(32)));
4801
4802        let mut bad_report = ValidationReport::default();
4803        let bad_csv = b"Script,Block increment size,Comments\n.BadMissing,,Missing\n.BadZero,0,Zero\n.BadOdd,24,Not multiple of 16\n.BadText,none,Old token\n";
4804        let _ = parse_scripts_block_sizes_with_report(
4805            bad_csv,
4806            "README.scripts.csv",
4807            &mut bad_report,
4808        );
4809        assert!(bad_report.has_errors());
4810        let formatted = bad_report.format_report();
4811        assert!(formatted.contains("missing a Block increment size"));
4812        assert!(formatted.contains("must be a positive multiple of 16"));
4813        assert!(formatted.contains("Invalid Block increment size 'none'"));
4814    }
4815
4816    #[crate::ctb_test]
4817    fn test_staged_and_csv_impl_linter_rejects_non_transformation_formats() {
4818        use crate::syntax::build_format_validation_registry;
4819        use crate::wat::{ImplStage, StagedDcImpl};
4820
4821        let repo_root = crate::find_repository_root().unwrap();
4822        let mut fmt_report = ValidationReport::default();
4823        let mut format_rows = crate::format::validate_all_format_files_from_disk(
4824            &repo_root.join("src/formats/dcdata/data-src/categories/formats"),
4825            None,
4826            &mut fmt_report,
4827        );
4828        let registry = build_format_validation_registry(&format_rows);
4829        assert!(!registry.is_transformation_format(656));
4830        assert!(registry.is_transformation_format(1680));
4831
4832        let known_fids: HashSet<usize> =
4833            format_rows.iter().filter_map(|r| r.short_id).collect();
4834        let mut dc_defns = crate::validation::validate_all_dc_files_from_disk(
4835            &repo_root.join("src/formats/dcdata/data-src/categories"),
4836            &known_fids,
4837            None,
4838            None,
4839            None,
4840            None,
4841            Some(&registry),
4842            &mut fmt_report,
4843        );
4844
4845        let ok_impl = StagedDcImpl {
4846            stage: ImplStage::Stage0,
4847            target: crate::DcShorthand::Format(1680),
4848            rel_path: "stage_0_impls/f1680_stagel3_to_wasm.wat".to_owned(),
4849            converts: Some((
4850                crate::DcShorthand::Short(2192),
4851                crate::DcShorthand::Short(1927),
4852            )),
4853            context_tokens: Vec::new(),
4854            decomp_tag: "semantic".to_owned(),
4855            tokens: vec![
4856                crate::DcShorthand::Short(1927),
4857                crate::DcShorthand::Short(1928),
4858            ],
4859        };
4860        let mut ok_report = ValidationReport::default();
4861        attach_staged_dc_impls_to_defns_with_registry(
4862            std::slice::from_ref(&ok_impl),
4863            &mut dc_defns,
4864            Some(&mut format_rows),
4865            Some(&known_fids),
4866            Some(&registry),
4867            &mut ok_report,
4868        );
4869        assert!(
4870            !ok_report.has_errors(),
4871            "Unexpected error: {}",
4872            ok_report.format_report()
4873        );
4874
4875        let bad_impl = StagedDcImpl {
4876            stage: ImplStage::Stage0,
4877            target: crate::DcShorthand::Format(656),
4878            rel_path: "stage_0_impls/f656_stagel3.wat".to_owned(),
4879            converts: None,
4880            context_tokens: Vec::new(),
4881            decomp_tag: "semantic".to_owned(),
4882            tokens: vec![
4883                crate::DcShorthand::Short(1927),
4884                crate::DcShorthand::Short(1928),
4885            ],
4886        };
4887        let mut bad_report = ValidationReport::default();
4888        attach_staged_dc_impls_to_defns_with_registry(
4889            &[bad_impl],
4890            &mut dc_defns,
4891            Some(&mut format_rows),
4892            Some(&known_fids),
4893            Some(&registry),
4894            &mut bad_report,
4895        );
4896        assert!(bad_report.has_errors());
4897        assert!(
4898            bad_report
4899                .format_report()
4900                .contains("non-transformation format f656"),
4901            "Got: {}",
4902            bad_report.format_report()
4903        );
4904    }
4905}