Created
October 7, 2019 06:17
-
-
Save nrkn/aae8121e1542168c5b9ec58387006106 to your computer and use it in GitHub Desktop.
Minimal instruction set
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const add = (memory, dest, src) => { | |
memory[dest] += memory[src] | |
} | |
const addV = (memory, dest, value) => { | |
memory[dest] += value | |
} | |
const sub = (memory, dest, src) => { | |
memory[dest] -= memory[src] | |
} | |
const subV = (memory, dest, value) => { | |
memory[dest] -= value | |
} | |
const copy = (memory, dest, src) => { | |
memory[dest] = memory[src] | |
} | |
const set = (memory, dest, value) => { | |
memory[dest] = value | |
} | |
const jmp = (memory, src) => { | |
return memory[src] | |
} | |
const jmpV = (_memory, value) => { | |
return value | |
} | |
const jmpz = (memory, dest, src) => { | |
if (memory[src] === 0) | |
return memory[dest] | |
} | |
const jmpVZ = (memory, value, src) => { | |
if (memory[src] === 0) | |
return value | |
} | |
const instr = { add, addV, sub, subV, copy, set, jmp, jmpV, jmpz, jmpVZ } | |
const memory = new Uint8Array(256) | |
const program = [ | |
// 0 - i = 0 | |
'set 0 0', | |
// 1 - length = 10 | |
'set 1 10', | |
// 2 - result = 0 | |
'set 2 0', | |
// :loop | |
// 3 - result += i | |
'add 2 0', | |
// 4 - i += 1 | |
'addV 0 1', | |
// 5 - length -= 1 | |
'subV 1 1', | |
// 6 - if length == 0 | |
'jmpVZ 8 1', | |
// 7 - else | |
'jmpV 3', | |
// 8 - break | |
'brk' | |
] | |
const parse = (instruction) => { | |
const [op, ...argSegs] = instruction.split(' ') | |
const args = argSegs.map(Number) | |
return [op, ...args] | |
} | |
const execute = (program) => { | |
const parsed = program.map(parse) | |
let counter = 0 | |
let [op, ...args] = parsed[counter] | |
while (op !== 'brk') { | |
const result = instr[op](memory, ...args) | |
if( typeof result === 'number' ) | |
counter = result | |
else | |
counter++ | |
[op, ...args] = parsed[counter] | |
} | |
} | |
const logMemory = () => console.log( | |
...Array.from(memory).map(v => String(v).padStart(3, ' ')), | |
'\n' | |
) | |
logMemory() | |
execute(program) | |
logMemory() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment