1#[allow(
24 unused_imports,
25 clippy::wildcard_imports,
26 reason = "Standard workspace module prelude"
27)]
28use crate::utilities::*;
29
30use anyhow::{Context, Result};
31use ctb_formats_dcdata::dc::{
32 DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID, SHORT_DC_REGION_START,
33};
34use ctb_formats_dcdata::dc_char::DcCharExt;
35use ctb_formats_dcdata::syntax::{DcRole, SyntaxRuleResolver};
36use ctb_formats_eite::transform::DocumentTransformation;
37use ctb_formats_utilities::FormatLog;
38use ctb_utilities::format_id::FormatId;
39
40use super::dctext::{DcList, dcarray_to_dclist, dclist_to_dcarray};
41use crate::{DcChar, DcMixedChunk, DcMstr, DcMstring};
42
43fn format_unicode_sequence(tokens: &[u128]) -> String {
44 let mut parts = Vec::with_capacity(tokens.len());
45 for &cp in tokens {
46 parts.push(format!("U+{cp:04X}"));
47 }
48 parts.join(" ")
49}
50
51pub fn transform_dclist_unicode_to_short_dc(
55 dclist: &[u128],
56 log: &mut FormatLog,
57) -> DcList {
58 let resolver = ctb_formats_dcdata::syntax::default_syntax_resolver();
59 let mut out = Vec::with_capacity(dclist.len());
60 let mut i = 0;
61
62 while let Some(remaining) = dclist.get(i..) {
63 let Some(&first) = remaining.first() else {
64 break;
65 };
66 if let Some((short_dc_gid, consumed_len)) =
67 resolver.equivalent_short_dc_for_unicode(remaining)
68 {
69 let short_id = short_dc_gid.saturating_sub(SHORT_DC_REGION_START);
70 let idx_u64 = u64::try_from(i).unwrap_or(0);
72 let matched = remaining.get(..consumed_len).unwrap_or(&[]);
74 let seq_desc = format_unicode_sequence(matched);
75 log.export_warning(
76 idx_u64,
77 &format!(
78 "Replaced Unicode {seq_desc} with equivalent short Dc {short_id}"
79 ),
80 );
81 out.push(short_dc_gid);
82 i = i.saturating_add(consumed_len.max(1));
83 } else {
84 out.push(first);
85 i = i.saturating_add(1);
86 }
87 }
88
89 out
90}
91
92pub fn apply_dc_transformation(
98 doc: &DcMstr,
99 transformation: SupportedDcTransformation,
100) -> Result<(DcMstring, FormatLog)> {
101 let mut out = DcMstring::new();
102 let mut log = FormatLog::default();
103
104 if transformation == SupportedDcTransformation::AddSystemGraphMostRecent {
105 let already_has_most_recent = matches!(
106 doc.chunks().next(),
107 Some(DcMixedChunk::Text(first_text))
108 if first_text.chars().next()
109 == Some(DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID)
110 );
111 if already_has_most_recent {
112 return Ok((doc.to_owned(), log));
113 }
114 out.push_system_graph_most_recent()?;
115 for chunk in doc.chunks() {
116 out.push_chunk(&chunk)?;
117 }
118 return Ok((out, log));
119 }
120
121 if transformation == SupportedDcTransformation::StageL3ToWasm {
122 let wasm_doc = crate::navigator::apply_graph_dc_transformation_format(
123 doc,
124 ctb_utilities::format_id::FormatId::StageL3ToWasm,
125 )?;
126 return Ok((wasm_doc, log));
127 }
128
129 if transformation == SupportedDcTransformation::StageR3ToStageL3 {
130 let stagel_doc = crate::navigator::apply_graph_dc_transformation_format(
131 doc,
132 ctb_utilities::format_id::FormatId::StageR3ToStageL3,
133 )?;
134 return Ok((stagel_doc, log));
135 }
136
137 if transformation == SupportedDcTransformation::SemanticToText {
138 let default_res = ctb_formats_dcdata::syntax::default_syntax_resolver();
139 let lowered =
140 apply_semantic_to_text_with_resolver(doc, default_res.as_ref())?;
141 return Ok((lowered, log));
142 }
143
144 for chunk in doc.chunks() {
145 if let DcMixedChunk::Text(text) = chunk {
146 let dclist = text.to_dclist();
147 let transformed_dclist = match transformation {
148 SupportedDcTransformation::AddSystemGraphMostRecent
149 | SupportedDcTransformation::StageL3ToWasm
150 | SupportedDcTransformation::StageR3ToStageL3
151 | SupportedDcTransformation::SemanticToText => {
152 dclist
153 }
154 SupportedDcTransformation::UnicodeToShortDc => {
155 transform_dclist_unicode_to_short_dc(&dclist, &mut log)
156 }
157 SupportedDcTransformation::CodeToText => {
158 let dca_conv = dclist_to_dcarray(&dclist)?;
159 log.merge(&dca_conv.log);
160 let transformed_dca =
161 DocumentTransformation::code_to_text_default()
162 .apply(&dca_conv.result)?;
163 let list_conv = dcarray_to_dclist(&transformed_dca)?;
164 log.merge(&list_conv.log);
165 list_conv.result
166 }
167 };
168 for dc in transformed_dclist {
169 out.push_char(DcChar::from_u128(dc));
170 }
171 } else {
172 out.push_chunk(&chunk)?;
173 }
174 }
175
176 Ok((out, log))
177}
178
179pub fn apply_semantic_to_text_with_resolver(
188 doc: &DcMstr,
189 resolver: &dyn SyntaxRuleResolver,
190) -> Result<DcMstring> {
191 let f19_dc = DcChar::from_u128(
192 FormatId::SemanticToText
193 .dc_id()
194 .context("FormatId::SemanticToText missing assigned Format Dc ID")?,
195 );
196 let mut pinned_holder: Option<
197 std::sync::Arc<ctb_formats_dcdata::syntax::DatasetRuleResolver>,
198 > = None;
199 if let Some(DcMixedChunk::Text(first_text)) = doc.chunks().next() {
200 let first_chars: Vec<DcChar> = first_text.chars().take(16).collect();
201 if let Some(pin_id) = scan_leading_pin_id(&first_chars, resolver)
202 && let Ok(pinned) =
203 ctb_formats_dcdata::syntax::syntax_resolver_at_most_recent(
204 pin_id,
205 )
206 {
207 pinned_holder = Some(pinned);
208 }
209 }
210 let active_resolver: &dyn SyntaxRuleResolver =
211 if let Some(ref pinned) = pinned_holder {
212 pinned.as_ref()
213 } else {
214 resolver
215 };
216
217 let mut out = DcMstring::new();
218 let mut is_first_text = true;
219 for chunk in doc.chunks() {
220 if let DcMixedChunk::Text(text) = chunk {
221 let chars: Vec<DcChar> = text.chars().collect();
222 if chars.is_empty() {
223 is_first_text = false;
224 continue;
225 }
226 if let Some(lowered_chunk) =
227 crate::converters::wasm::run_graph_stager_dcs_routine_with_quota(
228 f19_dc,
229 &chars,
230 active_resolver,
231 None,
232 )?
233 {
234 for sub_chunk in lowered_chunk.chunks() {
235 out.push_chunk(&sub_chunk)?;
236 }
237 } else {
238 let lowered_chars = lower_semantic_tokens_historical_fallback(
239 &chars,
240 active_resolver,
241 is_first_text,
242 );
243 for ch in lowered_chars {
244 out.push_char(ch);
245 }
246 }
247 is_first_text = false;
248 } else {
249 out.push_chunk(&chunk)?;
250 }
251 }
252 Ok(out)
253}
254
255fn scan_leading_pin_id(
256 chars: &[DcChar],
257 resolver: &dyn SyntaxRuleResolver,
258) -> Option<u128> {
259 let mut idx = skip_comment_frames(chars, 0, resolver);
260 let first = chars.get(idx).copied()?;
261 if !first
262 .fills_role_with(DcRole::GlobalGraphSystemBlockMostRecentNodeId, resolver)
263 {
264 return None;
265 }
266 idx = idx.saturating_add(1);
267 let next = chars.get(idx).copied()?;
268 let target = if next.fills_role_with(DcRole::Escape, resolver)
269 || next.fills_role_with(DcRole::QuoteFollowingDcAsAtom, resolver)
270 {
271 chars.get(idx.saturating_add(1)).copied()?
272 } else {
273 next
274 };
275 let gid = target.to_u128();
276 (ctb_storage_minimal::global_graph_layout::SYSTEM_REGION_START
277 ..=ctb_storage_minimal::global_graph_layout::SYSTEM_REGION_END)
278 .contains(&gid)
279 .then_some(gid)
280}
281
282fn skip_comment_frames(
283 chars: &[DcChar],
284 start: usize,
285 resolver: &dyn SyntaxRuleResolver,
286) -> usize {
287 let mut i = start;
288 while let Some(&tok) = chars.get(i) {
289 let is_single = tok.fills_role_with(DcRole::BeginSingleLineComment, resolver)
290 || tok.fills_role_with(DcRole::BeginSingleLineCommentNewLine, resolver);
291 let is_block = tok.fills_role_with(DcRole::BeginBlockComment, resolver)
292 || tok.fills_role_with(DcRole::BeginBlockCommentNewLine, resolver);
293 if !is_single && !is_block {
294 break;
295 }
296 let close_role = if is_single {
297 DcRole::EndSingleLineComment
298 } else {
299 DcRole::EndBlockComment
300 };
301 let saved = i;
302 i = i.saturating_add(1);
303 let mut closed = false;
304 while let Some(&inner) = chars.get(i) {
305 if inner.fills_role_with(DcRole::Escape, resolver)
306 || inner.fills_role_with(DcRole::QuoteFollowingDcAsAtom, resolver)
307 {
308 let i1 = i.saturating_add(1);
309 if inner.fills_role_with(DcRole::QuoteFollowingDcAsAtom, resolver)
310 && chars
311 .get(i1)
312 .is_some_and(|nx| nx.fills_role_with(DcRole::Escape, resolver))
313 {
314 i = i.saturating_add(3).min(chars.len());
315 } else {
316 i = i.saturating_add(2).min(chars.len());
317 }
318 continue;
319 }
320 i = i.saturating_add(1);
321 if inner.fills_role_with(close_role, resolver) {
322 closed = true;
323 break;
324 }
325 }
326 if !closed {
327 return saved;
328 }
329 }
330 i
331}
332
333fn resolve_single_dc_historical_teletype(
334 ch: DcChar,
335 resolver: &dyn SyntaxRuleResolver,
336 out: &mut Vec<DcChar>,
337) {
338 let gid = ch.to_u128();
339 if gid <= 0x10_FFFF {
340 if let Ok(cp) = u32::try_from(gid)
341 && char::from_u32(cp).is_some()
342 {
343 out.push(ch);
344 } else {
345 out.push(DcChar::from('\u{FFFD}'));
346 }
347 return;
348 }
349 let canon = resolver.canonical_token(gid);
350 if canon <= 0x10_FFFF
351 && let Ok(cp) = u32::try_from(canon)
352 && char::from_u32(cp).is_some()
353 {
354 out.push(DcChar::from_u128(canon));
355 return;
356 }
357 if let Some(mapped) = resolver.unicode_text_mapping(gid, true) {
358 for uc in mapped.chars() {
359 out.push(DcChar::from(uc));
360 }
361 return;
362 }
363 if ch.fills_role_with(DcRole::BeginDocument, resolver)
364 || ch.fills_role_with(DcRole::EndDocument, resolver)
365 || resolver.matches_named_type_starter("text_encoding_control", gid)
366 || resolver.matches_script(".Styling", gid)
367 || resolver.matches_script(".Colors", gid)
368 || resolver.matches_script(".DCE", gid)
369 || resolver.matches_script(".DCE sheets", gid)
370 || resolver.matches_script(".DCE versions", gid)
371 {
372 return;
373 }
374 out.push(DcChar::from('\u{FFFD}'));
375}
376
377fn lower_semantic_tokens_historical_fallback(
378 chars: &[DcChar],
379 resolver: &dyn SyntaxRuleResolver,
380 strip_leading_pin: bool,
381) -> Vec<DcChar> {
382 let mut pos = skip_comment_frames(chars, 0, resolver);
383 if strip_leading_pin
384 && let Some(first) = chars.get(pos).copied()
385 && first.fills_role_with(
386 DcRole::GlobalGraphSystemBlockMostRecentNodeId,
387 resolver,
388 )
389 && let Some(arg) = chars.get(pos.saturating_add(1)).copied()
390 {
391 if arg.fills_role_with(DcRole::Escape, resolver)
392 || arg.fills_role_with(DcRole::QuoteFollowingDcAsAtom, resolver)
393 {
394 if chars.get(pos.saturating_add(2)).is_some() {
395 pos = pos.saturating_add(3);
396 }
397 } else {
398 pos = pos.saturating_add(2);
399 }
400 }
401
402 let mut out = Vec::with_capacity(chars.len().saturating_sub(pos));
403 while pos < chars.len() {
404 pos = skip_comment_frames(chars, pos, resolver);
405 let Some(&tok) = chars.get(pos) else {
406 break;
407 };
408 if tok.fills_role_with(DcRole::Escape, resolver)
409 || tok.fills_role_with(DcRole::QuoteFollowingDcAsAtom, resolver)
410 {
411 let p1 = pos.saturating_add(1);
412 let Some(&nx) = chars.get(p1) else {
413 out.push(DcChar::from('\u{FFFD}'));
414 break;
415 };
416 let (escaped_ch, next_pos) =
417 if tok.fills_role_with(DcRole::QuoteFollowingDcAsAtom, resolver)
418 && nx.fills_role_with(DcRole::Escape, resolver)
419 && let Some(&nx2) = chars.get(pos.saturating_add(2))
420 {
421 (nx2, pos.saturating_add(3))
422 } else {
423 (nx, p1.saturating_add(1))
424 };
425 resolve_single_dc_historical_teletype(escaped_ch, resolver, &mut out);
426 pos = next_pos;
427 continue;
428 }
429 if tok.fills_role_with(DcRole::BeginErrorRecord, resolver) {
430 for b in "[error: ".chars() {
431 out.push(DcChar::from(b));
432 }
433 let mut ei = pos.saturating_add(1);
434 while let Some(&ech) = chars.get(ei) {
435 if ech.fills_role_with(DcRole::EndErrorRecord, resolver) {
436 ei = ei.saturating_add(1);
437 break;
438 }
439 let actual = if ech.fills_role_with(DcRole::Escape, resolver) {
440 if let Some(&nx) = chars.get(ei.saturating_add(1)) {
441 ei = ei.saturating_add(2);
442 nx
443 } else {
444 ei = chars.len();
445 ech
446 }
447 } else {
448 ei = ei.saturating_add(1);
449 ech
450 };
451 resolve_single_dc_historical_teletype(actual, resolver, &mut out);
452 }
453 out.push(DcChar::from(']'));
454 out.push(DcChar::from('\n'));
455 pos = ei;
456 continue;
457 }
458 resolve_single_dc_historical_teletype(tok, resolver, &mut out);
459 pos = pos.saturating_add(1);
460 }
461 out
462}
463
464pub fn apply_dc_transformations(
469 doc: &DcMstr,
470 transformations: &[SupportedDcTransformation],
471) -> Result<(DcMstring, FormatLog)> {
472 let mut current = doc.to_owned();
473 let mut total_log = FormatLog::default();
474 for &tr in transformations {
475 let (next, step_log) = apply_dc_transformation(¤t, tr)?;
476 total_log.merge(&step_log);
477 current = next;
478 }
479 Ok((current, total_log))
480}
481
482#[cfg(test)]
483#[allow(
484 clippy::panic,
485 clippy::expect_used,
486 clippy::unwrap_used,
487 clippy::unwrap_in_result,
488 clippy::panic_in_result_fn,
489 clippy::indexing_slicing,
490 clippy::arithmetic_side_effects,
491 reason = "Standard repository test boilerplate"
492)]
493mod tests {
494 use super::*;
495
496 #[crate::ctb_test]
497 fn test_unicode_to_short_dc_ascii_and_special_mappings() {
498 let mut log = FormatLog::default();
499 let input = vec![0x41, 0x2D, 0x2010, 0x26BD, 0xFE0F, 0x26BD, 0x03B1];
501 let out = transform_dclist_unicode_to_short_dc(&input, &mut log);
502 assert_eq!(
503 out,
504 vec![
505 SHORT_DC_REGION_START + 50,
506 SHORT_DC_REGION_START + 233,
507 SHORT_DC_REGION_START + 31,
508 SHORT_DC_REGION_START + 283,
509 SHORT_DC_REGION_START + 281,
510 0x03B1,
511 ]
512 );
513 assert_eq!(log.get_warnings().len(), 5);
514 assert!(log.get_warnings()[0].contains("U+0041"));
515 assert!(log.get_warnings()[0].contains("short Dc 50"));
516 assert!(log.get_warnings()[3].contains("U+26BD U+FE0F"));
517 assert!(log.get_warnings()[3].contains("short Dc 283"));
518 }
519
520 #[crate::ctb_test]
521 fn test_add_system_graph_most_recent_transformation() -> Result<()> {
522 let mut doc = DcMstring::new();
523 doc.push_char(DcChar::from_u128(0x41));
524 doc.push_char(DcChar::from_u128(0x42));
525
526 let expected_wm =
527 ctb_formats_dcdata::seed_graph::current_system_block_most_recent_node_id()?;
528 let (stamped, log) = apply_dc_transformation(
529 &doc,
530 SupportedDcTransformation::AddSystemGraphMostRecent,
531 )?;
532 assert!(!log.has_warnings());
533
534 let Some(DcMixedChunk::Text(first_text)) = stamped.chunks().next()
535 else {
536 panic!("Expected text chunk at start of stamped document");
537 };
538 let chars: Vec<DcChar> = first_text.chars().collect();
539 assert_eq!(
540 chars,
541 vec![
542 DC_GLOBAL_GRAPH_SYSTEM_BLOCK_MOST_RECENT_NODE_ID,
543 DcChar::from_u128(expected_wm),
544 DcChar::from_u128(0x41),
545 DcChar::from_u128(0x42),
546 ]
547 );
548
549 let (stamped_again, _) = apply_dc_transformation(
551 &stamped,
552 SupportedDcTransformation::AddSystemGraphMostRecent,
553 )?;
554 assert_eq!(stamped_again.as_bytes(), stamped.as_bytes());
555 Ok(())
556 }
557
558 #[crate::ctb_test]
559 fn test_stagel3_to_wasm_document_transformation() -> Result<()> {
560 let sg = ctb_formats_dcdata::SeedGraphIndex::shared()?;
561 let sl3_src = r#"
562v/l/u8/step l/u8/input
563 concat b"[" concat l/u8/input b"]".
564"#;
565 let tokens = ctb_formats_dcdata::stagel3::seed_linker::sl3_to_dc_tokens_with_seed_graph(
566 sl3_src, sg,
567 )?;
568 let mut stagel_doc = DcMstring::new();
569 for tok in tokens {
570 stagel_doc.push_char(tok);
571 }
572
573 let (wasm_doc, log) = apply_dc_transformation(
574 &stagel_doc,
575 SupportedDcTransformation::StageL3ToWasm,
576 )?;
577 assert!(!log.has_warnings());
578
579 let mut input = DcMstring::new();
580 input.push_char(DcChar::from_u128(0x6F));
581 input.push_char(DcChar::from_u128(0x6B));
582 let out = crate::converters::wasm::run_dc_wasm_pure_conversion(
583 &wasm_doc, &input,
584 )?;
585 let out_u128s: Vec<u128> =
586 out.to_dc_string()?.chars().map(DcChar::to_u128).collect();
587 assert_eq!(out_u128s, vec![0x5B, 0x6F, 0x6B, 0x5D]);
588 Ok(())
589 }
590
591 #[crate::ctb_test]
592 fn test_stager3_to_stagel3_and_wasm_document_transformations() -> Result<()> {
593 let sg = ctb_formats_dcdata::SeedGraphIndex::shared()?;
594 let sr3_src = r#"ns app/stager_pipe.
595
596brand u32/tag.
597
598struct boxPair
599 tag/id.
600 i32/delta.
601
602enum op
603 keep.
604 i32/shift.
605
606v/result/i32/applyOp boxPair/bp op/act
607 const u32/raw unwrap field /bp id.
608 const i32/base conv? /raw i32.
609 const i32/sum add? /base field /bp delta.
610 match /act
611 case keep result/i32:ok /sum.
612 case shift i32/s add /sum /s.
613 ::.
614
615pub v/l/u8/step l/u8/input
616 const boxPair/bp structNew boxPair:
617 delta i32:-5
618 id wrap u32:40 tag
619 ::.
620 const result/i32/res applyOp /bp op:shift i32:7.
621 if isOk /res
622 do
623 const i32/v unwrapOr okOr get l/i32: i32:42 :: u64:0 error:unexpectedNone i32:0.
624 if and eq /res result/i32:ok i32:42 eq /v i32:42
625 concat b"<" concat /input b">"
626 b"bad"
627 ::
628 b"err".
629"#;
630 let sr_tokens =
631 ctb_formats_dcdata::stagel3::seed_linker::sr3_to_dc_tokens_with_seed_graph(
632 sr3_src, sg,
633 )?;
634 let mut stager_doc = DcMstring::new();
635 for tok in sr_tokens {
636 stager_doc.push_char(tok);
637 }
638
639 let (stagel_doc, log1) = apply_dc_transformation(
641 &stager_doc,
642 SupportedDcTransformation::StageR3ToStageL3,
643 )?;
644 assert!(!log1.has_warnings());
645 let stagel_tokens: Vec<DcChar> = stagel_doc.to_dc_string()?.chars().collect();
646 let _validated =
647 ctb_formats_dcdata::stagel3::seed_linker::validate_dc_tokens_with_seed_graph(
648 &stagel_tokens,
649 sg,
650 )?;
651
652 let (wasm_doc, log_chain) = apply_dc_transformations(
654 &stager_doc,
655 &[
656 SupportedDcTransformation::StageR3ToStageL3,
657 SupportedDcTransformation::StageL3ToWasm,
658 ],
659 )?;
660 assert!(!log_chain.has_warnings());
661
662 let mut input = DcMstring::new();
663 input.push_char(DcChar::from_u128(0x68));
664 input.push_char(DcChar::from_u128(0x69));
665 let out = crate::converters::wasm::run_dc_wasm_pure_conversion(
666 &wasm_doc, &input,
667 )?;
668 let out_u128s: Vec<u128> =
669 out.to_dc_string()?.chars().map(DcChar::to_u128).collect();
670 assert_eq!(out_u128s, vec![0x3C, 0x68, 0x69, 0x3E]);
671 Ok(())
672 }
673
674 #[crate::ctb_test]
675 fn test_semantic_to_text_lowers_short_dcs_and_preserves_binary_chunks() -> Result<()> {
676 let mut doc = DcMstring::new();
677 doc.push_char(DcChar::from_short(57));
680 doc.push_char(DcChar::from_short(90));
681 doc.push_char(DcChar::from_short(120));
682 doc.push_binary(&[0xDE, 0xAD]);
683 doc.push_char(DcChar::from_short(19));
684
685 let (lowered, log) = apply_dc_transformation(
686 &doc,
687 SupportedDcTransformation::SemanticToText,
688 )?;
689 assert!(!log.has_warnings());
690 let chunks: Vec<DcMixedChunk<'_>> = lowered.chunks().collect();
691 assert_eq!(chunks.len(), 3);
692 let Some(DcMixedChunk::Text(prefix)) = chunks.first() else {
693 bail!("expected leading text chunk");
694 };
695 let prefix_u128s: Vec<u128> =
696 prefix.chars().map(DcChar::to_u128).collect();
697 assert_eq!(prefix_u128s, vec![0x48, 0x69, 0x0A]);
698 let Some(
699 DcMixedChunk::Binary { data, .. }
700 | DcMixedChunk::BinaryWithMetadata { data, .. },
701 ) = chunks.get(1)
702 else {
703 bail!("expected middle binary chunk");
704 };
705 assert_eq!(*data, [0xDE, 0xAD]);
706 let Some(DcMixedChunk::Text(suffix)) = chunks.get(2) else {
707 bail!("expected trailing text chunk");
708 };
709 let suffix_u128s: Vec<u128> =
710 suffix.chars().map(DcChar::to_u128).collect();
711 assert_eq!(suffix_u128s, vec![0x21]);
712 Ok(())
713 }
714}