first commit
This commit is contained in:
commit
42f0472185
|
@ -0,0 +1,6 @@
|
|||
rammodel/target
|
||||
rammodel/pkg
|
||||
rammodel/cargo.lock
|
||||
node_modules
|
||||
package-lock.json
|
||||
js/
|
|
@ -0,0 +1,7 @@
|
|||
#!/bin/bash
|
||||
{
|
||||
cd rammodel || exit
|
||||
wasm-pack build --target bundler
|
||||
cd ..
|
||||
}
|
||||
npx webpack
|
|
@ -0,0 +1,16 @@
|
|||
|
||||
.centred {
|
||||
text-align: center;
|
||||
margin: auto;
|
||||
max-width: 70vw;
|
||||
}
|
||||
|
||||
.vertical {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.horizontal {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en-US">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>JUMP!! HALT!! CATCH FIRE!!</title>
|
||||
|
||||
<link rel="stylesheet" href="css/style.css">
|
||||
<script src="js/bundle.js"></script>
|
||||
<script defer src="js/bundle.js"></script></head>
|
||||
<body>
|
||||
<div class="centred">
|
||||
<h3>L'incredibile interprete di RJ</h3>
|
||||
|
||||
<div class="interpreter vertical">
|
||||
<div class="programbox">
|
||||
</div>
|
||||
<div class="inputbox">
|
||||
|
||||
</div>
|
||||
<div class="memory">
|
||||
|
||||
</div>
|
||||
|
||||
<div class="errorbox"></div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,19 @@
|
|||
{
|
||||
"name": "cpuemu0",
|
||||
"version": "1.0.0",
|
||||
"description": "Simple assembly virtual machine",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"devDependencies": {
|
||||
"ts-loader": "^9.4.1",
|
||||
"typescript": "^4.1.3",
|
||||
"webpack-cli": "^4.10.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"cpuemulator": "file:rammodel/pkg"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,176 @@
|
|||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "0.7.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4f55bd91a0978cbfd91c457a164bab8b4001c833b7f323132c0a4e1922dd44e"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c1ad822118d20d2c234f427000d5acc36eabe1e29a348c89b63dd60b13f28e5d"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
|
||||
|
||||
[[package]]
|
||||
name = "cpuemulator"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"lazy_static",
|
||||
"regex",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.60"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "49409df3e3bf0856b916e2ceaca09ee28e6871cf7d9ce97a692cacfdb2a25a47"
|
||||
dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lazy_static"
|
||||
version = "1.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e82dad04139b71a90c080c8463fe0dc7902db5192d939bd0950f074d014339e1"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94e2ef8dbfc347b10c094890f778ee2e36ca9bb4262e86dc99cd217e35f3470b"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4c4eb3267174b8c6c2f654116623910a0fef09c4753f8dd83db29c48a0df988b"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.6.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a3f87b73ce11b1619a3c6332f45341e0047173771e8b8b73f87bfeefb7b56244"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "1.0.101"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e90cde112c4b9690b8cbe810cba9ddd8bc1d7472e2cae317b69e9438c1cba7d2"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dcc811dc4066ac62f84f11307873c4850cb653bfa9b1719cee2bd2204a4bc5dd"
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen"
|
||||
version = "0.2.83"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eaf9f5aceeec8be17c128b2e93e031fb8a4d469bb9c4ae2d7dc1888b26887268"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"wasm-bindgen-macro",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-backend"
|
||||
version = "0.2.83"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4c8ffb332579b0557b52d268b91feab8df3615f265d5270fec2a8c95b17c1142"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"log",
|
||||
"once_cell",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro"
|
||||
version = "0.2.83"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "052be0f94026e6cbc75cdefc9bae13fd6052cdcaf532fa6c45e7ae33a1e6c810"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"wasm-bindgen-macro-support",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro-support"
|
||||
version = "0.2.83"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "07bc0c051dc5f23e307b13285f9d75df86bfdf816c5721e573dec1f9b8aa193c"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"wasm-bindgen-backend",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-shared"
|
||||
version = "0.2.83"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c38c045535d93ec4f0b4defec448e4291638ee608530863b1e2ba115d4fff7f"
|
|
@ -0,0 +1,25 @@
|
|||
[package]
|
||||
name = "cpuemulator"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
path = "src/weblib.rs"
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
opt-level = 'z'
|
||||
|
||||
[dependencies]
|
||||
js-sys = "0.3.60"
|
||||
lazy_static = "1.4.0"
|
||||
regex = "1.6.0"
|
||||
wasm-bindgen = "0.2"
|
||||
|
||||
[[bin]]
|
||||
name = "executable"
|
||||
path = "src/main.rs"
|
||||
|
||||
|
|
@ -0,0 +1,248 @@
|
|||
use std::collections::VecDeque;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
type Word = u32;
|
||||
type Register = usize;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Instruction {
|
||||
READ(Register), // read n
|
||||
WRITE(Register), // write n
|
||||
LOAD(Register), // load =4
|
||||
LOADI(Word), // load 4 (load immediate)
|
||||
STORE(Register), //
|
||||
ADD(Register),
|
||||
ADDI(Word),
|
||||
SUB(Register),
|
||||
SUBI(Word),
|
||||
JUMP(Word),
|
||||
JZERO(Word),
|
||||
JGTZ(Word),
|
||||
JUMPR(Register),
|
||||
HALT,
|
||||
}
|
||||
|
||||
use Instruction::*;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum CpuErrors {
|
||||
EndOfInput,
|
||||
BadRegister,
|
||||
OverFlow,
|
||||
}
|
||||
|
||||
use CpuErrors::*;
|
||||
|
||||
pub struct CPU {
|
||||
pc: Register,
|
||||
acc: Register,
|
||||
program: Vec<Instruction>,
|
||||
regmemory: Vec<Word>,
|
||||
input_filo: VecDeque<Word>,
|
||||
output_filo: VecDeque<Word>,
|
||||
|
||||
pub stopped: bool,
|
||||
}
|
||||
|
||||
impl Default for CPU {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
pc: 9,
|
||||
acc: 0,
|
||||
program: vec![],
|
||||
regmemory: vec![0; 10],
|
||||
input_filo: vec![].into(),
|
||||
output_filo: vec![].into(),
|
||||
stopped: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CPU {
|
||||
pub fn showmem(&self) {
|
||||
print!("Memory: ");
|
||||
for i in 0..self.regmemory.len() - 1 {
|
||||
print!(" {} |", self.regmemory[i])
|
||||
}
|
||||
println!(" {}", self.regmemory[self.regmemory.len() - 1])
|
||||
}
|
||||
|
||||
pub fn showinput(&self) {
|
||||
print!("Input: ");
|
||||
for i in 0..self.input_filo.len() {
|
||||
print!(" {} ", self.input_filo[i])
|
||||
}
|
||||
print!("\n");
|
||||
}
|
||||
|
||||
pub fn showoutput(&self) {
|
||||
print!("Output: ");
|
||||
for i in 0..self.output_filo.len() {
|
||||
print!(" {} ", self.output_filo[i])
|
||||
}
|
||||
print!("\n");
|
||||
}
|
||||
|
||||
pub fn showstate(&self) {
|
||||
self.showmem();
|
||||
self.showinput();
|
||||
self.showoutput();
|
||||
}
|
||||
|
||||
pub fn exposestate(&self) -> (Vec<u32>, Vec<u32>, Vec<u32>) {
|
||||
return (self.regmemory.clone(), self.input_filo.clone().into(), self.output_filo.clone().into())
|
||||
|
||||
}
|
||||
|
||||
pub fn load(program: &Vec<Instruction>) -> Self {
|
||||
let mut p = Self::default();
|
||||
p.program = program.to_vec();
|
||||
return p;
|
||||
}
|
||||
|
||||
pub fn load_new(&mut self, program: &Vec<Instruction>) {
|
||||
self.program = program.to_vec();
|
||||
}
|
||||
|
||||
pub fn add_input(&mut self, w: Word) {
|
||||
self.input_filo.push_back(w);
|
||||
}
|
||||
|
||||
|
||||
fn getinput(&mut self) -> Result<Word, CpuErrors> {
|
||||
match self.input_filo.pop_front() {
|
||||
Some(w) => return Ok(w),
|
||||
None => return Err(EndOfInput),
|
||||
}
|
||||
}
|
||||
|
||||
fn writeoutput(&mut self, w: &Word) {
|
||||
self.output_filo.push_front(*w)
|
||||
}
|
||||
|
||||
fn pc_increase(&mut self) {
|
||||
self.regmemory[self.pc] += 1;
|
||||
}
|
||||
|
||||
fn readmemory(&mut self, addr: &Register) -> Result<Word, CpuErrors> {
|
||||
if addr >= &self.regmemory.len() {
|
||||
return Err(BadRegister);
|
||||
}
|
||||
|
||||
return Ok(self.regmemory[*addr]);
|
||||
}
|
||||
|
||||
fn writememory(&mut self, addr: &Register, w: Word) -> Result<(), CpuErrors> {
|
||||
if addr >= &self.regmemory.len() {
|
||||
return Err(BadRegister);
|
||||
}
|
||||
|
||||
self.regmemory[*addr] = w;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
pub fn execone(&mut self) -> Result<(), CpuErrors> {
|
||||
let acc = &self.acc.clone(); // constant
|
||||
let pc = &self.pc.clone(); // constant
|
||||
|
||||
let pc_val = self.readmemory(pc)?;
|
||||
let op = &self.program[pc_val as usize]; // fetch
|
||||
|
||||
match *op {
|
||||
READ(r) => {
|
||||
let k = self.getinput()?;
|
||||
self.writememory(&r, k)?;
|
||||
self.pc_increase();
|
||||
}
|
||||
|
||||
WRITE(r) => {
|
||||
let k = self.readmemory(&r)?;
|
||||
self.writeoutput(&k);
|
||||
self.pc_increase();
|
||||
}
|
||||
|
||||
LOAD(r) => {
|
||||
let k = self.readmemory(&r)?;
|
||||
self.writememory(acc, k)?;
|
||||
self.pc_increase();
|
||||
}
|
||||
|
||||
LOADI(w) => {
|
||||
self.writememory(acc, w)?;
|
||||
self.pc_increase();
|
||||
}
|
||||
|
||||
STORE(r) => {
|
||||
let k = self.readmemory(acc)?;
|
||||
self.writememory(&r, k)?;
|
||||
self.pc_increase();
|
||||
}
|
||||
|
||||
ADD(r) => {
|
||||
let k = &self.readmemory(&r)?;
|
||||
let acc_current = self.readmemory(acc)?;
|
||||
self.writememory(acc, acc_current + k)?;
|
||||
self.pc_increase();
|
||||
}
|
||||
|
||||
ADDI(w) => {
|
||||
let acc_current = self.readmemory(acc)?;
|
||||
self.writememory(acc, acc_current + w)?;
|
||||
self.pc_increase();
|
||||
}
|
||||
|
||||
|
||||
SUB(r) => {
|
||||
let k = &self.readmemory(&r)?;
|
||||
let acc_current = self.readmemory(acc)?;
|
||||
self.writememory(acc, acc_current - k)?;
|
||||
self.pc_increase();
|
||||
}
|
||||
|
||||
SUBI(w) => {
|
||||
let acc_current = self.readmemory(acc)?;
|
||||
self.writememory(acc, acc_current - w)?;
|
||||
self.pc_increase();
|
||||
}
|
||||
|
||||
JUMP(u) => {
|
||||
self.writememory(pc, u - 1)?;
|
||||
}
|
||||
|
||||
JZERO(u) => {
|
||||
let accval = self.readmemory(acc)?;
|
||||
if accval == 0 {
|
||||
self.writememory(pc, u - 1)?;
|
||||
} else {
|
||||
self.pc_increase();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
JGTZ(u) => {
|
||||
let accval = self.readmemory(acc)?;
|
||||
if accval > 0 {
|
||||
self.writememory(pc, u - 1)?;
|
||||
} else {
|
||||
self.pc_increase();
|
||||
}
|
||||
}
|
||||
|
||||
JUMPR(w) => {
|
||||
let u = self.readmemory(&w)?;
|
||||
self.writememory(pc, u)?;
|
||||
}
|
||||
|
||||
HALT => self.stopped = true,
|
||||
};
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
pub fn exec(&mut self) -> Result<(), CpuErrors> {
|
||||
while !self.stopped {
|
||||
self.execone()?;
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,68 @@
|
|||
mod parser;
|
||||
|
||||
use parser::{ParseError, parse_line, parse_program};
|
||||
use wasm_bindgen::prelude::*;
|
||||
use js_sys::Uint32Array;
|
||||
|
||||
use super::cpu::*;
|
||||
|
||||
#[wasm_bindgen]
|
||||
extern "C" {
|
||||
fn signalerror(s: &str);
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub struct WrapCpu {
|
||||
cpu: CPU
|
||||
// cpu: Vec<u32>
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl WrapCpu {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new() -> Self {
|
||||
return WrapCpu { cpu: CPU::default() }
|
||||
}
|
||||
|
||||
// view
|
||||
pub fn showmem(&self) -> Uint32Array {
|
||||
let (k, _, _) = self.cpu.exposestate();
|
||||
return Uint32Array::from(&k[..]);
|
||||
}
|
||||
|
||||
pub fn showinput(&self) -> Uint32Array {
|
||||
let (_, k, _) = self.cpu.exposestate();
|
||||
return Uint32Array::from(&k[..]);
|
||||
}
|
||||
|
||||
pub fn showoutput(&self) -> Uint32Array {
|
||||
let (_, _, k) = self.cpu.exposestate();
|
||||
return Uint32Array::from(&k[..]);
|
||||
}
|
||||
|
||||
pub fn add_input(&mut self, x: u32) {
|
||||
self.cpu.add_input(x)
|
||||
}
|
||||
|
||||
pub fn one_step(&mut self) {
|
||||
match self.cpu.execone() {
|
||||
Ok(()) => {},
|
||||
Err(k) => {signalerror(&format!("{:?}", k))}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn load_program(&mut self, prg: &str) {
|
||||
match parse_program(prg) {
|
||||
Ok(p) => {self.cpu.load_new(&p)}
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn test(&self) {
|
||||
signalerror("yolo")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,131 @@
|
|||
use crate::cpu::Instruction;
|
||||
use crate::cpu::Instruction::*;
|
||||
use std::collections::VecDeque;
|
||||
use regex::{Regex, RegexSet};
|
||||
use lazy_static::lazy_static;
|
||||
use std::boxed::Box;
|
||||
|
||||
// OOO WE PARSIN' WITH REGEX!!!
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum ParseError {
|
||||
ErrorAtLine(u32) // we only return the offending line.
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct FnWrap {
|
||||
pub f: fn(&str) -> Instruction
|
||||
}
|
||||
|
||||
impl FnWrap {
|
||||
fn new(f: fn(&str) -> Instruction) -> Self
|
||||
{
|
||||
FnWrap {f}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_program(s: &str) -> Result<Vec<Instruction>, ParseError> {
|
||||
|
||||
let mut posy: u32 = 0; // hoping no one will write a program this long...
|
||||
|
||||
|
||||
let mut res: VecDeque<Instruction> = vec![].into();
|
||||
|
||||
let lines = s.split("\n");
|
||||
|
||||
for line in lines {
|
||||
match parse_line(line) {
|
||||
Some(instr) => {
|
||||
|
||||
res.push_back(instr);
|
||||
|
||||
}
|
||||
None => return Err(ParseError::ErrorAtLine(posy))
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(res.into());
|
||||
}
|
||||
|
||||
// where the MAGIC happens!
|
||||
|
||||
pub fn parse_line(s: &str) -> Option<Instruction> {
|
||||
|
||||
// comping the example from https://docs.rs/regex/latest/regex/struct.RegexSet.html
|
||||
|
||||
|
||||
// COULD BE BETTER!!!!!!!!!
|
||||
let patternspairs =
|
||||
[ (FnWrap::new(|x| READ(x.parse().unwrap())), r"READ\s+(?P<reg>\d+)"),
|
||||
(FnWrap::new(|x| WRITE(x.parse().unwrap())),r"WRITE\s+(?P<reg>\d+)"),
|
||||
(FnWrap::new(|x| LOAD(x.parse().unwrap())), r"LOAD\s+(?P<reg>\d+)"),
|
||||
(FnWrap::new(|x| LOADI(x.parse().unwrap())),r"LOAD\s+=\s*(?P<num>\d+)"),
|
||||
(FnWrap::new(|x| STORE(x.parse().unwrap())),r"STORE\s+(?P<reg>\d+)"),
|
||||
(FnWrap::new(|x| ADD(x.parse().unwrap())), r"ADD\s+(?P<reg>\d+)"),
|
||||
(FnWrap::new(|x| ADDI(x.parse().unwrap())), r"ADD\s=\s*(?P<num>\d+)"),
|
||||
(FnWrap::new(|x| SUB(x.parse().unwrap())), r"SUB\s+(?P<reg>\d+)"),
|
||||
(FnWrap::new(|x| SUBI(x.parse().unwrap())), r"SUB\s=\s*(?P<num>\d+)"),
|
||||
(FnWrap::new(|x| JUMP(x.parse().unwrap())), r"JUMP\s+(?P<num>\d+)"),
|
||||
(FnWrap::new(|x| JZERO(x.parse().unwrap())),r"JZERO\s+(?P<num>\d+)"),
|
||||
(FnWrap::new(|x| JGTZ(x.parse().unwrap())), r"JGTZ\s+(?P<num>\d+)"),
|
||||
(FnWrap::new(|_| HALT), r"HALT")
|
||||
];
|
||||
|
||||
|
||||
// USE LAZY STATIC!!
|
||||
|
||||
// Compile a set matching any of our patterns.
|
||||
let set = RegexSet::new(&patternspairs.map(|(_, y)| y)).unwrap();
|
||||
// Compile each pattern independently.
|
||||
let regexes: Vec<_> = patternspairs.iter()
|
||||
.map(|(f, pat)| (f, Regex::new(pat).unwrap()))
|
||||
.collect();
|
||||
|
||||
// Match against the whole set first and identify the individual
|
||||
// matching patterns.
|
||||
let matches: Vec<_> = set.matches(s).into_iter().collect(); // we should only have one match
|
||||
|
||||
if matches.len() < 1 { // if there's less than one match, nothing matched! Wohoo!!
|
||||
return None;
|
||||
}
|
||||
|
||||
|
||||
// let's pick the appropriate constructor function, and
|
||||
let (f, reg) = ®exes[matches[0]];
|
||||
|
||||
// we run the regex that matched again to get the capture group.
|
||||
// then we just use the function f to build the instructon
|
||||
let param = reg.captures(s).unwrap().get(1).map_or("", |x| x.as_str());
|
||||
|
||||
// finally!
|
||||
return Some((f.f)(param));
|
||||
|
||||
// Matches arrive in the order the constituent patterns were declared,
|
||||
// not the order they appear in the input.
|
||||
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn single_line_test() {
|
||||
assert_eq!(parse_line("ADD 3"), Some(ADD(3)));
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn program_test() {
|
||||
let code =
|
||||
"READ 1\nLOAD 1\nJZERO 8\nSUB =1\nREAD 1\nWRITE 1\nJUMP 3\nHALT";
|
||||
|
||||
let program = vec![
|
||||
READ(1),
|
||||
LOAD(1),
|
||||
JZERO(8),
|
||||
SUBI(1),
|
||||
READ(1),
|
||||
WRITE(1),
|
||||
JUMP(3),
|
||||
HALT];
|
||||
|
||||
assert_eq!(parse_program(code), Ok(program));
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
|
||||
mod cpu;
|
||||
use cpu::Instruction::*;
|
||||
use cpu::*;
|
||||
|
||||
pub fn main() {
|
||||
test2();
|
||||
}
|
||||
|
||||
fn test2() {
|
||||
|
||||
let program1 = vec![
|
||||
READ(1),
|
||||
LOAD(1),
|
||||
JZERO(8),
|
||||
SUBI(1),
|
||||
READ(1),
|
||||
WRITE(1),
|
||||
JUMP(3),
|
||||
HALT];
|
||||
|
||||
let mut processor = CPU::load(&program1);
|
||||
|
||||
processor.add_input(5);
|
||||
processor.add_input(4);
|
||||
processor.add_input(8);
|
||||
processor.add_input(3);
|
||||
processor.add_input(1);
|
||||
processor.showstate();
|
||||
|
||||
println!("\n executing code!\n");
|
||||
|
||||
match processor.exec() {
|
||||
Ok(()) => {}
|
||||
Err(e) => println!("{:?}", e),
|
||||
};
|
||||
|
||||
processor.showstate();
|
||||
|
||||
}
|
||||
|
||||
|
||||
fn test1() {
|
||||
let program1 = vec![
|
||||
READ(1),
|
||||
READ(2),
|
||||
LOAD(1),
|
||||
ADD(2),
|
||||
STORE(3),
|
||||
WRITE(3),
|
||||
HALT];
|
||||
|
||||
let mut processor = CPU::load(&program1);
|
||||
|
||||
processor.add_input(3);
|
||||
processor.add_input(4);
|
||||
processor.showstate();
|
||||
|
||||
println!("\n executing code!\n");
|
||||
|
||||
match processor.exec() {
|
||||
Ok(()) => {}
|
||||
Err(e) => println!("{:?}", e),
|
||||
};
|
||||
|
||||
processor.showstate();
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
mod cpu;
|
||||
mod jswrap;
|
||||
use cpu::Instruction::*;
|
||||
use cpu::*;
|
||||
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
# What?
|
||||
|
||||
This is a simple random-access-machine emulator (not to be confused with random access memory) that I made for university.
|
||||
|
||||
Oh, also, _it doesn't work yet._
|
||||
|
||||
## Install?
|
||||
|
||||
You need `npm`, `cargo`, and also `wasm-pack`. Google those! They should be simple to install on any linux.
|
||||
|
||||
Then, run
|
||||
|
||||
```bash
|
||||
npm install
|
||||
./build.sh
|
||||
```
|
||||
|
||||
## Serve?
|
||||
|
||||
idk it's a static website lol
|
||||
|
||||
use nginx or whatever
|
||||
|
||||
|
||||
## This is very unprofessional. I don't get it!
|
||||
|
||||
Open a pull request. I'll document everything properly in a bit.
|
|
@ -0,0 +1,18 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
import http.server
|
||||
import socketserver
|
||||
|
||||
PORT = 8000
|
||||
|
||||
Handler = http.server.SimpleHTTPRequestHandler
|
||||
Handler.extensions_map.update({
|
||||
'.wasm': 'application/wasm',
|
||||
})
|
||||
|
||||
socketserver.TCPServer.allow_reuse_address = True
|
||||
with socketserver.TCPServer(("", PORT), Handler) as httpd:
|
||||
httpd.allow_reuse_address = True
|
||||
print("serving at port", PORT)
|
||||
httpd.serve_forever()
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
// const rust = import('../pkg/');
|
||||
import { WrapCpu } from 'cpuemulator';
|
||||
// const rust = import('../pkg/');
|
||||
|
||||
export function signalerror(x: string) {
|
||||
let box = document.getElementById("errorbox")
|
||||
if (box) {
|
||||
box.innerHTML = x
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export class Main {
|
||||
|
||||
|
||||
main() {
|
||||
let k = new WrapCpu;
|
||||
let mem = k.showmem();
|
||||
console.log(mem);
|
||||
k.test();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1 @@
|
|||
import('./index').catch(e => console.error('Error importing **index.ts**:', e));
|
|
@ -0,0 +1,6 @@
|
|||
import { Main, signalerror } from "./Main"
|
||||
|
||||
export { Main, signalerror}
|
||||
|
||||
let k = new Main;
|
||||
k.main();
|
|
@ -0,0 +1,68 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
/* Visit https://aka.ms/tsconfig.json to read more about this file */
|
||||
|
||||
/* Basic Options */
|
||||
// "incremental": true, /* Enable incremental compilation */
|
||||
"target": "esnext", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
|
||||
"module": "esnext", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
|
||||
"lib": ["esnext", "dom"], /* Specify library files to be included in the compilation. */
|
||||
// "allowJs": true, /* Allow javascript files to be compiled. */
|
||||
// "checkJs": true, /* Report errors in .js files. */
|
||||
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
|
||||
// "declaration": true, /* Generates corresponding '.d.ts' file. */
|
||||
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
|
||||
"sourceMap": true, /* Generates corresponding '.map' file. */
|
||||
// "outFile": "./", /* Concatenate and emit output to single file. */
|
||||
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
|
||||
// "composite": true, /* Enable project compilation */
|
||||
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
|
||||
// "removeComments": true, /* Do not emit comments to output. */
|
||||
// "noEmit": true, /* Do not emit outputs. */
|
||||
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
|
||||
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
|
||||
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
|
||||
|
||||
/* Strict Type-Checking Options */
|
||||
"strict": true, /* Enable all strict type-checking options. */
|
||||
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
|
||||
"strictNullChecks": true, /* Enable strict null checks. */
|
||||
"strictFunctionTypes": true, /* Enable strict checking of function types. */
|
||||
"strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
|
||||
"strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
|
||||
"noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
|
||||
"alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
|
||||
|
||||
/* Additional Checks */
|
||||
"noUnusedLocals": false, /* Report errors on unused locals. */
|
||||
"noUnusedParameters": true, /* Report errors on unused parameters. */
|
||||
"noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
|
||||
"noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
|
||||
|
||||
/* Module Resolution Options */
|
||||
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
|
||||
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
|
||||
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
|
||||
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
|
||||
// "typeRoots": [], /* List of folders to include type definitions from. */
|
||||
// "types": [], /* Type declaration files to be included in compilation. */
|
||||
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
|
||||
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
|
||||
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
|
||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||
|
||||
/* Source Map Options */
|
||||
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
|
||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
|
||||
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
|
||||
|
||||
/* Experimental Options */
|
||||
"experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
|
||||
"emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
|
||||
|
||||
/* Advanced Options */
|
||||
"skipLibCheck": true, /* Skip type checking of declaration files. */
|
||||
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
const path = require('path');
|
||||
// const HTMLWebpackPlugin = require('html-webpack-plugin');
|
||||
|
||||
module.exports = {
|
||||
// mode: 'development',
|
||||
mode: "production",
|
||||
devtool: 'eval-source-map',
|
||||
entry: './src/bootstrap.ts',
|
||||
output: {
|
||||
filename: 'bundle.js',
|
||||
path: path.resolve(__dirname, 'js'),
|
||||
},
|
||||
experiments: {
|
||||
syncWebAssembly: true
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.ts$/,
|
||||
use: 'ts-loader',
|
||||
include: [path.resolve(__dirname, 'src')],
|
||||
},
|
||||
],
|
||||
},
|
||||
resolve: {
|
||||
extensions: ['.ts', '.js'],
|
||||
},
|
||||
};
|
Loading…
Reference in New Issue