1#[allow(
28 unused_imports,
29 clippy::wildcard_imports,
30 reason = "Standard workspace module prelude"
31)]
32use crate::utilities::*;
33
34pub use ctb_formats_dcdata::stagel3::ast::StageDialect;
35pub use ctb_formats_dcdata::stagel3::{
36 ast, dc_tokens, eval, parser, seed_linker, stager_strings, validator,
37};
38pub mod rust_codegen;
39pub mod wasm_codegen;
40
41#[must_use]
44pub const fn is_sli3_byte(b: u8) -> bool {
45 matches!(b, b'A'..=b'Z' | b'/' | b':' | b' ' | b'\n' | b'"' | b'.')
46}
47
48fn hex_nibble_value(b: u8) -> Option<u8> {
49 match b {
50 b'0'..=b'9' => Some(b.saturating_sub(b'0')),
51 b'a'..=b'f' => Some(b.saturating_sub(b'a').saturating_add(10)),
52 b'A'..=b'F' => Some(b.saturating_sub(b'A').saturating_add(10)),
53 _ => None,
54 }
55}
56
57fn push_sli3_hex_byte_escape(byte: u8, out: &mut Vec<u8>) {
60 let hi = b'A'.saturating_add(byte >> 4);
61 let lo = b'A'.saturating_add(byte & 0x0F);
62 out.extend_from_slice(&[b'/', b'X', hi, lo]);
63}
64
65fn push_sli3_digit_token(digit_byte: u8, out: &mut Vec<u8>) {
67 let shifted = b'A'.saturating_add(digit_byte.saturating_sub(b'0'));
68 out.extend_from_slice(&[b'N', b':', shifted, b':']);
69}
70
71fn push_comment_char_escape(raw: u8, out: &mut Vec<u8>) {
75 out.extend_from_slice(b":CHAR:");
76 for dec_byte in raw.to_string().bytes() {
77 let shifted = b'A'.saturating_add(dec_byte.saturating_sub(b'0'));
78 out.push(shifted);
79 }
80 out.push(b':');
81}
82
83fn normalize_byte_or_dcts_literal(
84 input: &[u8],
85 pos: &mut usize,
86 allow_raw_utf8: bool,
87 prefix: &[u8],
88 out: &mut Vec<u8>,
89) -> Result<()> {
90 out.extend_from_slice(prefix);
91 while let Some(&b) = input.get(*pos) {
92 *pos = pos.saturating_add(1);
93 match b {
94 b'"' => {
95 out.push(b'"');
96 return Ok(());
97 }
98 b'\r' | b'\n' => {
99 bail!("Unescaped newline in quoted literal");
100 }
101 b'/' => {
102 let esc = *input
103 .get(*pos)
104 .context("Truncated '/' escape at end of quoted literal")?;
105 *pos = pos.saturating_add(1);
106 match esc {
107 b'"' => out.extend_from_slice(b"/\""),
108 b'/' => out.extend_from_slice(b"//"),
109 b'0' => push_sli3_hex_byte_escape(0x00, out),
110 b'a' => out.extend_from_slice(b"/A"),
111 b'b' => out.extend_from_slice(b"/B"),
112 b't' => out.extend_from_slice(b"/T"),
113 b'n' => out.extend_from_slice(b"/N"),
114 b'v' => out.extend_from_slice(b"/V"),
115 b'f' => out.extend_from_slice(b"/F"),
116 b'r' => out.extend_from_slice(b"/R"),
117 b'x' => {
118 let h0 = *input.get(*pos).context(
119 "Expected two hex digits after '/x' in quoted literal",
120 )?;
121 let h1 = *input.get(pos.saturating_add(1)).context(
122 "Expected second hex digit after '/x' in quoted literal",
123 )?;
124 *pos = pos.saturating_add(2);
125 let n0 = hex_nibble_value(h0).with_context(|| {
126 format!(
127 "Invalid hex digit '{}' in '/x' escape",
128 char::from(h0)
129 )
130 })?;
131 let n1 = hex_nibble_value(h1).with_context(|| {
132 format!(
133 "Invalid hex digit '{}' in '/x' escape",
134 char::from(h1)
135 )
136 })?;
137 push_sli3_hex_byte_escape((n0 << 4) | n1, out);
138 }
139 other => bail!(
140 "Invalid '/' escape '/{}' in quoted literal",
141 char::from(other)
142 ),
143 }
144 }
145 b'A'..=b'Z' | b' ' | b':' | b'.' => out.push(b),
146 0x21..=0x7E => push_sli3_hex_byte_escape(b, out),
147 0x80..=0xFF if allow_raw_utf8 => push_sli3_hex_byte_escape(b, out),
148 other => bail!(
149 "Disallowed raw byte 0x{other:02X} in quoted literal (use /x{:02x} or a slash escape)",
150 other
151 ),
152 }
153 }
154 bail!("Unclosed quoted literal")
155}
156
157pub fn decode_sli3_byte_literal_body(body: &[u8]) -> Result<Vec<u8>> {
164 let mut out = Vec::new();
165 let mut pos = 0usize;
166 while let Some(&b) = body.get(pos) {
167 pos = pos.saturating_add(1);
168 if b == b'/' {
169 let esc = *body
170 .get(pos)
171 .context("Truncated '/' escape in normalized byte literal")?;
172 pos = pos.saturating_add(1);
173 match esc {
174 b'"' => out.push(b'"'),
175 b'/' => out.push(b'/'),
176 b'A' => out.push(0x07),
177 b'B' => out.push(0x08),
178 b'T' => out.push(0x09),
179 b'N' => out.push(0x0A),
180 b'V' => out.push(0x0B),
181 b'F' => out.push(0x0C),
182 b'R' => out.push(0x0D),
183 b'X' => {
184 let hi = *body.get(pos).context(
185 "Truncated '/X' escape in normalized byte literal",
186 )?;
187 let lo = *body.get(pos.saturating_add(1)).context(
188 "Truncated '/X' escape in normalized byte literal",
189 )?;
190 pos = pos.saturating_add(2);
191 ensure!(
192 matches!(hi, b'A'..=b'P') && matches!(lo, b'A'..=b'P'),
193 "Invalid '/X' nibble letters in normalized byte literal"
194 );
195 out.push(((hi.saturating_sub(b'A')) << 4) | lo.saturating_sub(b'A'));
196 }
197 other => bail!(
198 "Invalid normalized escape '/{}' in byte literal",
199 char::from(other)
200 ),
201 }
202 } else {
203 ensure!(
204 matches!(b, b'A'..=b'Z' | b' ' | b':' | b'.'),
205 "Unexpected unescaped byte 0x{b:02X} in normalized byte literal"
206 );
207 out.push(b);
208 }
209 }
210 Ok(out)
211}
212
213pub fn normalize(input: &[u8]) -> Result<Vec<u8>> {
220 normalize_with_dialect(input, StageDialect::StageL3)
221}
222
223pub fn normalize_stager3(input: &[u8]) -> Result<Vec<u8>> {
230 let _ = std::str::from_utf8(input)
231 .context("StageR 3 source must be valid UTF-8")?;
232 normalize_with_dialect(input, StageDialect::StageR3)
233}
234
235pub fn normalize_with_dialect(
240 input: &[u8],
241 dialect: StageDialect,
242) -> Result<Vec<u8>> {
243 let mut out = Vec::with_capacity(input.len());
244 let mut pos = 0usize;
245 let mut at_line_start = true;
246 let mut at_expr_boundary = true;
247
248 while let Some(&raw) = input.get(pos) {
249 if raw == b'\r' {
251 pos = pos.saturating_add(1);
252 if input.get(pos) == Some(&b'\n') {
253 pos = pos.saturating_add(1);
254 }
255 out.push(b'\n');
256 at_line_start = true;
257 at_expr_boundary = true;
258 continue;
259 }
260 if raw == b'\n' {
261 pos = pos.saturating_add(1);
262 out.push(b'\n');
263 at_line_start = true;
264 at_expr_boundary = true;
265 continue;
266 }
267
268 if at_line_start && raw == b':' {
271 let next = input.get(pos.saturating_add(1)).copied();
272 if matches!(next, None | Some(b' ' | b'\r' | b'\n')) {
273 out.push(b':');
274 pos = pos.saturating_add(1);
275 while let Some(&cb) = input.get(pos) {
276 if cb == b'\r' {
277 pos = pos.saturating_add(1);
278 if input.get(pos) == Some(&b'\n') {
279 pos = pos.saturating_add(1);
280 }
281 out.push(b'\n');
282 break;
283 }
284 if cb == b'\n' {
285 pos = pos.saturating_add(1);
286 out.push(b'\n');
287 break;
288 }
289 pos = pos.saturating_add(1);
290 match cb {
291 b'a'..=b'z' => out.push(cb.to_ascii_uppercase()),
292 b'A'..=b'Z' | b' ' | b'.' | b'/' | b':' => out.push(cb),
293 b';' => out.push(b'.'),
294 b'0'..=b'9' => push_sli3_digit_token(cb, &mut out),
295 other => push_comment_char_escape(other, &mut out),
296 }
297 }
298 at_line_start = true;
299 at_expr_boundary = true;
300 continue;
301 }
302 }
303
304 if raw == b' ' {
305 pos = pos.saturating_add(1);
306 out.push(b' ');
307 at_expr_boundary = true;
308 continue;
309 }
310
311 at_line_start = false;
312
313 if at_expr_boundary
315 && matches!(raw, b'b' | b'B')
316 && input.get(pos.saturating_add(1)) == Some(&b'"')
317 {
318 pos = pos.saturating_add(2);
319 normalize_byte_or_dcts_literal(
320 input, &mut pos, false, b"B\"", &mut out,
321 )?;
322 at_expr_boundary = false;
323 continue;
324 }
325
326 if raw == b'"' {
328 ensure!(
329 at_expr_boundary,
330 "Unexpected '\"' attached directly to preceding token in StageL/StageR source"
331 );
332 ensure!(
333 dialect == StageDialect::StageR3,
334 "Bare '\"...\"' Dcts string literals belong to StageR 3; use b\"...\" (bytes) in StageL 3"
335 );
336 pos = pos.saturating_add(1);
337 normalize_byte_or_dcts_literal(input, &mut pos, true, b"\"", &mut out)?;
338 at_expr_boundary = false;
339 continue;
340 }
341
342 pos = pos.saturating_add(1);
343 match raw {
344 b';' | b'.' => {
345 out.push(b'.');
346 at_expr_boundary = true;
347 }
348 b'}' => {
349 out.extend_from_slice(b"::");
350 at_expr_boundary = true;
351 }
352 b':' => {
353 out.push(b':');
354 if input.get(pos) == Some(&b'-')
355 && input
356 .get(pos.saturating_add(1))
357 .is_some_and(u8::is_ascii_digit)
358 {
359 pos = pos.saturating_add(1);
360 out.extend_from_slice(b"N:M:");
361 at_expr_boundary = false;
362 } else {
363 at_expr_boundary = true;
364 }
365 }
366 b'/' => {
367 out.push(b'/');
368 at_expr_boundary = false;
369 }
370 b'?' => {
371 ensure!(
372 dialect == StageDialect::StageR3,
373 "'?' error-propagation alias belongs to StageR 3; StageL 3 does not use '?'"
374 );
375 let prev_is_alnum = pos
376 .checked_sub(2)
377 .and_then(|i| input.get(i))
378 .is_some_and(u8::is_ascii_alphanumeric);
379 let next_byte = input.get(pos).copied();
380 let next_is_delim = matches!(
381 next_byte,
382 None | Some(b' ' | b'\r' | b'\n' | b'.' | b';' | b'}')
383 ) || (next_byte == Some(b':')
384 && input.get(pos.saturating_add(1)) == Some(&b':'));
385 ensure!(
386 !at_expr_boundary && prev_is_alnum && next_is_delim,
387 "'?' in StageR 3 is only valid as a trailing error-propagation suffix on a verb or value reference"
388 );
389 out.push(b'/');
390 at_expr_boundary = false;
391 }
392 b'a'..=b'z' => {
393 out.push(raw.to_ascii_uppercase());
394 at_expr_boundary = false;
395 }
396 b'A'..=b'Z' => {
397 out.push(raw);
398 at_expr_boundary = false;
399 }
400 b'0'..=b'9' => {
401 push_sli3_digit_token(raw, &mut out);
402 at_expr_boundary = false;
403 }
404 other => {
405 bail!("Disallowed byte 0x{other:02X} in StageL/StageR source");
406 }
407 }
408 }
409
410 Ok(out)
411}
412
413#[cfg(test)]
414#[allow(
415 clippy::panic,
416 clippy::expect_used,
417 clippy::unwrap_used,
418 clippy::unwrap_in_result,
419 clippy::panic_in_result_fn,
420 clippy::indexing_slicing,
421 clippy::arithmetic_side_effects,
422 reason = "Standard repository test boilerplate"
423)]
424mod tests {
425 use super::*;
426 use crate::get_stagel_data;
427
428 #[crate::ctb_test]
429 fn test_normalize_sl3_fixtures() {
430 let input = get_stagel_data("fixtures/sl3/input.sl3")
431 .unwrap_or_else(|| panic!("Failed to load fixtures/sl3/input.sl3"));
432 let expected = get_stagel_data("fixtures/sl3/output.sli3")
433 .unwrap_or_else(|| {
434 panic!("Failed to load fixtures/sl3/output.sli3")
435 });
436
437 let normalized = normalize(&input).unwrap();
438 assert!(
439 normalized.iter().copied().all(is_sli3_byte),
440 "Every normalized .sli3 byte must belong to the 32-character StageL 3 alphabet"
441 );
442 assert_eq!(
443 String::from_utf8_lossy(&normalized),
444 String::from_utf8_lossy(&expected)
445 );
446 }
447
448 #[crate::ctb_test]
449 fn test_normalize_sr3_fixtures() {
450 let input = get_stagel_data("fixtures/sr3/input.sr3")
451 .unwrap_or_else(|| panic!("Failed to load fixtures/sr3/input.sr3"));
452 let expected = get_stagel_data("fixtures/sr3/output.sri3")
453 .unwrap_or_else(|| {
454 panic!("Failed to load fixtures/sr3/output.sri3")
455 });
456
457 let normalized = normalize_stager3(&input).unwrap();
458 assert!(
459 normalized.iter().copied().all(is_sli3_byte),
460 "Every normalized .sri3 byte must belong to the 32-character intermediate alphabet"
461 );
462 assert_eq!(
463 String::from_utf8_lossy(&normalized),
464 String::from_utf8_lossy(&expected)
465 );
466 }
467
468 #[crate::ctb_test]
469 fn test_normalize_comments_braces_semicolons_and_alphabet() -> Result<()> {
470 let src = b": Line 1 comment with \"quotes\", braces {}, and 42!\r\n :\r\nv/u32/id u32/x :: do u32/x; }\n";
471 let norm = normalize(src)?;
472 assert!(norm.iter().copied().all(is_sli3_byte));
473 let text = std::str::from_utf8(&norm)?;
474 assert!(!text.lines().next().unwrap().contains('"'));
476 assert_eq!(text.lines().nth(1), Some(" :"));
478 assert_eq!(
480 text.lines().nth(2),
481 Some("V/UN:D:N:C:/ID UN:D:N:C:/X :: DO UN:D:N:C:/X. ::")
482 );
483 assert!(normalize(b"v/void/bad { ::\n").is_err());
485 let signed = normalize(b"i32:-2147483648.\n")?;
488 assert!(signed.iter().copied().all(is_sli3_byte));
489 assert_eq!(
490 std::str::from_utf8(&signed)?,
491 "IN:D:N:C::N:M:N:C:N:B:N:E:N:H:N:E:N:I:N:D:N:G:N:E:N:I:.\n"
492 );
493 assert!(normalize(b"v/u32/foo-bar :: u32:0.\n").is_err());
494 Ok(())
495 }
496
497 #[crate::ctb_test]
498 fn test_normalize_bytes_and_dcts_literals_preserve_semantics() -> Result<()> {
499 assert!(normalize(b"t\"abc\"").is_err());
501 assert!(normalize_stager3(b"t\"abc\"").is_err());
502
503 let b_src = b"b\"Abc/0/x1a/x5c/n/\"//\"";
505 let b_norm = normalize(b_src)?;
506 assert!(b_norm.iter().copied().all(is_sli3_byte));
507 assert_eq!(
508 std::str::from_utf8(&b_norm)?,
509 "B\"A/XGC/XGD/XAA/XBK/XFM/N/\"//\""
510 );
511 let body = &b_norm[2..b_norm.len() - 1];
513 let decoded = decode_sli3_byte_literal_body(body)?;
514 assert_eq!(decoded, vec![b'A', b'b', b'c', 0x00, 0x1A, 0x5C, b'\n', b'"', b'/']);
515
516 assert!(normalize(b"\"hello @256@\"").is_err());
518 let sr_norm = normalize_stager3("s/x \"Hi @256@!\".\n".as_bytes())?;
519 assert!(sr_norm.iter().copied().all(is_sli3_byte));
520 let q_start = sr_norm.iter().position(|&c| c == b'"').unwrap();
521 let q_end = sr_norm.iter().rposition(|&c| c == b'"').unwrap();
522 let sr_decoded =
523 decode_sli3_byte_literal_body(&sr_norm[q_start + 1..q_end])?;
524 assert_eq!(std::str::from_utf8(&sr_decoded)?, "Hi @256@!");
525
526 assert!(normalize(b"add? /x /y.\n").is_err());
529 let sr_q = normalize_stager3(b"add? /x get? /xs /idx;\ndo? /optVar? }\n")?;
530 let sr_slash =
531 normalize_stager3(b"add/ /x get/ /xs /idx.\ndo/ /optVar/ ::\n")?;
532 assert_eq!(sr_q, sr_slash);
533 assert!(normalize_stager3(b"?bad.\n").is_err());
534 assert!(normalize_stager3(b"foo?bar.\n").is_err());
535 assert!(normalize_stager3(b"u32?:1.\n").is_err());
536 Ok(())
537 }
538
539 #[crate::ctb_test]
540 fn test_normalize_sr3_protects_dcts_strings_paths_and_comments() -> Result<()> {
541 let src = concat!(
542 ": \"quoted\"; } inside s/comment dcs/comment\n",
543 "const s/empty \"\".\n",
544 "const s/msg \"Hi @256@ /\" // /n; } café\".\n",
545 "const dcs/key dcsFromS? \"abc\".\n",
546 );
547 let norm = normalize_stager3(src.as_bytes())?;
548 assert!(
549 norm.iter().copied().all(is_sli3_byte),
550 "normalized .sri3 bytes must stay strictly within the 32-char alphabet"
551 );
552 let norm_str = std::str::from_utf8(&norm)?;
553 let lines: Vec<&str> = norm_str.lines().collect();
554 assert_eq!(lines.len(), 4);
555 assert!(!lines[0].contains('"'));
556 assert!(lines[0].contains(":CHAR:"));
557 assert!(lines[0].ends_with("S/COMMENT DCS/COMMENT"));
558 assert_eq!(lines[1], "CONST S/EMPTY \"\".");
559 assert!(lines[2].starts_with("CONST S/MSG \""));
560 let msg_start = lines[2].find('"').unwrap();
561 let msg_end = lines[2].rfind('"').unwrap();
562 let decoded =
563 decode_sli3_byte_literal_body(&lines[2].as_bytes()[msg_start + 1..msg_end])?;
564 assert_eq!(
565 std::str::from_utf8(&decoded)?,
566 "Hi @256@ \" / \n; } café"
567 );
568 assert_eq!(
569 lines[3],
570 "CONST DCS/KEY DCSFROMS/ \"/XGB/XGC/XGD\"."
571 );
572
573 assert!(normalize(b"\"\"").is_err());
576 assert!(normalize_stager3(b"\"unclosed").is_err());
577 assert!(normalize_stager3(b"\"bad /q escape\"").is_err());
578 Ok(())
579 }
580
581 #[crate::ctb_test]
582 fn test_stagel3_public_stager3_api_integration() -> Result<()> {
583 let program = r#"ns demo/api.
584
585pub brand u64/meter.
586pub type u64/nonZeroU64.
587pub struct spanVal :: u64/start u64/spanLen.
588pub enum tag
589 unit.
590 dcs/named.
591
592pub v/result/nonZeroU64/nz u64/n
593 if eq /n u64:0
594 result/nonZeroU64:err error:parseFailure
595 result/nonZeroU64:ok wrap /n nonZeroU64.
596
597pub v/u64/readNonZero nonZeroU64/nzVal :: unwrap /nzVal.
598
599pub v/result/b/roundtripCheck dc/inDc
600 test runs sr3 end to end
601 in dc:256
602 out result/b:ok true
603 const meter/m wrap u64:7 meter.
604 const spanVal/sp structNew spanVal: start unwrap /m spanLen u64:2 ::.
605 const nonZeroU64/nzVal nz? u64:3.
606 const dcs/txt dcsFromS? "hi".
607 const tag/t tag:named /txt.
608 const u64/nval
609 match /t
610 case unit u64:0.
611 case named dcs/inner len /inner.
612 ::.
613 const b/ok1 eq /inDc dc:256.
614 const b/ok2 eq readNonZero /nzVal u64:3.
615 const b/ok3 eq /nval u64:2.
616 const b/ok4 eq field /sp start u64:7.
617 result/b:ok and /ok1 and /ok2 and /ok3 /ok4.
618"#;
619 let tokens1 = dc_tokens::sr3_to_dc_tokens(program)?;
621 let text1 = dc_tokens::dc_tokens_to_sr3(&tokens1)?;
622 let tokens2 = dc_tokens::sr3_to_dc_tokens(&text1)?;
623 assert_eq!(tokens1, tokens2);
624
625 let parsed = parser::parse_sr3_module(program)?;
627 let validated = validator::validate_module(&parsed)?;
628 assert_eq!(validated.exports.brand_types.len(), 2);
629 let report = eval::run_sr3_module_inline_tests(program)?;
630 assert_eq!(report.ensure_all_passed()?, 1);
631
632 let sg = ctb_formats_dcdata::SeedGraphIndex::shared()?;
634 let sg_report =
635 seed_linker::eval_sr3_inline_tests_with_seed_graph(program, sg)?;
636 assert_eq!(sg_report.ensure_all_passed()?, 1);
637
638 let caller = r#"ns demo/caller.
639use demo/api: nonZeroU64 nz readNonZero ::.
640
641pub v/result/u64/doubleNz u64/x
642 test uses opaque type across module boundary
643 in u64:9
644 out result/u64:ok u64:18
645 const nonZeroU64/nzVal nz? /x.
646 const u64/raw readNonZero /nzVal.
647 mul /raw u64:2.
648"#;
649 let ws_report =
650 seed_linker::eval_stager_workspace_inline_tests_with_seed_graph(
651 &[
652 validator::ModuleInput {
653 source_path: Some("demo/api.sr3"),
654 source: program,
655 },
656 validator::ModuleInput {
657 source_path: Some("demo/caller.sr3"),
658 source: caller,
659 },
660 ],
661 sg,
662 )?;
663 assert_eq!(ws_report.ensure_all_passed()?, 2);
664 Ok(())
665 }
666
667 #[crate::ctb_test]
668 fn test_sl3_fixture_parses_validates_roundtrips_and_runs_tests()
669 -> Result<()> {
670 let src = include_str!("fixtures/sl3/input.sl3");
671 let sg = ctb_formats_dcdata::SeedGraphIndex::shared()?;
672 let _ws =
673 seed_linker::parse_and_validate_module_with_seed_graph(src, sg)?;
674
675 let tokens1 = seed_linker::sl3_to_dc_tokens_with_seed_graph(src, sg)?;
676 let text1 = dc_tokens::dc_tokens_to_sl3(&tokens1)?;
677 let tokens2 =
678 seed_linker::sl3_to_dc_tokens_with_seed_graph(&text1, sg)?;
679 let text2 = dc_tokens::dc_tokens_to_sl3(&tokens2)?;
680 assert_eq!(text1, text2);
681 let tokens3 =
682 seed_linker::sl3_to_dc_tokens_with_seed_graph(&text2, sg)?;
683 assert_eq!(tokens2, tokens3);
684
685 let report =
686 seed_linker::eval_sl3_inline_tests_with_seed_graph(src, sg)?;
687 assert_eq!(report.ensure_all_passed()?, 10);
688 let roundtrip_report =
689 seed_linker::eval_sl3_inline_tests_with_seed_graph(&text1, sg)?;
690 assert_eq!(roundtrip_report.ensure_all_passed()?, 10);
691
692 assert!(
694 parser::parse_module(
695 "v/u32/f :: v/u32 u32/x :: /x :: u32:1.\n"
696 )
697 .is_err()
698 );
699 Ok(())
700 }
701
702 #[crate::ctb_test]
703 fn test_sr3_fixture_parses_validates_roundtrips_and_runs_tests()
704 -> Result<()> {
705 let src = include_str!("fixtures/sr3/input.sr3");
706 let parsed = parser::parse_sr3_module(src)?;
707 let _validated = validator::validate_module(&parsed)?;
708
709 let tokens1 = dc_tokens::sr3_to_dc_tokens(src)?;
710 let text1 = dc_tokens::dc_tokens_to_sr3(&tokens1)?;
711 let tokens2 = dc_tokens::sr3_to_dc_tokens(&text1)?;
712 assert_eq!(tokens1, tokens2);
713
714 let report = eval::run_sr3_module_inline_tests(src)?;
715 assert_eq!(report.ensure_all_passed()?, 6);
716
717 let sg = ctb_formats_dcdata::SeedGraphIndex::shared()?;
718 let sg_report =
719 seed_linker::eval_sr3_inline_tests_with_seed_graph(src, sg)?;
720 assert_eq!(sg_report.ensure_all_passed()?, 6);
721
722 assert!(
724 parser::parse_sr3_module(
725 "v/void/bad\n let u32/acc u32:0.\n v/void u32/d ::\n set /acc wrapAdd /acc /d.\n :: u32:5.\n"
726 )
727 .is_err()
728 );
729 assert!(
730 parser::parse_sr3_module(
731 "v/void/badCloser\n let u32/acc u32:0.\n v/void u32/d ::\n set /acc wrapAdd /acc /d.\n :: u32:5.\n"
732 )
733 .is_err()
734 );
735 Ok(())
736 }
737
738 #[crate::ctb_test]
739 fn test_sl3_and_sr3_allow_contextual_identifiers_and_reject_collisions()
740 -> Result<()> {
741 let sr3_program = r#"ns demo/idents.
742
743pub struct rec :: u64/in u64/out u64/s u64/b u64/len u64/type u64/error.
744pub enum tag
745 in.
746 u64/out.
747 s/error.
748
749pub v/u64/useFields u64/in u64/out u64/s u64/b u64/len u64/type u64/error
750 test checks contextual identifiers in bindings fields and variants
751 in u64:1 u64:2 u64:3 u64:4 u64:5 u64:6 u64:7
752 out u64:30.
753 const rec/r structNew rec:
754 in /in
755 out /out
756 s /s
757 b /b
758 len /len
759 type /type
760 error /error
761 ::.
762 const tag/t tag:out field /r in.
763 const u64/v
764 match /t
765 case in u64:0.
766 case out u64/x wrapAdd /x u64:2.
767 case error s/txt byteLen /txt.
768 ::.
769 wrapAdd /v wrapAdd field /r type wrapAdd field /r error wrapAdd field /r len wrapAdd field /r b wrapAdd field /r s field /r out.
770"#;
771 let parsed = parser::parse_sr3_module(sr3_program)?;
772 let _validated = validator::validate_module(&parsed)?;
773 let tokens1 = dc_tokens::sr3_to_dc_tokens(sr3_program)?;
774 let text1 = dc_tokens::dc_tokens_to_sr3(&tokens1)?;
775 let tokens2 = dc_tokens::sr3_to_dc_tokens(&text1)?;
776 assert_eq!(tokens1, tokens2);
777 let report = eval::run_sr3_module_inline_tests(sr3_program)?;
778 assert_eq!(report.ensure_all_passed()?, 1);
779
780 let sl3_program = r#"struct rec :: u32 u32 u32.
781struct boxU32 :: u32.
782v/u32/b u32/x :: /x.
783v/u32/useIdents u32/in u32/out u32/len u32/type u32/error
784 test allows non-type words in StageL 3
785 in u32:1 u32:2 u32:3 u32:4 u32:5
786 out u32:20.
787 const rec/r structNew rec: /in /out /len ::.
788 const boxU32/wrap structNew boxU32: b /error ::.
789 add field /r u32:0 add field /r u32:1 add field /r u32:2 add field /wrap u32:0 add /type /error.
790"#;
791 let sl3_parsed = parser::parse_module(sl3_program)?;
792 let _sl3_validated = validator::validate_module(&sl3_parsed)?;
793 let sl3_rep = super::eval::run_module_inline_tests(sl3_program)?;
794 assert_eq!(sl3_rep.ensure_all_passed()?, 1);
795
796 let sl3_in_routine = r#"v/u32/in u32/out
797 test allows routines named after test keywords
798 in u32:4
799 out u32:4.
800 /out.
801"#;
802 let in_rep = super::eval::run_module_inline_tests(sl3_in_routine)?;
803 assert_eq!(in_rep.ensure_all_passed()?, 1);
804
805 assert!(parser::parse_sr3_module("brand u64/i32.\n").is_err());
807 assert!(parser::parse_sr3_module("type u64/s.\n").is_err());
808 assert!(
809 parser::parse_sr3_module("struct option :: u64/x.\n").is_err()
810 );
811 assert!(parser::parse_sr3_module("enum result unit.\n").is_err());
812 assert!(parser::parse_module("struct s :: u32.\n").is_err());
813 assert!(parser::parse_module("struct option :: u32.\n").is_err());
814 assert!(parser::parse_module("struct U32 :: u32.\n").is_err());
815
816 assert!(
818 parser::parse_sr3_module("v/u64/if u64/x :: /x.\n").is_err()
819 );
820 assert!(
821 parser::parse_sr3_module("v/u64/add u64/x :: /x.\n").is_err()
822 );
823 assert!(
824 parser::parse_sr3_module("v/u64/match u64/x :: /x.\n").is_err()
825 );
826 assert!(
827 parser::parse_sr3_module("v/u64/fault u64/x :: /x.\n").is_err()
828 );
829 assert!(
830 parser::parse_sr3_module("v/u64/rem u64/x :: /x.\n").is_err()
831 );
832 assert!(
833 parser::parse_sr3_module("v/u64/bitcast u64/x :: /x.\n").is_err()
834 );
835 assert!(parser::parse_module("v/u32/add u32/x :: /x.\n").is_err());
836 assert!(parser::parse_module("v/u32/ADD u32/x :: /x.\n").is_err());
837 assert!(
838 parser::parse_module("v/u32/requestCapability u32/x :: /x.\n")
839 .is_err()
840 );
841 assert!(parser::parse_module("v/u32/match u32/x :: /x.\n").is_err());
842 assert!(parser::parse_module("v/u32/makeRat u32/x :: /x.\n").is_err());
843 assert!(parser::parse_module("v/u32/explode u32/x :: /x.\n").is_err());
844 assert!(
845 parser::parse_module(
846 "ns std/bytes.\npub v/l/u8/explode l/u8/x :: /x.\n"
847 )
848 .is_ok()
849 );
850 assert!(
851 parser::parse_sr3_module(
852 "ns std/bytes.\npub v/l/u8/explode l/u8/x :: /x.\n"
853 )
854 .is_err()
855 );
856 Ok(())
857 }
858}