1use crate::ctbnbdl::CtbnbdlFramingDcs;
25use crate::graph_index::{
26 BuildGraphIndex, BuildSeedEntity,
27 resolve_ctbnbdl_framing_dcs_from_graph_dir,
28};
29use crate::license_consts::DEFAULT_AGPL_HEADER;
30use crate::shorthand::DcShorthand;
31use anyhow::{Context, Result, bail, ensure};
32use std::collections::{BTreeSet, HashSet};
33use std::fs;
34use std::path::Path;
35
36#[derive(Debug, Clone)]
37struct DcConstRecord {
38 short_id: u32,
39 ident: String,
40 name: String,
41 description: String,
42}
43
44fn is_valid_rust_ident(ident: &str) -> bool {
46 if ident.is_empty() {
47 return false;
48 }
49 let mut chars = ident.chars();
50 let Some(first) = chars.next() else {
51 return false;
52 };
53 if !first.is_ascii_alphabetic() && first != '_' {
54 return false;
55 }
56 chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
57}
58
59#[must_use]
61pub fn to_screaming_snake_case(ident: &str) -> String {
62 if ident.chars().all(|c| !c.is_ascii_lowercase()) {
63 return ident.to_string();
64 }
65
66 let chars: Vec<char> = ident.chars().collect();
67 let mut out = String::with_capacity(ident.len().saturating_add(4));
68
69 for (i, &ch) in chars.iter().enumerate() {
70 if ch == '_' {
71 if !out.ends_with('_') {
72 out.push('_');
73 }
74 continue;
75 }
76 if i > 0 && ch.is_ascii_uppercase() {
77 let prev = chars.get(i.saturating_sub(1)).copied();
78 let next = chars.get(i.saturating_add(1)).copied();
79 let prev_is_lower_or_digit = prev
80 .is_some_and(|p| p.is_ascii_lowercase() || p.is_ascii_digit());
81 let prev_is_upper = prev.is_some_and(|p| p.is_ascii_uppercase());
82 let next_is_lower = next.is_some_and(|n| n.is_ascii_lowercase());
83
84 if (prev_is_lower_or_digit || (prev_is_upper && next_is_lower))
85 && !out.ends_with('_')
86 {
87 out.push('_');
88 }
89 }
90 out.push(ch.to_ascii_uppercase());
91 }
92
93 out
94}
95
96fn collect_dc_const_records(
98 index: &BuildGraphIndex,
99) -> Result<Vec<DcConstRecord>> {
100 let sh_name = index.require_ident("CanonicalName")?;
101 let sh_desc = index.require_ident("Description")?;
102
103 let mut records = Vec::new();
104 let mut seen_idents = HashSet::new();
105 let mut seen_shorts = HashSet::new();
106
107 for short_id in index.all_short_dc_ids()? {
108 let subj = DcShorthand::Short(short_id);
109 let Some(ident_raw) = index.ident_for_shorthand(subj) else {
110 continue;
111 };
112 let ident = ident_raw.trim().to_string();
113 ensure!(
114 is_valid_rust_ident(&ident),
115 "Invalid @ident(\"{ident}\") on Dc {short_id}"
116 );
117 let const_name = format!("DC_{}", to_screaming_snake_case(&ident));
118 if !seen_idents.insert(const_name.clone()) {
119 bail!(
120 "Duplicate @ident(\"{ident}\") (constant {const_name}) on Dc {short_id}"
121 );
122 }
123 if !seen_shorts.insert(short_id) {
124 bail!("Duplicate short ID {short_id} with @ident(\"{ident}\")");
125 }
126 let name = index
128 .single_property_string(subj, sh_name)
129 .unwrap_or_default()
130 .trim()
131 .to_string();
132 let description = index
134 .single_property_string(subj, sh_desc)
135 .unwrap_or_default()
136 .trim()
137 .to_string();
138
139 records.push(DcConstRecord {
140 short_id,
141 ident,
142 name,
143 description,
144 });
145 }
146
147 records.sort_by_key(|r| r.short_id);
148 Ok(records)
149}
150
151fn collect_pending_csv_dc_const_records(
152 categories_dir: &Path,
153 records: &mut Vec<DcConstRecord>,
154) -> Result<()> {
155 if !categories_dir.is_dir() {
156 return Ok(());
157 }
158 let mut seen_shorts: HashSet<u32> =
159 records.iter().map(|r| r.short_id).collect();
160 let mut seen_idents: HashSet<String> = records
161 .iter()
162 .map(|r| format!("DC_{}", to_screaming_snake_case(&r.ident)))
163 .collect();
164
165 let mut entries: Vec<_> = fs::read_dir(categories_dir)?
166 .filter_map(std::result::Result::ok)
167 .map(|e| e.path())
168 .filter(|p| p.extension().and_then(|s| s.to_str()) == Some("csv"))
169 .collect();
170 entries.sort();
171
172 for path in entries {
173 let mut rdr = csv::ReaderBuilder::new()
174 .has_headers(true)
175 .flexible(true)
176 .from_path(&path)?;
177 for result in rdr.records() {
178 let row = result?;
179 let Some(short_str) = row.get(1).map(str::trim) else {
180 continue;
181 };
182 let Ok(short_id) = short_str.parse::<u32>() else {
183 continue;
184 };
185 if seen_shorts.contains(&short_id) {
186 continue;
187 }
188 let Some(xrefs) = row.get(8) else {
189 continue;
190 };
191 let Some(ident_start) = xrefs.find("@ident(\"") else {
192 continue;
193 };
194 let Some(after_prefix) = xrefs.get(ident_start.saturating_add(8)..)
195 else {
196 continue;
197 };
198 let Some(ident_end) = after_prefix.find("\")") else {
199 continue;
200 };
201 let Some(ident_slice) = after_prefix.get(..ident_end) else {
202 continue;
203 };
204 let ident = ident_slice.trim().to_string();
205 if !is_valid_rust_ident(&ident) {
206 continue;
207 }
208 let const_name = format!("DC_{}", to_screaming_snake_case(&ident));
209 if !seen_idents.insert(const_name) {
210 continue;
211 }
212 seen_shorts.insert(short_id);
213 let name = row.get(2).unwrap_or("").trim().to_string();
215 let description = row.get(9).unwrap_or("").trim().to_string();
217 records.push(DcConstRecord {
218 short_id,
219 ident,
220 name,
221 description,
222 });
223 }
224 }
225 records.sort_by_key(|r| r.short_id);
226 Ok(())
227}
228
229fn format_dc_code_from_records(records: &[DcConstRecord]) -> String {
230 let mut out = String::new();
231 out.push_str(DEFAULT_AGPL_HEADER);
232 out.push_str("\n\n");
233 out.push_str(
234 "//! Constants and definitions for Document Character (Dc) data.\n",
235 );
236 out.push_str(
237 "//! @generated by ctb-build-support::dc_codegen from category data tables.\n",
238 );
239 out.push_str("//! Do not edit by hand.\n\n");
240 out.push_str(
241 "#[allow(\n unused_imports,\n clippy::wildcard_imports,\n reason = \"Standard workspace module prelude\"\n)]\nuse crate::utilities::*;\n\n",
242 );
243 out.push_str(
244 "pub use ctb_storage_minimal::global_graph_layout::{\n SHORT_DC_REGION_END, SHORT_DC_REGION_START,\n};\n\n",
245 );
246 out.push_str("pub use crate::dc_char::DcChar;\n\n");
247
248 for rec in records {
249 let const_name = to_screaming_snake_case(&rec.ident);
250 let doc = if rec.description.is_empty() {
251 &rec.name
252 } else {
253 &rec.description
254 };
255 let doc_clean = doc.replace('\n', " ").replace('\r', "");
256 out.push_str(&format!(
257 "/// {} (Dc {}).\npub const DC_{}: DcChar = DcChar::from_short({});\n",
258 doc_clean, rec.short_id, const_name, rec.short_id
259 ));
260 }
261
262 out.push_str(
263 "\n/// Converts a short Document Character (Dc) ID to its long (Global Graph) ID.\n",
264 );
265 out.push_str("#[must_use]\n");
266 out.push_str("pub fn short_to_long_dc(short_id: u32) -> u128 {\n");
267 out.push_str(
268 " SHORT_DC_REGION_START.saturating_add(u128::from(short_id))\n",
269 );
270 out.push_str("}\n\n");
271
272 out.push_str(
273 "/// Converts a long (Global Graph) Document Character ID to its short Dc ID, if within short range.\n",
274 );
275 out.push_str("#[must_use]\n");
276 out.push_str("pub fn long_to_short_dc(dc_id: u128) -> Option<u32> {\n");
277 out.push_str(
278 " if (SHORT_DC_REGION_START..=SHORT_DC_REGION_END).contains(&dc_id) {\n",
279 );
280 out.push_str(
281 " u32::try_from(dc_id.saturating_sub(SHORT_DC_REGION_START)).ok()\n",
282 );
283 out.push_str(" } else {\n");
284 out.push_str(" None\n");
285 out.push_str(" }\n");
286 out.push_str("}\n");
287
288 out
289}
290
291pub fn generate_dc_code_from_index(index: &BuildGraphIndex) -> Result<String> {
296 let records = collect_dc_const_records(index)?;
297 Ok(format_dc_code_from_records(&records))
298}
299
300pub fn generate_dc_code(graph_dir: &Path) -> Result<String> {
305 let index = BuildGraphIndex::from_graph_dir(graph_dir)?;
306 let mut records = collect_dc_const_records(&index)?;
307 if let Ok(repo_root) = crate::find_repository_root_from(graph_dir) {
308 let categories_dir = repo_root
309 .join("src")
310 .join("formats")
311 .join("dcdata")
312 .join("data-src")
313 .join("categories");
314 collect_pending_csv_dc_const_records(&categories_dir, &mut records)?;
315 }
316 Ok(format_dc_code_from_records(&records))
317}
318
319pub fn generate_dc_file(base_dir: &Path) -> Result<bool> {
324 let repo_root = crate::find_repository_root_from(base_dir)?;
325 let graph_dir = repo_root.join("assets").join("data").join("graph");
326 let out_file = repo_root
327 .join("src")
328 .join("formats")
329 .join("dcdata")
330 .join("dc.generated.rs");
331
332 ensure!(
333 graph_dir.is_dir(),
334 "Could not locate system graph directory at {}",
335 graph_dir.display()
336 );
337
338 let code = generate_dc_code(&graph_dir)?;
339
340 if let Ok(existing) = fs::read_to_string(&out_file) {
341 if existing == code {
342 return Ok(false);
343 }
344 }
345
346 fs::write(&out_file, code)
347 .with_context(|| format!("Failed to write {}", out_file.display()))?;
348 Ok(true)
349}
350
351fn format_short_id_pattern(ids: &BTreeSet<u32>) -> String {
353 let mut ranges: Vec<(u32, u32)> = Vec::new();
354 for &id in ids {
355 if let Some(last) = ranges.last_mut() {
356 if id == last.1.saturating_add(1) {
357 last.1 = id;
358 continue;
359 }
360 }
361 ranges.push((id, id));
362 }
363
364 let parts: Vec<String> = ranges
365 .into_iter()
366 .map(|(start, end)| {
367 if start == end {
368 format!("{start}")
369 } else if end == start.saturating_add(1) {
370 format!("{start} | {end}")
371 } else {
372 format!("{start}..={end}")
373 }
374 })
375 .collect();
376
377 if parts.is_empty() {
378 "u32::MAX".to_string()
379 } else {
380 parts.join(" | ")
381 }
382}
383
384pub fn generate_role_code_from_index(
389 index: &BuildGraphIndex,
390) -> Result<String> {
391 let records = collect_dc_const_records(index)?;
392
393 let require_short = |ident: &str| -> Result<u32> {
394 let sh = index.require_ident(ident)?;
395 let DcShorthand::Short(sid) = sh else {
396 bail!("Expected Short Dc for @ident(\"{ident}\"), found {sh}");
397 };
398 Ok(sid)
399 };
400
401 let base64_start = require_short("Base64Start")?;
402 let base64_end = require_short("Base64End")?;
403 let base64_padding = require_short("Base64Padding")?;
404 ensure!(
405 base64_start <= base64_end,
406 "Base64Start ({base64_start}) must be <= Base64End ({base64_end})"
407 );
408 let base64_digits: BTreeSet<u32> = (base64_start..=base64_end).collect();
409
410 let mut type_tokens: BTreeSet<u32> = BTreeSet::new();
413 for short_id in index.all_short_dc_ids()? {
414 let subj = DcShorthand::Short(short_id);
415 if matches!(
416 index.subject_script(subj),
417 Some(".EM Types" | ".EL Types" | ".Semantic:Ontological")
418 ) {
419 type_tokens.insert(short_id);
420 }
421 }
422 for ident in [
423 "TypeUnion",
424 "FilePathDelimiter",
425 "TypeIntersection",
426 "FormatParamApplication",
427 "ValueRange",
428 ] {
429 type_tokens.insert(require_short(ident)?);
430 }
431
432 let sh_syntax_rule = index.require_ident("SyntaxRule")?;
436 let sh_subpat = index.require_ident("SubpatternMatch")?;
437 let mut evaluable_starters: BTreeSet<u32> = BTreeSet::new();
438 for short_id in index.all_short_dc_ids()? {
439 let subj = DcShorthand::Short(short_id);
440 if matches!(
441 index.subject_script(subj),
442 Some(
443 ".EM Routines"
444 | ".EM Builtins"
445 | ".EL Routines"
446 | ".EL Builtins"
447 )
448 ) {
449 evaluable_starters.insert(short_id);
450 }
451 }
452 if let Some(val_seed_id) = index
453 .seed_node_id(&BuildSeedEntity::NamedConstruct("value".to_string()))
454 {
455 if let Some(DcShorthand::Long(rule_node_id)) = index
456 .single_property(DcShorthand::Long(val_seed_id), sh_syntax_rule)
457 {
458 if let Some(tokens) = index.node_tokens(rule_node_id) {
459 for window in tokens.windows(2) {
460 if let &[op, DcShorthand::Short(sid)] = window {
461 if op == sh_subpat {
462 evaluable_starters.insert(sid);
463 }
464 }
465 }
466 }
467 }
468 }
469 for ident in [
470 "EquivalentRepresentations",
471 "PartiallyEquivalentRepresentations",
472 ] {
473 evaluable_starters.insert(require_short(ident)?);
474 }
475
476 let base64_digits_pat = format_short_id_pattern(&base64_digits);
477 let type_tokens_pat = format_short_id_pattern(&type_tokens);
478 let evaluable_starters_pat = format_short_id_pattern(&evaluable_starters);
479
480 let mut out = String::new();
481 out.push_str(DEFAULT_AGPL_HEADER);
482 out.push_str("\n\n");
483 out.push_str(
484 "//! Document Character (Dc) syntactic and semantic role classifications.\n",
485 );
486 out.push_str("//!\n");
487 out.push_str(
488 "//! @generated by ctb-build-support::dc_codegen from category data tables.\n",
489 );
490 out.push_str("//! Do not edit by hand.\n\n");
491 out.push_str(
492 "#[allow(\n unused_imports,\n clippy::wildcard_imports,\n reason = \"Standard workspace module prelude\"\n)]\nuse crate::utilities::*;\n\n",
493 );
494 out.push_str(
495 "use ctb_utilities::dc_char::{FORMAT_REGION_END, FORMAT_REGION_START};\n",
496 );
497 out.push_str("use serde::{Deserialize, Serialize};\n\n");
498
499 out.push_str(
500 "/// Classification of syntactic framing and semantic roles for Document\n",
501 );
502 out.push_str("/// Characters.\n");
503 out.push_str(
504 "#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]\n",
505 );
506 out.push_str("pub enum DcRole {\n");
507
508 for rec in &records {
509 let doc = if rec.description.is_empty() {
510 &rec.name
511 } else {
512 &rec.description
513 };
514 let doc_clean = doc.replace('\n', " ").replace('\r', "");
515 out.push_str(&format!(
516 " /// {} (`{}`).\n {},\n",
517 doc_clean, rec.short_id, rec.ident
518 ));
519 }
520
521 out.push_str(
522 " /// Base64 encapsulation digit character (0..=63).\n\
523 Base64Digit,\n\
524 /// Built-in type token, format token, or type operator.\n\
525 TypeToken,\n\
526 /// Expression starter token that can be evaluated (`.EM Routines`, references, invocations, representation sets).\n\
527 EvaluableExpressionStarter,\n\
528}\n\n"
529 );
530
531 out.push_str("impl DcRole {\n");
532 out.push_str(
533 " /// Returns the defining short Dc ID for this role, if uniquely defined by a single Document Character.\n\
534#[must_use]\n\
535pub fn defining_short(self) -> Option<u32> {\n\
536match self {\n"
537 );
538 for rec in &records {
539 out.push_str(&format!(
540 " Self::{} => Some({}),\n",
541 rec.ident, rec.short_id
542 ));
543 }
544 out.push_str(
545 " _ => None,\n\
546}\n\
547}\n\n\
548 /// Returns the defining `DcChar` for this role, if uniquely defined by a single Document Character.\n\
549#[must_use]\n\
550pub fn defining_dc(self) -> Option<DcChar> {\n\
551self.defining_short().map(DcChar::from_short)\n\
552}\n\n\
553 /// Returns true if the given canonical token (in global graph `u128` layout)\n\
554/// directly matches this role.\n\
555#[must_use]\n\
556pub fn matches_canonical(self, token: u128) -> bool {\n\
557let short = DcChar::from_u128(token).to_short().ok();\n\
558match self {\n"
559 );
560 for rec in &records {
561 out.push_str(&format!(
562 " Self::{} => short == Some({}),\n",
563 rec.ident, rec.short_id
564 ));
565 }
566 out.push_str(&format!(
567 " Self::Base64Digit => matches!(short, Some({base64_digits_pat})),\n\
568Self::TypeToken => {{\n\
569(FORMAT_REGION_START..=FORMAT_REGION_END).contains(&token)\n\
570|| matches!(short, Some({type_tokens_pat}))\n\
571}}\n\
572Self::EvaluableExpressionStarter => {{\n\
573matches!(short, Some({evaluable_starters_pat}))\n\
574}}\n\
575}}\n\
576}}\n\n\
577 /// Returns the Base64 numeral digit value (`0..=63`) or padding sentinel\n\
578/// (`64`) if `token` represents a Base64 encapsulation character.\n\
579#[must_use]\n\
580pub fn base64_digit_value(token: u128) -> Option<u8> {{\n\
581let short = DcChar::from_u128(token).to_short().ok()?;\n\
582if short == {base64_padding} {{\n\
583Some(64)\n\
584}} else if ({base64_start}..={base64_end}).contains(&short) {{\n\
585u8::try_from(short.saturating_sub({base64_start})).ok()\n\
586}} else {{\n\
587None\n\
588}}\n\
589}}\n\
590}}\n"
591 ));
592
593 Ok(out)
594}
595
596pub fn generate_role_code(graph_dir: &Path) -> Result<String> {
601 let index = BuildGraphIndex::from_graph_dir(graph_dir)?;
602 generate_role_code_from_index(&index)
603}
604
605pub fn generate_role_file(base_dir: &Path) -> Result<bool> {
610 let repo_root = crate::find_repository_root_from(base_dir)?;
611 let graph_dir = repo_root.join("assets").join("data").join("graph");
612 let out_file = repo_root
613 .join("src")
614 .join("formats")
615 .join("dcdata")
616 .join("syntax")
617 .join("role.generated.rs");
618
619 ensure!(
620 graph_dir.is_dir(),
621 "Could not locate system graph directory at {}",
622 graph_dir.display()
623 );
624
625 let code = generate_role_code(&graph_dir)?;
626
627 if let Ok(existing) = fs::read_to_string(&out_file) {
628 if existing == code {
629 return Ok(false);
630 }
631 }
632
633 fs::write(&out_file, code)
634 .with_context(|| format!("Failed to write {}", out_file.display()))?;
635 Ok(true)
636}
637
638pub fn resolve_ctbnbdl_framing_dcs(
643 graph_dir: &Path,
644) -> Result<CtbnbdlFramingDcs> {
645 resolve_ctbnbdl_framing_dcs_from_graph_dir(graph_dir)
646}
647
648#[cfg(test)]
649#[allow(
650 clippy::panic,
651 clippy::expect_used,
652 clippy::unwrap_used,
653 clippy::unwrap_in_result,
654 clippy::panic_in_result_fn,
655 clippy::indexing_slicing,
656 clippy::arithmetic_side_effects,
657 reason = "Standard repository test boilerplate"
658)]
659mod tests {
660 use super::*;
661
662 #[test]
663 fn test_to_screaming_snake_case() {
664 assert_eq!(to_screaming_snake_case("BeginNumber"), "BEGIN_NUMBER");
665 assert_eq!(
666 to_screaming_snake_case("StartEncapsulationUtf8"),
667 "START_ENCAPSULATION_UTF8"
668 );
669 assert_eq!(to_screaming_snake_case("LangSay"), "LANG_SAY");
670 assert_eq!(to_screaming_snake_case("LongDc"), "LONG_DC");
671 assert_eq!(to_screaming_snake_case("ALREADY_UPPER"), "ALREADY_UPPER");
672 }
673
674 #[test]
675 fn test_generate_dc_code_succeeds() {
676 let manifest = Path::new(env!("CARGO_MANIFEST_DIR"));
677 let repo_root = crate::find_repository_root_from(manifest).unwrap();
678 let graph_dir = repo_root.join("assets").join("data").join("graph");
679
680 let code = generate_dc_code(&graph_dir).unwrap();
681 assert!(
682 code.contains(
683 "pub const DC_RANGE: DcChar = DcChar::from_short(4);"
684 )
685 );
686 assert!(code.contains(
687 "pub const DC_LONG_DC: DcChar = DcChar::from_short(308);"
688 ));
689 assert!(code.contains("pub fn short_to_long_dc("));
690 assert!(code.contains("pub fn long_to_short_dc("));
691 }
692
693 #[test]
694 fn test_generate_role_code_succeeds() {
695 let manifest = Path::new(env!("CARGO_MANIFEST_DIR"));
696 let repo_root = crate::find_repository_root_from(manifest).unwrap();
697 let graph_dir = repo_root.join("assets").join("data").join("graph");
698
699 let code = generate_role_code(&graph_dir).unwrap();
700 assert!(code.contains("pub enum DcRole {"));
701 assert!(code.contains("BeginNumber,"));
702 assert!(code.contains("BeginLiteral,"));
703 assert!(code.contains("TypeToken,"));
704 assert!(code.contains("EvaluableExpressionStarter,"));
705 assert!(
706 code.contains(
707 "pub fn matches_canonical(self, token: u128) -> bool"
708 )
709 );
710 assert!(
711 code.contains(
712 "pub fn base64_digit_value(token: u128) -> Option<u8>"
713 )
714 );
715 }
716
717 #[test]
718 fn test_resolve_ctbnbdl_framing_dcs_succeeds() {
719 let manifest = Path::new(env!("CARGO_MANIFEST_DIR"));
720 let repo_root = crate::find_repository_root_from(manifest).unwrap();
721 let graph_dir = repo_root.join("assets").join("data").join("graph");
722
723 let framing = resolve_ctbnbdl_framing_dcs(&graph_dir).unwrap();
724 assert_eq!(framing.begin_node, DcShorthand::Short(617));
725 assert_eq!(framing.end_node, DcShorthand::Short(618));
726 assert_eq!(framing.escape, DcShorthand::Short(255));
727 assert_eq!(framing.evaluate_as_atom, DcShorthand::Short(616));
728 assert_eq!(framing.has_a, DcShorthand::Short(584));
729 assert_eq!(framing.has_value, DcShorthand::Short(610));
730 assert_eq!(framing.preferred, DcShorthand::Short(570));
731 assert_eq!(framing.supersedes, DcShorthand::Short(591));
732 assert_eq!(framing.retracts, DcShorthand::Short(592));
733 assert_eq!(framing.enclosing_document, DcShorthand::Short(615));
734 assert_eq!(framing.is_instance_of, DcShorthand::Short(586));
735 assert_eq!(framing.is_subtype_of, DcShorthand::Short(587));
736 assert_eq!(framing.is_based_on, DcShorthand::Short(588));
737 assert_eq!(framing.is_deprecated, DcShorthand::Short(589));
738 assert_eq!(framing.is_closing_delimiter_for, DcShorthand::Short(590));
739 assert_eq!(framing.is_associated_with, DcShorthand::Short(598));
740 }
741}