Implemented parsing a file to run the code.

master
Zed A. Shaw 2 years ago
parent 1c655b9b53
commit c905af1214
  1. 27
      src/buttons.js
  2. 23
      src/runner.js
  3. 5
      tests/basic.btn
  4. 11
      tests/basic_tests.js

@ -21,11 +21,11 @@ export class ButtonMachine {
* @constructor
* @param { Array } code -- The array of arrays for the code.
*/
constructor(code) {
constructor() {
this.stack = [];
this.ram = new Array(64).fill(0);
this.ip = 0;
this.code = code;
this.code = [];
this.max_ticks = 256;
this.tick = 0;
this.registers = {
@ -66,7 +66,7 @@ export class ButtonMachine {
* @return { Array[String] } -- List of registers.
*/
register_names() {
return Object.entries(this.registers);
return Object.getOwnPropertyNames(this.registers);
}
/**
@ -434,10 +434,29 @@ export class ButtonMachine {
}
}
load(code) {
this.code = code;
}
/**
* Coming soon.
*/
static parse(code) {
parse(code) {
const lines = code.split("\n");
const result = lines.map(l => {
let t = l.split(" ");
let inst = t.slice(0,1);
let data = t.slice(1).map(i => {
let num = parseInt(i, 10);
return isNaN(num) ? i : num;
});
return inst.concat(data);
});
// remove empty operations/lines
return result.filter(t => t[0] !== "");
}
}

@ -0,0 +1,23 @@
import { ButtonMachine } from '../src/buttons.js';
import fs from "fs";
import assert from "assert";
let machine = new ButtonMachine();
const ops = ButtonMachine.operations();
const registers = machine.register_names();
assert(process.argv[2] !== undefined, "USAGE: runner.js [source.btn]");
const source = fs.readFileSync(process.argv[2]);
const code = machine.parse(source.toString());
console.log("CODE", code);
machine.load(code);
machine.run();
console.log("STACK TOP", machine.stack_top);
console.log("REGISTERS", machine.registers);
console.log("STACK", machine.stack);
console.log("RAM", machine.ram);

@ -1,7 +1,6 @@
PUSH 10
PUSH 1
SUB
JZ 5
ADD
JZ 6
JUMP 1
PUSH 100
HALT

@ -1,18 +1,19 @@
import { ButtonMachine } from '../src/buttons.js';
let code = [
['PUSH', -10], // start at -10
['PUSH', 1], // increment by 1
['PUSH', -10],
['PUSH', 1],
['ADD'],
['POKE', 1], // put it in ram, IX++
['JNZ', 1], // the previous test fails so it jumps to loop again
['POKE', 1],
['JNZ', 1],
['STOR', 'IX'],
['POP'],
['PEEK', 1],
['JNZ', 6],
];
let machine = new ButtonMachine(code);
let machine = new ButtonMachine();
machine.load(code);
const ops = ButtonMachine.operations();
const registers = machine.register_names();

Loading…
Cancel
Save