frustration/frustration.rs

141 lines
2.6 KiB
Rust
Raw Normal View History

2022-03-22 04:45:42 +01:00
use std::io;
use std::convert::TryFrom;
//const CORE_SIZE: usize = 32640;
const CORE_SIZE: usize = 128;
#[derive(Debug)]
struct Core {
ram: [u16; CORE_SIZE],
ip: usize,
dstack: [u16; 64],
tds: usize,
rstack: [u16; 64],
trs: usize
}
fn new_core() -> Core {
return Core { ram: [0; CORE_SIZE], ip: 0,
dstack: [0; 64], tds: 0,
rstack: [0; 64], trs: 0 };
}
fn push(c: &mut Core, val: u16) {
c.dstack[c.tds] = val;
c.tds += 1;
}
fn pop(c: &mut Core) -> u16 {
c.tds -= 1;
return c.dstack[c.tds];
}
fn to_r(c: &mut Core, val: u16) {
c.rstack[c.trs] = val;
c.trs += 1;
}
fn from_r(c: &mut Core) -> u16 {
c.trs -= 1;
return c.rstack[c.trs];
}
fn call(c: &mut Core, val: u16) {
to_r(c, u16::try_from(c.ip).unwrap()); // or panic
c.ip = val as usize;
}
fn ret(c: &mut Core) {
c.ip = from_r(c) as usize;
}
fn store(c: &mut Core) {
let addr = pop(c);
let val = pop(c);
c.ram[addr as usize] = val;
}
fn load(c: &mut Core) {
let addr = pop(c);
push(c, c.ram[addr as usize]);
}
fn add(c: &mut Core) {
let v1 = pop(c);
let v2 = pop(c);
push(c, v1 + v2);
}
fn sub(c: &mut Core) {
let v1 = pop(c);
let v2 = pop(c);
push(c, v2 - v1);
}
fn mul(c: &mut Core) {
let v1 = pop(c);
let v2 = pop(c);
push(c, v1 * v2);
}
fn div(c: &mut Core) {
let v1 = pop(c);
let v2 = pop(c);
push(c, v2 / v1);
}
fn dot(c: &mut Core) {
print!("{} ", pop(c));
}
fn rpn(c: &mut Core, s: &str) {
let ss = s.trim();
let tokens = ss.split(" ");
for t in tokens {
match t {
"+" => {
add(c);
},
"-" => {
sub(c);
},
"*" => {
mul(c);
},
"/" => {
div(c);
},
"@" => {
load(c);
},
"!" => {
store(c);
},
"." => {
dot(c);
},
_ => {
let val = t.parse::<u16>();
match val {
Ok(n) => { push(c, n) }
Err(_) => { if t != "" { println!("{}?", t) }}
}
}
}
}
}
fn main() {
let mut c = new_core();
loop {
let mut buf = String::new();
match io::stdin().read_line(&mut buf) {
Ok(_) => { rpn(&mut c, &buf); println!(" ok");}
Err(e) => { break; }
}
}
//push(&mut c, 56); push(&mut c, 9); mul(&mut c); dot(&mut c);
//let v = pop(&mut c); call(&mut c, v);
println!("{:?}", c);
}