lib-tisc/src/test.rs

78 lines
2.1 KiB
Rust
Raw Normal View History

2024-05-04 18:11:13 +02:00
use crate::{
VM, Linker, Assembler
};
#[test]
fn test_vm() {
let mut vm = VM::new(0x1000);
2024-05-09 15:41:45 +02:00
let mut linker = Linker::new();
2024-05-04 18:11:13 +02:00
2024-05-09 15:41:45 +02:00
linker.add_procedure("@",
crate::Assembler::new()
.inst( crate::VM_Instruction::Fetch )
2024-05-04 18:11:13 +02:00
.build());
2024-05-09 15:41:45 +02:00
linker.add_procedure("!",
crate::Assembler::new()
.inst( crate::VM_Instruction::Store )
2024-05-04 18:11:13 +02:00
.build());
2024-05-09 15:41:45 +02:00
2024-05-13 16:03:43 +02:00
linker.add_procedure("int-add",
2024-05-09 15:41:45 +02:00
crate::Assembler::new()
2024-05-13 16:03:43 +02:00
.inst( crate::VM_Instruction::IntAdd )
2024-05-04 18:11:13 +02:00
.build());
2024-05-13 16:03:43 +02:00
linker.add_procedure("int-sub",
2024-05-09 15:41:45 +02:00
crate::Assembler::new()
2024-05-13 16:03:43 +02:00
.inst( crate::VM_Instruction::BitNeg )
2024-05-04 18:11:13 +02:00
.lit(1)
2024-05-13 16:03:43 +02:00
.inst( crate::VM_Instruction::IntAdd )
.inst( crate::VM_Instruction::IntAdd )
2024-05-04 18:11:13 +02:00
.build());
// declare variable 'x' at address 0x86
2024-05-09 15:41:45 +02:00
linker.add_procedure("x",
crate::Assembler::new()
2024-05-04 18:11:13 +02:00
.lit(0x86)
.build());
/*
* compile & run the following program:
*
* x = 100 + 23;
* if( x != 123 ) {
* emit('*');
* 333
* } else {
* emit('+');
* 666
* }
*/
2024-05-09 15:41:45 +02:00
linker.add_procedure("main",
crate::Assembler::new()
2024-05-04 18:11:13 +02:00
// x = 123
2024-05-13 16:03:43 +02:00
.lit(100).lit(23).call("int-add")
2024-05-09 15:41:45 +02:00
.call("x").call("!")
2024-05-04 18:11:13 +02:00
2024-05-09 15:41:45 +02:00
// if ( 123 - x ) { emit '*' } else { emit '+' }
2024-05-04 18:11:13 +02:00
.lit(123)
2024-05-09 15:41:45 +02:00
.call("x").call("@")
2024-05-13 16:03:43 +02:00
.call("int-sub")
2024-05-04 18:11:13 +02:00
.branch(
crate::Assembler::new()
2024-05-09 15:41:45 +02:00
.lit(42).inst(crate::VM_Instruction::Emit)
2024-05-04 18:11:13 +02:00
.lit(111),
crate::Assembler::new()
2024-05-09 15:41:45 +02:00
.lit(43).inst(crate::VM_Instruction::Emit)
.lit(222))
2024-05-04 18:11:13 +02:00
.build());
2024-05-09 15:41:45 +02:00
let main_addr = linker.get_link_addr(&"main".into()).expect("main not foudn");
let bytecode = linker.link_total().expect("link error");
vm.load( bytecode );
vm.execute( main_addr );
assert_eq!( vm.data_stack, vec![ 222 ] );
println!("\nvm.datastack = {:?}", vm.data_stack);
2024-05-04 18:11:13 +02:00
}