JSFiddle - React, Tailwind, and code Playground
by esbullington
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/sprintf/1.0.1/sprintf.min.js"></script>
<div id="printf"></div>
JavaScript
// Register VM
// ported from C program by Vishal Kanaujia
// http://www.opensourceforu.com/2011/06/virtual-machines-for-abstraction-dalvik-vm/
// Little printf making use of
// https://github.com/alexei/sprintf.js
function printf(s, arr) {
var t = vsprintf(s, arr);
console.log(t);
var el = document.getElementById("printf");
var span = document.createElement("span");
span.innerText = t;
el.appendChild(span);
}
const NUM_REGS = 4;
const INVALID = -1;
var opCodes = {
HALT: 0x0,
LOAD: 0x1,
ADD: 0x2
};
/*
* Register set of the VM
*/
var regs = new Array(NUM_REGS);
/*
* VM specific data for an instruction
*/
function VMData(reg1, reg2, reg3, op, scal) {
this.reg1 = reg1;
this.reg2 = reg2;
this.reg3 = reg3;
this.op = op;
this.scal = scal;
}
/*
* Addressing Modes:
* - Registers used as r0, r1,..rn.
* - Scalar/ Constant (immediate) values represented as #123
* - Memory addresses begin with @4556
*/
/*
* Instruction codes:
* Since we have very small number of instructions, we can have
* instructions that have following structure:
* - 16-bit instructions
*
* Operands get 8-bits, so range of number supported by our VM
* will be 0-255.
* The operands gets place from LSB bit position
* |7|6|5|4|3|2|1|0|
*
* Register number can we encoded in 4-bits
* |11|10|9|8|
*
* Remaining 4-bits will be used by opcode encoding.
* |15|14|13|12|
*
* So an "LOAD reg0 #20" instruction would assume following encoding:
* <0001> <0000> <00010100>
* or 0x1014 is the hex representation of given instruction.
*/
/*********************************************/
/* Instruction cycle: Fetch, Decode, Execute */
/*********************************************/
/*
* Current state of machine: It's a binary true/false
*/
var running = true
/*
* Program Counter
*/
var pc = 0;
/*
* Fetch instruction from code array
*/
function fetchInstruction(code) {
if (pc == NUM_REGS) return INVALID;
return...