{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Machine interpreter\n",
"\n",
"## Instructions\n",
"\n",
"Three registers, `a`, `b`, and `c`. \n",
"Program counter, `pc`.\n",
"Unlimited memory in numbered addresses, completely separate from program storage.\n",
"\n",
"Each register and memory location can hold 8-byte integers (Java `long`s).\n",
"\n",
"Machine carries out the instruction at location `pc`. After it's executed, `pc` increments by 1.\n",
"\n",
"`jmp` and `jpz` override this normal change in `pc`.\n",
"\n",
"| Instruction | Description |\n",
"|:------------|:------------|\n",
"| `inc r` | increment contents of register `r` |\n",
"| `dec r` | decrement contents of register `r` |\n",
"| `set r i` | set contents of register `r` to literal value `i` |\n",
"| `cpy r s` | set contents of register `r` into register `s` | \n",
"| `sto r m` | store contents of register `r` into memory location `m` |\n",
"| `ld r m` | load contents of memory location `m` into register `r` |\n",
"| `jmp i` | jump to instruction `i` places forward |\n",
"| `jpz r i` | jump to instruction `i` places forward if
register `r` contains zero, otherwise continue to next instruction |\n",
"\n",
"For `jmp` and `jpz`, `i` is relative to the current instruction. `i` can be negative to jump to earlier places in the program. `i`=1 is a no-op, `i`=0 causes an infinite loop."
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def new_machine():\n",
" return {'pc': 0, \n",
" 'a': 0,\n",
" 'b': 0, \n",
" 'c': 0,\n",
" 'instructions': []}"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def show_machine(machine):\n",
" return ', '.join('{}: {}'.format(sk, machine[int(sk) if sk.isnumeric() else sk]) \n",
" for sk in sorted(str(k) for k in machine)\n",
" if sk != 'instructions')"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def inc(reg, machine):\n",
" machine[reg] += 1\n",
" machine['pc'] += 1"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def dec(reg, machine):\n",
" machine[reg] -= 1\n",
" machine['pc'] += 1"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def jmp(addr, machine):\n",
" machine['pc'] += addr"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def jpz(reg, addr, machine):\n",
" if machine[reg] == 0:\n",
" machine['pc'] += addr\n",
" else:\n",
" machine['pc'] += 1"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def set_literal(reg, literal, machine):\n",
" machine[reg] = literal\n",
" machine['pc'] += 1"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def cpy(from_reg, to_reg, machine):\n",
" machine[to_reg] = machine[from_reg]\n",
" machine['pc'] += 1"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def sto(reg, addr, machine):\n",
" machine[addr] = machine[reg]\n",
" machine['pc'] += 1"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def ld(reg, addr, machine):\n",
" if addr in machine:\n",
" machine[reg] = machine[addr]\n",
" else:\n",
" machine[reg] = 0\n",
" machine['pc'] += 1"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"instruction_table = {'inc': inc, 'dec': dec, 'jmp': jmp,\n",
" 'jpz': jpz, 'set': set_literal, 'cpy': cpy,\n",
" 'sto': sto, 'ld': ld}\n",
"numeric_args_table = {'jmp': [0], 'jpz': [1], 'set': [1], 'sto': [1], 'ld': [1]}"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def parse(instruction):\n",
" words = instruction.split()\n",
" instr = words[0]\n",
" args = words[1:]\n",
" if instr in numeric_args_table:\n",
" for p in numeric_args_table[instr]:\n",
" args[p] = int(args[p])\n",
" return instruction_table[instr], args"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'a': 2, 'b': 1, 'c': 0, 'instructions': [], 'pc': 3}"
]
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"m = new_machine()\n",
"inc('a', m)\n",
"cargs = ['a', 'b']\n",
"cpy(*cargs, m)\n",
"inc('a', m)\n",
"m"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def program_from_instructions(prog, machine):\n",
" machine['instructions'] = [parse(instr) for instr in prog]"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def program_from_listing(listing, machine):\n",
" labelled_instructions = [i for i in listing.split('\\n') if i]\n",
" instructions = replace_labels(labelled_instructions)\n",
" program_from_instructions(instructions, machine)"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def replace_labels(listing):\n",
" locations = {}\n",
" for n, i in enumerate(listing):\n",
" if ':' in i:\n",
" locations[i.split(':')[0]] = n\n",
"\n",
" unlabelled_listing = []\n",
" for n, i in enumerate(listing):\n",
" instr = i.split()\n",
" if ':' in i:\n",
" instr = i.split(':')[1].split()\n",
" else:\n",
" instr = i.split()\n",
" terms = []\n",
" for term in instr:\n",
" if term in locations:\n",
" terms += [str(locations[term] - n)]\n",
" else:\n",
" terms += [term]\n",
" transformed_instr = ' '.join(terms)\n",
" unlabelled_listing += [transformed_instr]\n",
" \n",
" return unlabelled_listing "
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['inc', 'a']"
]
},
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"'fred: inc a'.split(':')[1].split()"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['set a 10', 'dec a', 'inc b', 'sto b 1', 'jpz a 2', 'jmp -4']"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"program = \"\"\"\n",
" set a 10\n",
"loop: dec a\n",
" inc b\n",
" sto b 1\n",
" jpz a 2\n",
" jmp loop\n",
"\"\"\"\n",
"labelled_instructions = [i for i in program.split('\\n') if i]\n",
"instructions = replace_labels(labelled_instructions)\n",
"instructions"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def run(machine, initial_state=None, trace=False):\n",
" if initial_state:\n",
" machine.update(initial_state)\n",
" while machine['pc'] < len(machine['instructions']):\n",
" if trace:\n",
" print(show_machine(machine))\n",
" cmd, args = machine['instructions'][machine['pc']]\n",
" cmd(*args, machine)"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def execute(listing, initial_state=None, trace=False):\n",
" m = new_machine()\n",
" program_from_listing(listing, m)\n",
" run(m, initial_state=initial_state, trace=trace)\n",
" return m"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'a': 3,\n",
" 'b': 2,\n",
" 'c': 0,\n",
" 'instructions': [(, ['a']),\n",
" (, ['a']),\n",
" (, ['a', 'b']),\n",
" (, ['a'])],\n",
" 'pc': 4}"
]
},
"execution_count": 42,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"program = \"\"\"\n",
"inc a\n",
"inc a\n",
"cpy a b\n",
"inc a\n",
"\"\"\"\n",
"execute(program)"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'b': 10,\n",
" 1: 10,\n",
" 'instructions': [(, ['a', 10]),\n",
" (, ['a']),\n",
" (, ['b']),\n",
" (, ['b', 1]),\n",
" (, ['a', 2]),\n",
" (, [-4])],\n",
" 'pc': 6,\n",
" 'a': 0,\n",
" 'c': 20}"
]
},
"execution_count": 43,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"program = \"\"\"\n",
"set a 10\n",
"dec a\n",
"inc b\n",
"sto b 1\n",
"jpz a 2\n",
"jmp -4\n",
"\"\"\"\n",
"# m = new_machine()\n",
"# program_from_listing(program, m)\n",
"# run(m)\n",
"execute(program, initial_state={'c': 20})"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'b': 10,\n",
" 1: 10,\n",
" 'instructions': [(, ['a', 10]),\n",
" (, ['a']),\n",
" (, ['b']),\n",
" (, ['b', 1]),\n",
" (, ['a', 2]),\n",
" (, [-4])],\n",
" 'pc': 6,\n",
" 'a': 0,\n",
" 'c': 20}"
]
},
"execution_count": 44,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"program = \"\"\"\n",
" set a 10\n",
"loop: dec a\n",
" inc b\n",
" sto b 1\n",
" jpz a 2\n",
" jmp loop\n",
"\"\"\"\n",
"execute(program, initial_state={'c': 20})"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'a': 0,\n",
" 'b': 1,\n",
" 'c': 5,\n",
" 'instructions': [(, ['c', 'a']),\n",
" (, ['b', 0]),\n",
" (, ['a']),\n",
" (, ['b', 3]),\n",
" (, ['b']),\n",
" (, [2]),\n",
" (, ['b']),\n",
" (, ['a', 3]),\n",
" (, [-6])],\n",
" 'pc': 10}"
]
},
"execution_count": 45,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"program = \"\"\"\n",
"cpy c a\n",
"set b 0\n",
"dec a\n",
"jpz b 3\n",
"dec b\n",
"jmp 2\n",
"inc b\n",
"jpz a 3\n",
"jmp -6\n",
"\"\"\"\n",
"# m = new_machine()\n",
"# program_from_listing(program, m)\n",
"# run(m)\n",
"execute(program, initial_state={'c': 5})"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'a': 0,\n",
" 'b': 1,\n",
" 'c': 5,\n",
" 'instructions': [(, ['c', 'a']),\n",
" (, ['b', 0]),\n",
" (, ['a']),\n",
" (, ['b', 3]),\n",
" (, ['b']),\n",
" (, [2]),\n",
" (, ['b']),\n",
" (, ['a', 2]),\n",
" (, [-6])],\n",
" 'pc': 9}"
]
},
"execution_count": 49,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# b holds parity of number in c: (c % 2)\n",
"program = \"\"\"\n",
" cpy c a\n",
" set b 0\n",
"loop: dec a\n",
" jpz b odd\n",
" dec b\n",
" jmp end\n",
"odd: inc b\n",
"end: jpz a 2\n",
" jmp loop\n",
"\"\"\"\n",
"# m = new_machine()\n",
"# program_from_listing(program, m)\n",
"# run(m)\n",
"execute(program, initial_state={'c': 5})"
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'10: 7, a: 0, b: 1, c: 3, pc: 11'"
]
},
"execution_count": 52,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# c holds floor(a/2)\n",
"program = \"\"\"\n",
" sto a 10\n",
" set c 0\n",
" set b 0\n",
"loop: dec a\n",
" jpz b odd\n",
" dec b\n",
" inc c\n",
" jmp end\n",
"odd: inc b\n",
"end: jpz a 2\n",
" jmp loop\n",
"\"\"\"\n",
"# m = new_machine()\n",
"# program_from_listing(program, m)\n",
"# run(m)\n",
"show_machine(execute(program, initial_state={'a': 7}))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.2+"
}
},
"nbformat": 4,
"nbformat_minor": 2
}