1pub mod prelude;
6
7use seq_map::SeqMap;
8use source_map_cache::{SourceMap, SourceMapWrapper};
9use std::fmt::{Display, Formatter};
10use std::io;
11use std::io::Write;
12use std::num::ParseIntError;
13use std::path::{Path, PathBuf};
14use std::str::FromStr;
15use std::thread::sleep;
16use std::time::Duration;
17use swamp_runtime::prelude::{CodeGenOptions, RunMode};
18use swamp_runtime::{
19 compile_codegen_and_create_vm, CompileAndCodeGenOptions, CompileAndVmResult, CompileOptions,
20 RunOptions, StandardOnlyHostCallbacks,
21};
22use swamp_vm::VmState;
23use time_dilation::ScopedTimer;
24use tracing::error;
25
26#[must_use]
27pub fn colorize_parts(parts: &[String]) -> String {
28 let new_parts: Vec<_> = parts
29 .iter()
30 .map(|x| format!("{}", tinter::bright_cyan(x)))
31 .collect();
32
33 new_parts.join("::")
34}
35
36#[must_use]
37pub fn colorful_module_name(parts: &[String]) -> String {
38 let x = if parts[0] == "crate" {
39 &parts[1..]
40 } else {
41 parts
42 };
43
44 colorize_parts(x)
45}
46
47#[must_use]
48pub fn pretty_module_parts(parts: &[String]) -> String {
49 let new_parts: Vec<_> = parts.iter().map(std::string::ToString::to_string).collect();
50
51 new_parts.join("::")
52}
53
54#[must_use]
55pub fn pretty_module_name(parts: &[String]) -> String {
56 let x = if parts[0] == "crate" {
57 &parts[1..]
58 } else {
59 parts
60 };
61
62 pretty_module_parts(x)
63}
64
65#[must_use]
66pub fn matches_pattern(test_name: &str, pattern: &str) -> bool {
67 if pattern.ends_with("::") {
68 test_name.starts_with(pattern)
69 } else if pattern.contains('*') {
70 let parts: Vec<&str> = pattern.split('*').collect();
71 if parts.len() > 2 {
72 return false;
73 }
74
75 let prefix = parts[0];
76 let suffix = if parts.len() == 2 { parts[1] } else { "" }; if !test_name.starts_with(prefix) {
79 return false;
80 }
81
82 let remaining_name = &test_name[prefix.len()..];
83 remaining_name.ends_with(suffix)
84 } else {
85 test_name == pattern
86 }
87}
88#[must_use]
89pub fn test_name_matches_filter(test_name: &str, filter_string: &str) -> bool {
90 if filter_string.trim().is_empty() {
91 return true;
92 }
93
94 let patterns: Vec<&str> = filter_string.split(',').collect();
95
96 for pattern in patterns {
97 let trimmed_pattern = pattern.trim();
98
99 if matches_pattern(test_name, trimmed_pattern) {
100 return true;
101 }
102 }
103
104 false
105}
106
107pub enum StepBehavior {
108 ResumeExecution,
109 WaitForUserInput,
110 Pause(Duration),
111}
112
113pub enum StepParseError {
114 UnknownVariant(String),
115 MissingDuration,
116 ParseInt(ParseIntError),
117}
118
119impl Display for StepParseError {
120 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
121 match self {
122 Self::UnknownVariant(_) => write!(f, "unknown"),
123 Self::MissingDuration => write!(f, "missing duration"),
124 Self::ParseInt(_) => write!(f, "parse int failed"),
125 }
126 }
127}
128
129impl FromStr for StepBehavior {
130 type Err = StepParseError;
131
132 fn from_str(s: &str) -> Result<Self, Self::Err> {
133 let lower = s.to_lowercase();
134 let mut parts = lower.splitn(2, ':');
135 let variant = parts.next().unwrap();
136
137 match variant {
138 "resume" => Ok(Self::ResumeExecution),
139 "wait" => Ok(Self::WaitForUserInput),
140 "pause" => match parts.next() {
141 Some(ms_str) => {
142 let ms: u64 = ms_str.parse().map_err(StepParseError::ParseInt)?;
143 Ok(Self::Pause(Duration::from_millis(ms)))
144 }
145 None => Err(StepParseError::MissingDuration),
146 },
147
148 other => Err(StepParseError::UnknownVariant(other.to_string())),
149 }
150 }
151}
152
153pub struct TestRunOptions {
154 pub should_run: bool,
155 pub iteration_count: usize,
156 pub debug_output: bool,
157 pub print_output: bool,
158 pub debug_opcodes: bool,
159 pub debug_operations: bool,
160 pub debug_stats: bool,
161 pub show_semantic: bool,
162 pub show_assembly: bool,
163 pub assembly_filter: Option<String>,
164 pub show_modules: bool,
165 pub show_types: bool,
166 pub step_behaviour: StepBehavior,
167 pub debug_memory_enabled: bool,
168}
169
170pub fn init_logger() {
171 tracing_subscriber::fmt()
172 .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
173 .with_writer(std::io::stderr)
174 .init();
175}
176
177#[derive(Clone)]
178pub struct TestInfo {
179 pub name: String,
180}
181impl Display for TestInfo {
182 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
183 write!(f, "{}", self.name)
184 }
185}
186
187pub struct TestResult {
188 pub passed_tests: Vec<TestInfo>,
189 pub failed_tests: Vec<TestInfo>,
190}
191
192impl TestResult {
193 #[must_use]
194 pub const fn succeeded(&self) -> bool {
195 self.failed_tests.is_empty()
196 }
197}
198
199#[must_use] pub fn run_tests_source_map(test_dir: &Path, options: &TestRunOptions,
200 filter: &str,
201 module_suffix: &str, ) -> TestResult {
202 let mut mounts = SeqMap::new();
203 mounts.insert("crate".to_string(), test_dir.to_path_buf()).expect("TODO: panic message");
204 let mut source_map = SourceMap::new(&mounts).unwrap();
205
206 run_tests(&mut source_map, options, filter, module_suffix)
207}
208
209#[allow(clippy::too_many_lines)]
211pub fn run_tests(
212 source_map: &mut SourceMap,
213 options: &TestRunOptions,
214 filter: &str,
215 module_suffix: &str,
216) -> TestResult {
217 let crate_main_path = &["crate".to_string(), module_suffix.to_string()];
218 let compile_and_code_gen_options = CompileAndCodeGenOptions {
219 compile_options: CompileOptions {
220 show_semantic: options.show_semantic,
221 show_modules: options.show_modules,
222 show_types: options.show_types,
223 show_errors: true,
224 show_warnings: true,
225 show_hints: false,
226 show_information: false,
227 },
228 code_gen_options: CodeGenOptions {
229 show_disasm: options.show_assembly,
230 disasm_filter: options.assembly_filter.clone(),
231 show_debug: options.debug_output,
232 show_types: options.show_types,
233 ignore_host_call: true,
234 },
235 skip_codegen: false,
236 run_mode: RunMode::Deployed,
237 };
238
239 let internal_result =
240 compile_codegen_and_create_vm(source_map, crate_main_path, &compile_and_code_gen_options)
241 .unwrap();
242
243 let CompileAndVmResult::CompileAndVm(mut result) = internal_result else {
244 panic!("didn't work to compile")
245 };
246
247 let mut passed_tests = Vec::new();
248
249 let mut panic_tests = Vec::new();
250 let mut trap_tests = Vec::new();
251 let mut failed_tests = Vec::new();
252 let mut expected_panic_passed: Vec<TestInfo> = Vec::new();
253 let mut expected_trap_passed: Vec<TestInfo> = Vec::new();
254
255 if options.should_run {
256 let should_run_in_debug_mode = true; let run_first_options = RunOptions {
259 debug_stats_enabled: options.debug_stats,
260 debug_opcodes_enabled: options.debug_opcodes,
261 debug_operations_enabled: options.debug_operations,
262 debug_memory_enabled: options.debug_memory_enabled,
263 max_count: 0,
264 use_color: true,
265 debug_info: &result.codegen.code_gen_result.debug_info,
266 source_map_wrapper: SourceMapWrapper {
267 source_map,
268 current_dir: PathBuf::default(),
269 },
270 };
271
272 swamp_runtime::run_first_time(
273 &mut result.codegen.vm,
274 &result.codegen.code_gen_result.constants_in_order,
275 &mut StandardOnlyHostCallbacks {},
276 &run_first_options,
277 );
278
279 {
280 let _bootstrap_timer = ScopedTimer::new("run tests a bunch of times");
281
282 for (module_name, module) in result.compile.program.modules.modules() {
283 let mut has_shown_mod_name = false;
284 for internal_fn in module.definition_table.internal_functions() {
285 if !internal_fn.attributes.has_attribute("test") {
286 continue;
287 }
288 if options.debug_output && !has_shown_mod_name {
289 has_shown_mod_name = true;
291 }
292 let function_to_run = result
293 .codegen
294 .code_gen_result
295 .functions
296 .get(&internal_fn.program_unique_id)
297 .unwrap();
298
299 let all_attributes = &function_to_run.internal_function_definition.attributes;
300
301 let mut expected_vm_state = VmState::Normal;
302
303 if !all_attributes.is_empty() {
304 let code =
305 all_attributes.get_string_from_fn_arg("should_trap", "expected", 0);
306 if let Some(code) = code {
307 expected_vm_state = VmState::Trap(code.parse().unwrap());
308 } else {
309 let panic_message = all_attributes.get_string_from_fn_arg(
310 "should_panic",
311 "expected",
312 0,
313 );
314 if let Some(panic_message) = panic_message {
315 expected_vm_state = VmState::Panic(panic_message.clone());
316 }
317 }
318 }
319
320 let complete_name = format!(
321 "{}::{}",
322 colorful_module_name(module_name),
323 tinter::blue(&function_to_run.internal_function_definition.assigned_name)
324 );
325 let formal_name = format!(
326 "{}::{}",
327 pretty_module_name(module_name),
328 &function_to_run.internal_function_definition.assigned_name
329 );
330
331 if !test_name_matches_filter(&formal_name, filter) {
332 continue;
333 }
334
335 let test_info = TestInfo { name: formal_name };
336
337
338 if should_run_in_debug_mode {
339 eprintln!("πstarting test in debug '{complete_name}'");
340 for _ in 0..options.iteration_count {
341 result.codegen.vm.memory_mut().reset_allocator();
342 swamp_runtime::run_function_with_debug(
343 &mut result.codegen.vm,
344 &function_to_run.ip_range,
345 &mut StandardOnlyHostCallbacks {},
346 &RunOptions {
347 debug_stats_enabled: options.debug_stats,
348 debug_opcodes_enabled: options.debug_opcodes,
349 debug_operations_enabled: options.debug_operations,
350 debug_memory_enabled: options.debug_memory_enabled,
351 max_count: 0,
352 use_color: true,
353 debug_info: &result.codegen.code_gen_result.debug_info,
354 source_map_wrapper: SourceMapWrapper {
355 source_map,
356 current_dir: PathBuf::default(),
357 },
358 },
359 );
360
361 while result.codegen.vm.state == VmState::Step {
362 handle_step(&options.step_behaviour);
363 result.codegen.vm.state = VmState::Normal;
364 result.codegen.vm.resume(&mut StandardOnlyHostCallbacks {});
365 }
366
367 if result.codegen.vm.state != expected_vm_state {
368 break;
369 }
370 }
371 } else {
372 eprintln!("πstarting test in fast mode '{complete_name}'");
373 for _ in 0..options.iteration_count {
374 result.codegen.vm.memory_mut().reset_allocator();
375 swamp_runtime::run_as_fast_as_possible(
376 &mut result.codegen.vm,
377 function_to_run,
378 &mut StandardOnlyHostCallbacks {},
379 RunOptions {
380 debug_stats_enabled: options.debug_stats,
381 debug_opcodes_enabled: options.debug_opcodes,
382 debug_operations_enabled: options.debug_operations,
383 max_count: 0,
384 use_color: true,
385 debug_info: &result.codegen.code_gen_result.debug_info,
386 source_map_wrapper: SourceMapWrapper {
387 source_map,
388 current_dir: PathBuf::default(),
389 },
390 debug_memory_enabled: options.debug_memory_enabled,
391 },
392 );
393 while result.codegen.vm.state == VmState::Step {
394 handle_step(&options.step_behaviour);
395 result.codegen.vm.state = VmState::Normal;
396 result.codegen.vm.resume(&mut StandardOnlyHostCallbacks {});
397 }
398 if result.codegen.vm.state != expected_vm_state {
399 break;
400 }
401 }
402 }
403
404 if expected_vm_state == VmState::Normal {
405 match &result.codegen.vm.state {
406 VmState::Panic(message) => {
407 panic_tests.push(test_info);
408 error!(message, "PANIC!");
409 eprintln!("β Panic {complete_name} {message}");
410 }
411 VmState::Normal => {
412 passed_tests.push(test_info);
413 eprintln!("β
{complete_name} worked!");
414 }
415 VmState::Trap(trap_code) => {
416 trap_tests.push(test_info);
417 error!(%trap_code, "TRAP");
418 eprintln!("β trap {complete_name} {trap_code}");
419 }
420
421 VmState::Step | VmState::Halt => {
422 panic_tests.push(test_info);
423 error!("Step or Halt");
424 eprintln!("β trap {complete_name}");
425 }
426 }
427 } else if let VmState::Trap(expected_trap_code) = expected_vm_state {
428 match &result.codegen.vm.state {
429 VmState::Trap(actual_trap_code) => {
430 if actual_trap_code.is_sort_of_equal(&expected_trap_code) {
431 expected_trap_passed.push(test_info.clone());
432 eprintln!(
433 "β
Expected Trap {complete_name} (code: {actual_trap_code})"
434 );
435 } else {
436 failed_tests.push(test_info.clone());
437 error!(%expected_trap_code, %actual_trap_code, "WRONG TRAP CODE");
438 eprintln!(
439 "β Wrong Trap Code {complete_name} (Expected: {expected_trap_code}, Got: {actual_trap_code})"
440 );
441 }
442 }
443 VmState::Normal => {
444 failed_tests.push(test_info.clone());
445 error!("Expected TRAP, got NORMAL");
446 eprintln!("β Expected Trap {complete_name}, but it ran normally.");
447 }
448 VmState::Panic(message) => {
449 failed_tests.push(test_info.clone());
450 error!(message, "Expected TRAP, got PANIC");
451 eprintln!(
452 "β Expected Trap {complete_name}, but it panicked: {message}"
453 );
454 }
455 VmState::Step | VmState::Halt => {
456 panic_tests.push(test_info);
457 error!("Step or Halt");
458 eprintln!("β trap {complete_name}");
459 }
460 }
461 } else if let VmState::Panic(expected_panic_message) = expected_vm_state {
462 match &result.codegen.vm.state {
463 VmState::Panic(actual_panic_message) => {
464 if actual_panic_message.contains(&expected_panic_message) {
465 expected_panic_passed.push(test_info.clone());
466 eprintln!(
467 "β
Expected Panic {complete_name} (message contains: \"{expected_panic_message}\")",
468 );
469 } else {
470 failed_tests.push(test_info.clone());
471 error!(
472 expected_panic_message,
473 actual_panic_message, "WRONG PANIC MESSAGE"
474 );
475 eprintln!(
476 "β Wrong Panic Message {complete_name} (Expected contains: \"{expected_panic_message}\", Got: \"{actual_panic_message}\")"
477 );
478 }
479 }
480 VmState::Normal => {
481 failed_tests.push(test_info.clone());
482 error!("Expected PANIC, got NORMAL");
483 eprintln!(
484 "β Expected Panic {complete_name}, but it ran normally."
485 );
486 }
487 VmState::Trap(trap_code) => {
488 failed_tests.push(test_info.clone());
489 error!(%trap_code, "Expected PANIC, got TRAP");
490 eprintln!(
491 "β Expected Panic {complete_name}, but it trapped: {trap_code}"
492 );
493 }
494 VmState::Step | VmState::Halt => {
495 panic_tests.push(test_info);
496 error!("Step or Halt");
497 eprintln!("β trap {complete_name}");
498 }
499 }
500 }
501 }
502 }
503 }
504
505 let passed_normal_count = passed_tests.len();
507 let unexpected_panic_count = panic_tests.len();
508 let unexpected_trap_count = trap_tests.len();
509 let failed_mismatch_count = failed_tests.len(); let expected_panic_pass_count = expected_panic_passed.len();
512 let expected_trap_pass_count = expected_trap_passed.len();
513
514 let total_passed_count =
516 passed_normal_count + expected_panic_pass_count + expected_trap_pass_count;
517 let total_failed_count =
518 unexpected_panic_count + unexpected_trap_count + failed_mismatch_count;
519 let total_tests_run = total_passed_count + total_failed_count;
520
521 println!("\n---\nπ Test Run Complete! π\n");
525
526 println!("Results:");
527 println!(" β
Passed Normally: {passed_normal_count}");
528 println!(" β
Passed (Expected Panic): {expected_panic_pass_count}");
529 println!(" β
Passed (Expected Trap): {expected_trap_pass_count}");
530
531 if total_failed_count > 0 {
532 println!(" β **TOTAL FAILED:** {total_failed_count}", );
533 }
534
535 println!(" Total Tests Run: {total_tests_run}", );
536
537 if total_failed_count > 0 {
541 println!("\n--- Failing Tests Details ---");
542
543 if unexpected_panic_count > 0 {
544 println!("\n### Unexpected Panics:");
545 for test in &panic_tests {
546 println!("- β {}", test.name);
547 }
548 }
549
550 if unexpected_trap_count > 0 {
551 println!("\n### Unexpected Traps:");
552 for test in &trap_tests {
553 println!("- β {}", test.name);
554 }
555 }
556
557 if failed_mismatch_count > 0 {
558 println!("\n### Other Failures:");
559 for test in &failed_tests {
560 println!("- β {}", test.name);
561 }
562 }
563 }
564
565 eprintln!("\n\nvm stats {:?}", result.codegen.vm.debug);
566 }
567
568 let failed_tests = [trap_tests, panic_tests].concat();
569 TestResult {
570 passed_tests,
571 failed_tests,
572 }
573}
574
575fn handle_step(step_behavior: &StepBehavior) {
576 match step_behavior {
577 StepBehavior::ResumeExecution => {}
578 StepBehavior::WaitForUserInput => {
579 wait_for_user_pressing_enter();
580 }
581 StepBehavior::Pause(duration) => {
582 eprintln!("step. waiting {duration:?}");
583 sleep(*duration);
584 }
585 }
586}
587
588fn wait_for_user_pressing_enter() {
589 let mut buf = String::new();
590 print!("Step detected. press ENTER to continue");
591 io::stdout().flush().unwrap();
592
593 io::stdin().read_line(&mut buf).expect("should work");
595}