Compare commits

...

4 Commits

Author SHA1 Message Date
_ c50c16b9db 🐛 bug: fix io.write and take off the `max_iters` restriction
The math is lining up with PUC Lua and LuaJIT. Now I can actually check
the speed.
2023-10-01 01:36:40 -05:00
_ fb46ede3ca 🐛 bug: fix OP_TEST ignoring `k`
I didn't know what `k` was a few days ago.
2023-10-01 01:33:47 -05:00
_ a9820677e9 🐛 bug: fix some stuff in calling native functions 2023-10-01 01:06:15 -05:00
_ 06638574f7 🔊 improve error message for this error with the missing math lib 2023-09-30 23:41:12 -05:00
8 changed files with 222 additions and 48 deletions

View File

@ -29,6 +29,7 @@
- [x] Hash tables
- [x] Fizzbuzz
- [ ] Closures
- [ ] Error handling
- [ ] Garbage collection
- [ ] Long strings
- [ ] Using arrays internally for tables

View File

@ -1,4 +1,4 @@
#[derive (Debug, PartialEq)]
#[derive (Clone, Copy, Debug, PartialEq)]
pub enum Instruction {
Add (u8, u8, u8),
AddI (u8, u8, i8),

View File

@ -221,8 +221,6 @@ pub fn parse_block <R: Read> (rdr: &mut R, blocks: &mut Vec <Block>)
{
// Ignore things I haven't implemented yet
use crate::value::Value;
parse_string (rdr)?; // function name
parse_int (rdr).unwrap (); // start line in source code
parse_int (rdr).unwrap (); // last line in source code

View File

@ -8,7 +8,7 @@ mod value;
#[cfg (test)]
mod tests;
fn main () {
fn main () -> Result <(), state::StepError> {
use state::State;
let mut list_bytecode = false;
@ -64,11 +64,10 @@ fn main () {
vm.debug_print = true;
}
let max_iters = 2000;
let mut in_break = false;
let mut last_input = String::new ();
for _ in 0..max_iters {
loop {
if in_break || breakpoints.iter ().any (|bp| vm.at_breakpoint (bp)) {
in_break = true;
dbg! (&vm.stack);
@ -86,17 +85,17 @@ fn main () {
match input.as_str ().trim_end () {
"c" => in_break = false,
"q" => return,
"q" => return Ok (()),
"registers" => {
dbg! (&vm.registers);
continue;
}
"s" => {
match vm.step () {
match vm.step ()? {
None => (),
Some (state::StepOutput::ChunkReturned (x)) => {
dbg! (x);
return;
return Ok (());
},
}
continue;
@ -105,11 +104,11 @@ fn main () {
}
}
match vm.step () {
match vm.step ()? {
None => (),
Some (state::StepOutput::ChunkReturned (x)) => {
dbg! (x);
return;
return Ok (());
},
}
}

View File

@ -59,8 +59,21 @@ pub struct State <'a> {
upvalues: &'a [Value],
}
fn lw_print (l: &mut State) -> i32 {
for i in 0..u8::try_from (l.get_top ()).unwrap () {
fn lw_io_write (l: &mut State, num_args: usize) -> usize {
for i in 0..u8::try_from (num_args).unwrap () {
match l.reg (i) {
Value::Float (x) => print! ("{}", x),
Value::Integer (x) => print! ("{}", x),
Value::String (x) => print! ("{}", x),
_ => panic! ("Can't io.write this value"),
}
}
// TODO: PUC Lua actually returns the file handle here.
0
}
fn lw_print (l: &mut State, num_args: usize) -> usize {
for i in 0..u8::try_from (num_args).unwrap () {
let input = l.reg (i);
if i == 0 {
@ -75,14 +88,66 @@ fn lw_print (l: &mut State) -> i32 {
1
}
fn lw_sqrt (l: &mut State, num_args: usize) -> usize {
assert! (num_args >= 1, "math.sqrt needs 1 argument");
let input = l.reg (0).as_float ().unwrap ();
let output = input.sqrt ();
*l.reg_mut (0) = Value::from (output);
1
}
fn lw_string_format (l: &mut State, num_args: usize) -> usize {
assert! (num_args >= 1, "string.format needs at least 1 argument");
assert_eq! (l.get_top (), 2, "string.format not fully implemented");
let f_string = l.reg (0).as_str ().unwrap ();
assert_eq! (f_string, "%0.9f");
let num = l.reg (1).as_float ().unwrap ();
let output = format! ("{:0.9}", num);
*l.reg_mut (0) = Value::from (output);
1
}
fn lw_tonumber (l: &mut State, num_args: usize) -> usize {
assert_eq! (num_args, 1, "tonumber only implemented for 1 argument");
let output = match l.reg (0) {
Value::Float (x) => Value::Float (*x),
Value::Integer (x) => Value::Integer (*x),
Value::String (x) => {
if let Ok (x) = str::parse::<i64> (x) {
Value::from (x)
}
else if let Ok (x) = str::parse::<f64> (x) {
Value::from (x)
}
else {
Value::Nil
}
},
_ => Value::Nil,
};
*l.reg_mut (0) = output;
1
}
pub enum StepOutput {
ChunkReturned (Vec <Value>),
}
#[derive (Debug)]
pub struct StepError {
frame: StackFrame,
inst: Instruction,
msg: &'static str,
}
impl <'a> State <'a> {
pub fn new (chunk: &'a Chunk, upvalues: &'a [Value]) -> Self {
Self {
registers: vec! [Value::Nil; 16],
// TODO: Stack is actually supposed to grow to a limit of
// idk 10,000. I thought it was fixed at 256.
registers: vec! [Value::Nil; 256],
top: 0,
stack: vec! [
StackFrame {
@ -108,9 +173,25 @@ impl <'a> State <'a> {
let arg = args.map (|s| Value::from (s)).enumerate ();
let arg = Value::from_iter (arg.map (|(i, v)| (Value::from (i), v)));
let io = [
("write", Value::RsFunc (lw_io_write)),
].into_iter ().map (|(k, v)| (k.to_string (), v));
let math = [
("sqrt", Value::RsFunc (lw_sqrt)),
].into_iter ().map (|(k, v)| (k.to_string (), v));
let string = [
("format", Value::RsFunc (lw_string_format)),
].into_iter ().map (|(k, v)| (k.to_string (), v));
let env = [
("arg", arg),
("io", Value::from_iter (io.into_iter ())),
("math", Value::from_iter (math.into_iter ())),
("print", Value::RsFunc (lw_print)),
("string", Value::from_iter (string.into_iter ())),
("tonumber", Value::RsFunc (lw_tonumber)),
].into_iter ().map (|(k, v)| (k.to_string (), v));
vec! [
@ -140,7 +221,17 @@ impl <'a> State <'a> {
self.top - self.stack.last ().unwrap ().register_offset
}
pub fn step (&mut self) -> Option <StepOutput> {
fn make_step_error (&self, msg: &'static str, inst: &Instruction) -> StepError
{
StepError {
frame: self.stack.last ().unwrap ().clone (),
inst: inst.clone (),
msg,
}
}
pub fn step (&mut self) -> Result <Option <StepOutput>, StepError>
{
let chunk = self.chunk;
self.step_count += 1;
@ -161,6 +252,10 @@ impl <'a> State <'a> {
// let r = &mut self.registers [frame.register_offset..];
let k = &block.constants;
let make_step_error = |msg| {
self.make_step_error (msg, instruction)
};
match instruction {
Instruction::Add (a, b, c) => {
let v_b = self.reg (*b);
@ -192,7 +287,7 @@ impl <'a> State <'a> {
*self.reg_mut (*a) = x;
},
Instruction::Call (a, b, _c) => {
Instruction::Call (a, b, c) => {
let b = usize::from (*b);
// Take arguments from registers [a + 1, a + b)
@ -230,7 +325,7 @@ impl <'a> State <'a> {
}
// Skip the PC increment at the bottom of the loop
return None;
return Ok (None);
},
Value::RsFunc (x) => {
let current_frame = self.stack.last ().unwrap ();
@ -242,21 +337,30 @@ impl <'a> State <'a> {
});
// No clue what the '1' is doing here
self.top = new_offset + b - 1;
let b = if b == 0 {
self.top - *a as usize
}
else {
b
};
// Call
let num_results = x (self);
let num_results = x (self, b - 1);
let popped_frame = self.stack.pop ().unwrap ();
let offset = popped_frame.register_offset - 1;
for i in (offset)..(offset + usize::try_from (num_results).unwrap ()) {
self.registers [i] = self.registers [i + 1 + usize::from (*a)].take ();
self.registers [i] = self.registers [i + 1].take ();
}
// Set up top for the next call
if *c == 0 {
self.top = popped_frame.register_offset - 1 + num_results;
}
},
_ => {
let stack = &self.stack;
panic! ("Cannot call value {a:?}. backtrace: {stack:?}");
Err (make_step_error ("Cannot call value"))?;
},
}
},
@ -293,7 +397,9 @@ impl <'a> State <'a> {
}
else {
let v_b = v_b.as_float ().unwrap_or_else (|| panic! ("{v_b}"));
let v_c = v_c.as_float ().unwrap_or_else (|| panic! ("{v_c}"));
let v_c = v_c.as_float ().ok_or_else (|| make_step_error ("C must be a number"))?;
Value::from (v_b / v_c)
};
@ -341,9 +447,9 @@ impl <'a> State <'a> {
},
Instruction::GetField (a, b, c) => {
let t = match self.reg (*b) {
Value::Nil => panic! ("R[B] must not be nil {}:{}", frame.block_idx, frame.program_counter),
Value::Nil => Err (make_step_error ("R[B] must not be nil"))?,
Value::Table (t) => t,
_ => panic! ("R[B] must be a table"),
_ => Err (make_step_error ("R[B] must be a table"))?,
};
let key = match &k [usize::from (*c)] {
@ -428,11 +534,17 @@ impl <'a> State <'a> {
Instruction::Jmp (s_j) => next_pc += s_j,
Instruction::Len (a, b) => {
let len = match self.reg (*b) {
Value::String (s) => s.len (),
_ => unimplemented!(),
Value::BogusClosure (_) => Err (make_step_error ("attempt to get length of a function value"))?,
Value::Boolean (_) => Err (make_step_error ("attempt to get length of a boolean value"))?,
Value::Float (_) => Err (make_step_error ("attempt to get length of a number value"))?,
Value::Integer (_) => Err (make_step_error ("attempt to get length of a number value"))?,
Value::Nil => Err (make_step_error ("attempt to get length of a nil value"))?,
Value::RsFunc (_) => Err (make_step_error ("attempt to get length of a function value"))?,
Value::String (s) => s.len ().into (),
Value::Table (t) => t.borrow ().length ().into (),
};
*self.reg_mut (*a) = len.into ();
*self.reg_mut (*a) = len;
}
Instruction::LoadF (a, sbx) => {
*self.reg_mut (*a) = Value::Float (*sbx as f64);
@ -570,15 +682,18 @@ impl <'a> State <'a> {
for i in (offset)..(offset - 1 + b) {
self.registers [i] = self.registers [i + 1 + a].take ();
}
self.top = popped_frame.register_offset - 1 + b - 1;
}
else {
// Return from the entire program
return Some (StepOutput::ChunkReturned (self.registers [a..(a + b - 1)].to_vec()));
return Ok (Some (StepOutput::ChunkReturned (self.registers [a..(a + b - 1)].to_vec())));
}
},
Instruction::Return0 => {
self.stack.pop ();
let popped_frame = self.stack.pop ().unwrap ();
next_pc = self.stack.last ().unwrap ().program_counter;
self.top = popped_frame.register_offset - 1 + 0;
},
Instruction::Return1 (a) => {
let a = usize::try_from (*a).unwrap ();
@ -602,6 +717,8 @@ impl <'a> State <'a> {
// Shift output register down
let offset = popped_frame.register_offset;
self.registers [offset - 1] = self.registers [offset + a].take ();
self.top = popped_frame.register_offset - 1 + 1;
},
Instruction::SetField (a, b, c, k_flag) => {
let value = if *k_flag {
@ -697,10 +814,10 @@ impl <'a> State <'a> {
frame.block_idx = closure.idx;
// Skip the PC increment
return None;
return Ok (None);
},
Instruction::Test (a, _k) => {
if self.reg (*a).is_truthy() {
Instruction::Test (a, k) => {
if self.reg (*a).is_truthy() != *k {
next_pc += 1;
}
},
@ -727,11 +844,11 @@ impl <'a> State <'a> {
frame.program_counter = next_pc;
}
None
Ok (None)
}
pub fn execute_chunk (&mut self, breakpoints: &[Breakpoint])
-> Vec <Value> {
-> Result <Vec <Value>, StepError> {
let max_iters = 2000;
for _ in 0..max_iters {
@ -739,9 +856,9 @@ impl <'a> State <'a> {
dbg! (&self);
}
match self.step () {
match self.step ()? {
None => (),
Some (StepOutput::ChunkReturned (x)) => return x,
Some (StepOutput::ChunkReturned (x)) => return Ok (x),
}
}

View File

@ -25,7 +25,7 @@ fn calculate_hash<T: Hash>(t: &T) -> u64 {
fn run_chunk (args: &[&str], chunk: &Chunk) -> Vec <Value> {
let upvalues = State::upvalues_from_args (args.into_iter ().map (|s| s.to_string ()));
let mut vm = State::new (chunk, &upvalues);
vm.execute_chunk (&[])
vm.execute_chunk (&[]).unwrap ()
}
/// Takes arguments and Lua bytecode, loads it, runs it,
@ -120,7 +120,7 @@ fn bools () {
let upvalues = State::upvalues_from_args (arg.into_iter ().map (|s| s.to_string ()));
let mut vm = State::new (&chunk, &upvalues);
let actual = vm.execute_chunk (&[]);
let actual = vm.execute_chunk (&[]).unwrap ();
assert_eq! (actual, expected);
}
}
@ -176,7 +176,7 @@ fn floats () {
let expected: Vec <Value> = expected;
let upvalues = State::upvalues_from_args (arg.into_iter ().map (|s| s.to_string ()));
let mut vm = State::new (&chunk, &upvalues);
let actual = vm.execute_chunk (&[]);
let actual = vm.execute_chunk (&[]).unwrap ();
assert_eq! (actual, expected);
}
@ -198,7 +198,7 @@ fn fma () {
let expected: Vec <Value> = expected;
let upvalues = State::upvalues_from_args (arg.into_iter ().map (|s| s.to_string ()));
let mut vm = State::new (&chunk, &upvalues);
let actual = vm.execute_chunk (&[]);
let actual = vm.execute_chunk (&[]).unwrap ();
assert_eq! (actual, expected);
}
@ -368,14 +368,50 @@ fn value_size () {
// with 64-bit floats
//
// It would be nice if LunarWaveVM is the same or better.
// There are some exploratory things in this test, too
// I'm also just checking a bunch of my assumptions about how
// Rust organizes and sizes different types
use std::mem::size_of;
assert! (size_of::<Box <()>> () <= 8);
assert! (size_of::<std::rc::Rc <()>> () <= 8);
{
// Make sure that Rx / Box are both pointers that hide the size
// of big types
assert! (size_of::<Box <()>> () <= 8);
assert! (size_of::<std::rc::Rc <()>> () <= 8);
}
let sz = size_of::<crate::value::Value> ();
let expected = 16;
assert! (sz <= expected, "{sz} > {expected}");
{
// Make sure LWVM's Values are 16 bytes or smaller.
// Because types are usually aligned to their size, f64s
// are supposed to be aligned to 8 bytes. So even an `Option <f64>`
// uses 8 bytes to say "Some" or "None".
// I could _maybe_ fudge this somehow but it's fine to start with.
let sz = size_of::<crate::value::Value> ();
let expected = 16;
assert! (sz <= expected, "{sz} > {expected}");
}
{
// All these are 8 bytes for the same reason Value is 16 bytes.
// Luckily Rust doesn't seem to stack the 4-byte overhead
// of Result and Option.
let sz = size_of::<(i32, i32)> ();
let expected = 8;
assert! (sz == expected, "{sz} != {expected}");
let sz = size_of::<Option <i32>> ();
let expected = 8;
assert! (sz == expected, "{sz} != {expected}");
let sz = size_of::<Result <i32, i32>> ();
let expected = 8;
assert! (sz == expected, "{sz} != {expected}");
let sz = size_of::<Result <Option <i32>, i32>> ();
let expected = 8;
assert! (sz == expected, "{sz} != {expected}");
}
}

View File

@ -26,7 +26,7 @@ pub enum Value {
Float (f64),
Integer (i64),
RsFunc (fn (&mut crate::state::State) -> i32),
RsFunc (fn (&mut crate::state::State, usize) -> usize),
String (Rc <String>),
Table (Rc <RefCell <Table>>),
@ -207,6 +207,13 @@ impl Value {
}
}
pub fn as_str (&self) -> Option <&str> {
match self {
Self::String (x) => Some (x.as_str ()),
_ => None,
}
}
pub fn as_table (&self) -> Option <&Rc <RefCell <Table>>> {
match self {
Self::Table (t) => Some (t),
@ -265,6 +272,15 @@ impl Table {
) {
self.insert_inner (a.into (), b.into ())
}
pub fn length (&self) -> i64 {
for i in 1..i64::MAX {
if self.get (i) == Value::Nil {
return i - 1;
}
}
0
}
}
impl FromIterator <(Value, Value)> for Table {

View File

@ -0,0 +1,7 @@
print ()
print ("asdf")
print (math.sqrt (16))
print (math.sqrt (16.0))
local N = tonumber (arg and arg [1]) or 1000
print (N)