Compare commits
5 Commits
bba98043c7
...
130330b688
Author | SHA1 | Date |
---|---|---|
_ | 130330b688 | |
_ | eb32a53d18 | |
_ | 08bbb53900 | |
_ | b9865b7174 | |
_ | 247d6b7a24 |
|
@ -22,6 +22,8 @@ fn lunar_wave (args: Vec <String>) -> Result <Vec <lwvm::Value>, lwvm::StepError
|
|||
let mut arg_iter = args.iter ();
|
||||
let _exe_name = arg_iter.next ().unwrap ();
|
||||
|
||||
let mut si = lwvm::Interner::default ();
|
||||
|
||||
while let Some (arg) = arg_iter.next () {
|
||||
match arg.as_str () {
|
||||
"--break" => {
|
||||
|
@ -40,7 +42,7 @@ fn lunar_wave (args: Vec <String>) -> Result <Vec <lwvm::Value>, lwvm::StepError
|
|||
let mut buf = vec! [];
|
||||
std::io::stdin ().read_to_end (&mut buf).unwrap ();
|
||||
let bc = lwvm::ensure_bytecode (buf).unwrap ();
|
||||
chunk = Some (lwvm::parse_chunk (&bc).unwrap ());
|
||||
chunk = Some (lwvm::parse_chunk (&bc, &mut si).unwrap ());
|
||||
|
||||
lua_args = vec! ["-".to_string ()];
|
||||
},
|
||||
|
@ -51,7 +53,7 @@ fn lunar_wave (args: Vec <String>) -> Result <Vec <lwvm::Value>, lwvm::StepError
|
|||
}
|
||||
else if chunk.is_none () {
|
||||
let bc = lwvm::compile_bytecode_from_file (x);
|
||||
chunk = Some (lwvm::parse_chunk (&bc).unwrap ());
|
||||
chunk = Some (lwvm::parse_chunk (&bc, &mut si).unwrap ());
|
||||
|
||||
lua_args = vec! [x.to_string ()];
|
||||
}
|
||||
|
@ -68,10 +70,12 @@ fn lunar_wave (args: Vec <String>) -> Result <Vec <lwvm::Value>, lwvm::StepError
|
|||
chunk,
|
||||
list_bytecode,
|
||||
lua_args,
|
||||
si,
|
||||
}),
|
||||
None => repl (ReplParams {
|
||||
list_bytecode,
|
||||
lua_args,
|
||||
si,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
@ -81,11 +85,13 @@ struct DebuggerParams {
|
|||
chunk: lwvm::Chunk,
|
||||
list_bytecode: bool,
|
||||
lua_args: Vec <String>,
|
||||
si: lwvm::Interner,
|
||||
}
|
||||
|
||||
struct ReplParams {
|
||||
list_bytecode: bool,
|
||||
lua_args: Vec <String>,
|
||||
si: lwvm::Interner,
|
||||
}
|
||||
|
||||
/// The interpreter mode, which has optional debugging abilities
|
||||
|
@ -97,9 +103,7 @@ fn debugger (params: DebuggerParams) -> Result <Vec <lwvm::Value>, lwvm::StepErr
|
|||
dbg! (¶ms.chunk);
|
||||
}
|
||||
|
||||
let upvalues = lwvm::State::upvalues_from_args (params.lua_args.into_iter ());
|
||||
|
||||
let mut vm = lwvm::State::new (params.chunk, upvalues);
|
||||
let mut vm = lwvm::State::new_with_args (params.chunk, params.si, params.lua_args.into_iter ());
|
||||
if std::env::var("LWVM_DEBUG").is_ok() {
|
||||
vm.debug_print = true;
|
||||
}
|
||||
|
@ -160,9 +164,7 @@ fn debugger (params: DebuggerParams) -> Result <Vec <lwvm::Value>, lwvm::StepErr
|
|||
|
||||
fn repl (params: ReplParams) -> Result <Vec <lwvm::Value>, lwvm::StepError>
|
||||
{
|
||||
let upvalues = lwvm::State::upvalues_from_args (params.lua_args.into_iter ());
|
||||
|
||||
let mut vm = lwvm::State::new (lwvm::Chunk::default (), upvalues);
|
||||
let mut vm = lwvm::State::new_with_args (lwvm::Chunk::default (), params.si, params.lua_args.into_iter ());
|
||||
|
||||
println! ("Lunar Wave 0.1.0-modified Copyright (C) 2023 ReactorScram (implements Lua 5.4 Copyright (C) 1994-2022 Lua.org, PUC-Rio");
|
||||
|
||||
|
@ -188,7 +190,7 @@ fn repl (params: ReplParams) -> Result <Vec <lwvm::Value>, lwvm::StepError>
|
|||
continue;
|
||||
},
|
||||
};
|
||||
let chunk = lwvm::parse_chunk (&bytecode).unwrap ();
|
||||
let chunk = lwvm::parse_chunk (&bytecode, &mut vm.si).unwrap ();
|
||||
|
||||
if params.list_bytecode {
|
||||
dbg! (&chunk);
|
||||
|
|
|
@ -0,0 +1,636 @@
|
|||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
fn main () {
|
||||
// PUC Lua is 250 ms
|
||||
// I'm using AOT Rust here so anything more than that
|
||||
// is simply embarrassing
|
||||
|
||||
fn timer <F: Fn ()> (f: F, label: &str) {
|
||||
let start = Instant::now ();
|
||||
f ();
|
||||
let stop = Instant::now ();
|
||||
println! ("{}: {} ms", label, (stop - start).as_millis ());
|
||||
}
|
||||
|
||||
// timer (|| n_body::<BTreeTable> (100000), "BTreeTable");
|
||||
// timer (|| n_body::<BTreeTable2> (100000), "BTreeTable2");
|
||||
// timer (|| n_body::<HashTable> (100000), "HashTable");
|
||||
// timer (|| n_body_2::<HashTable2> (100000), "HashTable2");
|
||||
|
||||
// Fastest on my system, at 83 ms
|
||||
timer (|| n_body_2::<BTreeTable3> (100000), "BTreeTable3");
|
||||
timer (|| n_body_2::<BTreeTable3> (500000), "BTreeTable3");
|
||||
timer (|| n_body_3::<BTreeTable4> (500000), "BTreeTable4");
|
||||
}
|
||||
|
||||
trait Table {
|
||||
fn get (&self, key: &str) -> f64;
|
||||
fn set (&mut self, key: &'static str, value: f64);
|
||||
}
|
||||
|
||||
#[derive (Default)]
|
||||
struct BTreeTable (BTreeMap <String, f64>);
|
||||
|
||||
impl Table for BTreeTable {
|
||||
fn get (&self, key: &str) -> f64 {
|
||||
*self.0.get (key).unwrap ()
|
||||
}
|
||||
|
||||
fn set (&mut self, key: &str, value: f64) {
|
||||
self.0.insert (key.to_string (), value);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive (Default)]
|
||||
struct BTreeTable2 (BTreeMap <&'static str, f64>);
|
||||
|
||||
impl Table for BTreeTable2 {
|
||||
fn get (&self, key: &str) -> f64 {
|
||||
*self.0.get (key).unwrap ()
|
||||
}
|
||||
|
||||
fn set (&mut self, key: &'static str, value: f64) {
|
||||
self.0.insert (key, value);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive (Default)]
|
||||
struct HashTable (HashMap <String, f64>);
|
||||
|
||||
impl Table for HashTable {
|
||||
fn get (&self, key: &str) -> f64 {
|
||||
*self.0.get (key).unwrap ()
|
||||
}
|
||||
|
||||
fn set (&mut self, key: &str, value: f64) {
|
||||
self.0.insert (key.to_string (), value);
|
||||
}
|
||||
}
|
||||
|
||||
const PI: f64 = 3.141592653589793f64;
|
||||
const SOLAR_MASS: f64 = 4.0 * PI * PI;
|
||||
|
||||
fn n_body <T: Default + Table> (num_iters: usize) {
|
||||
const X: &str = "x";
|
||||
const Y: &str = "y";
|
||||
const Z: &str = "z";
|
||||
const VX: &str = "vx";
|
||||
const VY: &str = "vy";
|
||||
const VZ: &str = "vz";
|
||||
const MASS: &str = "mass";
|
||||
|
||||
let days_per_year = 365.24;
|
||||
|
||||
let mut bodies = vec! [];
|
||||
{
|
||||
let mut t = T::default ();
|
||||
t.set (X, 0.0);
|
||||
t.set (Y, 0.0);
|
||||
t.set (Z, 0.0);
|
||||
t.set (VX, 0.0);
|
||||
t.set (VY, 0.0);
|
||||
t.set (VZ, 0.0);
|
||||
t.set (MASS, SOLAR_MASS);
|
||||
|
||||
bodies.push (t);
|
||||
}
|
||||
{
|
||||
let mut t = T::default ();
|
||||
t.set (X, 4.84143144246472090e+00);
|
||||
t.set (Y, -1.16032004402742839e+00);
|
||||
t.set (Z, -1.03622044471123109e-01);
|
||||
t.set (VX, 1.66007664274403694e-03 * days_per_year);
|
||||
t.set (VY, 7.69901118419740425e-03 * days_per_year);
|
||||
t.set (VZ, -6.90460016972063023e-05 * days_per_year);
|
||||
t.set (MASS, 9.54791938424326609e-04 * SOLAR_MASS);
|
||||
|
||||
bodies.push (t);
|
||||
}
|
||||
{
|
||||
let mut t = T::default ();
|
||||
t.set (X, 8.34336671824457987e+00);
|
||||
t.set (Y, 4.12479856412430479e+00);
|
||||
t.set (Z, -4.03523417114321381e-01);
|
||||
t.set (VX, -2.76742510726862411e-03 * days_per_year);
|
||||
t.set (VY, 4.99852801234917238e-03 * days_per_year);
|
||||
t.set (VZ, 2.30417297573763929e-05 * days_per_year);
|
||||
t.set (MASS, 2.85885980666130812e-04 * SOLAR_MASS);
|
||||
|
||||
bodies.push (t);
|
||||
}
|
||||
{
|
||||
let mut t = T::default ();
|
||||
t.set (X, 1.28943695621391310e+01);
|
||||
t.set (Y, -1.51111514016986312e+01);
|
||||
t.set (Z, -2.23307578892655734e-01);
|
||||
t.set (VX, 2.96460137564761618e-03 * days_per_year);
|
||||
t.set (VY, 2.37847173959480950e-03 * days_per_year);
|
||||
t.set (VZ, -2.96589568540237556e-05 * days_per_year);
|
||||
t.set (MASS, 4.36624404335156298e-05 * SOLAR_MASS);
|
||||
|
||||
bodies.push (t);
|
||||
}
|
||||
{
|
||||
let mut t = T::default ();
|
||||
t.set (X, 1.53796971148509165e+01);
|
||||
t.set (Y, -2.59193146099879641e+01);
|
||||
t.set (Z, 1.79258772950371181e-01);
|
||||
t.set (VX, 2.68067772490389322e-03 * days_per_year);
|
||||
t.set (VY, 1.62824170038242295e-03 * days_per_year);
|
||||
t.set (VZ, -9.51592254519715870e-05 * days_per_year);
|
||||
t.set (MASS, 5.15138902046611451e-05 * SOLAR_MASS);
|
||||
|
||||
bodies.push (t);
|
||||
}
|
||||
|
||||
fn advance <T: Table> (bodies: &mut [T], dt: f64) {
|
||||
let nbody = bodies.len ();
|
||||
|
||||
for i in 0..nbody {
|
||||
let bix;
|
||||
let biy;
|
||||
let biz;
|
||||
let bimass;
|
||||
let mut bivx;
|
||||
let mut bivy;
|
||||
let mut bivz;
|
||||
{
|
||||
let bi = &mut bodies [i];
|
||||
bix = bi.get (X);
|
||||
biy = bi.get (Y);
|
||||
biz = bi.get (Z);
|
||||
bimass = bi.get (MASS);
|
||||
bivx = bi.get (VX);
|
||||
bivy = bi.get (VY);
|
||||
bivz = bi.get (VZ);
|
||||
}
|
||||
|
||||
for j in i + 1..nbody {
|
||||
let bj = &mut bodies [j];
|
||||
let dx = bix - bj.get (X);
|
||||
let dy = biy - bj.get (Y);
|
||||
let dz = biz - bj.get (Z);
|
||||
let mut mag = (dx * dx + dy * dy + dz * dz).sqrt ();
|
||||
mag = dt / (mag * mag * mag);
|
||||
let mut bm = bj.get (MASS) * mag;
|
||||
bivx -= dx * bm;
|
||||
bivy -= dy * bm;
|
||||
bivz -= dz * bm;
|
||||
bm = bimass * mag;
|
||||
bj.set (VX, bj.get (VX) + dx * bm);
|
||||
bj.set (VY, bj.get (VY) + dy * bm);
|
||||
bj.set (VZ, bj.get (VZ) + dz * bm);
|
||||
}
|
||||
|
||||
let bi = &mut bodies [i];
|
||||
bi.set (VX, bivx);
|
||||
bi.set (VY, bivy);
|
||||
bi.set (VZ, bivz);
|
||||
bi.set (X, bix + dt * bivx);
|
||||
bi.set (Y, biy + dt * bivy);
|
||||
bi.set (Z, biz + dt * bivz);
|
||||
}
|
||||
}
|
||||
|
||||
fn energy <T: Table> (bodies: &[T]) -> f64 {
|
||||
let mut e = 0.0;
|
||||
for (i, bi) in bodies.iter ().enumerate () {
|
||||
let vx = bi.get (VX);
|
||||
let vy = bi.get (VY);
|
||||
let vz = bi.get (VZ);
|
||||
let bim = bi.get (MASS);
|
||||
|
||||
e += 0.5 * bim * (vx * vx + vy * vy + vz * vz);
|
||||
|
||||
for j in i + 1..bodies.len () {
|
||||
let bj = &bodies [j];
|
||||
let dx = bi.get (X) - bj.get (X);
|
||||
let dy = bi.get (Y) - bj.get (Y);
|
||||
let dz = bi.get (Z) - bj.get (Z);
|
||||
let distance = (dx * dx + dy * dy + dz * dz).sqrt ();
|
||||
e -= (bim * bj.get (MASS)) / distance;
|
||||
}
|
||||
}
|
||||
|
||||
e
|
||||
}
|
||||
|
||||
fn offset_momentum <T: Table> (b: &mut [T]) {
|
||||
let mut px = 0.0;
|
||||
let mut py = 0.0;
|
||||
let mut pz = 0.0;
|
||||
|
||||
for bi in b.iter () {
|
||||
let bim = bi.get (MASS);
|
||||
px += bi.get (VX) * bim;
|
||||
py += bi.get (VY) * bim;
|
||||
pz += bi.get (VZ) * bim;
|
||||
}
|
||||
|
||||
let bimass = b [0].get (MASS);
|
||||
b [0].set (VX, -px / bimass);
|
||||
b [0].set (VY, -py / bimass);
|
||||
b [0].set (VZ, -pz / bimass);
|
||||
}
|
||||
|
||||
offset_momentum (&mut bodies);
|
||||
println! ("{:0.9}", energy (&bodies));
|
||||
for _ in 0..num_iters {
|
||||
advance (&mut bodies, 0.01);
|
||||
}
|
||||
println! ("{:0.9}", energy (&bodies));
|
||||
}
|
||||
|
||||
trait Table2 {
|
||||
fn get (&self, key: i64) -> f64;
|
||||
fn set (&mut self, key: i64, value: f64);
|
||||
}
|
||||
|
||||
#[derive (Default)]
|
||||
struct BTreeTable3 (BTreeMap <i64, f64>);
|
||||
|
||||
impl Table2 for BTreeTable3 {
|
||||
fn get (&self, key: i64) -> f64 {
|
||||
*self.0.get (&key).unwrap ()
|
||||
}
|
||||
|
||||
fn set (&mut self, key: i64, value: f64) {
|
||||
self.0.insert (key, value);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive (Default)]
|
||||
struct HashTable2 (HashMap <i64, f64>);
|
||||
|
||||
impl Table2 for HashTable2 {
|
||||
fn get (&self, key: i64) -> f64 {
|
||||
*self.0.get (&key).unwrap ()
|
||||
}
|
||||
|
||||
fn set (&mut self, key: i64, value: f64) {
|
||||
self.0.insert (key, value);
|
||||
}
|
||||
}
|
||||
|
||||
fn n_body_2 <T: Default + Table2> (num_iters: usize) {
|
||||
const X: i64 = 1;
|
||||
const Y: i64 = 2;
|
||||
const Z: i64 = 3;
|
||||
const VX: i64 = 4;
|
||||
const VY: i64 = 5;
|
||||
const VZ: i64 = 6;
|
||||
const MASS: i64 = 7;
|
||||
|
||||
let days_per_year = 365.24;
|
||||
|
||||
let mut bodies = vec! [];
|
||||
{
|
||||
let mut t = T::default ();
|
||||
t.set (X, 0.0);
|
||||
t.set (Y, 0.0);
|
||||
t.set (Z, 0.0);
|
||||
t.set (VX, 0.0);
|
||||
t.set (VY, 0.0);
|
||||
t.set (VZ, 0.0);
|
||||
t.set (MASS, SOLAR_MASS);
|
||||
|
||||
bodies.push (t);
|
||||
}
|
||||
{
|
||||
let mut t = T::default ();
|
||||
t.set (X, 4.84143144246472090e+00);
|
||||
t.set (Y, -1.16032004402742839e+00);
|
||||
t.set (Z, -1.03622044471123109e-01);
|
||||
t.set (VX, 1.66007664274403694e-03 * days_per_year);
|
||||
t.set (VY, 7.69901118419740425e-03 * days_per_year);
|
||||
t.set (VZ, -6.90460016972063023e-05 * days_per_year);
|
||||
t.set (MASS, 9.54791938424326609e-04 * SOLAR_MASS);
|
||||
|
||||
bodies.push (t);
|
||||
}
|
||||
{
|
||||
let mut t = T::default ();
|
||||
t.set (X, 8.34336671824457987e+00);
|
||||
t.set (Y, 4.12479856412430479e+00);
|
||||
t.set (Z, -4.03523417114321381e-01);
|
||||
t.set (VX, -2.76742510726862411e-03 * days_per_year);
|
||||
t.set (VY, 4.99852801234917238e-03 * days_per_year);
|
||||
t.set (VZ, 2.30417297573763929e-05 * days_per_year);
|
||||
t.set (MASS, 2.85885980666130812e-04 * SOLAR_MASS);
|
||||
|
||||
bodies.push (t);
|
||||
}
|
||||
{
|
||||
let mut t = T::default ();
|
||||
t.set (X, 1.28943695621391310e+01);
|
||||
t.set (Y, -1.51111514016986312e+01);
|
||||
t.set (Z, -2.23307578892655734e-01);
|
||||
t.set (VX, 2.96460137564761618e-03 * days_per_year);
|
||||
t.set (VY, 2.37847173959480950e-03 * days_per_year);
|
||||
t.set (VZ, -2.96589568540237556e-05 * days_per_year);
|
||||
t.set (MASS, 4.36624404335156298e-05 * SOLAR_MASS);
|
||||
|
||||
bodies.push (t);
|
||||
}
|
||||
{
|
||||
let mut t = T::default ();
|
||||
t.set (X, 1.53796971148509165e+01);
|
||||
t.set (Y, -2.59193146099879641e+01);
|
||||
t.set (Z, 1.79258772950371181e-01);
|
||||
t.set (VX, 2.68067772490389322e-03 * days_per_year);
|
||||
t.set (VY, 1.62824170038242295e-03 * days_per_year);
|
||||
t.set (VZ, -9.51592254519715870e-05 * days_per_year);
|
||||
t.set (MASS, 5.15138902046611451e-05 * SOLAR_MASS);
|
||||
|
||||
bodies.push (t);
|
||||
}
|
||||
|
||||
fn advance <T: Table2> (bodies: &mut [T], dt: f64) {
|
||||
let nbody = bodies.len ();
|
||||
|
||||
for i in 0..nbody {
|
||||
let bix;
|
||||
let biy;
|
||||
let biz;
|
||||
let bimass;
|
||||
let mut bivx;
|
||||
let mut bivy;
|
||||
let mut bivz;
|
||||
{
|
||||
let bi = &mut bodies [i];
|
||||
bix = bi.get (X);
|
||||
biy = bi.get (Y);
|
||||
biz = bi.get (Z);
|
||||
bimass = bi.get (MASS);
|
||||
bivx = bi.get (VX);
|
||||
bivy = bi.get (VY);
|
||||
bivz = bi.get (VZ);
|
||||
}
|
||||
|
||||
for j in i + 1..nbody {
|
||||
let bj = &mut bodies [j];
|
||||
let dx = bix - bj.get (X);
|
||||
let dy = biy - bj.get (Y);
|
||||
let dz = biz - bj.get (Z);
|
||||
let mut mag = (dx * dx + dy * dy + dz * dz).sqrt ();
|
||||
mag = dt / (mag * mag * mag);
|
||||
let mut bm = bj.get (MASS) * mag;
|
||||
bivx -= dx * bm;
|
||||
bivy -= dy * bm;
|
||||
bivz -= dz * bm;
|
||||
bm = bimass * mag;
|
||||
bj.set (VX, bj.get (VX) + dx * bm);
|
||||
bj.set (VY, bj.get (VY) + dy * bm);
|
||||
bj.set (VZ, bj.get (VZ) + dz * bm);
|
||||
}
|
||||
|
||||
let bi = &mut bodies [i];
|
||||
bi.set (VX, bivx);
|
||||
bi.set (VY, bivy);
|
||||
bi.set (VZ, bivz);
|
||||
bi.set (X, bix + dt * bivx);
|
||||
bi.set (Y, biy + dt * bivy);
|
||||
bi.set (Z, biz + dt * bivz);
|
||||
}
|
||||
}
|
||||
|
||||
fn energy <T: Table2> (bodies: &[T]) -> f64 {
|
||||
let mut e = 0.0;
|
||||
for (i, bi) in bodies.iter ().enumerate () {
|
||||
let vx = bi.get (VX);
|
||||
let vy = bi.get (VY);
|
||||
let vz = bi.get (VZ);
|
||||
let bim = bi.get (MASS);
|
||||
|
||||
e += 0.5 * bim * (vx * vx + vy * vy + vz * vz);
|
||||
|
||||
for j in i + 1..bodies.len () {
|
||||
let bj = &bodies [j];
|
||||
let dx = bi.get (X) - bj.get (X);
|
||||
let dy = bi.get (Y) - bj.get (Y);
|
||||
let dz = bi.get (Z) - bj.get (Z);
|
||||
let distance = (dx * dx + dy * dy + dz * dz).sqrt ();
|
||||
e -= (bim * bj.get (MASS)) / distance;
|
||||
}
|
||||
}
|
||||
|
||||
e
|
||||
}
|
||||
|
||||
fn offset_momentum <T: Table2> (b: &mut [T]) {
|
||||
let mut px = 0.0;
|
||||
let mut py = 0.0;
|
||||
let mut pz = 0.0;
|
||||
|
||||
for bi in b.iter () {
|
||||
let bim = bi.get (MASS);
|
||||
px += bi.get (VX) * bim;
|
||||
py += bi.get (VY) * bim;
|
||||
pz += bi.get (VZ) * bim;
|
||||
}
|
||||
|
||||
let bimass = b [0].get (MASS);
|
||||
b [0].set (VX, -px / bimass);
|
||||
b [0].set (VY, -py / bimass);
|
||||
b [0].set (VZ, -pz / bimass);
|
||||
}
|
||||
|
||||
offset_momentum (&mut bodies);
|
||||
println! ("{:0.9}", energy (&bodies));
|
||||
for _ in 0..num_iters {
|
||||
advance (&mut bodies, 0.01);
|
||||
}
|
||||
println! ("{:0.9}", energy (&bodies));
|
||||
}
|
||||
|
||||
trait Table3 {
|
||||
fn get (&self, key: u64) -> f64;
|
||||
fn set (&mut self, key: u64, value: f64);
|
||||
}
|
||||
|
||||
#[derive (Default)]
|
||||
struct BTreeTable4 (BTreeMap <u64, f64>);
|
||||
|
||||
impl Table3 for BTreeTable4 {
|
||||
fn get (&self, key: u64) -> f64 {
|
||||
*self.0.get (&key).unwrap ()
|
||||
}
|
||||
|
||||
fn set (&mut self, key: u64, value: f64) {
|
||||
self.0.insert (key, value);
|
||||
}
|
||||
}
|
||||
|
||||
fn n_body_3 <T: Default + Table3> (num_iters: usize) {
|
||||
const X: u64 = 1;
|
||||
const Y: u64 = 2;
|
||||
const Z: u64 = 3;
|
||||
const VX: u64 = 4;
|
||||
const VY: u64 = 5;
|
||||
const VZ: u64 = 6;
|
||||
const MASS: u64 = 7;
|
||||
|
||||
let days_per_year = 365.24;
|
||||
|
||||
let mut bodies = vec! [];
|
||||
{
|
||||
let mut t = T::default ();
|
||||
t.set (X, 0.0);
|
||||
t.set (Y, 0.0);
|
||||
t.set (Z, 0.0);
|
||||
t.set (VX, 0.0);
|
||||
t.set (VY, 0.0);
|
||||
t.set (VZ, 0.0);
|
||||
t.set (MASS, SOLAR_MASS);
|
||||
|
||||
bodies.push (t);
|
||||
}
|
||||
{
|
||||
let mut t = T::default ();
|
||||
t.set (X, 4.84143144246472090e+00);
|
||||
t.set (Y, -1.16032004402742839e+00);
|
||||
t.set (Z, -1.03622044471123109e-01);
|
||||
t.set (VX, 1.66007664274403694e-03 * days_per_year);
|
||||
t.set (VY, 7.69901118419740425e-03 * days_per_year);
|
||||
t.set (VZ, -6.90460016972063023e-05 * days_per_year);
|
||||
t.set (MASS, 9.54791938424326609e-04 * SOLAR_MASS);
|
||||
|
||||
bodies.push (t);
|
||||
}
|
||||
{
|
||||
let mut t = T::default ();
|
||||
t.set (X, 8.34336671824457987e+00);
|
||||
t.set (Y, 4.12479856412430479e+00);
|
||||
t.set (Z, -4.03523417114321381e-01);
|
||||
t.set (VX, -2.76742510726862411e-03 * days_per_year);
|
||||
t.set (VY, 4.99852801234917238e-03 * days_per_year);
|
||||
t.set (VZ, 2.30417297573763929e-05 * days_per_year);
|
||||
t.set (MASS, 2.85885980666130812e-04 * SOLAR_MASS);
|
||||
|
||||
bodies.push (t);
|
||||
}
|
||||
{
|
||||
let mut t = T::default ();
|
||||
t.set (X, 1.28943695621391310e+01);
|
||||
t.set (Y, -1.51111514016986312e+01);
|
||||
t.set (Z, -2.23307578892655734e-01);
|
||||
t.set (VX, 2.96460137564761618e-03 * days_per_year);
|
||||
t.set (VY, 2.37847173959480950e-03 * days_per_year);
|
||||
t.set (VZ, -2.96589568540237556e-05 * days_per_year);
|
||||
t.set (MASS, 4.36624404335156298e-05 * SOLAR_MASS);
|
||||
|
||||
bodies.push (t);
|
||||
}
|
||||
{
|
||||
let mut t = T::default ();
|
||||
t.set (X, 1.53796971148509165e+01);
|
||||
t.set (Y, -2.59193146099879641e+01);
|
||||
t.set (Z, 1.79258772950371181e-01);
|
||||
t.set (VX, 2.68067772490389322e-03 * days_per_year);
|
||||
t.set (VY, 1.62824170038242295e-03 * days_per_year);
|
||||
t.set (VZ, -9.51592254519715870e-05 * days_per_year);
|
||||
t.set (MASS, 5.15138902046611451e-05 * SOLAR_MASS);
|
||||
|
||||
bodies.push (t);
|
||||
}
|
||||
|
||||
fn advance <T: Table3> (bodies: &mut [T], dt: f64) {
|
||||
let nbody = bodies.len ();
|
||||
|
||||
for i in 0..nbody {
|
||||
let bix;
|
||||
let biy;
|
||||
let biz;
|
||||
let bimass;
|
||||
let mut bivx;
|
||||
let mut bivy;
|
||||
let mut bivz;
|
||||
{
|
||||
let bi = &mut bodies [i];
|
||||
bix = bi.get (X);
|
||||
biy = bi.get (Y);
|
||||
biz = bi.get (Z);
|
||||
bimass = bi.get (MASS);
|
||||
bivx = bi.get (VX);
|
||||
bivy = bi.get (VY);
|
||||
bivz = bi.get (VZ);
|
||||
}
|
||||
|
||||
for j in i + 1..nbody {
|
||||
let bj = &mut bodies [j];
|
||||
let dx = bix - bj.get (X);
|
||||
let dy = biy - bj.get (Y);
|
||||
let dz = biz - bj.get (Z);
|
||||
let mut mag = (dx * dx + dy * dy + dz * dz).sqrt ();
|
||||
mag = dt / (mag * mag * mag);
|
||||
let mut bm = bj.get (MASS) * mag;
|
||||
bivx -= dx * bm;
|
||||
bivy -= dy * bm;
|
||||
bivz -= dz * bm;
|
||||
bm = bimass * mag;
|
||||
bj.set (VX, bj.get (VX) + dx * bm);
|
||||
bj.set (VY, bj.get (VY) + dy * bm);
|
||||
bj.set (VZ, bj.get (VZ) + dz * bm);
|
||||
}
|
||||
|
||||
let bi = &mut bodies [i];
|
||||
bi.set (VX, bivx);
|
||||
bi.set (VY, bivy);
|
||||
bi.set (VZ, bivz);
|
||||
bi.set (X, bix + dt * bivx);
|
||||
bi.set (Y, biy + dt * bivy);
|
||||
bi.set (Z, biz + dt * bivz);
|
||||
}
|
||||
}
|
||||
|
||||
fn energy <T: Table3> (bodies: &[T]) -> f64 {
|
||||
let mut e = 0.0;
|
||||
for (i, bi) in bodies.iter ().enumerate () {
|
||||
let vx = bi.get (VX);
|
||||
let vy = bi.get (VY);
|
||||
let vz = bi.get (VZ);
|
||||
let bim = bi.get (MASS);
|
||||
|
||||
e += 0.5 * bim * (vx * vx + vy * vy + vz * vz);
|
||||
|
||||
for j in i + 1..bodies.len () {
|
||||
let bj = &bodies [j];
|
||||
let dx = bi.get (X) - bj.get (X);
|
||||
let dy = bi.get (Y) - bj.get (Y);
|
||||
let dz = bi.get (Z) - bj.get (Z);
|
||||
let distance = (dx * dx + dy * dy + dz * dz).sqrt ();
|
||||
e -= (bim * bj.get (MASS)) / distance;
|
||||
}
|
||||
}
|
||||
|
||||
e
|
||||
}
|
||||
|
||||
fn offset_momentum <T: Table3> (b: &mut [T]) {
|
||||
let mut px = 0.0;
|
||||
let mut py = 0.0;
|
||||
let mut pz = 0.0;
|
||||
|
||||
for bi in b.iter () {
|
||||
let bim = bi.get (MASS);
|
||||
px += bi.get (VX) * bim;
|
||||
py += bi.get (VY) * bim;
|
||||
pz += bi.get (VZ) * bim;
|
||||
}
|
||||
|
||||
let bimass = b [0].get (MASS);
|
||||
b [0].set (VX, -px / bimass);
|
||||
b [0].set (VY, -py / bimass);
|
||||
b [0].set (VZ, -pz / bimass);
|
||||
}
|
||||
|
||||
offset_momentum (&mut bodies);
|
||||
println! ("{:0.9}", energy (&bodies));
|
||||
for _ in 0..num_iters {
|
||||
advance (&mut bodies, 0.01);
|
||||
}
|
||||
println! ("{:0.9}", energy (&bodies));
|
||||
}
|
|
@ -2,6 +2,7 @@ mod error;
|
|||
mod instruction;
|
||||
mod loader;
|
||||
mod state;
|
||||
mod string_interner;
|
||||
mod value;
|
||||
|
||||
pub use error::Error as Error;
|
||||
|
@ -15,6 +16,7 @@ pub use state::Chunk as Chunk;
|
|||
pub use state::State as State;
|
||||
pub use state::StepError as StepError;
|
||||
pub use state::StepOutput as StepOutput;
|
||||
pub use string_interner::Interner as Interner;
|
||||
pub use value::Value as Value;
|
||||
|
||||
#[cfg (test)]
|
||||
|
|
|
@ -5,7 +5,8 @@ use crate::{
|
|||
state::{
|
||||
Block,
|
||||
Chunk,
|
||||
}
|
||||
},
|
||||
string_interner::Interner,
|
||||
};
|
||||
|
||||
pub fn compile_bytecode_from_file (path: &str) -> Vec <u8> {
|
||||
|
@ -242,7 +243,7 @@ fn parse_i64 <R: Read> (rdr: &mut R) -> Option <i64> {
|
|||
// code, but I don't like recursion in general, and I don't know
|
||||
// why PUC wrote it that way.
|
||||
|
||||
pub fn parse_block <R: Read> (rdr: &mut R, blocks: &mut Vec <Block>)
|
||||
pub fn parse_block <R: Read> (rdr: &mut R, si: &mut Interner, blocks: &mut Vec <Block>)
|
||||
-> Option <()>
|
||||
{
|
||||
// Ignore things I haven't implemented yet
|
||||
|
@ -273,12 +274,12 @@ pub fn parse_block <R: Read> (rdr: &mut R, blocks: &mut Vec <Block>)
|
|||
|
||||
let val = match const_type {
|
||||
3 => parse_i64 (rdr).unwrap ().into (),
|
||||
4 => parse_string (rdr).unwrap ().into (),
|
||||
4 => si.to_value (parse_string (rdr).unwrap ().as_str ()),
|
||||
|
||||
// For LUA_TNUMBER, PUC Lua uses a macro that adds 16 to signify a float
|
||||
19 => parse_float (rdr).unwrap ().into (),
|
||||
// 0x10 + 4 = long string
|
||||
20 => parse_string (rdr).unwrap ().into (),
|
||||
20 => si.to_value (parse_string (rdr).unwrap ().as_str ()),
|
||||
x => panic! ("Constant {} has type {}", i, x),
|
||||
};
|
||||
|
||||
|
@ -312,7 +313,7 @@ pub fn parse_block <R: Read> (rdr: &mut R, blocks: &mut Vec <Block>)
|
|||
// Subfunctions. PUC calls them protos.
|
||||
let protos_count = parse_int (rdr).unwrap ();
|
||||
for _ in 0..protos_count {
|
||||
parse_block (rdr, blocks).unwrap ();
|
||||
parse_block (rdr, si, blocks).unwrap ();
|
||||
}
|
||||
|
||||
// Skip over debug stuff
|
||||
|
@ -348,12 +349,12 @@ pub fn parse_block <R: Read> (rdr: &mut R, blocks: &mut Vec <Block>)
|
|||
Some (())
|
||||
}
|
||||
|
||||
pub fn parse_chunk (buf: &[u8]) -> Option <Chunk> {
|
||||
pub fn parse_chunk (buf: &[u8], si: &mut Interner) -> Option <Chunk> {
|
||||
let mut rdr = std::io::Cursor::new (buf);
|
||||
parse_chunk_from_reader (&mut rdr)
|
||||
parse_chunk_from_reader (&mut rdr, si)
|
||||
}
|
||||
|
||||
pub fn parse_chunk_from_reader <R: Read> (rdr: &mut R) -> Option <Chunk> {
|
||||
pub fn parse_chunk_from_reader <R: Read> (rdr: &mut R, si: &mut Interner) -> Option <Chunk> {
|
||||
// Discard 32 bytes from the start of the file.
|
||||
// This is magic number, version number, etc.
|
||||
|
||||
|
@ -364,7 +365,7 @@ pub fn parse_chunk_from_reader <R: Read> (rdr: &mut R) -> Option <Chunk> {
|
|||
|
||||
let mut blocks = vec![];
|
||||
|
||||
parse_block (rdr, &mut blocks).unwrap ();
|
||||
parse_block (rdr, si, &mut blocks).unwrap ();
|
||||
|
||||
Some (Chunk {
|
||||
blocks,
|
||||
|
@ -373,6 +374,8 @@ pub fn parse_chunk_from_reader <R: Read> (rdr: &mut R) -> Option <Chunk> {
|
|||
|
||||
#[cfg (test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn load_size () {
|
||||
let f = |input: &[u8]| {
|
||||
|
@ -441,6 +444,8 @@ mod tests {
|
|||
fn parse_nested_functions () {
|
||||
use std::io::Read;
|
||||
|
||||
let mut si = Interner::default ();
|
||||
|
||||
let bytecode = include_bytes! ("../test_vectors/functions.luac");
|
||||
|
||||
{
|
||||
|
@ -451,7 +456,7 @@ mod tests {
|
|||
|
||||
let mut blocks = vec! [];
|
||||
|
||||
super::parse_block (&mut rdr, &mut blocks).unwrap ();
|
||||
super::parse_block (&mut rdr, &mut si, &mut blocks).unwrap ();
|
||||
|
||||
assert_eq! (blocks [0].instructions.len (), 15);
|
||||
assert_eq! (blocks [1].instructions.len (), 6);
|
||||
|
@ -461,7 +466,7 @@ mod tests {
|
|||
}
|
||||
|
||||
if false {
|
||||
let file = crate::loader::parse_chunk (bytecode).unwrap ();
|
||||
let file = crate::loader::parse_chunk (bytecode, &mut si).unwrap ();
|
||||
|
||||
assert_eq! (file.blocks.len (), 5);
|
||||
}
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
use crate::{
|
||||
instruction::Instruction,
|
||||
string_interner::Interner,
|
||||
value::{
|
||||
BogusClosure,
|
||||
Value,
|
||||
|
@ -54,7 +55,10 @@ pub struct State {
|
|||
pub debug_print: bool,
|
||||
step_count: u32,
|
||||
chunk: Chunk,
|
||||
upvalues: Vec <Value>,
|
||||
pub upvalues: Vec <Value>,
|
||||
pub si: Interner,
|
||||
register_offset: usize,
|
||||
block_idx: usize,
|
||||
}
|
||||
|
||||
fn lw_io_write (l: &mut State, num_args: usize) -> usize {
|
||||
|
@ -62,7 +66,7 @@ fn lw_io_write (l: &mut State, num_args: usize) -> usize {
|
|||
match l.reg (i) {
|
||||
Value::Float (x) => print! ("{}", x),
|
||||
Value::Integer (x) => print! ("{}", x),
|
||||
Value::String (x) => print! ("{}", x),
|
||||
Value::String (x) => print! ("{}", l.si.get (*x)),
|
||||
_ => panic! ("Can't io.write this value"),
|
||||
}
|
||||
}
|
||||
|
@ -97,12 +101,12 @@ 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");
|
||||
assert_eq! (Value::String (f_string), l.to_string ("%0.9f"));
|
||||
let num = l.reg (1).as_float ().unwrap ();
|
||||
|
||||
let output = format! ("{:0.9}", num);
|
||||
|
||||
*l.reg_mut (0) = Value::from (output);
|
||||
*l.reg_mut (0) = l.to_string (&output);
|
||||
1
|
||||
}
|
||||
|
||||
|
@ -117,14 +121,14 @@ fn lw_table_concat (l: &mut State, num_args: usize) -> usize {
|
|||
|
||||
for i in 0..t.length () {
|
||||
if i > 0 {
|
||||
s.push_str (joiner);
|
||||
s.push_str (l.si.get (joiner));
|
||||
}
|
||||
let x = t.get_int (i + 1);
|
||||
s.push_str (&format! ("{}", x));
|
||||
}
|
||||
s
|
||||
};
|
||||
*l.reg_mut (0) = Value::from (s);
|
||||
*l.reg_mut (0) = l.to_string (&s);
|
||||
1
|
||||
}
|
||||
|
||||
|
@ -137,15 +141,15 @@ fn lw_table_pack (l: &mut State, num_args: usize) -> usize {
|
|||
1
|
||||
}
|
||||
|
||||
fn tonumber (value: &Value) -> Value {
|
||||
fn tonumber (l: &State, value: &Value) -> Value {
|
||||
match value {
|
||||
Value::Float (x) => Value::Float (*x),
|
||||
Value::Integer (x) => Value::Integer (*x),
|
||||
Value::String (x) => {
|
||||
if let Ok (x) = str::parse::<i64> (x) {
|
||||
if let Ok (x) = str::parse::<i64> (l.si.get (*x)) {
|
||||
Value::from (x)
|
||||
}
|
||||
else if let Ok (x) = str::parse::<f64> (x) {
|
||||
else if let Ok (x) = str::parse::<f64> (l.si.get (*x)) {
|
||||
Value::from (x)
|
||||
}
|
||||
else {
|
||||
|
@ -158,7 +162,7 @@ fn tonumber (value: &Value) -> Value {
|
|||
|
||||
fn lw_tonumber (l: &mut State, num_args: usize) -> usize {
|
||||
assert_eq! (num_args, 1, "tonumber only implemented for 1 argument");
|
||||
let output = tonumber (l.reg (0));
|
||||
let output = tonumber (&l, l.reg (0));
|
||||
*l.reg_mut (0) = output;
|
||||
1
|
||||
}
|
||||
|
@ -191,6 +195,30 @@ impl State {
|
|||
step_count: 0,
|
||||
chunk,
|
||||
upvalues,
|
||||
si: Default::default (),
|
||||
register_offset: 0,
|
||||
block_idx: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_with_args <I: Iterator <Item = String>> (chunk: Chunk, mut si: Interner, args: I) -> Self {
|
||||
let upvalues = Self::upvalues_from_args (&mut si, args);
|
||||
|
||||
Self {
|
||||
// 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::default (),
|
||||
],
|
||||
debug_print: false,
|
||||
step_count: 0,
|
||||
chunk,
|
||||
upvalues,
|
||||
si,
|
||||
register_offset: 0,
|
||||
block_idx: 0,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -199,27 +227,27 @@ impl State {
|
|||
frame.block_idx == bp.block_idx && frame.program_counter == bp.program_counter
|
||||
}
|
||||
|
||||
pub fn upvalues_from_args <I: Iterator <Item = String>> (args: I) -> Vec <Value>
|
||||
pub fn upvalues_from_args <I: Iterator <Item = String>> (si: &mut Interner, args: I) -> Vec <Value>
|
||||
{
|
||||
let arg = args.map (|s| Value::from (s)).enumerate ();
|
||||
let arg = Value::from_iter (arg.map (|(i, v)| (Value::from (i), v)));
|
||||
let arg = args.map (|s| si.intern (&s)).enumerate ();
|
||||
let arg = Value::from_iter (arg.map (|(i, v)| (Value::from (i), Value::String (v))));
|
||||
|
||||
let io = [
|
||||
let io: Vec <_> = [
|
||||
("write", Value::RsFunc (lw_io_write)),
|
||||
].into_iter ().map (|(k, v)| (k.to_string (), v));
|
||||
].into_iter ().map (|(k, v)| (si.intern (k), v)).collect ();
|
||||
|
||||
let math = [
|
||||
let math: Vec <_> = [
|
||||
("sqrt", Value::RsFunc (lw_sqrt)),
|
||||
].into_iter ().map (|(k, v)| (k.to_string (), v));
|
||||
].into_iter ().map (|(k, v)| (si.intern (k), v)).collect ();
|
||||
|
||||
let string = [
|
||||
let string: Vec <_> = [
|
||||
("format", Value::RsFunc (lw_string_format)),
|
||||
].into_iter ().map (|(k, v)| (k.to_string (), v));
|
||||
].into_iter ().map (|(k, v)| (si.intern (k), v)).collect ();
|
||||
|
||||
let table = [
|
||||
let table: Vec <_> = [
|
||||
("concat", Value::RsFunc (lw_table_concat)),
|
||||
("pack", Value::RsFunc (lw_table_pack)),
|
||||
].into_iter ().map (|(k, v)| (k.to_string (), v));
|
||||
].into_iter ().map (|(k, v)| (si.intern (k), v)).collect ();
|
||||
|
||||
let env = [
|
||||
("arg", arg),
|
||||
|
@ -229,7 +257,7 @@ impl State {
|
|||
("string", Value::from_iter (string.into_iter ())),
|
||||
("table", Value::from_iter (table.into_iter ())),
|
||||
("tonumber", Value::RsFunc (lw_tonumber)),
|
||||
].into_iter ().map (|(k, v)| (k.to_string (), v));
|
||||
].into_iter ().map (|(k, v)| (si.intern (k), v));
|
||||
|
||||
vec! [
|
||||
Value::from_iter (env.into_iter ()),
|
||||
|
@ -244,13 +272,11 @@ impl State {
|
|||
/// Short form to get access to a register within our window
|
||||
|
||||
pub fn reg (&self, i: u8) -> &Value {
|
||||
let frame = self.stack.last ().unwrap ();
|
||||
&self.registers [frame.register_offset + i as usize]
|
||||
&self.registers [self.register_offset + i as usize]
|
||||
}
|
||||
|
||||
pub fn reg_mut (&mut self, i: u8) -> &mut Value {
|
||||
let frame = self.stack.last ().unwrap ();
|
||||
&mut self.registers [frame.register_offset + i as usize]
|
||||
&mut self.registers [self.register_offset + i as usize]
|
||||
}
|
||||
|
||||
// For native functions to check how many args they got
|
||||
|
@ -267,18 +293,120 @@ impl State {
|
|||
}
|
||||
}
|
||||
|
||||
fn op_add (&mut self, a: u8, b: u8, c: u8) -> bool {
|
||||
let v_b = self.reg (b);
|
||||
let v_c = self.reg (c);
|
||||
|
||||
*self.reg_mut (a) = match (v_b, v_c) {
|
||||
(Value::Float (b), Value::Float (c)) => Value::from (b + c),
|
||||
(Value::Integer (b), Value::Integer (c)) => Value::from (b + c),
|
||||
(Value::Integer (b), Value::Float (c)) => Value::from (*b as f64 + c),
|
||||
(Value::Float (b), Value::Integer (c)) => Value::from (b + *c as f64),
|
||||
_ => return false,
|
||||
};
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
fn op_get_field (&mut self, a: u8, b: u8, c: u8) {
|
||||
let block = self.chunk.blocks.get (self.block_idx).unwrap ();
|
||||
let constants = &block.constants;
|
||||
|
||||
let key = match &constants [usize::from (c)] {
|
||||
Value::String (s) => s,
|
||||
_ => panic! ("K[C] must be a string"),
|
||||
};
|
||||
|
||||
let val = match &self.registers [self.register_offset + usize::from (b)] {
|
||||
Value::Nil => panic! ("R[B] must not be nil"),
|
||||
Value::Table (t) => t.borrow ().get_str (*key).clone (),
|
||||
_ => panic! ("R[B] must be a table"),
|
||||
};
|
||||
|
||||
*self.reg_mut (a) = val;
|
||||
}
|
||||
|
||||
fn op_get_table (&mut self, a: u8, b: u8, c: u8) {
|
||||
let t = match self.reg (b) {
|
||||
Value::Table (t) => t,
|
||||
_ => panic! ("R[B] must be a table"),
|
||||
};
|
||||
|
||||
let key = self.reg (c);
|
||||
|
||||
let val = t.borrow ().get (key.clone ()).clone ();
|
||||
|
||||
*self.reg_mut (a) = val;
|
||||
}
|
||||
|
||||
fn op_mmbin (&mut self, a: u8, b: u8, _c: u8) {
|
||||
let a = self.reg (a);
|
||||
let b = self.reg (b);
|
||||
|
||||
if a.as_float().is_some() && b.as_float().is_some () {
|
||||
// No need for metamethods
|
||||
}
|
||||
else {
|
||||
panic! ("Not sure how to implement OP_MMBIN for these 2 values {a:?}, {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn op_mul (&mut self, a: u8, b: u8, c: u8) -> bool {
|
||||
let v_b = self.reg (b);
|
||||
let v_c = self.reg (c);
|
||||
|
||||
*self.reg_mut (a) = match (v_b, v_c) {
|
||||
(Value::Float (b), Value::Float (c)) => Value::from (b * c),
|
||||
(Value::Integer (b), Value::Integer (c)) => Value::from (b * c),
|
||||
(Value::Integer (b), Value::Float (c)) => Value::from (*b as f64 * c),
|
||||
(Value::Float (b), Value::Integer (c)) => Value::from (b * *c as f64),
|
||||
_ => return false,
|
||||
};
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
fn op_set_field (&mut self, a: u8, b: u8, c: u8, k: bool) {
|
||||
let frame = self.stack.last ().unwrap ();
|
||||
let block = self.chunk.blocks.get (frame.block_idx).unwrap ();
|
||||
let constants = &block.constants;
|
||||
|
||||
let value = if k {
|
||||
&constants [usize::from (c)]
|
||||
}
|
||||
else {
|
||||
self.reg (c)
|
||||
}
|
||||
.clone ();
|
||||
|
||||
let b = usize::try_from (b).unwrap ();
|
||||
|
||||
let key = match constants.get (b).unwrap () {
|
||||
Value::String (s) => *s,
|
||||
_ => panic! ("SetField only supports string keys"),
|
||||
};
|
||||
|
||||
let mut dst = self.reg (a).as_table ()
|
||||
.expect ("SetField only works on tables").borrow_mut ();
|
||||
|
||||
dst.insert_str (key, value);
|
||||
}
|
||||
|
||||
pub fn step (&mut self) -> Result <Option <StepOutput>, StepError>
|
||||
{
|
||||
self.step_count += 1;
|
||||
|
||||
let frame = self.stack.last_mut ().unwrap ().clone ();
|
||||
let block = self.chunk.blocks.get (frame.block_idx).unwrap ();
|
||||
let frame = self.stack.last ().unwrap ();
|
||||
self.block_idx = frame.block_idx;
|
||||
self.register_offset = frame.register_offset;
|
||||
let block_idx = frame.block_idx;
|
||||
let block = self.chunk.blocks.get (block_idx).unwrap ();
|
||||
|
||||
let mut next_pc = frame.program_counter;
|
||||
|
||||
let pc = usize::try_from (frame.program_counter).expect ("program_counter is not a valid usize");
|
||||
let instruction = match block.instructions.get (pc) {
|
||||
Some (x) => x,
|
||||
Some (x) => *x,
|
||||
None => {
|
||||
dbg! (&self.stack);
|
||||
panic! ("program_counter went out of bounds");
|
||||
|
@ -289,25 +417,14 @@ impl State {
|
|||
let k = &block.constants;
|
||||
|
||||
let make_step_error = |msg| {
|
||||
self.make_step_error (msg, instruction)
|
||||
self.make_step_error (msg, &instruction)
|
||||
};
|
||||
|
||||
match instruction.clone () {
|
||||
match instruction {
|
||||
Instruction::Add (a, b, c) => {
|
||||
let v_b = self.reg (b);
|
||||
let v_c = self.reg (c);
|
||||
|
||||
let x = if let (Some (v_b), Some (v_c)) = (v_b.as_int (), v_c.as_int ())
|
||||
{
|
||||
Value::from (v_b + v_c)
|
||||
if self.op_add (a, b, c) {
|
||||
next_pc += 1;
|
||||
}
|
||||
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}"));
|
||||
Value::from (v_b + v_c)
|
||||
};
|
||||
|
||||
*self.reg_mut (a) = x;
|
||||
},
|
||||
Instruction::AddI (a, b, s_c) => {
|
||||
let v_b = self.reg (b);
|
||||
|
@ -343,15 +460,12 @@ impl State {
|
|||
Value::BogusClosure (rc) => {
|
||||
let idx = rc.borrow ().idx;
|
||||
|
||||
let block_idx = frame.block_idx;
|
||||
let target_block = idx;
|
||||
|
||||
let current_frame = self.stack.last ().unwrap ();
|
||||
|
||||
self.stack.push (StackFrame {
|
||||
program_counter: 0,
|
||||
block_idx: target_block,
|
||||
register_offset: current_frame.register_offset + a as usize + 1,
|
||||
register_offset: self.register_offset + a as usize + 1,
|
||||
});
|
||||
|
||||
if self.debug_print {
|
||||
|
@ -364,19 +478,19 @@ impl State {
|
|||
return Ok (None);
|
||||
},
|
||||
Value::RsFunc (x) => {
|
||||
let current_frame = self.stack.last ().unwrap ();
|
||||
let new_offset = current_frame.register_offset + usize::from (a) + 1;
|
||||
let old_offset = self.register_offset;
|
||||
self.register_offset = old_offset + usize::from (a) + 1;
|
||||
|
||||
// Trash the stack frame so it doesn't point to a
|
||||
// valid Lua function
|
||||
self.stack.push (StackFrame {
|
||||
program_counter: 65535, // Bogus for native functions
|
||||
block_idx: 65535, // Bogus
|
||||
register_offset: new_offset,
|
||||
register_offset: self.register_offset,
|
||||
});
|
||||
|
||||
let num_args = if b == 0 {
|
||||
self.top - new_offset
|
||||
self.top - self.register_offset
|
||||
}
|
||||
else {
|
||||
b - 1
|
||||
|
@ -386,7 +500,8 @@ impl State {
|
|||
let num_results = x (self, num_args);
|
||||
|
||||
let popped_frame = self.stack.pop ().unwrap ();
|
||||
let offset = popped_frame.register_offset - 1;
|
||||
self.register_offset = old_offset;
|
||||
let offset = old_offset + usize::from (a);
|
||||
|
||||
for i in (offset)..(offset + usize::try_from (num_results).unwrap ()) {
|
||||
self.registers [i] = self.registers [i + 1].take ();
|
||||
|
@ -479,32 +594,10 @@ impl State {
|
|||
*self.reg_mut (a + 3) = start.into ();
|
||||
},
|
||||
Instruction::GetField (a, b, c) => {
|
||||
let t = match self.reg (b) {
|
||||
Value::Nil => Err (make_step_error ("R[B] must not be nil"))?,
|
||||
Value::Table (t) => t,
|
||||
_ => Err (make_step_error ("R[B] must be a table"))?,
|
||||
};
|
||||
|
||||
let key = match &k [usize::from (c)] {
|
||||
Value::String (s) => s,
|
||||
_ => panic! ("K[C] must be a string"),
|
||||
};
|
||||
|
||||
let val = t.borrow ().get_str (key.as_str ()).clone ();
|
||||
|
||||
*self.reg_mut (a) = val;
|
||||
self.op_get_field (a, b, c);
|
||||
},
|
||||
Instruction::GetTable (a, b, c) => {
|
||||
let t = match self.reg (b) {
|
||||
Value::Table (t) => t,
|
||||
_ => panic! ("R[B] must be a table"),
|
||||
};
|
||||
|
||||
let key = self.reg (c);
|
||||
|
||||
let val = t.borrow ().get (key.clone ());
|
||||
|
||||
*self.reg_mut (a) = val;
|
||||
self.op_get_table (a, b, c);
|
||||
},
|
||||
Instruction::GetTabUp (a, b, c) => {
|
||||
let b = usize::try_from (b).unwrap ();
|
||||
|
@ -530,18 +623,18 @@ impl State {
|
|||
let table = value.as_table ().expect ("GetTabUp only works on tables").borrow ();
|
||||
|
||||
let key = match k.get (c).unwrap () {
|
||||
Value::String (s) => String::from (s.as_ref()),
|
||||
Value::String (s) => *s,
|
||||
_ => panic! ("GetTabUp only supports string keys"),
|
||||
};
|
||||
|
||||
*self.reg_mut (a) = table.get (key);
|
||||
*self.reg_mut (a) = table.get_str (key).clone ();
|
||||
},
|
||||
Instruction::GetI (a, b, c) => {
|
||||
let key = i64::try_from (c).unwrap ();
|
||||
|
||||
let value = {
|
||||
let table = self.reg (b).as_table ().expect ("GetI only works on tables").borrow ();
|
||||
table.get_int (key)
|
||||
table.get_int (key).clone ()
|
||||
};
|
||||
|
||||
*self.reg_mut (a) = value;
|
||||
|
@ -573,7 +666,7 @@ impl State {
|
|||
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::String (s) => self.si.get (*s).len ().into (),
|
||||
Value::Table (t) => t.borrow ().length ().into (),
|
||||
};
|
||||
|
||||
|
@ -599,16 +692,8 @@ impl State {
|
|||
Instruction::LoadTrue (a) => {
|
||||
*self.reg_mut (a) = true.into ();
|
||||
},
|
||||
Instruction::MmBin (a, b, _c) => {
|
||||
let a = self.reg (a);
|
||||
let b = self.reg (b);
|
||||
|
||||
if a.as_float().is_some() && b.as_float().is_some () {
|
||||
// No need for metamethods
|
||||
}
|
||||
else {
|
||||
panic! ("Not sure how to implememtn OP_MMBIN for these 2 values {a:?}, {b:?}");
|
||||
}
|
||||
Instruction::MmBin (a, b, c) => {
|
||||
self.op_mmbin (a, b, c);
|
||||
},
|
||||
Instruction::MmBinI (_a, _s_b, _c, _k) => {
|
||||
// Ignore
|
||||
|
@ -629,20 +714,12 @@ impl State {
|
|||
*self.reg_mut (a) = self.reg (b).clone ();
|
||||
},
|
||||
Instruction::Mul (a, b, c) => {
|
||||
let v_b = self.reg (b);
|
||||
let v_c = self.reg (c);
|
||||
// If we handled the mul as a regular int or float,
|
||||
// skip the OP_MMBIN that probably comes after this
|
||||
|
||||
let x = if let (Some (v_b), Some (v_c)) = (v_b.as_int (), v_c.as_int ())
|
||||
{
|
||||
Value::from (v_b * v_c)
|
||||
if self.op_mul (a, b, c) {
|
||||
next_pc += 1;
|
||||
}
|
||||
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}"));
|
||||
Value::from (v_b * v_c)
|
||||
};
|
||||
|
||||
*self.reg_mut (a) = x;
|
||||
},
|
||||
Instruction::MulK (a, b, c) => {
|
||||
let v_b = self.reg (b);
|
||||
|
@ -754,25 +831,7 @@ impl State {
|
|||
self.top = popped_frame.register_offset - 1 + 1;
|
||||
},
|
||||
Instruction::SetField (a, b, c, k_flag) => {
|
||||
let value = if k_flag {
|
||||
&k [usize::from (c)]
|
||||
}
|
||||
else {
|
||||
self.reg (c)
|
||||
}
|
||||
.clone ();
|
||||
|
||||
let b = usize::try_from (b).unwrap ();
|
||||
|
||||
let key = match k.get (b).unwrap () {
|
||||
Value::String (s) => s.as_ref (),
|
||||
_ => panic! ("SetField only supports string keys"),
|
||||
};
|
||||
|
||||
let mut dst = self.reg (a).as_table ()
|
||||
.expect ("SetField only works on tables").borrow_mut ();
|
||||
|
||||
dst.insert_str (key.as_str (), value);
|
||||
self.op_set_field (a, b, c, k_flag);
|
||||
},
|
||||
Instruction::SetI (a, b, c, k_flag) => {
|
||||
let value = if k_flag {
|
||||
|
@ -946,7 +1005,7 @@ impl State {
|
|||
pub fn eval (&mut self, src: &str) -> Result <Vec <Value>, crate::Error>
|
||||
{
|
||||
let bytecode = crate::compile_bytecode (src.as_bytes ().to_vec ())?;
|
||||
let chunk = crate::parse_chunk (&bytecode).unwrap ();
|
||||
let chunk = crate::parse_chunk (&bytecode, &mut self.si).unwrap ();
|
||||
|
||||
self.set_chunk (chunk);
|
||||
Ok (self.execute ()?)
|
||||
|
@ -971,4 +1030,8 @@ impl State {
|
|||
self.stack = vec! [Default::default ()];
|
||||
self.chunk = chunk;
|
||||
}
|
||||
|
||||
pub fn to_string (&mut self, s: &str) -> Value {
|
||||
Value::String (self.si.intern (s))
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,56 @@
|
|||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::value::Value;
|
||||
|
||||
#[derive (Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
pub struct InternedString (i64);
|
||||
|
||||
#[derive (Debug, Default)]
|
||||
pub struct Interner {
|
||||
table_fwd: BTreeMap <String, i64>,
|
||||
table_rev: BTreeMap <i64, String>,
|
||||
counter: i64,
|
||||
}
|
||||
|
||||
impl Interner {
|
||||
pub fn get (&self, s: InternedString) -> &str {
|
||||
self.table_rev.get (&s.0).unwrap ()
|
||||
}
|
||||
|
||||
pub fn intern (&mut self, s: &str) -> InternedString {
|
||||
match self.table_fwd.get (s) {
|
||||
Some (x) => InternedString (*x),
|
||||
None => {
|
||||
self.counter += 1;
|
||||
if self.counter == i64::MAX {
|
||||
panic! ("Out of IDs");
|
||||
}
|
||||
self.table_fwd.insert (s.to_string (), self.counter);
|
||||
self.table_rev.insert (self.counter, s.to_string ());
|
||||
InternedString (self.counter)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_value (&mut self, s: &str) -> Value {
|
||||
Value::from (self.intern (s))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg (test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test () {
|
||||
let mut interner = Interner::default ();
|
||||
|
||||
assert_eq! (interner.intern ("x").0, 1);
|
||||
assert_eq! (interner.intern ("x").0, 1);
|
||||
assert_eq! (interner.intern ("y").0, 2);
|
||||
assert_eq! (interner.intern ("z").0, 3);
|
||||
assert_eq! (interner.intern ("y").0, 2);
|
||||
|
||||
assert_eq! (interner.intern ("asdf").0, 4);
|
||||
}
|
||||
}
|
|
@ -8,6 +8,7 @@ use crate::{
|
|||
Chunk,
|
||||
State,
|
||||
},
|
||||
string_interner::Interner,
|
||||
value::Value,
|
||||
};
|
||||
|
||||
|
@ -22,18 +23,18 @@ fn calculate_hash<T: Hash>(t: &T) -> u64 {
|
|||
/// Takes arguments and a parsed Lua chunk, runs its,
|
||||
/// and returns the output
|
||||
|
||||
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);
|
||||
fn run_chunk (vm: &mut State, args: &[&str], chunk: Chunk) -> Vec <Value> {
|
||||
vm.upvalues = State::upvalues_from_args(&mut vm.si, args.into_iter ().map (|s| s.to_string ()));
|
||||
vm.set_chunk (chunk);
|
||||
vm.execute ().unwrap ()
|
||||
}
|
||||
|
||||
/// Takes arguments and Lua bytecode, loads it, runs it,
|
||||
/// and return the output
|
||||
|
||||
fn run_bytecode (args: &[&str], bc: &[u8]) -> Vec <Value> {
|
||||
let chunk = loader::parse_chunk (&bc).unwrap ();
|
||||
run_chunk (args, chunk)
|
||||
fn run_bytecode (vm: &mut State, args: &[&str], bc: &[u8]) -> Vec <Value> {
|
||||
let chunk = loader::parse_chunk (&bc, &mut vm.si).unwrap ();
|
||||
run_chunk (vm, args, chunk)
|
||||
}
|
||||
|
||||
/// Takes arguments and Lua source code,
|
||||
|
@ -41,9 +42,9 @@ fn run_bytecode (args: &[&str], bc: &[u8]) -> Vec <Value> {
|
|||
/// runs it,
|
||||
/// and returns the output
|
||||
|
||||
fn run_source (args: &[&str], s: &str) -> Vec <Value> {
|
||||
fn run_source (vm: &mut State, args: &[&str], s: &str) -> Vec <Value> {
|
||||
let bc = loader::compile_bytecode (s.as_bytes ().to_vec ()).unwrap ();
|
||||
run_bytecode (args, &bc)
|
||||
run_bytecode (vm, args, &bc)
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
@ -62,6 +63,8 @@ fn bools () {
|
|||
return x
|
||||
*/
|
||||
|
||||
let mut si = Interner::default ();
|
||||
|
||||
let chunk = Chunk {
|
||||
blocks: vec! [
|
||||
Block {
|
||||
|
@ -90,8 +93,8 @@ fn bools () {
|
|||
Inst::Return (2, 1, 1, false),
|
||||
],
|
||||
constants: vec! [
|
||||
"arg".into (),
|
||||
"print".into (),
|
||||
si.to_value ("arg"),
|
||||
si.to_value ("print"),
|
||||
],
|
||||
upvalues: vec! [],
|
||||
},
|
||||
|
@ -112,15 +115,15 @@ fn bools () {
|
|||
],
|
||||
};
|
||||
|
||||
let mut vm = crate::State::new_with_args (Chunk::default (), si, vec! [].into_iter());
|
||||
|
||||
for (arg, expected) in [
|
||||
(vec! ["_exe_name"], vec! [98.into ()]),
|
||||
(vec! ["_exe_name", "asdf"], vec! [99.into ()]),
|
||||
] {
|
||||
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.clone (), upvalues);
|
||||
let actual = vm.execute ().unwrap ();
|
||||
let actual = run_chunk (&mut vm, &arg, chunk.clone ());
|
||||
assert_eq! (actual, expected);
|
||||
}
|
||||
}
|
||||
|
@ -129,9 +132,11 @@ fn bools () {
|
|||
fn closure () {
|
||||
let source = include_bytes! ("../test_vectors/closure.lua");
|
||||
let bytecode = &crate::loader::compile_bytecode (source.to_vec ()).unwrap ();
|
||||
let chunk = crate::loader::parse_chunk (bytecode).unwrap ();
|
||||
let mut si = Interner::default ();
|
||||
let chunk = crate::loader::parse_chunk (bytecode, &mut si).unwrap ();
|
||||
|
||||
assert_eq! (run_chunk (&["_exe_name"], chunk), vec! [Value::from (23i64)]);
|
||||
let mut vm = crate::State::new_with_args (Chunk::default (), si, vec! [].into_iter());
|
||||
assert_eq! (run_chunk (&mut vm, &["_exe_name"], chunk), vec! [Value::from (23i64)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
@ -146,6 +151,8 @@ fn floats () {
|
|||
return x
|
||||
*/
|
||||
|
||||
let mut si = Interner::default ();
|
||||
|
||||
let block = Block {
|
||||
instructions: vec! [
|
||||
Inst::VarArgPrep (0),
|
||||
|
@ -161,7 +168,7 @@ fn floats () {
|
|||
],
|
||||
constants: vec! [
|
||||
0.5.into (),
|
||||
"print".into (),
|
||||
si.to_value ("print"),
|
||||
],
|
||||
upvalues: vec! [],
|
||||
};
|
||||
|
@ -169,14 +176,14 @@ fn floats () {
|
|||
blocks: vec! [block],
|
||||
};
|
||||
|
||||
let mut vm = crate::State::new_with_args (Chunk::default (), si, vec! [].into_iter());
|
||||
|
||||
for (arg, expected) in [
|
||||
(vec! ["_exe_name"], vec! [3.5.into ()]),
|
||||
(vec! ["_exe_name", " "], vec! [3.5.into ()]),
|
||||
] {
|
||||
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.clone (), upvalues);
|
||||
let actual = vm.execute ().unwrap ();
|
||||
let actual = run_chunk (&mut vm, &arg, chunk.clone ());
|
||||
|
||||
assert_eq! (actual, expected);
|
||||
}
|
||||
|
@ -185,15 +192,15 @@ fn floats () {
|
|||
#[test]
|
||||
fn fma () {
|
||||
let source = include_bytes! ("../test_vectors/fma.lua");
|
||||
let mut si = Interner::default ();
|
||||
let bytecode = &crate::loader::compile_bytecode (source.to_vec ()).unwrap ();
|
||||
let chunk = crate::loader::parse_chunk (bytecode).unwrap ();
|
||||
let chunk = crate::loader::parse_chunk (bytecode, &mut si).unwrap ();
|
||||
assert_eq! (chunk.blocks.len (), 5);
|
||||
|
||||
assert_eq! (chunk.blocks [3].upvalues.len (), 2);
|
||||
|
||||
let arg = vec! ["_exe_name"];
|
||||
let upvalues = State::upvalues_from_args (arg.into_iter ().map (|s| s.to_string ()));
|
||||
let mut vm = State::new (chunk, upvalues);
|
||||
|
||||
let mut vm = crate::State::new_with_args (chunk, si, vec! ["_exe_name".to_string ()].into_iter ());
|
||||
let actual = vm.execute ().unwrap ();
|
||||
let expected = vec! [Value::from (122)];
|
||||
|
||||
|
@ -202,9 +209,8 @@ fn fma () {
|
|||
|
||||
#[test]
|
||||
fn function_calls () {
|
||||
let upvalues = crate::State::upvalues_from_args (vec! ["_exe_name".to_string ()].into_iter ());
|
||||
|
||||
let mut vm = crate::State::new (crate::Chunk::default (), upvalues);
|
||||
let si = Interner::default ();
|
||||
let mut vm = crate::State::new_with_args (crate::Chunk::default (), si, vec! ["_exe_name".to_string ()].into_iter ());
|
||||
|
||||
vm.eval ("print (x ())").ok ();
|
||||
vm.eval ("x = function () return 5 end").ok ();
|
||||
|
@ -216,9 +222,8 @@ fn function_calls () {
|
|||
|
||||
#[test]
|
||||
fn function_returns () {
|
||||
let upvalues = crate::State::upvalues_from_args (vec! ["_exe_name".to_string ()].into_iter ());
|
||||
|
||||
let mut vm = crate::State::new (crate::Chunk::default (), upvalues);
|
||||
let si = Interner::default ();
|
||||
let mut vm = crate::State::new_with_args (crate::Chunk::default (), si, vec! ["_exe_name".to_string ()].into_iter ());
|
||||
|
||||
assert_eq! (
|
||||
vm.eval ("return ((function () return 5 end)())").unwrap (),
|
||||
|
@ -241,6 +246,8 @@ fn heap () {
|
|||
};
|
||||
use crate::value::Table;
|
||||
|
||||
let mut si = Interner::default ();
|
||||
|
||||
{
|
||||
let mut allocations = HashMap::new ();
|
||||
let mut ctr = 0;
|
||||
|
@ -255,7 +262,7 @@ fn heap () {
|
|||
|
||||
allocations.get_mut (&a).unwrap ().insert (1, c);
|
||||
|
||||
allocations.get_mut (&c).unwrap ().insert (2, "eee");
|
||||
allocations.get_mut (&c).unwrap ().insert (2, si.to_value ("eee"));
|
||||
}
|
||||
|
||||
if true {
|
||||
|
@ -292,10 +299,12 @@ fn heap () {
|
|||
|
||||
#[test]
|
||||
fn is_93 () {
|
||||
assert_eq! (Value::from ("93"), Value::from ("93"));
|
||||
assert_ne! (Value::from ("94"), Value::from ("93"));
|
||||
assert_ne! (calculate_hash (&Value::from ("94")), calculate_hash (&Value::from ("93")));
|
||||
assert_ne! (Value::Nil, Value::from ("93"));
|
||||
let mut si = Interner::default ();
|
||||
|
||||
assert_eq! (si.to_value ("93"), si.to_value ("93"));
|
||||
assert_ne! (si.to_value ("94"), si.to_value ("93"));
|
||||
assert_ne! (calculate_hash (&si.to_value ("94")), calculate_hash (&si.to_value ("93")));
|
||||
assert_ne! (Value::Nil, si.to_value ("93"));
|
||||
|
||||
let src = br#"
|
||||
if arg [1] == "93" then
|
||||
|
@ -308,15 +317,17 @@ fn is_93 () {
|
|||
"#;
|
||||
|
||||
let bc = loader::compile_bytecode (src.to_vec ()).unwrap ();
|
||||
let chunk = loader::parse_chunk (&bc).unwrap ();
|
||||
let chunk = loader::parse_chunk (&bc, &mut si).unwrap ();
|
||||
|
||||
assert_eq! (chunk.blocks [0].instructions [3], Inst::EqK (0, 1, false));
|
||||
|
||||
let mut vm = crate::State::new_with_args (Chunk::default (), si, vec! [].into_iter());
|
||||
|
||||
let run = run_chunk;
|
||||
|
||||
assert_eq! (run (&[""], chunk.clone ()), vec! [Value::from (1)]);
|
||||
assert_eq! (run (&["", "93"], chunk.clone ()), vec! [Value::from (0)]);
|
||||
assert_eq! (run (&["", "94"], chunk.clone ()), vec! [Value::from (1)]);
|
||||
assert_eq! (run (&mut vm, &[""], chunk.clone ()), vec! [Value::from (1)]);
|
||||
assert_eq! (run (&mut vm, &["", "93"], chunk.clone ()), vec! [Value::from (0)]);
|
||||
assert_eq! (run (&mut vm, &["", "94"], chunk.clone ()), vec! [Value::from (1)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
@ -369,7 +380,9 @@ fn tables_1 () {
|
|||
print (t ["t"][1])
|
||||
"#;
|
||||
|
||||
run_source (&[], src);
|
||||
let si = Interner::default ();
|
||||
let mut vm = crate::State::new_with_args (Chunk::default (), si, vec! [].into_iter());
|
||||
run_source (&mut vm, &[], src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
@ -384,23 +397,29 @@ fn tables_2 () {
|
|||
print (a [2])
|
||||
"#;
|
||||
|
||||
run_source (&[], src);
|
||||
let si = Interner::default ();
|
||||
let mut vm = crate::State::new_with_args (Chunk::default (), si, vec! [].into_iter());
|
||||
run_source (&mut vm, &[], src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tailcall () {
|
||||
use crate::instruction::Instruction;
|
||||
|
||||
let mut si = Interner::default ();
|
||||
|
||||
let src = br#"
|
||||
return tonumber ("5")
|
||||
"#;
|
||||
|
||||
let bc = loader::compile_bytecode (src.to_vec ()).unwrap ();
|
||||
let chunk = loader::parse_chunk (&bc).unwrap ();
|
||||
let chunk = loader::parse_chunk (&bc, &mut si).unwrap ();
|
||||
|
||||
assert_eq! (chunk.blocks [0].instructions [3], Instruction::TailCall (0, 2, 1, false));
|
||||
|
||||
let actual = run_chunk (&[], chunk);
|
||||
let mut vm = crate::State::new_with_args (Chunk::default (), si, vec! [].into_iter());
|
||||
|
||||
let actual = run_chunk (&mut vm, &[], chunk);
|
||||
let expected = vec! [Value::from (5)];
|
||||
|
||||
assert_eq! (actual, expected);
|
||||
|
|
|
@ -4,11 +4,16 @@ use std::{
|
|||
Eq,
|
||||
PartialEq,
|
||||
},
|
||||
collections::HashMap,
|
||||
collections::{BTreeMap, HashMap},
|
||||
fmt,
|
||||
rc::Rc,
|
||||
};
|
||||
|
||||
use crate::string_interner::{
|
||||
Interner,
|
||||
InternedString,
|
||||
};
|
||||
|
||||
#[derive (Debug, Eq, PartialEq)]
|
||||
pub struct BogusClosure {
|
||||
// I'm pretty sure this should be absolute?
|
||||
|
@ -27,7 +32,7 @@ pub enum Value {
|
|||
|
||||
Integer (i64),
|
||||
RsFunc (fn (&mut crate::state::State, usize) -> usize),
|
||||
String (Rc <String>),
|
||||
String (InternedString),
|
||||
Table (Rc <RefCell <Table>>),
|
||||
|
||||
// These are all bogus, I haven't figured out how to implement
|
||||
|
@ -47,7 +52,7 @@ impl fmt::Debug for Value {
|
|||
Value::Float (x) => write! (f, "{:?}", x),
|
||||
Value::Integer (x) => write! (f, "{}", x),
|
||||
Value::RsFunc (x) => write! (f, "function: {:?}", x),
|
||||
Value::String (s) => write! (f, "\"{}\"", s),
|
||||
Value::String (s) => write! (f, "unimplemented Debug",),
|
||||
Value::Table (t) => write! (f, "{:?}", t.borrow ()),
|
||||
|
||||
Value::BogusClosure (x) => write! (f, "{:?}", x.borrow ()),
|
||||
|
@ -70,7 +75,7 @@ impl fmt::Display for Value {
|
|||
Value::Float (x) => write! (f, "{:?}", x),
|
||||
Value::Integer (x) => write! (f, "{}", x),
|
||||
Value::RsFunc (x) => write! (f, "function: {:?}", x),
|
||||
Value::String (s) => write! (f, "{}", s),
|
||||
Value::String (s) => write! (f, "unimplemented Display"),
|
||||
Value::Table (t) => write! (f, "table: {:?}", std::rc::Rc::as_ptr (t)),
|
||||
|
||||
Value::BogusClosure (x) => write! (f, "BogusClosure: {:?}", std::rc::Rc::as_ptr (x)),
|
||||
|
@ -90,18 +95,6 @@ impl From <bool> for Value {
|
|||
}
|
||||
}
|
||||
|
||||
impl From <String> for Value {
|
||||
fn from (x: String) -> Self {
|
||||
Self::String (x.into ())
|
||||
}
|
||||
}
|
||||
|
||||
impl From <&str> for Value {
|
||||
fn from (x: &str) -> Self {
|
||||
Self::from (String::from (x))
|
||||
}
|
||||
}
|
||||
|
||||
impl From <i32> for Value {
|
||||
fn from (x: i32) -> Self {
|
||||
Self::Integer (i64::from (x))
|
||||
|
@ -126,6 +119,12 @@ impl From <usize> for Value {
|
|||
}
|
||||
}
|
||||
|
||||
impl From <InternedString> for Value {
|
||||
fn from (x: InternedString) -> Self {
|
||||
Self::String (x)
|
||||
}
|
||||
}
|
||||
|
||||
impl From <Table> for Value {
|
||||
fn from (x: Table) -> Self {
|
||||
Self::Table (Rc::new (RefCell::new (x)))
|
||||
|
@ -139,9 +138,9 @@ impl FromIterator <(Value, Value)> for Value {
|
|||
}
|
||||
}
|
||||
|
||||
impl FromIterator <(String, Value)> for Value {
|
||||
fn from_iter <I: IntoIterator <Item=(String, Value)>> (i: I) -> Self {
|
||||
Self::from_iter (i.into_iter ().map (|(s, v)| (Value::from (s), v)))
|
||||
impl FromIterator <(InternedString, Value)> for Value {
|
||||
fn from_iter <I: IntoIterator <Item=(InternedString, Value)>> (i: I) -> Self {
|
||||
Self::from_iter (i.into_iter ().map (|(s, v)| (Value::String (s), v)))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -209,9 +208,9 @@ impl Value {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn as_str (&self) -> Option <&str> {
|
||||
pub fn as_str (&self) -> Option <InternedString> {
|
||||
match self {
|
||||
Self::String (x) => Some (x.as_str ()),
|
||||
Self::String (x) => Some (*x),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
@ -223,6 +222,10 @@ impl Value {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn from_str (si: &mut Interner, s: &str) -> Value {
|
||||
Value::String (si.intern (s))
|
||||
}
|
||||
|
||||
pub fn is_truthy (&self) -> bool {
|
||||
// And this is something Lua does better than JS and Python.
|
||||
|
||||
|
@ -244,55 +247,40 @@ impl Value {
|
|||
pub struct Table {
|
||||
array: Vec <Value>,
|
||||
hash: HashMap <Value, Value>,
|
||||
map: BTreeMap <InternedString, Value>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Table {
|
||||
fn fmt (&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write! (f, "Table {:#?}", self.hash)?;
|
||||
write! (f, "Table {:#?}", self.map)?;
|
||||
|
||||
Ok (())
|
||||
}
|
||||
}
|
||||
|
||||
impl Table {
|
||||
fn get_inner (&self, key: &Value) -> Value {
|
||||
// self.hash.get (key).cloned ().unwrap_or_default ()
|
||||
for (hay, value) in &self.hash {
|
||||
if key == hay {
|
||||
return value.clone ();
|
||||
}
|
||||
fn get_inner (&self, key: &Value) -> &Value {
|
||||
match key {
|
||||
Value::Nil => &NIL,
|
||||
Value::String (x) => self.map.get (x).unwrap_or (&NIL),
|
||||
Value::Integer (x) => self.array.get (usize::try_from (*x).unwrap ()).unwrap_or (&NIL),
|
||||
x => self.hash.get (x).unwrap_or (&NIL),
|
||||
}
|
||||
|
||||
Value::Nil
|
||||
}
|
||||
|
||||
pub fn get <A: Into <Value>> (&self, key: A) -> Value {
|
||||
pub fn get <A: Into <Value>> (&self, key: A) -> &Value {
|
||||
self.get_inner (&(key.into ()))
|
||||
}
|
||||
|
||||
pub fn get_int (&self, key: i64) -> Value {
|
||||
self.get_inner (&(key.into ()))
|
||||
pub fn get_int (&self, key: i64) -> &Value {
|
||||
self.array.get (usize::try_from (key).unwrap ()).unwrap_or (&NIL)
|
||||
}
|
||||
|
||||
pub fn get_str (&self, key: &str) -> &Value {
|
||||
for (hay, value) in &self.hash {
|
||||
if Some (key) == hay.as_str () {
|
||||
return value;
|
||||
}
|
||||
pub fn get_str (&self, key: InternedString) -> &Value {
|
||||
match self.map.get (&key) {
|
||||
None => &NIL,
|
||||
Some (x) => x,
|
||||
}
|
||||
|
||||
&NIL
|
||||
}
|
||||
|
||||
fn insert_inner (&mut self, a: Value, b: Value) {
|
||||
for (hay, value) in &mut self.hash {
|
||||
if &a == hay {
|
||||
*value = b;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
self.hash.insert (a, b);
|
||||
}
|
||||
|
||||
/// Insert value at arbitrary key
|
||||
|
@ -302,30 +290,34 @@ impl Table {
|
|||
a: A,
|
||||
b: B,
|
||||
) {
|
||||
self.insert_inner (a.into (), b.into ())
|
||||
match a.into () {
|
||||
Value::Integer (x) => self.insert_int (x, b),
|
||||
Value::Nil => (),
|
||||
Value::String (x) => {
|
||||
self.map.insert (x, b.into ());
|
||||
},
|
||||
x => {
|
||||
self.hash.insert (x, b.into ());
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Insert value at integer key
|
||||
|
||||
pub fn insert_int <A: Into <Value>> (&mut self, k: i64, v: A)
|
||||
{
|
||||
self.insert_inner (k.into (), v.into ())
|
||||
let k = usize::try_from (k).unwrap ();
|
||||
self.array.resize (k + 1, NIL);
|
||||
self.array [k] = v.into ();
|
||||
}
|
||||
|
||||
pub fn insert_str (&mut self, key: &str, v: Value) {
|
||||
for (hay, value) in &mut self.hash {
|
||||
if Some (key) == hay.as_str () {
|
||||
*value = v;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
self.hash.insert (key.into (), v);
|
||||
pub fn insert_str (&mut self, key: InternedString, v: Value) {
|
||||
self.map.insert (key, v);
|
||||
}
|
||||
|
||||
pub fn length (&self) -> i64 {
|
||||
for i in 1..i64::MAX {
|
||||
if self.get (i) == Value::Nil {
|
||||
if self.get (i) == &NIL {
|
||||
return i - 1;
|
||||
}
|
||||
}
|
||||
|
@ -336,21 +328,18 @@ impl Table {
|
|||
impl FromIterator <(Value, Value)> for Table {
|
||||
fn from_iter<I: IntoIterator<Item = (Value, Value)>> (i: I) -> Self
|
||||
{
|
||||
let hash = i.into_iter ().collect ();
|
||||
Self {
|
||||
array: Default::default (),
|
||||
hash,
|
||||
let mut that = Self::default ();
|
||||
for (k, v) in i.into_iter () {
|
||||
that.insert (k, v);
|
||||
}
|
||||
that
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg (test)]
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
use super::{
|
||||
Table,
|
||||
Value,
|
||||
};
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn smoke () {
|
||||
|
@ -364,25 +353,26 @@ mod tests {
|
|||
#[test]
|
||||
fn tables () {
|
||||
let nil = Value::Nil;
|
||||
let mut si = Interner::default ();
|
||||
|
||||
assert_ne! (Value::from (18.0), Value::from (19.0));
|
||||
|
||||
let mut t = HashMap::new ();
|
||||
t.insert (Value::from ("x"), Value::from (19.0));
|
||||
assert_eq! (t.get (&Value::from ("x")), Some (&Value::from (19.0)));
|
||||
t.insert (Value::from_str (&mut si, "x"), Value::from (19.0));
|
||||
assert_eq! (t.get (&Value::from_str (&mut si, "x")), Some (&Value::from (19.0)));
|
||||
|
||||
let mut t = Table::default ();
|
||||
|
||||
assert_eq! (t.get ("a"), nil);
|
||||
assert_eq! (t.get ("b"), nil);
|
||||
assert_eq! (t.get (si.intern ("a")), &nil);
|
||||
assert_eq! (t.get (si.intern ("b")), &nil);
|
||||
|
||||
t.insert ("a", 1993);
|
||||
t.insert ("b", 2007);
|
||||
t.insert (si.to_value ("a"), 1993);
|
||||
t.insert (si.to_value ("b"), 2007);
|
||||
|
||||
assert_eq! (t.get ("a"), 1993);
|
||||
assert_eq! (t.get ("b"), 2007);
|
||||
assert_eq! (t.get (si.intern ("a")), &Value::from (1993));
|
||||
assert_eq! (t.get (si.intern ("b")), &Value::from (2007));
|
||||
|
||||
t.insert (19, 93);
|
||||
assert_eq! (t.get (19), 93);
|
||||
assert_eq! (t.get (19), &Value::from (93));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -19,16 +19,18 @@ fn embedding () {
|
|||
1
|
||||
}
|
||||
|
||||
let mut si = lwvm::Interner::default ();
|
||||
|
||||
let bc = lwvm::compile_bytecode (src.to_vec ()).unwrap ();
|
||||
let chunk = lwvm::parse_chunk (&bc).unwrap ();
|
||||
let chunk = lwvm::parse_chunk (&bc, &mut si).unwrap ();
|
||||
|
||||
let host_lib = [
|
||||
("add", Value::RsFunc (host_add)),
|
||||
].into_iter ().map (|(k, v)| (k.to_string (), v));
|
||||
].into_iter ().map (|(k, v)| (si.intern (k), v));
|
||||
|
||||
let env = [
|
||||
("host_lib", Value::from_iter (host_lib.into_iter ())),
|
||||
].into_iter ().map (|(k, v)| (k.to_string (), v));
|
||||
].into_iter ().map (|(k, v)| (si.intern (k), v));
|
||||
|
||||
let upvalues = vec! [
|
||||
Value::from_iter (env.into_iter ()),
|
||||
|
|
Loading…
Reference in New Issue