1mod err_wrt;
6pub mod prelude;
7
8use seq_map::SeqMap;
9use source_map_cache::{FileId, KeepTrackOfSourceLine, SourceFileLineInfo, SourceMapLookup};
10use source_map_cache::{SourceMap, SourceMapWrapper};
11use std::env::current_dir;
12use std::fmt::Write as FmtWrite;
13use std::hash::{DefaultHasher, Hash, Hasher};
14use std::path::{Path, PathBuf};
15use swamp_analyzer::Program;
16use swamp_code_gen::{ConstantInfo, GenFunctionInfo};
17use swamp_code_gen_program::{code_gen_program, CodeGenOptions};
18pub use swamp_compile::CompileOptions;
19use swamp_dep_loader::{swamp_registry_path, RunMode};
20use swamp_semantic::{ConstantId, InternalFunctionDefinitionRef, InternalFunctionId};
21use swamp_std::pack::pack;
22use swamp_std::print::print_fn;
23use swamp_types::TypeRef;
24use swamp_vm::host::{HostArgs, HostFunctionCallback};
25use swamp_vm::memory::ExecutionMode;
26use swamp_vm::{TrapCode, Vm, VmSetup, VmState};
27use swamp_vm_debug_info::{DebugInfo, DebugInfoForPc};
28use swamp_vm_disasm::{disasm_color, display_lines};
29use swamp_vm_layout::LayoutCache;
30use swamp_vm_types::types::BasicTypeKind;
31use swamp_vm_types::{BinaryInstruction, InstructionPosition, InstructionRange};
32
33pub struct RunConstantsOptions {
34 pub stderr_adapter: Option<Box<dyn FmtWrite>>,
35}
36
37pub struct RunOptions<'a> {
38 pub debug_stats_enabled: bool,
40 pub debug_opcodes_enabled: bool,
41 pub debug_info: &'a DebugInfo,
42 pub source_map_wrapper: SourceMapWrapper<'a>,
43 pub debug_operations_enabled: bool,
44 pub max_count: usize, pub use_color: bool,
46 pub debug_memory_enabled: bool,
47}
48
49pub fn run_constants_in_order(
50 vm: &mut Vm,
51 constants_in_order: &SeqMap<ConstantId, ConstantInfo>,
52 host_function_callback: &mut dyn HostFunctionCallback,
53 options: &RunOptions,
54) {
55 vm.memory_mut().set_heap_directly_after_constant_area();
56 for (_key, constant) in constants_in_order {
57 vm.reset_call_stack();
59
60 if constant.target_constant_memory.ty().is_scalar() {} else {
61 vm.registers[0] = constant.target_constant_memory.addr().0;
63 }
64
65 run_function_with_debug(vm, &constant.ip_range, host_function_callback, options);
66
67 if constant.target_constant_memory.ty().is_scalar() {
68 match constant.target_constant_memory.ty().kind {
69 BasicTypeKind::S32 | BasicTypeKind::Fixed32 | BasicTypeKind::U32 => {
70 let heap_ptr = vm
71 .memory_mut()
72 .get_heap_ptr(constant.target_constant_memory.addr().0 as usize)
73 .cast::<u32>();
74 unsafe {
75 *heap_ptr = vm.registers[0];
76 }
77 }
78 BasicTypeKind::B8 | BasicTypeKind::U8 => {
79 let heap_ptr = vm
80 .memory_mut()
81 .get_heap_ptr(constant.target_constant_memory.addr().0 as usize)
82 .cast::<u8>();
83 unsafe {
84 *heap_ptr = vm.registers[0] as u8;
85 }
86 }
87 _ => todo!(),
88 }
89 }
90
91 let return_layout = constant.target_constant_memory.ty();
92
93 assert_eq!(
94 constant.target_constant_memory.size(),
95 return_layout.total_size
96 );
97
98 }
114
115 vm.memory_mut().incorporate_heap_into_constant_area();
117}
118
119#[must_use]
121pub fn crate_and_registry(path_to_swamp: &Path, run_mode: &RunMode) -> SourceMap {
122 let mut mounts = SeqMap::new();
123 mounts
125 .insert("crate".to_string(), path_to_swamp.to_path_buf())
126 .unwrap();
127
128 if let Some(found_swamp_home) = swamp_registry_path(run_mode) {
129 mounts
130 .insert("registry".to_string(), found_swamp_home)
131 .unwrap();
132 }
133
134 SourceMap::new(&mounts).expect("source map failed")
135}
136
137pub struct CompileAndMaybeCodeGenResult {
138 pub compile: CompileResult,
139 pub codegen: Option<CodeGenResult>,
140}
141
142pub struct CompileResult {
143 pub program: Program,
144}
145
146pub struct CodeGenResult {
147 pub instructions: Vec<BinaryInstruction>,
148 pub constants_in_order: SeqMap<ConstantId, ConstantInfo>,
149 pub functions: SeqMap<InternalFunctionId, GenFunctionInfo>,
150 pub prepared_constant_memory: Vec<u8>,
151 pub layout_cache: LayoutCache,
152 pub debug_info: DebugInfo,
153}
154
155impl CodeGenResult {
156 #[must_use]
157 pub fn find_function(&self, formal_name: &str) -> Option<&GenFunctionInfo> {
158 self.functions
159 .values()
160 .find(|&func| func.internal_function_definition.assigned_name == formal_name)
161 }
162}
163
164pub fn compile_main_path(
165 source_map: &mut SourceMap,
166 root_module_path: &[String],
167 options: &CompileOptions,
168) -> Option<CompileResult> {
169 let program =
170 swamp_compile::bootstrap_and_compile(source_map, root_module_path, options).ok()?;
171
172 Some(CompileResult { program })
173}
174
175#[must_use]
176pub fn code_gen(
177 program: &Program,
178 source_map_wrapper: &SourceMapWrapper,
179 code_gen_options: &CodeGenOptions,
180) -> CodeGenResult {
181 let top_gen_state = code_gen_program(program, source_map_wrapper, code_gen_options);
182
183 let all_types = top_gen_state.codegen_state.layout_cache.clone();
184 let (instructions, constants_in_order, emit_function_infos, constant_memory, debug_info) =
185 top_gen_state.take_instructions_and_constants();
186
187 CodeGenResult {
188 debug_info,
189 instructions,
190 constants_in_order,
191 functions: emit_function_infos,
192 prepared_constant_memory: constant_memory,
193 layout_cache: all_types,
194 }
195}
196
197#[must_use]
198pub fn create_vm_with_standard_settings(
199 instructions: &[BinaryInstruction],
200 prepared_constant_memory: &[u8],
201) -> Vm {
202 let vm_setup = VmSetup {
203 stack_memory_size: 64 * 1024 * 1024, heap_memory_size: 512 * 1024, constant_memory: prepared_constant_memory.to_vec(),
206 debug_opcodes_enabled: false,
207 debug_stats_enabled: false,
208 debug_operations_enabled: false,
209 };
210
211 Vm::new(instructions.to_vec(), vm_setup)
212}
213
214pub fn run_first_time(
215 vm: &mut Vm,
216 constants_in_order: &SeqMap<ConstantId, ConstantInfo>,
217 host_function_callback: &mut dyn HostFunctionCallback,
218 options: &RunOptions,
219) {
220 run_constants_in_order(vm, constants_in_order, host_function_callback, options);
221}
222
223pub fn run_as_fast_as_possible(
224 vm: &mut Vm,
225 function_to_run: &GenFunctionInfo,
226 host_function_callback: &mut dyn HostFunctionCallback,
227 run_options: RunOptions,
228) {
229 vm.reset_minimal_stack_and_fp();
230 vm.state = VmState::Normal;
231 vm.debug_opcodes_enabled = false;
232 vm.debug_operations_enabled = run_options.debug_operations_enabled;
233 vm.debug_stats_enabled = run_options.debug_stats_enabled;
234
235 vm.execute_from_ip(&function_to_run.ip_range.start, host_function_callback);
236 if matches!(vm.state, VmState::Trap(_) | VmState::Panic(_)) {
237 show_crash_info(vm, run_options.debug_info, &run_options.source_map_wrapper);
238 }
239}
240
241fn calculate_memory_checksum(memory: &[u8]) -> u64 {
242 let mut hasher = DefaultHasher::new();
243 memory.hash(&mut hasher);
244 hasher.finish()
245}
246
247pub fn run_function(
248 vm: &mut Vm,
249 ip_range: &InstructionRange,
250 host_function_callback: &mut dyn HostFunctionCallback,
251 run_options: &RunOptions,
252) {
253 vm.reset_minimal_stack_and_fp();
254
255 vm.state = VmState::Normal;
256
257 vm.execute_from_ip(&ip_range.start, host_function_callback);
258
259 if matches!(vm.state, VmState::Trap(_) | VmState::Panic(_)) {
260 show_crash_info(vm, run_options.debug_info, &run_options.source_map_wrapper);
261 }
262}
263
264pub fn show_call_stack(
265 vm: &Vm,
266 debug_info: &DebugInfo,
267 info: &DebugInfoForPc,
268 source_map_wrapper: &SourceMapWrapper,
269) {
270 eprintln!("\nš Call stack:");
272
273 if info.meta.node.span.file_id != 0 {
275 let (line, _column) = source_map_wrapper.source_map.get_span_location_utf8(
276 info.meta.node.span.file_id,
277 info.meta.node.span.offset as usize,
278 );
279 let relative_path = source_map_wrapper
280 .source_map
281 .fetch_relative_filename(info.meta.node.span.file_id);
282
283 if let Some(source_line) =
285 source_map_wrapper.get_source_line(info.meta.node.span.file_id as FileId, line)
286 {
287 eprintln!(
288 " {}: {} {}",
289 tinter::bright_cyan("0"),
290 tinter::blue(&info.function_debug_info.name),
291 tinter::bright_black("(current)")
292 );
293 eprintln!(
294 "{:4} {} {}",
295 tinter::bright_black(&line.to_string()),
296 tinter::green("|"),
297 source_line.trim()
298 );
299 eprintln!(
300 "{} {}",
301 tinter::bright_black("->"),
302 tinter::cyan(&format!("{relative_path}:{line}"))
303 );
304 } else {
305 eprintln!(
306 " {}: {} {}",
307 tinter::bright_cyan("0"),
308 tinter::blue(&info.function_debug_info.name),
309 tinter::bright_black("(current)")
310 );
311 eprintln!(
312 "{} {}",
313 tinter::bright_black("->"),
314 tinter::cyan(&format!("{relative_path}:{line}"))
315 );
316 }
317 } else {
318 eprintln!(
319 " {}: {} {}",
320 tinter::bright_cyan("0"),
321 tinter::blue(&info.function_debug_info.name),
322 tinter::bright_black("(current)")
323 );
324 }
325
326 let call_stack = vm.call_stack();
327 for (i, frame) in call_stack.iter().enumerate().rev() {
328 let frame_pc = if frame.return_address > 0 {
329 frame.return_address - 1
330 } else {
331 frame.return_address
332 };
333
334 if let Some(frame_info) = debug_info.fetch(frame_pc) {
335 if frame_info.meta.node.span.file_id != 0 {
336 let (line, _column) = source_map_wrapper.source_map.get_span_location_utf8(
337 frame_info.meta.node.span.file_id,
338 frame_info.meta.node.span.offset as usize,
339 );
340 let relative_path = source_map_wrapper
341 .source_map
342 .fetch_relative_filename(frame_info.meta.node.span.file_id);
343
344 if let Some(source_line) = source_map_wrapper
345 .get_source_line(frame_info.meta.node.span.file_id as FileId, line)
346 {
347 eprintln!(
348 " {}: {}",
349 tinter::bright_cyan(&(i + 1).to_string()),
350 tinter::blue(&frame_info.function_debug_info.name)
351 );
352 eprintln!(
353 "{:4} {} {}",
354 tinter::bright_black(&line.to_string()),
355 tinter::green("|"),
356 source_line.trim()
357 );
358 eprintln!(
359 "{} {}",
360 tinter::bright_black("->"),
361 tinter::cyan(&format!("{relative_path}:{line}"))
362 );
363 } else {
364 eprintln!(
365 " {}: {}",
366 tinter::bright_cyan(&(i + 1).to_string()),
367 tinter::blue(&frame_info.function_debug_info.name)
368 );
369 eprintln!(
370 "{} {}",
371 tinter::bright_black("->"),
372 tinter::cyan(&format!("{relative_path}:{line}"))
373 );
374 }
375 } else {
376 eprintln!(
377 " {}: {}",
378 tinter::bright_cyan(&(i + 1).to_string()),
379 tinter::blue(&frame_info.function_debug_info.name)
380 );
381 }
382 } else {
383 eprintln!(
384 " {}: {} {}",
385 tinter::bright_cyan(&(i + 1).to_string()),
386 tinter::red("<unknown function>"),
387 tinter::bright_black(&format!("(pc: {frame_pc:04X})"))
388 );
389 }
390 }
391}
392
393pub fn show_crash_info(vm: &Vm, debug_info: &DebugInfo, source_map_wrapper: &SourceMapWrapper) {
394 let pc = vm.pc();
395
396 let trap_pc = if pc > 0 { pc - 1 } else { pc };
399
400 if let Some(info) = debug_info.fetch(trap_pc) {
401 match &vm.state {
402 VmState::Trap(trap_code) => {
403 eprintln!("\nš« VM TRAP: {trap_code}");
404 }
405 VmState::Panic(message) => {
406 eprintln!("\nš„ VM PANIC: {message}");
407 }
408 _ => unreachable!(),
409 }
410
411 if info.meta.node.span.file_id != 0 {
412 let (line, column) = source_map_wrapper.source_map.get_span_location_utf8(
413 info.meta.node.span.file_id,
414 info.meta.node.span.offset as usize,
415 );
416
417 eprintln!("š Source location:");
418 let mut string = String::new();
419 display_lines(
420 &mut string,
421 info.meta.node.span.file_id as FileId,
422 line.saturating_sub(2), line + 2, source_map_wrapper,
425 true,
426 );
427 eprint!("{string}");
428
429 let relative_path = source_map_wrapper
430 .source_map
431 .fetch_relative_filename(info.meta.node.span.file_id);
432 eprintln!(" at {relative_path}:{line}:{column}");
433 }
434
435 let instruction = &vm.instructions()[trap_pc];
437 let disassembler_string = disasm_color(
438 instruction,
439 &info.function_debug_info.frame_memory,
440 &info.meta,
441 &InstructionPosition(trap_pc as u32),
442 );
443 eprintln!("š» Failing instruction: {trap_pc:04X}> {disassembler_string}");
444
445 show_call_stack(vm, debug_info, &info, source_map_wrapper);
446 }
447}
448
449pub fn run_function_with_debug(
450 vm: &mut Vm,
451 function_to_run: &InstructionRange,
452 host_function_callback: &mut dyn HostFunctionCallback,
453 run_options: &RunOptions,
454) {
455 vm.reset_minimal_stack_and_fp();
456 vm.state = VmState::Normal;
458 vm.debug_opcodes_enabled = run_options.debug_opcodes_enabled;
459 vm.debug_operations_enabled = run_options.debug_operations_enabled;
460 vm.debug_stats_enabled = run_options.debug_stats_enabled;
461 vm.set_pc(&function_to_run.start);
462
463 let mut debug_count = 0;
464
465 let use_color = run_options.use_color;
466
467 let mut last_line_info = KeepTrackOfSourceLine::new();
468
469 let saved_fp = vm.memory().constant_memory_size;
470 let hash_before: u64 = if run_options.debug_memory_enabled {
471 calculate_memory_checksum(vm.all_memory_up_to(saved_fp))
472 } else {
473 0
474 };
475
476 while !vm.is_execution_complete() {
477 debug_count += 1;
478
479 if run_options.max_count != 0 && (debug_count >= run_options.max_count) {
480 if vm.state == VmState::Normal {
481 vm.internal_trap(TrapCode::StoppedByTestHarness);
482 }
483 break;
484 }
485
486 let pc = vm.pc();
487 #[cfg(feature = "debug_vm")]
488 if run_options.debug_opcodes_enabled {
489 let regs = [
490 0, 1, 2, 3, 4, 5, 6, 7, 8, 128, 129, 130, 131, 132, 133, 134, 135,
491 ];
492 if use_color {
493 print!(
494 "{}",
495 tinter::bright_black(&format!("fp:{:08X}, sp:{:08X} ", vm.fp(), vm.sp(), ))
496 );
497
498 for reg in regs {
499 let reg_name = &format!("r{reg}");
500 print!(
501 "{}",
502 tinter::bright_black(&format!("{reg_name:>3}:{:08X}, ", vm.registers[reg]))
503 );
504 }
505 println!();
506 } else {
507 print!("{}", &format!("fp:{:08X}, sp:{:08X}, ", vm.fp(), vm.sp()));
509
510 for reg in regs {
511 let reg_name = &format!("r{reg}");
512 print!("{}", &format!("{reg_name:>3}:{:08X}, ", vm.registers[reg]));
513 }
514 println!();
515 }
516
517 let info = run_options.debug_info.fetch(pc).unwrap();
518
519 if info.meta.node.span.file_id != 0 {
520 let (line, column) = run_options
521 .source_map_wrapper
522 .source_map
523 .get_span_location_utf8(
524 info.meta.node.span.file_id,
525 info.meta.node.span.offset as usize,
526 );
527 let source_line_info = SourceFileLineInfo {
528 row: line,
529 file_id: info.meta.node.span.file_id as usize,
530 };
531
532 if let Some((start_row, end_row)) =
533 last_line_info.check_if_new_line(&source_line_info)
534 {
535 let mut string = String::new();
536 display_lines(
537 &mut string,
538 source_line_info.file_id as FileId,
539 start_row,
540 end_row,
541 &run_options.source_map_wrapper,
542 true,
543 );
544 print!("{string}");
545 }
546 }
547
548 let instruction = &vm.instructions()[pc];
549 let string = disasm_color(
550 instruction,
551 &info.function_debug_info.frame_memory,
552 &info.meta,
553 &InstructionPosition(pc as u32),
554 );
555 println!("{pc:04X}> {string}");
556 }
557
558 vm.step(host_function_callback);
559
560 if matches!(vm.state, VmState::Trap(_) | VmState::Panic(_)) {
562 show_crash_info(vm, run_options.debug_info, &run_options.source_map_wrapper);
563 }
564
565 if run_options.debug_memory_enabled
566 && vm.memory().execution_mode != ExecutionMode::ConstantEvaluation
567 {
568 let hash_after = calculate_memory_checksum(vm.all_memory_up_to(saved_fp));
570 assert!(
572 (hash_after == hash_before),
573 "INTERNAL ERROR: constant memory has been written to"
574 );
575 }
576 }
577}
578
579pub struct CompileAndCodeGenOptions {
580 pub compile_options: CompileOptions,
581 pub code_gen_options: CodeGenOptions,
582 pub skip_codegen: bool,
583 pub run_mode: RunMode,
584}
585
586#[must_use]
587pub fn compile_and_code_gen(
588 source_map: &mut SourceMap,
589 main_module_path: &[String],
590 options: &CompileAndCodeGenOptions,
591) -> Option<CompileAndMaybeCodeGenResult> {
592 let current_dir = PathBuf::from(Path::new(""));
593
594 let compile_result =
595 compile_main_path(source_map, main_module_path, &options.compile_options)?;
596
597 let source_map_wrapper = SourceMapWrapper {
598 source_map,
599 current_dir,
600 };
601
602 let maybe_code_gen_result =
603 if options.skip_codegen || !compile_result.program.state.errors().is_empty() {
604 None
605 } else {
606 let code_gen_result = code_gen(
607 &compile_result.program,
608 &source_map_wrapper,
609 &options.code_gen_options,
610 );
611 Some(code_gen_result)
612 };
613
614 Some(
615 CompileAndMaybeCodeGenResult {
616 compile: compile_result,
617 codegen: maybe_code_gen_result,
618 },
619 )
620}
621
622pub struct CompileCodeGenVmResult {
623 pub compile: CompileResult,
624 pub codegen: CodeGenAndVmResult,
625}
626
627pub enum CompileAndVmResult {
628 CompileOnly(CompileResult),
629 CompileAndVm(CompileCodeGenVmResult),
630}
631
632pub struct CodeGenAndVmResult {
633 pub vm: Vm,
634 pub code_gen_result: CodeGenResult,
635}
636
637pub struct StandardOnlyHostCallbacks {}
638
639impl HostFunctionCallback for StandardOnlyHostCallbacks {
640 fn dispatch_host_call(&mut self, args: HostArgs) {
641 match args.function_id {
642 1 => print_fn(args),
643 2 => pack(args),
644
645 _ => panic!("unknown external {}", args.function_id),
646 }
647 }
648}
649
650impl CompileCodeGenVmResult {
651 #[must_use]
652 pub fn get_internal_member_function(
653 &self,
654 ty: &TypeRef,
655 member_function_str: &str,
656 ) -> Option<&InternalFunctionDefinitionRef> {
657 self.compile
658 .program
659 .state
660 .associated_impls
661 .get_internal_member_function(ty, member_function_str)
662 }
663 #[must_use]
664 pub fn get_gen_internal_member_function(
665 &self,
666 ty: &TypeRef,
667 member_function_str: &str,
668 ) -> Option<&GenFunctionInfo> {
669 let x = self
670 .get_internal_member_function(ty, member_function_str)
671 .unwrap();
672
673 self.codegen
674 .code_gen_result
675 .functions
676 .get(&x.program_unique_id)
677 }
678}
679
680#[must_use]
681pub fn compile_codegen_and_create_vm_and_run_first_time(
682 source_map: &mut SourceMap,
683 root_module: &[String],
684 compile_and_code_gen_options: CompileAndCodeGenOptions,
685) -> Option<CompileAndVmResult> {
686 let result =
687 compile_codegen_and_create_vm(source_map, root_module, &compile_and_code_gen_options);
688 if let Some(mut first_result) = result {
689 if let CompileAndVmResult::CompileAndVm(found_result) = &mut first_result {
690 let mut callbacks = StandardOnlyHostCallbacks {};
691 let run_first_options = RunOptions {
692 debug_stats_enabled: false,
693 debug_opcodes_enabled: false,
694 debug_operations_enabled: false,
695 use_color: true,
696 max_count: 0,
697 debug_info: &found_result.codegen.code_gen_result.debug_info,
698 source_map_wrapper: SourceMapWrapper {
699 source_map,
700 current_dir: current_dir().unwrap(),
701 },
702 debug_memory_enabled: false,
703 };
704
705 run_first_time(
706 &mut found_result.codegen.vm,
707 &found_result.codegen.code_gen_result.constants_in_order,
708 &mut callbacks,
709 &run_first_options,
710 );
711 Some(first_result)
712 } else {
713 None
714 }
715 } else {
716 None
717 }
718}
719
720#[must_use]
722pub fn compile_codegen_and_create_vm(
723 source_map: &mut SourceMap,
724 root_module: &[String],
725 compile_and_code_gen_options: &CompileAndCodeGenOptions,
726) -> Option<CompileAndVmResult> {
727 let compile_and_maybe_code_gen =
728 compile_and_code_gen(source_map, root_module, compile_and_code_gen_options)?;
729
730 if let Some(code_gen_result) = compile_and_maybe_code_gen.codegen {
731 let vm = create_vm_with_standard_settings(
732 &code_gen_result.instructions,
733 &code_gen_result.prepared_constant_memory,
734 );
735
736 let code_gen_and_vm = CodeGenAndVmResult {
737 vm,
738 code_gen_result,
739 };
740
741 Some(CompileAndVmResult::CompileAndVm(CompileCodeGenVmResult {
742 compile: compile_and_maybe_code_gen.compile,
743 codegen: code_gen_and_vm,
744 }))
745 } else {
746 Some(CompileAndVmResult::CompileOnly(
747 compile_and_maybe_code_gen.compile,
748 ))
749 }
750}