Skip to content

Instantly share code, notes, and snippets.

@ravener
Created June 29, 2018 18:03
Show Gist options
  • Save ravener/cb74226ffaed7d2ca5d5d9f807907a0c to your computer and use it in GitHub Desktop.
Save ravener/cb74226ffaed7d2ca5d5d9f807907a0c to your computer and use it in GitHub Desktop.
Virtual Machine in JavaScript
/*
MIT License
Copyright (c) 2018 Free TNT
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* A simple Virtual Machine in JavaScript.
* Currently all it does is push and pop from stack and do
* addition.
*/
class VM {
constructor(code) {
// Array of bytecode integers.
this.program = code;
// Weather the VM is running.
this.running = false;
// Stack Pointer.
this.sp = -1;
// Program Counter.
this.pc = 0;
// Stack Array.
this.stack = new Array(256);
}
// Evalute a single instruction.
eval(instr) {
switch(instr) {
case 0: { // EXIT
this.running = false;
break;
}
case 1: { // PUSH
const val = this.next();
console.log("Pushed %d in the stack", val);
this.push(val);
break;
}
case 2: { // POP
const val = this.pop();
console.log("Popped %d from the stack", val);
break;
}
case 3: { // ADD
const b = this.pop();
const a = this.pop();
console.log("Pushed sum of %d + %d in the stack", a, b);
this.push(a + b);
break;
}
}
}
// Run the VM.
run() {
this.running = true;
while(this.running) {
this.eval(this.next());
}
}
// Pop a value from top of the stack.
pop() {
return this.stack[this.sp--];
}
// Push a value on top of stack.
push(value) {
this.stack[++this.sp] = value;
}
// Fetch the next bytecode from the program.
next() {
return this.program[this.pc++];
}
}
// PUSH 5, PUSH 2, ADD, POP, EXIT
// 5 + 2
const vm = new VM([ 1, 5, 1, 2, 3, 2, 0 ]);
// Start the VM.
vm.run();
@batshalregmi
Copy link

batshalregmi commented Jun 29, 2018

fake
lol xd
jk

@L3NNY0969
Copy link

lol

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment