1#[allow(
24 unused_imports,
25 clippy::wildcard_imports,
26 reason = "Standard workspace module prelude"
27)]
28use crate::utilities::*;
29
30use anyhow::{Context, Result, bail};
31use std::collections::{HashMap, HashSet};
32use std::fs;
33use std::path::{Path, PathBuf};
34
35pub use ctb_storage_minimal::global_graph_layout::{
36 FORMAT_REGION_START, SHORT_DC_REGION_START,
37};
38pub use ctb_storage_minimal::shorthand::{
39 parse_format_shorthand, parse_unicode_shorthand,
40};
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
44pub struct TableUpdateStats {
45 pub files_scanned: usize,
46 pub files_modified: usize,
47 pub new_ids_assigned: usize,
48 pub dc_ids_recalculated: usize,
49 pub max_short_id: usize,
50}
51
52pub const UNIFIED_SCHEMA_HEADER: [&str; 19] = [
54 "Dc",
55 "Short",
56 "Name (!=deprecated)",
57 "◌",
58 "⇆",
59 "Aa",
60 "Type",
61 "Script",
62 "Aliases; >=xref, <=decompos., :=Dc syntax, @chain",
63 "Description",
64 "Extensions (Primary extension first, followed by comma-separated alternatives)",
65 "MIME (Primary MIME type first, followed by comma-separated aliases)",
66 "Apple Uniform Type Identifier (UTI)",
67 "Apple Type code",
68 "Import support\n(for trans_:\n =run the tr.)",
69 "Export support\n(for trans_:\n =reverse the\n tr.)",
70 "Tests",
71 "Variant Types\n(comma-\n delimited)",
72 "References",
73];
74
75const GENERATED_FILE_LICENSE_HEADER: &str = r"// SPDX-License-Identifier: AGPL-3.0-or-later
77/*
78This file is part of Collective Toolbox, a database and document workspace and utilities.
79Copyright (C) 2026 Collective Toolbox Developers
80Contact: info@collectivetoolbox.com
81
82This program is free software: you can redistribute it and/or modify it under
83the terms of the GNU Affero General Public License as published by the Free
84Software Foundation, either version 3 of the License, or (at your option) any
85later version.
86
87This program is distributed in the hope that it will be useful, but WITHOUT ANY
88WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
89A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
90
91You should have received a copy of the GNU Affero General Public License along
92with this program. If not, see <https://www.gnu.org/licenses/>.
93*/";
94
95#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
97pub struct MergedGenerationStats {
98 pub dc_records_merged: usize,
99 pub format_records_merged: usize,
100 pub unicode_records_merged: usize,
101 pub total_records_merged: usize,
102}
103
104pub use ctb_build_support::{
105 find_repository_root, find_repository_root_from, is_unassigned_id,
106};
107
108pub fn is_empty_row(row: &[String]) -> bool {
110 row.iter().all(|cell| cell.trim().is_empty())
111}
112
113pub fn read_csv_file(path: &Path) -> Result<(Vec<String>, Vec<Vec<String>>)> {
115 let content = fs::read_to_string(path)
116 .with_context(|| format!("Failed to read CSV at {}", path.display()))?;
117
118 let mut rdr = csv::ReaderBuilder::new()
119 .has_headers(false)
120 .flexible(true)
121 .from_reader(content.as_bytes());
122
123 let mut rows = Vec::new();
124 for result in rdr.records() {
125 let record: csv::StringRecord = result.with_context(|| {
126 format!("Failed to parse record in {}", path.display())
127 })?;
128 rows.push(
129 record
130 .iter()
131 .map(std::string::ToString::to_string)
132 .collect::<Vec<String>>(),
133 );
134 }
135
136 if rows.is_empty() {
137 return Ok((Vec::new(), Vec::new()));
138 }
139
140 let header = rows.remove(0);
141
142 for (idx, row) in rows.iter().enumerate() {
143 if is_empty_row(row) {
144 continue;
145 }
146 let line_no = idx.saturating_add(2);
147 ensure!(
148 row.len() == header.len(),
149 "Mismatched column count in {}:{}: found {} columns, expected {} (header has {} columns)",
150 path.display(),
151 line_no,
152 row.len(),
153 header.len(),
154 header.len()
155 );
156 }
157
158 Ok((header, rows))
159}
160
161fn serialize_csv_bytes(
163 path: &Path,
164 header: &[String],
165 rows: &[Vec<String>],
166) -> Result<Vec<u8>> {
167 let mut wtr = csv::WriterBuilder::new()
168 .flexible(false)
169 .from_writer(Vec::new());
170
171 wtr.write_record(header).with_context(|| {
172 format!("Failed to write header to {}", path.display())
173 })?;
174
175 for (idx, row) in rows.iter().enumerate() {
176 let line_no = idx.saturating_add(2);
177 ensure!(
178 row.len() == header.len(),
179 "Cannot write row {} with {} columns to {} (header has {} columns)",
180 line_no,
181 row.len(),
182 path.display(),
183 header.len()
184 );
185 wtr.write_record(row).with_context(|| {
186 format!("Failed to write row to {}", path.display())
187 })?;
188 }
189
190 wtr.into_inner()
191 .with_context(|| format!("Failed to flush CSV for {}", path.display()))
192}
193
194pub fn write_csv_file(
197 path: &Path,
198 header: &[String],
199 rows: &[Vec<String>],
200) -> Result<()> {
201 let bytes = serialize_csv_bytes(path, header, rows)?;
202 if fs::read(path).ok().as_deref() == Some(bytes.as_slice()) {
203 return Ok(());
204 }
205 fs::write(path, bytes)
206 .with_context(|| format!("Failed to save CSV to {}", path.display()))?;
207 Ok(())
208}
209
210struct ProcessedCategoryCsv {
211 path: PathBuf,
212 file_name: String,
213 header: Vec<String>,
214 rows: Vec<Vec<String>>,
215 modified: bool,
216}
217
218pub const PREEXISTING_CONTIGUOUS_DC_MAX: u32 = 1928;
221
222pub const PREEXISTING_CONTIGUOUS_FORMAT_MAX: u32 = 655;
225
226#[derive(Debug, Clone, PartialEq, Eq)]
227struct AllocatedScriptBlock {
228 script: String,
229 start: u32,
230 end_exclusive: u32,
231 max_used: u32,
232}
233
234#[derive(Debug, Clone)]
235struct ScriptBlockAllocator {
236 script_block_sizes: HashMap<String, Option<u32>>,
237 first_block_start: u32,
238 blocks: Vec<AllocatedScriptBlock>,
239 max_short_id: u32,
240 max_allowed_id: u32,
241}
242
243const BLOCK_REGISTRY_HEADER: [&str; 4] = [
244 "Script",
245 "First long ID",
246 "Last long ID",
247 "Last allocated long ID",
248];
249
250fn assigned_category_id(raw: &str, formats: bool) -> Result<Option<u32>> {
251 let trimmed = raw.trim();
252 let numeric = if formats {
253 if let Some(numeric) = trimmed.strip_prefix('f') {
254 numeric
255 } else {
256 trimmed
257 }
258 } else {
259 trimmed
260 };
261 if !numeric.is_empty() && numeric.bytes().all(|byte| byte.is_ascii_digit())
262 {
263 return Ok(Some(
264 numeric.parse().context("Short ID exceeds numeric range")?,
265 ));
266 }
267 ensure!(is_unassigned_id(trimmed), "Invalid category ID: {raw}");
268 Ok(None)
269}
270
271impl ScriptBlockAllocator {
272 fn load_script_block_sizes(
273 data_src_dir: Option<&Path>,
274 ) -> Result<HashMap<String, Option<u32>>> {
275 let (csv_bytes, label) = if let Some(dir) = data_src_dir {
276 let disk_path = dir.join("README.scripts.csv");
277 if disk_path.is_file() {
278 (
279 fs::read(&disk_path).with_context(|| {
280 format!("Failed to read {}", disk_path.display())
281 })?,
282 disk_path.display().to_string(),
283 )
284 } else {
285 let bytes = crate::get_dc_data_file("README.scripts.csv")
286 .context("Could not locate embedded README.scripts.csv")?;
287 (bytes, "data/README.scripts.csv".to_string())
288 }
289 } else {
290 let bytes = crate::get_dc_data_file("README.scripts.csv")
291 .context("Could not locate embedded README.scripts.csv")?;
292 (bytes, "data/README.scripts.csv".to_string())
293 };
294
295 let mut report = crate::report::ValidationReport::new();
296 let map = crate::validation::parse_scripts_block_sizes_with_report(
297 &csv_bytes,
298 &label,
299 &mut report,
300 );
301 ensure!(
302 !report.has_errors(),
303 "Invalid README.scripts.csv:\n{}",
304 report.format_report()
305 );
306 Ok(map)
307 }
308
309 fn from_existing(
310 script_block_sizes: HashMap<String, Option<u32>>,
311 preexisting_cap: u32,
312 mut assigned: Vec<(u32, String)>,
313 mut blocks: Vec<AllocatedScriptBlock>,
314 region_start: u128,
315 region_end: u128,
316 ) -> Result<Self> {
317 assigned.sort_by(|a, b| a.0.cmp(&b.0));
318 let max_allowed_id = u32::try_from(
319 region_end
320 .checked_sub(region_start)
321 .context("Invalid ID region")?,
322 )?;
323 let mut seen = HashSet::new();
324 for (id, _) in &assigned {
325 ensure!(*id <= max_allowed_id, "Maximum short ID exceeded: {id}");
326 ensure!(seen.insert(*id), "Duplicate short ID: {id}");
327 }
328
329 let max_short_id = assigned.last().map_or(0, |&(id, _)| id);
331 let first_block_start = preexisting_cap
332 .checked_add(1)
333 .and_then(|id| id.checked_next_multiple_of(16))
334 .context("Legacy ID boundary overflow")?;
335 blocks.sort_by_key(|block| block.start);
336 let mut previous_end = first_block_start;
337 for block in &blocks {
338 ensure!(
339 script_block_sizes.contains_key(&block.script),
340 "Unknown script '{}' in block registry",
341 block.script
342 );
343 ensure!(
344 block.start.is_multiple_of(16)
345 && block.end_exclusive.is_multiple_of(16)
346 && block.start < block.end_exclusive,
347 "Invalid hexadecimal-aligned block for '{}'",
348 block.script
349 );
350 ensure!(
351 block.start >= previous_end,
352 "Overlapping or legacy-region block for '{}'",
353 block.script
354 );
355 ensure!(
356 block.end_exclusive
357 <= max_allowed_id
358 .checked_add(1)
359 .context("ID region overflow")?,
360 "Maximum short ID exceeded by block for '{}'",
361 block.script
362 );
363 ensure!(
364 block.max_used >= block.start.saturating_sub(1)
365 && block.max_used < block.end_exclusive,
366 "Invalid allocation high-water mark for '{}'",
367 block.script
368 );
369 previous_end = block.end_exclusive;
370 }
371 for (id, script) in assigned {
372 if id <= preexisting_cap {
373 continue;
374 }
375 ensure!(
376 script_block_sizes.contains_key(&script),
377 "Assigned short ID {id} has unknown script '{script}'"
378 );
379 let block = blocks
380 .iter_mut()
381 .find(|block| id >= block.start && id < block.end_exclusive)
382 .with_context(|| {
383 format!("Assigned short ID {id} has no reserved block")
384 })?;
385 ensure!(
388 block.script == script || id <= block.max_used,
389 "Assigned short ID {id} has script '{script}', but its block belongs to '{}' and {id} exceeds the block's allocated high-water mark ({})",
390 block.script,
391 block.max_used
392 );
393 block.max_used = block.max_used.max(id);
394 }
395
396 Ok(Self {
397 script_block_sizes,
398 first_block_start,
399 blocks,
400 max_short_id,
401 max_allowed_id,
402 })
403 }
404
405 fn load(
406 script_block_sizes: HashMap<String, Option<u32>>,
407 preexisting_cap: u32,
408 assigned: Vec<(u32, String)>,
409 registry_path: &Path,
410 region_start: u128,
411 region_end: u128,
412 ) -> Result<Self> {
413 let mut blocks = Vec::new();
414 match fs::metadata(registry_path) {
415 Ok(_) => {
416 let (header, rows) = read_csv_file(registry_path)?;
417 ensure!(
418 header.iter().map(String::as_str).eq(BLOCK_REGISTRY_HEADER),
419 "Invalid block registry header in {}",
420 registry_path.display()
421 );
422 for row in rows {
423 if is_empty_row(&row) {
424 continue;
425 }
426 let mut cells = row.iter();
427 let script = cells
428 .next()
429 .context("Missing block script")?
430 .trim()
431 .to_string();
432 let mut ids = Vec::new();
433 for cell in cells {
434 let hex = cell.strip_prefix("0x").context(
435 "Block IDs must use 0x hexadecimal long IDs",
436 )?;
437 let long_id = u128::from_str_radix(hex, 16)?;
438 let short_id = long_id
439 .checked_sub(region_start)
440 .context("Block ID precedes its region")?;
441 ids.push(u32::try_from(short_id)?);
442 }
443 let mut ids = ids.into_iter();
444 let start = ids.next().context("Missing block start")?;
445 let end_exclusive = ids
446 .next()
447 .context("Missing block end")?
448 .checked_add(1)
449 .context("Block end overflow")?;
450 let max_used = ids
451 .next()
452 .context("Missing allocation high-water mark")?;
453 blocks.push(AllocatedScriptBlock {
454 script,
455 start,
456 end_exclusive,
457 max_used,
458 });
459 }
460 }
461 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
462 Err(error) => {
463 return Err(error).context("Failed to read block registry");
464 }
465 }
466 Self::from_existing(
467 script_block_sizes,
468 preexisting_cap,
469 assigned,
470 blocks,
471 region_start,
472 region_end,
473 )
474 .with_context(|| {
475 format!("Invalid block registry {}", registry_path.display())
476 })
477 }
478
479 fn registry_csv(
480 &self,
481 path: PathBuf,
482 region_start: u128,
483 ) -> Result<ProcessedCategoryCsv> {
484 let header = BLOCK_REGISTRY_HEADER
485 .iter()
486 .map(|cell| (*cell).to_string())
487 .collect::<Vec<_>>();
488 let mut rows = Vec::new();
489 for block in &self.blocks {
490 let last = block
491 .end_exclusive
492 .checked_sub(1)
493 .context("Invalid block end")?;
494 let mut row = vec![block.script.clone()];
495 for id in [block.start, last, block.max_used] {
496 let long_id = region_start
497 .checked_add(u128::from(id))
498 .context("Long ID overflow")?;
499 row.push(format!("0x{long_id:X}"));
500 }
501 rows.push(row);
502 }
503 let bytes = serialize_csv_bytes(&path, &header, &rows)?;
504 let modified = match fs::read(&path) {
505 Ok(existing) => existing != bytes,
506 Err(error) if error.kind() == std::io::ErrorKind::NotFound => true,
507 Err(error) => {
508 return Err(error).context("Failed to read block registry");
509 }
510 };
511 Ok(ProcessedCategoryCsv {
512 path,
513 file_name: String::new(),
514 header,
515 rows,
516 modified,
517 })
518 }
519
520 fn allocate(
521 &mut self,
522 script: &str,
523 file_name: &str,
524 line_no: usize,
525 ) -> Result<u32> {
526 let trimmed = script.trim();
527 ensure!(
528 !trimmed.is_empty(),
529 "Cannot allocate ID in {file_name}:{line_no}: missing Script"
530 );
531 let Some(&size_opt) = self.script_block_sizes.get(trimmed) else {
532 bail!(
533 "Cannot allocate ID in {file_name}:{line_no}: unknown script '{trimmed}' (not registered in README.scripts.csv)"
534 );
535 };
536 let Some(block_size) = size_opt else {
537 bail!(
538 "Cannot allocate ID in {file_name}:{line_no}: script '{trimmed}' has Block increment size 'TBD' in README.scripts.csv"
539 );
540 };
541
542 if let Some(open_block) = self.blocks.iter_mut().find(|b| {
543 b.script == trimmed
544 && b.max_used
545 .checked_add(1)
546 .is_some_and(|id| id < b.end_exclusive)
547 }) {
548 let next_id = open_block
549 .max_used
550 .checked_add(1)
551 .context("Short ID overflow")?;
552 open_block.max_used = next_id;
553 self.max_short_id = self.max_short_id.max(next_id);
554 return Ok(next_id);
555 }
556
557 let mut cand_start = self.first_block_start;
558 for b in &self.blocks {
559 let cand_end = cand_start
560 .checked_add(block_size)
561 .context("Block end overflow")?;
562 if cand_end <= b.start {
563 break;
564 }
565 if cand_start < b.end_exclusive {
566 cand_start = b.end_exclusive;
567 }
568 }
569
570 let end_exclusive = cand_start
571 .checked_add(block_size)
572 .context("Block end overflow")?;
573 ensure!(
574 end_exclusive <= self.max_allowed_id.saturating_add(1),
575 "Cannot allocate ID in {file_name}:{line_no}: maximum short ID exceeded"
576 );
577 self.blocks.push(AllocatedScriptBlock {
578 script: trimmed.to_string(),
579 start: cand_start,
580 end_exclusive,
581 max_used: cand_start,
582 });
583 self.blocks.sort_by_key(|b| b.start);
584 self.max_short_id = self.max_short_id.max(cand_start);
585 Ok(cand_start)
586 }
587}
588
589fn process_dc_category_files(
590 categories_dir: &Path,
591) -> Result<(
592 Vec<ProcessedCategoryCsv>,
593 TableUpdateStats,
594 ProcessedCategoryCsv,
595)> {
596 if !categories_dir.is_dir() {
597 bail!(
598 "Dc categories directory not found at {}",
599 categories_dir.display()
600 );
601 }
602
603 let script_block_sizes =
604 ScriptBlockAllocator::load_script_block_sizes(categories_dir.parent())?;
605
606 let mut csv_paths = Vec::new();
607 for entry in fs::read_dir(categories_dir)? {
608 let entry = entry?;
609 let path = entry.path();
610 if path.is_file() {
611 let Some(file_name) = path.file_name().and_then(|n| n.to_str())
612 else {
613 continue;
614 };
615 if file_name.ends_with(".csv")
616 && file_name != "schema.csv"
617 && !file_name.ends_with(".generated.csv")
618 {
619 csv_paths.push(path);
620 }
621 }
622 }
623 csv_paths.sort();
624
625 let mut assigned_entries = Vec::new();
627 let mut files_data = Vec::new();
628 let mut scanned_non_unicode_files = 0usize;
629
630 for path in &csv_paths {
631 let Some(file_name) = path
632 .file_name()
633 .and_then(|n| n.to_str())
634 .map(str::to_string)
635 else {
636 continue;
637 };
638 let is_unicode_clarifications =
639 file_name == "unicode-clarifications.csv";
640 if !is_unicode_clarifications {
641 scanned_non_unicode_files =
642 scanned_non_unicode_files.saturating_add(1);
643 }
644 let (header, rows) = read_csv_file(path)?;
645 if !is_unicode_clarifications {
646 for row in &rows {
647 if is_empty_row(row) {
648 continue;
649 }
650 if let Some(dc_str) = row.first() {
651 if dc_str.trim().starts_with('u')
652 || dc_str.trim().starts_with('U')
653 {
654 continue;
655 }
656 }
657 if let Some(short_str) = row.get(1) {
658 if let Some(id) = assigned_category_id(short_str, false)
659 .with_context(|| {
660 format!(
661 "Invalid short ID in {file_name}: {short_str}"
662 )
663 })?
664 {
665 let script =
667 row.get(7).map_or("", |s| s.trim()).to_string();
668 assigned_entries.push((id, script));
669 }
670 }
671 }
672 }
673 files_data.push((path.clone(), file_name, header, rows));
674 }
675
676 let registry_path = categories_dir
677 .parent()
678 .context("Missing data source directory")?
679 .join("README.dc-blocks.csv");
680 let mut allocator = ScriptBlockAllocator::load(
681 script_block_sizes,
682 PREEXISTING_CONTIGUOUS_DC_MAX,
683 assigned_entries,
684 ®istry_path,
685 SHORT_DC_REGION_START,
686 crate::dc::SHORT_DC_REGION_END,
687 )?;
688
689 let mut stats = TableUpdateStats {
690 files_scanned: scanned_non_unicode_files,
691 max_short_id: usize::try_from(allocator.max_short_id).unwrap_or(0),
693 ..Default::default()
694 };
695
696 let mut processed = Vec::with_capacity(files_data.len());
698 for (path, file_name, header, mut rows) in files_data {
699 let mut modified = false;
700 if file_name != "unicode-clarifications.csv" {
701 for (row_idx, row) in rows.iter_mut().enumerate() {
702 if is_empty_row(row) {
703 continue;
704 }
705 if let Some(dc_str) = row.first() {
706 if dc_str.trim().starts_with('u')
707 || dc_str.trim().starts_with('U')
708 {
709 continue;
710 }
711 }
712
713 while row.len() < 2 {
715 row.push(String::new());
716 }
717
718 let short_unassigned = match row.get(1) {
719 Some(s) => assigned_category_id(s, false)?.is_none(),
720 None => true,
721 };
722
723 if short_unassigned {
724 let name = match row.get(2) {
725 Some(s) => s.as_str(),
726 None => "",
727 };
728 if name.is_empty() && is_empty_row(row) {
729 continue;
730 }
731
732 let line_no = row_idx.saturating_add(2);
733 let script = row.get(7).map_or("", |s| s.as_str());
735 let new_short =
736 allocator.allocate(script, &file_name, line_no)?;
737 let new_dc = SHORT_DC_REGION_START
738 .saturating_add(u128::from(new_short));
739
740 if let Some(cell) = row.get_mut(0) {
741 *cell = new_dc.to_string();
742 }
743 if let Some(cell) = row.get_mut(1) {
744 *cell = new_short.to_string();
745 }
746
747 stats.new_ids_assigned =
748 stats.new_ids_assigned.saturating_add(1);
749 modified = true;
750 } else if let Some(short_str) = row.get(1) {
751 if let Ok(s_id) = short_str.trim().parse::<u32>() {
752 let expected_dc = SHORT_DC_REGION_START
753 .saturating_add(u128::from(s_id));
754 let current_dc = match row.first() {
755 Some(s) => s.trim(),
756 None => "",
757 };
758 if current_dc != expected_dc.to_string() {
759 if let Some(cell) = row.get_mut(0) {
760 *cell = expected_dc.to_string();
761 }
762 stats.dc_ids_recalculated =
763 stats.dc_ids_recalculated.saturating_add(1);
764 modified = true;
765 }
766 }
767 }
768 }
769 }
770 if modified {
771 stats.files_modified = stats.files_modified.saturating_add(1);
772 }
773 processed.push(ProcessedCategoryCsv {
774 path,
775 file_name,
776 header,
777 rows,
778 modified,
779 });
780 }
781
782 stats.max_short_id = usize::try_from(allocator.max_short_id).unwrap_or(0);
784 let registry =
785 allocator.registry_csv(registry_path, SHORT_DC_REGION_START)?;
786 Ok((processed, stats, registry))
787}
788
789pub(crate) fn load_dc_category_csvs_with_assigned_ids(
793 categories_dir: &Path,
794) -> Result<Vec<(String, Vec<u8>)>> {
795 let (processed, _, _) = process_dc_category_files(categories_dir)?;
796 let mut out = Vec::with_capacity(processed.len());
797 for file in processed {
798 let bytes = if file.modified {
799 serialize_csv_bytes(&file.path, &file.header, &file.rows)?
800 } else {
801 fs::read(&file.path).with_context(|| {
802 format!("Failed to read CSV at {}", file.path.display())
803 })?
804 };
805 out.push((file.file_name, bytes));
806 }
807 Ok(out)
808}
809
810pub fn assign_and_update_dc_categories(
816 repo_root: &Path,
817) -> Result<TableUpdateStats> {
818 let categories_dir =
819 repo_root.join("src/formats/dcdata/data-src/categories");
820 let (processed, stats, registry) =
821 process_dc_category_files(&categories_dir)?;
822 write_processed_categories(processed, registry)?;
823 Ok(stats)
824}
825
826fn write_processed_categories(
827 processed: Vec<ProcessedCategoryCsv>,
828 registry: ProcessedCategoryCsv,
829) -> Result<()> {
830 let mut writes = Vec::new();
831 for file in std::iter::once(registry).chain(processed) {
832 if file.modified {
833 let bytes =
834 serialize_csv_bytes(&file.path, &file.header, &file.rows)?;
835 writes.push((file.path, bytes));
836 }
837 }
838 for (path, bytes) in writes {
839 fs::write(&path, bytes).with_context(|| {
840 format!("Failed to save CSV to {}", path.display())
841 })?;
842 }
843 Ok(())
844}
845
846fn format_category_to_script(raw_cat: &str) -> String {
847 let trimmed = raw_cat.trim();
848 if trimmed.is_empty() {
849 ".Formats".to_string()
850 } else if trimmed.starts_with(".Formats:") {
851 trimmed.to_string()
852 } else {
853 format!(".Formats:{trimmed}")
854 }
855}
856
857fn process_format_category_files(
858 formats_dir: &Path,
859) -> Result<(
860 Vec<ProcessedCategoryCsv>,
861 TableUpdateStats,
862 ProcessedCategoryCsv,
863)> {
864 if !formats_dir.is_dir() {
865 bail!("Formats directory not found at {}", formats_dir.display());
866 }
867
868 let script_block_sizes = ScriptBlockAllocator::load_script_block_sizes(
869 formats_dir.parent().and_then(Path::parent),
870 )?;
871
872 let mut csv_paths = Vec::new();
873 for entry in fs::read_dir(formats_dir)? {
874 let entry = entry?;
875 let path = entry.path();
876 if path.is_file() {
877 let Some(file_name) = path.file_name().and_then(|n| n.to_str())
878 else {
879 continue;
880 };
881 if file_name.ends_with(".csv")
882 && file_name != "schema.csv"
883 && !file_name.ends_with(".generated.csv")
884 {
885 csv_paths.push(path);
886 }
887 }
888 }
889 csv_paths.sort();
890
891 let mut assigned_entries = Vec::new();
893 let mut files_data = Vec::new();
894
895 for path in &csv_paths {
896 let Some(file_name) = path
897 .file_name()
898 .and_then(|n| n.to_str())
899 .map(str::to_string)
900 else {
901 continue;
902 };
903 let (header, rows) = read_csv_file(path)?;
904 for row in &rows {
905 if is_empty_row(row) {
906 continue;
907 }
908 if let Some(short_str) = row.get(1) {
909 if let Some(id) = assigned_category_id(short_str, true)
910 .with_context(|| {
911 format!("Invalid format ID in {file_name}: {short_str}")
912 })?
913 {
914 let script = format_category_to_script(
916 row.get(4).map_or("", |s| s.as_str()),
917 );
918 assigned_entries.push((id, script));
919 }
920 }
921 }
922 files_data.push((path.clone(), file_name, header, rows));
923 }
924
925 let registry_path = formats_dir
926 .parent()
927 .and_then(Path::parent)
928 .context("Missing data source directory")?
929 .join("README.format-blocks.csv");
930 let mut allocator = ScriptBlockAllocator::load(
931 script_block_sizes,
932 PREEXISTING_CONTIGUOUS_FORMAT_MAX,
933 assigned_entries,
934 ®istry_path,
935 FORMAT_REGION_START,
936 crate::FORMAT_REGION_END,
937 )?;
938
939 let mut stats = TableUpdateStats {
940 files_scanned: files_data.len(),
941 max_short_id: usize::try_from(allocator.max_short_id).unwrap_or(0),
943 ..Default::default()
944 };
945
946 let mut processed = Vec::with_capacity(files_data.len());
948 for (path, file_name, header, mut rows) in files_data {
949 let mut modified = false;
950
951 for (row_idx, row) in rows.iter_mut().enumerate() {
952 if is_empty_row(row) {
953 continue;
954 }
955
956 while row.len() < 2 {
957 row.push(String::new());
958 }
959
960 let short_unassigned = match row.get(1) {
961 Some(s) => assigned_category_id(s, true)?.is_none(),
962 None => true,
963 };
964
965 if short_unassigned {
966 let ident = match row.get(2) {
967 Some(s) => s.as_str(),
968 None => "",
969 };
970 let label = match row.get(3) {
971 Some(s) => s.as_str(),
972 None => "",
973 };
974 if ident.is_empty() && label.is_empty() && is_empty_row(row) {
975 continue;
976 }
977
978 let line_no = row_idx.saturating_add(2);
979 let script = format_category_to_script(
981 row.get(4).map_or("", |s| s.as_str()),
982 );
983 let new_short =
984 allocator.allocate(&script, &file_name, line_no)?;
985 let new_dc =
986 FORMAT_REGION_START.saturating_add(u128::from(new_short));
987
988 if let Some(cell) = row.get_mut(0) {
989 *cell = new_dc.to_string();
990 }
991 if let Some(cell) = row.get_mut(1) {
992 *cell = new_short.to_string();
993 }
994
995 stats.new_ids_assigned =
996 stats.new_ids_assigned.saturating_add(1);
997 modified = true;
998 } else if let Some(short_str) = row.get(1) {
999 if let Some(s_id) = assigned_category_id(short_str, true)? {
1000 let s_id_u128 = u128::from(s_id);
1001 let expected_dc =
1002 FORMAT_REGION_START.saturating_add(s_id_u128);
1003 let current_dc = match row.first() {
1004 Some(s) => s.trim(),
1005 None => "",
1006 };
1007 if current_dc != expected_dc.to_string() {
1008 if let Some(cell) = row.get_mut(0) {
1009 *cell = expected_dc.to_string();
1010 }
1011 stats.dc_ids_recalculated =
1012 stats.dc_ids_recalculated.saturating_add(1);
1013 modified = true;
1014 }
1015 }
1016 }
1017 }
1018
1019 if modified {
1020 stats.files_modified = stats.files_modified.saturating_add(1);
1021 }
1022 processed.push(ProcessedCategoryCsv {
1023 path,
1024 file_name,
1025 header,
1026 rows,
1027 modified,
1028 });
1029 }
1030
1031 stats.max_short_id = usize::try_from(allocator.max_short_id).unwrap_or(0);
1033 let registry =
1034 allocator.registry_csv(registry_path, FORMAT_REGION_START)?;
1035 Ok((processed, stats, registry))
1036}
1037
1038pub(crate) fn load_format_category_csvs_with_assigned_ids(
1042 formats_dir: &Path,
1043) -> Result<Vec<(String, Vec<u8>)>> {
1044 let (processed, _, _) = process_format_category_files(formats_dir)?;
1045 let mut out = Vec::with_capacity(processed.len());
1046 for file in processed {
1047 let bytes = if file.modified {
1048 serialize_csv_bytes(&file.path, &file.header, &file.rows)?
1049 } else {
1050 fs::read(&file.path).with_context(|| {
1051 format!("Failed to read CSV at {}", file.path.display())
1052 })?
1053 };
1054 out.push((file.file_name, bytes));
1055 }
1056 Ok(out)
1057}
1058
1059pub fn assign_and_update_format_categories(
1065 repo_root: &Path,
1066) -> Result<TableUpdateStats> {
1067 let formats_dir =
1068 repo_root.join("src/formats/dcdata/data-src/categories/formats");
1069 let (processed, stats, registry) =
1070 process_format_category_files(&formats_dir)?;
1071 write_processed_categories(processed, registry)?;
1072 Ok(stats)
1073}
1074
1075pub fn validate_category_allocations(repo_root: &Path) -> Result<()> {
1078 let categories_dir =
1079 repo_root.join("src/formats/dcdata/data-src/categories");
1080 process_dc_category_files(&categories_dir)?;
1081 process_format_category_files(&categories_dir.join("formats"))?;
1082 Ok(())
1083}
1084
1085pub fn check_category_csvs_need_no_id_updates(repo_root: &Path) -> Result<()> {
1088 let categories_dir =
1089 repo_root.join("src/formats/dcdata/data-src/categories");
1090 let (_, dc_stats, dc_registry) =
1091 process_dc_category_files(&categories_dir)?;
1092 ensure!(
1093 !dc_registry.modified,
1094 "Dc block registry needs updating before reconciliation"
1095 );
1096 ensure!(
1097 dc_stats.files_modified == 0,
1098 "Dc category CSVs have {} unassigned or inconsistent IDs across {} file(s); assign IDs before running manifest-enforced or dry-run reconciliation",
1099 dc_stats
1100 .new_ids_assigned
1101 .saturating_add(dc_stats.dc_ids_recalculated),
1102 dc_stats.files_modified
1103 );
1104 let formats_dir = categories_dir.join("formats");
1105 let (_, fmt_stats, fmt_registry) =
1106 process_format_category_files(&formats_dir)?;
1107 ensure!(
1108 !fmt_registry.modified,
1109 "Format block registry needs updating before reconciliation"
1110 );
1111 ensure!(
1112 fmt_stats.files_modified == 0,
1113 "Format category CSVs have {} unassigned or inconsistent IDs across {} file(s); assign IDs before running manifest-enforced or dry-run reconciliation",
1114 fmt_stats
1115 .new_ids_assigned
1116 .saturating_add(fmt_stats.dc_ids_recalculated),
1117 fmt_stats.files_modified
1118 );
1119 Ok(())
1120}
1121
1122pub fn generate_merged_csvs(repo_root: &Path) -> Result<MergedGenerationStats> {
1126 let mut stats = MergedGenerationStats::default();
1127 let canonical_header: Vec<String> = UNIFIED_SCHEMA_HEADER
1128 .iter()
1129 .map(std::string::ToString::to_string)
1130 .collect();
1131
1132 let formats_dir =
1134 repo_root.join("src/formats/dcdata/data-src/categories/formats");
1135 let mut all_format_rows = Vec::new();
1136 if formats_dir.is_dir() {
1137 for entry in fs::read_dir(&formats_dir)? {
1138 let entry = entry?;
1139 let path = entry.path();
1140 if path.is_file() {
1141 let Some(file_name) = path.file_name().and_then(|n| n.to_str())
1142 else {
1143 continue;
1144 };
1145 if file_name.ends_with(".csv")
1146 && file_name != "schema.csv"
1147 && !file_name.ends_with(".generated.csv")
1148 {
1149 let (_, rows) = read_csv_file(&path)?;
1150 for row in rows {
1151 if !is_empty_row(&row) {
1152 let get = |idx: usize| -> String {
1154 row.get(idx).cloned().unwrap_or_default()
1155 };
1156 let label = get(3);
1157 let ident = get(2);
1158 let is_deprecated = label.starts_with('!')
1159 || ident.starts_with('!');
1160 let clean_label =
1161 label.trim_start_matches('!').trim();
1162 let name_cell = if is_deprecated {
1163 format!("!{clean_label}")
1164 } else {
1165 clean_label.to_string()
1166 };
1167
1168 let short_cell = if let Ok(s_id) =
1169 parse_format_shorthand(&get(1))
1170 {
1171 format!("f{s_id}")
1172 } else if let Ok(dc_id) = get(0).parse::<u128>() {
1173 let s_id =
1174 dc_id.saturating_sub(FORMAT_REGION_START);
1175 format!("f{s_id}")
1176 } else {
1177 get(1)
1178 };
1179
1180 let format_category = get(4);
1181 let script_cell = if format_category.is_empty() {
1182 ".Formats".to_string()
1183 } else {
1184 format!(".Formats:{format_category}")
1185 };
1186
1187 let clean_ident =
1188 ident.trim_start_matches('!').trim();
1189 let mut alias_parts = Vec::new();
1190 if !clean_ident.is_empty() {
1191 alias_parts.push(format!(
1192 "@ident(\"{}\")",
1193 escape_directive_string(clean_ident)
1194 ));
1195 }
1196 let raw_nicknames = get(10);
1197 if !raw_nicknames.is_empty() {
1198 for nick in
1199 crate::shared::split_comma_separated_items(
1200 &raw_nicknames,
1201 )
1202 {
1203 if !nick.is_empty() {
1204 alias_parts.push(format!(
1205 "@nick(\"{}\")",
1206 escape_directive_string(&nick)
1207 ));
1208 }
1209 }
1210 }
1211 let base_chain_syn = get(5);
1212 if !base_chain_syn.is_empty() {
1213 alias_parts.push(base_chain_syn);
1214 }
1215 let aliases_cell = alias_parts.join(", ");
1216
1217 let unified_row = vec![
1218 get(0), short_cell, name_cell, "0".to_string(), "BN".to_string(), String::new(), "!Cx".to_string(), script_cell, aliases_cell, get(15), get(6), get(7), get(8), get(9), get(11), get(12), get(13), get(14), get(16), ];
1238 all_format_rows.push(unified_row);
1239 }
1240 }
1241 }
1242 }
1243 }
1244
1245 all_format_rows.sort_by(|a, b| {
1246 let id_a = a
1248 .first()
1249 .and_then(|s| s.trim().parse::<u128>().ok())
1250 .unwrap_or(u128::MAX);
1251 let id_b = b
1253 .first()
1254 .and_then(|s| s.trim().parse::<u128>().ok())
1255 .unwrap_or(u128::MAX);
1256 id_a.cmp(&id_b)
1257 });
1258
1259 let target_path =
1260 repo_root.join("src/formats/dcdata/data-src/formats.generated.csv");
1261 write_csv_file(&target_path, &canonical_header, &all_format_rows)?;
1262 stats.format_records_merged = all_format_rows.len();
1263 }
1264
1265 let categories_dir =
1267 repo_root.join("src/formats/dcdata/data-src/categories");
1268 let mut all_dc_rows = Vec::new();
1269 if categories_dir.is_dir() {
1270 for entry in fs::read_dir(&categories_dir)? {
1271 let entry = entry?;
1272 let path = entry.path();
1273 if path.is_file() {
1274 let Some(file_name) = path.file_name().and_then(|n| n.to_str())
1275 else {
1276 continue;
1277 };
1278 if file_name.ends_with(".csv")
1279 && file_name != "schema.csv"
1280 && !file_name.ends_with(".generated.csv")
1281 && file_name != "unicode-clarifications.csv"
1282 {
1283 let (_, rows) = read_csv_file(&path)?;
1284 for mut row in rows {
1285 if !is_empty_row(&row) {
1286 if let Some(dc_cell) = row.first_mut() {
1287 if let Ok(cp) = parse_unicode_shorthand(dc_cell)
1288 {
1289 *dc_cell = cp.to_string();
1290 if let Some(short_cell) = row.get_mut(1) {
1291 short_cell.clear();
1292 }
1293 }
1294 }
1295 let get = |idx: usize| -> String {
1297 row.get(idx).cloned().unwrap_or_default()
1298 };
1299 let unified_row = vec![
1300 get(0), get(1), get(2), get(3), get(4), get(5), get(6), get(7), get(8), get(9), String::new(), String::new(), String::new(), String::new(), String::new(), String::new(), String::new(), String::new(), String::new(), ];
1320 all_dc_rows.push(unified_row);
1321 }
1322 }
1323 }
1324 }
1325 }
1326
1327 all_dc_rows.sort_by(|a, b| {
1328 let id_a = a
1330 .first()
1331 .and_then(|s| s.trim().parse::<u128>().ok())
1332 .unwrap_or(u128::MAX);
1333 let id_b = b
1335 .first()
1336 .and_then(|s| s.trim().parse::<u128>().ok())
1337 .unwrap_or(u128::MAX);
1338 id_a.cmp(&id_b)
1339 });
1340
1341 let target_path =
1342 repo_root.join("src/formats/dcdata/data-src/DcList.generated.csv");
1343 write_csv_file(&target_path, &canonical_header, &all_dc_rows)?;
1344 stats.dc_records_merged = all_dc_rows.len();
1345 }
1346
1347 let mut unicode_clarifications: HashMap<u32, (String, String)> =
1349 HashMap::new();
1350 let clar_path = repo_root.join(
1351 "src/formats/dcdata/data-src/categories/unicode-clarifications.csv",
1352 );
1353 if clar_path.is_file() {
1354 if let Ok((_, rows)) = read_csv_file(&clar_path) {
1355 for row in rows {
1356 if let Some(dc_cell) = row.first() {
1357 if let Ok(cp) = parse_unicode_shorthand(dc_cell) {
1358 let aliases = row.get(8).cloned().unwrap_or_default();
1360 let desc = row.get(9).cloned().unwrap_or_default();
1362 unicode_clarifications.insert(cp, (aliases, desc));
1363 }
1364 }
1365 }
1366 }
1367 }
1368
1369 let unicode_records = ctb_formats_unicode::get_assigned_unicode_records();
1371 let mut all_unicode_rows = Vec::with_capacity(unicode_records.len());
1372 for rec in unicode_records {
1373 let name_str = if rec.is_deprecated {
1374 format!("!{}", rec.name)
1375 } else {
1376 rec.name
1377 };
1378 let (merged_aliases, merged_desc) =
1379 if let Some((clar_aliases, clar_desc)) =
1380 unicode_clarifications.get(&rec.cp)
1381 {
1382 let a = if rec.aliases.is_empty() {
1383 format_canonical_aliases_cell(clar_aliases)
1384 } else if !clar_aliases.is_empty() {
1385 format_canonical_aliases_cell(&format!(
1386 "{}, {}",
1387 rec.aliases, clar_aliases
1388 ))
1389 } else {
1390 rec.aliases
1391 };
1392 let d = if rec.description.is_empty() {
1393 clar_desc.clone()
1394 } else if !clar_desc.is_empty() {
1395 format!("{}; {}", rec.description, clar_desc)
1396 } else {
1397 rec.description
1398 };
1399 (a, d)
1400 } else {
1401 (rec.aliases, rec.description)
1402 };
1403
1404 all_unicode_rows.push(vec![
1405 rec.cp.to_string(), format!("u{:x}", rec.cp), name_str, rec.combining_class.to_string(), rec.bidi_class.to_string(), String::new(), rec.general_category.to_string(), rec.script, merged_aliases, merged_desc, String::new(), String::new(), String::new(), String::new(), String::new(), String::new(), String::new(), String::new(), String::new(), ]);
1425 }
1426
1427 let _unicode_target_path =
1428 repo_root.join("src/formats/dcdata/data-src/unicode.generated.csv");
1429 stats.unicode_records_merged = all_unicode_rows.len();
1431
1432 let mut combined_rows = Vec::with_capacity(
1434 all_unicode_rows
1435 .len()
1436 .saturating_add(all_dc_rows.len())
1437 .saturating_add(all_format_rows.len()),
1438 );
1439
1440 combined_rows.extend(all_unicode_rows);
1441 combined_rows.extend(all_dc_rows);
1442 combined_rows.extend(all_format_rows);
1443
1444 combined_rows.sort_by(|a, b| {
1445 let id_a = a
1447 .first()
1448 .and_then(|s| s.trim().parse::<u128>().ok())
1449 .unwrap_or(u128::MAX);
1450 let id_b = b
1452 .first()
1453 .and_then(|s| s.trim().parse::<u128>().ok())
1454 .unwrap_or(u128::MAX);
1455 id_a.cmp(&id_b)
1456 });
1457
1458 let _all_target_path =
1459 repo_root.join("src/formats/dcdata/data-src/all.generated.csv");
1460 stats.total_records_merged = combined_rows.len();
1462
1463 let old_dc_json =
1465 repo_root.join("src/formats/dcdata/data-src/DcList.generated.json");
1466 if old_dc_json.exists() {
1467 let _ = fs::remove_file(&old_dc_json);
1468 }
1469 let old_fmt_json =
1470 repo_root.join("src/formats/dcdata/data-src/formats.generated.json");
1471 if old_fmt_json.exists() {
1472 let _ = fs::remove_file(&old_fmt_json);
1473 }
1474
1475 Ok(stats)
1476}
1477
1478fn escape_directive_string(s: &str) -> String {
1480 let mut res = String::with_capacity(s.len().saturating_add(4));
1481 for c in s.chars() {
1482 match c {
1483 '\\' => res.push_str("\\\\"),
1484 '"' => res.push_str("\\\""),
1485 other => res.push(other),
1486 }
1487 }
1488 res
1489}
1490
1491fn format_canonical_aliases_cell(raw: &str) -> String {
1493 if raw.trim().is_empty() {
1494 return String::new();
1495 }
1496 let mut report = crate::report::ValidationReport::new();
1497 let parsed = crate::column_spec::parse_aliases_or_base_column(
1498 raw,
1499 "",
1500 0,
1501 &mut report,
1502 false,
1503 );
1504 let mut parts = Vec::new();
1505 for fa in parsed.formal_aliases {
1506 parts.push(format!(
1507 "@formalAlias{}(\"{}\")",
1508 fa.kind,
1509 escape_directive_string(&fa.alias)
1510 ));
1511 }
1512 if let Some(ident) = parsed.rust_ident {
1513 parts.push(format!("@ident(\"{}\")", escape_directive_string(&ident)));
1514 }
1515 if parsed.stable_ident {
1516 parts.push("@stable_ident()".to_string());
1517 }
1518 if let Some(title) = parsed.title {
1519 parts.push(format!("@title(\"{}\")", escape_directive_string(&title)));
1520 }
1521 for nick in parsed.nicknames {
1522 parts.push(format!("@nick(\"{}\")", escape_directive_string(&nick)));
1523 }
1524 let mut seen_aliases = HashSet::new();
1525 for a in parsed.aliases {
1526 if seen_aliases.insert(a.to_lowercase()) {
1527 parts.push(a);
1528 }
1529 }
1530 for xr in parsed.cross_references {
1531 if xr.starts_with('>') {
1532 parts.push(xr);
1533 } else {
1534 parts.push(format!("@xref({xr})"));
1535 }
1536 }
1537 for d in parsed.decompositions {
1538 parts.push(d);
1539 }
1540 for an in parsed.annotations {
1541 parts
1542 .push(format!("@annotation(\"{}\")", escape_directive_string(&an)));
1543 }
1544 if let Some(syn) = parsed.syntax_raw {
1545 parts.push(syn);
1546 }
1547 if let Some(chain) = parsed.format_spec_raw {
1548 parts.push(chain);
1549 }
1550 if let Some(closes) = parsed.closes {
1551 parts.push(format!("@closes({closes})"));
1552 }
1553 for bo in parsed.based_on {
1554 parts.push(format!("@based_on({bo})"));
1555 }
1556 for imp in parsed.implies {
1557 parts.push(format!("@implies({imp})"));
1558 }
1559 for os in parsed.os_associations {
1560 parts.push(format!("@os({os})"));
1561 }
1562 for mn in parsed.magic_names {
1563 parts
1564 .push(format!("@magic_name(\"{}\")", escape_directive_string(&mn)));
1565 }
1566 parts.join(", ")
1567}
1568
1569fn to_snake_case(s: &str) -> String {
1570 let mut res = String::new();
1571 let mut prev_is_upper = false;
1572 for (i, c) in s.chars().enumerate() {
1573 if c.is_uppercase() {
1574 if i > 0 && !prev_is_upper {
1575 res.push('_');
1576 }
1577 res.push(c.to_ascii_lowercase());
1578 prev_is_upper = true;
1579 } else {
1580 res.push(c);
1581 prev_is_upper = false;
1582 }
1583 }
1584 res
1585}
1586
1587fn to_screaming_snake_case(s: &str) -> String {
1588 to_snake_case(s).to_ascii_uppercase()
1589}
1590
1591pub(crate) fn write_if_changed(path: &Path, content: &str) -> Result<bool> {
1592 if path.exists() {
1593 if let Ok(existing) = fs::read_to_string(path) {
1594 if existing == content {
1595 return Ok(false);
1596 }
1597 }
1598 }
1599 if let Some(parent) = path.parent() {
1600 fs::create_dir_all(parent)?;
1601 }
1602 fs::write(path, content)?;
1603 Ok(true)
1604}
1605
1606pub use ctb_build_support::dc_codegen::{generate_dc_code, generate_dc_file};
1607pub use ctb_build_support::format_id_codegen::{
1608 generate_format_id_code, generate_format_id_file,
1609};
1610
1611#[cfg(test)]
1612#[allow(
1613 clippy::panic,
1614 clippy::expect_used,
1615 clippy::unwrap_used,
1616 clippy::unwrap_in_result,
1617 clippy::panic_in_result_fn,
1618 clippy::indexing_slicing,
1619 clippy::arithmetic_side_effects,
1620 reason = "Standard repository test boilerplate"
1621)]
1622mod tests {
1623 use super::*;
1624
1625 #[crate::ctb_test]
1626 fn test_is_unassigned_id() {
1627 assert!(is_unassigned_id(""));
1628 assert!(is_unassigned_id(" "));
1629 assert!(is_unassigned_id("AUTO"));
1630 assert!(is_unassigned_id("auto"));
1631 assert!(is_unassigned_id("TBD"));
1632 assert!(is_unassigned_id("?"));
1633 assert!(is_unassigned_id("-"));
1634 assert!(is_unassigned_id("todo"));
1635 assert!(is_unassigned_id("unassigned"));
1636
1637 assert!(!is_unassigned_id("0"));
1638 assert!(!is_unassigned_id("123"));
1639 assert!(!is_unassigned_id(" 456 "));
1640 }
1641
1642 #[crate::ctb_test]
1643 fn test_no_hole_backfilling_invariant() {
1644 let temp_dir = tempfile::tempdir().unwrap();
1646 let cat_dir = temp_dir
1647 .path()
1648 .join("src/formats/dcdata/data-src/categories");
1649 fs::create_dir_all(&cat_dir).unwrap();
1650
1651 let header = vec![
1652 "Dc".to_string(),
1653 "Short".to_string(),
1654 "Name (!=deprecated)".to_string(),
1655 "◌".to_string(),
1656 "⇆".to_string(),
1657 "Aa".to_string(),
1658 "Type".to_string(),
1659 "Script".to_string(),
1660 "Aliases".to_string(),
1661 "Description".to_string(),
1662 ];
1663
1664 let rows = vec![
1665 vec![
1666 "1114112".to_string(),
1667 "0".to_string(),
1668 "Null".to_string(),
1669 "0".to_string(),
1670 "BN".to_string(),
1671 String::new(),
1672 "Cc".to_string(),
1673 ".Controls".to_string(),
1674 String::new(),
1675 String::new(),
1676 ],
1677 vec![
1678 "1114132".to_string(),
1679 "20".to_string(),
1680 "Twenty".to_string(),
1681 "0".to_string(),
1682 "BN".to_string(),
1683 String::new(),
1684 "Po".to_string(),
1685 ".Punctuation".to_string(),
1686 String::new(),
1687 String::new(),
1688 ],
1689 vec![
1690 String::new(),
1691 "AUTO".to_string(),
1692 "NewItem".to_string(),
1693 "0".to_string(),
1694 "BN".to_string(),
1695 String::new(),
1696 "Po".to_string(),
1697 ".Punctuation".to_string(),
1698 String::new(),
1699 String::new(),
1700 ],
1701 ];
1702
1703 let test_file = cat_dir.join("test.csv");
1704 write_csv_file(&test_file, &header, &rows).unwrap();
1705
1706 let stats = assign_and_update_dc_categories(temp_dir.path()).unwrap();
1707 assert_eq!(stats.new_ids_assigned, 1);
1708 assert_eq!(stats.max_short_id, 1936);
1709
1710 let (_, updated_rows) = read_csv_file(&test_file).unwrap();
1711 let auto_row = &updated_rows[2];
1712 assert_eq!(auto_row[1], "1936");
1714 assert_eq!(auto_row[0], (SHORT_DC_REGION_START + 1936).to_string());
1715 }
1716
1717 #[crate::ctb_test]
1718 fn test_script_block_allocator_alignment_overflow_increment_change_and_tbd()
1719 {
1720 let mut sizes = HashMap::new();
1721 sizes.insert(".Small".to_string(), Some(32));
1722 sizes.insert(".Large".to_string(), Some(256));
1723 sizes.insert(".Other".to_string(), Some(64));
1724 sizes.insert(".TbdScript".to_string(), None);
1725
1726 let mut alloc = ScriptBlockAllocator::from_existing(
1728 sizes.clone(),
1729 PREEXISTING_CONTIGUOUS_DC_MAX,
1730 vec![(0, ".Controls".to_string()), (1928, ".WASM".to_string())],
1731 Vec::new(),
1732 SHORT_DC_REGION_START,
1733 crate::dc::SHORT_DC_REGION_END,
1734 )
1735 .unwrap();
1736 assert_eq!(alloc.first_block_start, 1936);
1737
1738 let s0 = alloc.allocate(".Small", "test.csv", 2).unwrap();
1740 assert_eq!(s0, 1936);
1741 assert_eq!(s0 % 16, 0);
1742
1743 let l0 = alloc.allocate(".Large", "test.csv", 3).unwrap();
1745 assert_eq!(l0, 1968);
1746 assert_eq!(l0 % 16, 0);
1747
1748 for expected in 1937..1968 {
1750 let next = alloc.allocate(".Small", "test.csv", 4).unwrap();
1751 assert_eq!(next, expected);
1752 }
1753
1754 let s32 = alloc.allocate(".Small", "test.csv", 5).unwrap();
1757 assert_eq!(s32, 2224);
1758 assert_eq!(s32 % 16, 0);
1759
1760 let tbd_err = alloc
1762 .allocate(".TbdScript", "test.csv", 6)
1763 .unwrap_err()
1764 .to_string();
1765 assert!(tbd_err.contains("TBD"), "unexpected error: {tbd_err}");
1766 let unk_err = alloc
1767 .allocate(".Unknown", "test.csv", 7)
1768 .unwrap_err()
1769 .to_string();
1770 assert!(
1771 unk_err.contains("unknown script"),
1772 "unexpected error: {unk_err}"
1773 );
1774
1775 sizes.insert(".Large".to_string(), Some(128));
1777 let mut assigned = vec![
1778 (0, ".Controls".to_string()),
1779 (1928, ".WASM".to_string()),
1780 (1968, ".Large".to_string()),
1781 (2224, ".Small".to_string()),
1782 ];
1783 for id in 1936..1968 {
1784 assigned.push((id, ".Small".to_string()));
1785 }
1786 let mut shrunk_alloc = ScriptBlockAllocator::from_existing(
1787 sizes,
1788 PREEXISTING_CONTIGUOUS_DC_MAX,
1789 assigned,
1790 alloc.blocks,
1791 SHORT_DC_REGION_START,
1792 crate::dc::SHORT_DC_REGION_END,
1793 )
1794 .unwrap();
1795 let o0 = shrunk_alloc.allocate(".Other", "test.csv", 8).unwrap();
1796 assert_eq!(o0, 2256);
1797 assert_eq!(o0 % 16, 0);
1798 }
1799
1800 #[crate::ctb_test]
1801 fn test_script_block_allocator_rejects_invalid_ids() {
1802 let sizes = HashMap::from([(".Small".to_string(), Some(32))]);
1803 assert!(
1804 ScriptBlockAllocator::from_existing(
1805 sizes.clone(),
1806 1928,
1807 vec![
1808 (1936, ".Small".to_string()),
1809 (1936, ".Small".to_string())
1810 ],
1811 Vec::new(),
1812 SHORT_DC_REGION_START,
1813 crate::dc::SHORT_DC_REGION_END,
1814 )
1815 .is_err()
1816 );
1817 assert!(
1818 ScriptBlockAllocator::from_existing(
1819 sizes.clone(),
1820 1928,
1821 vec![(1_114_112, ".Small".to_string())],
1822 Vec::new(),
1823 SHORT_DC_REGION_START,
1824 crate::dc::SHORT_DC_REGION_END,
1825 )
1826 .is_err()
1827 );
1828 let mut allocator = ScriptBlockAllocator::from_existing(
1829 sizes,
1830 1928,
1831 vec![(1928, ".WASM".to_string())],
1832 Vec::new(),
1833 SHORT_DC_REGION_START,
1834 crate::dc::SHORT_DC_REGION_END,
1835 )
1836 .unwrap();
1837 allocator.max_allowed_id = 1935;
1838 assert!(allocator.allocate(".Small", "test.csv", 2).is_err());
1839 }
1840
1841 #[crate::ctb_test]
1842 fn test_script_block_allocator_csv_round_trip_and_manual_shrink() {
1843 for (region_start, region_end, cap) in [
1844 (
1845 SHORT_DC_REGION_START,
1846 crate::dc::SHORT_DC_REGION_END,
1847 PREEXISTING_CONTIGUOUS_DC_MAX,
1848 ),
1849 (
1850 FORMAT_REGION_START,
1851 crate::FORMAT_REGION_END,
1852 PREEXISTING_CONTIGUOUS_FORMAT_MAX,
1853 ),
1854 ] {
1855 let temp = tempfile::tempdir().unwrap();
1856 let path = temp.path().join("blocks.csv");
1857 let mut sizes = HashMap::from([
1858 (".Small".to_string(), Some(32)),
1859 (".Other".to_string(), Some(16)),
1860 ]);
1861 let mut allocator = ScriptBlockAllocator::load(
1862 sizes.clone(),
1863 cap,
1864 Vec::new(),
1865 &path,
1866 region_start,
1867 region_end,
1868 )
1869 .unwrap();
1870 let first = allocator.allocate(".Small", "test.csv", 2).unwrap();
1871 let second = allocator.allocate(".Small", "test.csv", 3).unwrap();
1872 let registry =
1873 allocator.registry_csv(path.clone(), region_start).unwrap();
1874 assert!(registry.modified);
1875 assert_eq!(
1876 registry.rows[0][1],
1877 format!("0x{:X}", region_start + u128::from(first))
1878 );
1879 assert_eq!((region_start + u128::from(first)) % 16, 0);
1880 let last = u128::from(first + 31) + region_start;
1881 assert_eq!(last % 16, 15);
1882 write_csv_file(&path, ®istry.header, ®istry.rows).unwrap();
1883 sizes.insert(".Small".to_string(), Some(16));
1884 let mut reloaded = ScriptBlockAllocator::load(
1885 sizes.clone(),
1886 cap,
1887 Vec::new(),
1888 &path,
1889 region_start,
1890 region_end,
1891 )
1892 .unwrap();
1893 assert!(
1894 !reloaded
1895 .registry_csv(path.clone(), region_start)
1896 .unwrap()
1897 .modified
1898 );
1899 assert_eq!(reloaded.blocks[0].end_exclusive, first + 32);
1900 assert_eq!(
1901 reloaded.allocate(".Small", "test.csv", 4).unwrap(),
1902 second + 1
1903 );
1904 assert_eq!(
1905 reloaded.allocate(".Other", "test.csv", 5).unwrap(),
1906 first + 32
1907 );
1908
1909 let mut rows = registry.rows;
1910 rows[0][2] =
1911 format!("0x{:X}", region_start + u128::from(first + 15));
1912 write_csv_file(&path, ®istry.header, &rows).unwrap();
1913 let mut shrunk = ScriptBlockAllocator::load(
1914 sizes.clone(),
1915 cap,
1916 vec![(second, ".Small".to_string())],
1917 &path,
1918 region_start,
1919 region_end,
1920 )
1921 .unwrap();
1922 assert_eq!(
1923 shrunk.allocate(".Other", "test.csv", 6).unwrap(),
1924 first + 16
1925 );
1926 assert!(
1927 ScriptBlockAllocator::load(
1928 sizes,
1929 cap,
1930 vec![(first + 16, ".Small".to_string())],
1931 &path,
1932 region_start,
1933 region_end,
1934 )
1935 .is_err()
1936 );
1937 }
1938 }
1939
1940 #[crate::ctb_test]
1941 fn test_script_block_allocator_registry_validation() {
1942 let sizes = HashMap::from([
1943 (".Small".to_string(), Some(32)),
1944 (".Other".to_string(), Some(16)),
1945 ]);
1946 let block = AllocatedScriptBlock {
1947 script: ".Small".to_string(),
1948 start: 1936,
1949 end_exclusive: 1968,
1950 max_used: 1936,
1951 };
1952 let validate = |blocks, assigned| {
1953 ScriptBlockAllocator::from_existing(
1954 sizes.clone(),
1955 PREEXISTING_CONTIGUOUS_DC_MAX,
1956 assigned,
1957 blocks,
1958 SHORT_DC_REGION_START,
1959 crate::dc::SHORT_DC_REGION_END,
1960 )
1961 };
1962 assert!(
1963 validate(vec![block.clone(), block.clone()], Vec::new()).is_err()
1964 );
1965 assert!(
1966 validate(vec![block.clone()], vec![(1937, ".Other".to_string())])
1967 .is_err()
1968 );
1969 assert!(
1970 validate(vec![block.clone()], vec![(1936, ".Unknown".to_string())])
1971 .is_err()
1972 );
1973 let mut moved =
1974 validate(vec![block.clone()], vec![(1936, ".Other".to_string())])
1975 .unwrap();
1976 assert_eq!(moved.allocate(".Small", "test.csv", 2).unwrap(), 1937);
1977 assert_eq!(moved.allocate(".Other", "test.csv", 3).unwrap(), 1968);
1978 assert!(
1979 validate(Vec::new(), vec![(1936, ".Small".to_string())]).is_err()
1980 );
1981 for invalid in [
1982 AllocatedScriptBlock {
1983 start: 1937,
1984 ..block.clone()
1985 },
1986 AllocatedScriptBlock {
1987 end_exclusive: 1967,
1988 ..block.clone()
1989 },
1990 AllocatedScriptBlock {
1991 max_used: 1968,
1992 ..block.clone()
1993 },
1994 AllocatedScriptBlock {
1995 max_used: 1934,
1996 ..block.clone()
1997 },
1998 AllocatedScriptBlock {
1999 start: 1920,
2000 ..block.clone()
2001 },
2002 AllocatedScriptBlock {
2003 end_exclusive: 1_114_128,
2004 ..block.clone()
2005 },
2006 AllocatedScriptBlock {
2007 script: ".Unknown".to_string(),
2008 ..block.clone()
2009 },
2010 ] {
2011 assert!(validate(vec![invalid], Vec::new()).is_err());
2012 }
2013 let final_block = AllocatedScriptBlock {
2014 start: 1_114_096,
2015 end_exclusive: 1_114_112,
2016 max_used: 1_114_110,
2017 ..block
2018 };
2019 let mut allocator = validate(vec![final_block], Vec::new()).unwrap();
2020 assert_eq!(
2021 allocator.allocate(".Small", "test.csv", 2).unwrap(),
2022 1_114_111
2023 );
2024 allocator.first_block_start = 1_114_096;
2025 assert!(allocator.allocate(".Small", "test.csv", 3).is_err());
2026 }
2027
2028 #[crate::ctb_test]
2029 fn test_script_block_allocator_rejected_updates_leave_files_unchanged() {
2030 for formats in [false, true] {
2031 let temp = tempfile::tempdir().unwrap();
2032 let data = temp.path().join("src/formats/dcdata/data-src");
2033 let categories = data.join("categories");
2034 let directory = if formats {
2035 categories.join("formats")
2036 } else {
2037 categories
2038 };
2039 fs::create_dir_all(&directory).unwrap();
2040 let path = directory.join("test.csv");
2041 let (header, script, region_start) = if formats {
2042 (
2043 vec!["Dc", "Short", "Ident", "Name", "Category"],
2044 "encoding",
2045 FORMAT_REGION_START,
2046 )
2047 } else {
2048 (
2049 vec![
2050 "Dc",
2051 "Short",
2052 "Name",
2053 "Combining",
2054 "Bidi",
2055 "Case",
2056 "Type",
2057 "Script",
2058 ],
2059 ".Controls",
2060 SHORT_DC_REGION_START,
2061 )
2062 };
2063 let header =
2064 header.into_iter().map(str::to_string).collect::<Vec<_>>();
2065 let make_row = |id: &str| {
2066 let mut row = vec![String::new(); header.len()];
2067 row[1] = id.to_string();
2068 row[2] = "Test".to_string();
2069 *row.last_mut().unwrap() = script.to_string();
2070 row
2071 };
2072 for ids in [
2073 ["0", "0"],
2074 ["0", "1114112"],
2075 ["0", "18446744073709551616"],
2076 ["0", "1937"],
2077 ] {
2078 write_csv_file(&path, &header, &ids.map(make_row)).unwrap();
2079 let before = fs::read(&path).unwrap();
2080 let result = if formats {
2081 assign_and_update_format_categories(temp.path())
2082 } else {
2083 assign_and_update_dc_categories(temp.path())
2084 };
2085 assert!(result.is_err(), "accepted invalid IDs {ids:?}");
2086 assert_eq!(fs::read(&path).unwrap(), before);
2087 assert!(
2088 !data
2089 .join(if formats {
2090 "README.format-blocks.csv"
2091 } else {
2092 "README.dc-blocks.csv"
2093 })
2094 .exists()
2095 );
2096 }
2097 let mut rows = vec![
2098 make_row(if formats { "f0" } else { "0" }),
2099 make_row("AUTO"),
2100 ];
2101 rows[0][0] = region_start.to_string();
2102 write_csv_file(&path, &header, &rows).unwrap();
2103 if formats {
2104 assign_and_update_format_categories(temp.path()).unwrap();
2105 } else {
2106 assign_and_update_dc_categories(temp.path()).unwrap();
2107 }
2108 let before = fs::read(&path).unwrap();
2109 let stats = if formats {
2110 assign_and_update_format_categories(temp.path()).unwrap()
2111 } else {
2112 assign_and_update_dc_categories(temp.path()).unwrap()
2113 };
2114 assert_eq!(stats.files_modified, 0);
2115 assert_eq!(fs::read(&path).unwrap(), before);
2116 let (_, rows) = read_csv_file(&path).unwrap();
2117 assert_eq!(rows[0][1], if formats { "f0" } else { "0" });
2118 }
2119 }
2120
2121 #[crate::ctb_test]
2122 fn test_codegen_from_system_graph() {
2123 let manifest = Path::new(env!("CARGO_MANIFEST_DIR"));
2124 let repo_root = find_repository_root_from(manifest).unwrap();
2125 let graph_dir = repo_root.join("assets/data/graph");
2126
2127 let dc_code = generate_dc_code(&graph_dir).unwrap();
2128 assert!(
2129 dc_code.contains(
2130 "pub const DC_RANGE: DcChar = DcChar::from_short(4);"
2131 ),
2132 "dc_code did not contain DC_RANGE"
2133 );
2134 let role_code =
2135 ctb_build_support::dc_codegen::generate_role_code(&graph_dir)
2136 .unwrap();
2137 assert!(
2138 role_code.contains("BeginNumber,"),
2139 "role_code did not contain BeginNumber"
2140 );
2141
2142 let fmt_code = generate_format_id_code(&graph_dir).unwrap();
2143 assert!(
2144 fmt_code.contains("Self::Utf8 => \"f0\","),
2145 "fmt_code did not map Utf8 to f0"
2146 );
2147 }
2148
2149 #[crate::ctb_test]
2150 fn test_generate_format_id_file() {
2151 let manifest = Path::new(env!("CARGO_MANIFEST_DIR"));
2152 let updated = generate_format_id_file(manifest).unwrap();
2153 println!("format_id.generated.rs generated: {updated}");
2154 let dc_updated = generate_dc_file(manifest).unwrap();
2155 println!("dc.generated.rs generated: {dc_updated}");
2156 let repo_root = find_repository_root_from(manifest).unwrap();
2157 let merged = generate_merged_csvs(&repo_root).unwrap();
2158 println!("merged csvs generated: {merged:?}");
2159 }
2160}