4 "cell_type": "markdown",
7 "# Machine interpreter\n",
11 "Three registers, `a`, `b`, and `c`. \n",
12 "Program counter, `pc`.\n",
13 "Unlimited memory in numbered addresses, completely separate from program storage.\n",
15 "Each register and memory location can hold 8-byte integers (Java `long`s).\n",
17 "Machine carries out the instruction at location `pc`. After it's executed, `pc` increments by 1.\n",
19 "`jmp` and `jpz` override this normal change in `pc`.\n",
21 "| Instruction | Description |\n",
22 "|:------------|:------------|\n",
23 "| `inc r` | increment contents of register `r` |\n",
24 "| `dec r` | decrement contents of register `r` |\n",
25 "| `set r i` | set contents of register `r` to literal value `i` |\n",
26 "| `cpy r s` | set contents of register `r` into register `s` | \n",
27 "| `sto r m` | store contents of register `r` into memory location `m` |\n",
28 "| `ld r m` | load contents of memory location `m` into register `r` |\n",
29 "| `jmp i` | jump to instruction `i` places forward |\n",
30 "| `jpz r i` | jump to instruction `i` places forward if<br>register `r` contains zero, otherwise continue to next instruction |\n",
32 "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."
37 "execution_count": 22,
43 "def new_machine():\n",
44 " return {'pc': 0, \n",
48 " 'instructions': []}"
53 "execution_count": 23,
59 "def show_machine(machine):\n",
60 " return ', '.join('{}: {}'.format(sk, machine[int(sk) if sk.isnumeric() else sk]) \n",
61 " for sk in sorted(str(k) for k in machine)\n",
62 " if sk != 'instructions')"
67 "execution_count": 24,
73 "def inc(reg, machine):\n",
74 " machine[reg] += 1\n",
80 "execution_count": 25,
86 "def dec(reg, machine):\n",
87 " machine[reg] -= 1\n",
93 "execution_count": 26,
99 "def jmp(addr, machine):\n",
100 " machine['pc'] += addr"
105 "execution_count": 27,
111 "def jpz(reg, addr, machine):\n",
112 " if machine[reg] == 0:\n",
113 " machine['pc'] += addr\n",
115 " machine['pc'] += 1"
120 "execution_count": 28,
126 "def set_literal(reg, literal, machine):\n",
127 " machine[reg] = literal\n",
128 " machine['pc'] += 1"
133 "execution_count": 29,
139 "def cpy(from_reg, to_reg, machine):\n",
140 " machine[to_reg] = machine[from_reg]\n",
141 " machine['pc'] += 1"
146 "execution_count": 30,
152 "def sto(reg, addr, machine):\n",
153 " machine[addr] = machine[reg]\n",
154 " machine['pc'] += 1"
159 "execution_count": 31,
165 "def ld(reg, addr, machine):\n",
166 " if addr in machine:\n",
167 " machine[reg] = machine[addr]\n",
169 " machine[reg] = 0\n",
170 " machine['pc'] += 1"
175 "execution_count": 32,
181 "instruction_table = {'inc': inc, 'dec': dec, 'jmp': jmp,\n",
182 " 'jpz': jpz, 'set': set_literal, 'cpy': cpy,\n",
183 " 'sto': sto, 'ld': ld}\n",
184 "numeric_args_table = {'jmp': [0], 'jpz': [1], 'set': [1], 'sto': [1], 'ld': [1]}"
189 "execution_count": 33,
195 "def parse(instruction):\n",
196 " words = instruction.split()\n",
197 " instr = words[0]\n",
198 " args = words[1:]\n",
199 " if instr in numeric_args_table:\n",
200 " for p in numeric_args_table[instr]:\n",
201 " args[p] = int(args[p])\n",
202 " return instruction_table[instr], args"
207 "execution_count": 34,
213 "{'a': 2, 'b': 1, 'c': 0, 'instructions': [], 'pc': 3}"
216 "execution_count": 34,
218 "output_type": "execute_result"
222 "m = new_machine()\n",
224 "cargs = ['a', 'b']\n",
232 "execution_count": 35,
238 "def program_from_instructions(prog, machine):\n",
239 " machine['instructions'] = [parse(instr) for instr in prog]"
244 "execution_count": 36,
250 "def program_from_listing(listing, machine):\n",
251 " labelled_instructions = [i for i in listing.split('\\n') if i]\n",
252 " instructions = replace_labels(labelled_instructions)\n",
253 " program_from_instructions(instructions, machine)"
258 "execution_count": 37,
264 "def replace_labels(listing):\n",
266 " for n, i in enumerate(listing):\n",
268 " locations[i.split(':')[0]] = n\n",
270 " unlabelled_listing = []\n",
271 " for n, i in enumerate(listing):\n",
272 " instr = i.split()\n",
274 " instr = i.split(':')[1].split()\n",
276 " instr = i.split()\n",
278 " for term in instr:\n",
279 " if term in locations:\n",
280 " terms += [str(locations[term] - n)]\n",
282 " terms += [term]\n",
283 " transformed_instr = ' '.join(terms)\n",
284 " unlabelled_listing += [transformed_instr]\n",
286 " return unlabelled_listing "
291 "execution_count": 38,
300 "execution_count": 38,
302 "output_type": "execute_result"
306 "'fred: inc a'.split(':')[1].split()"
311 "execution_count": 39,
317 "['set a 10', 'dec a', 'inc b', 'sto b 1', 'jpz a 2', 'jmp -4']"
320 "execution_count": 39,
322 "output_type": "execute_result"
326 "program = \"\"\"\n",
334 "labelled_instructions = [i for i in program.split('\\n') if i]\n",
335 "instructions = replace_labels(labelled_instructions)\n",
341 "execution_count": 40,
347 "def run(machine, initial_state=None, trace=False):\n",
348 " if initial_state:\n",
349 " machine.update(initial_state)\n",
350 " while machine['pc'] < len(machine['instructions']):\n",
352 " print(show_machine(machine))\n",
353 " cmd, args = machine['instructions'][machine['pc']]\n",
354 " cmd(*args, machine)"
359 "execution_count": 41,
365 "def execute(listing, initial_state=None, trace=False):\n",
366 " m = new_machine()\n",
367 " program_from_listing(listing, m)\n",
368 " run(m, initial_state=initial_state, trace=trace)\n",
374 "execution_count": 42,
383 " 'instructions': [(<function __main__.inc>, ['a']),\n",
384 " (<function __main__.inc>, ['a']),\n",
385 " (<function __main__.cpy>, ['a', 'b']),\n",
386 " (<function __main__.inc>, ['a'])],\n",
390 "execution_count": 42,
392 "output_type": "execute_result"
396 "program = \"\"\"\n",
407 "execution_count": 43,
415 " 'instructions': [(<function __main__.set_literal>, ['a', 10]),\n",
416 " (<function __main__.dec>, ['a']),\n",
417 " (<function __main__.inc>, ['b']),\n",
418 " (<function __main__.sto>, ['b', 1]),\n",
419 " (<function __main__.jpz>, ['a', 2]),\n",
420 " (<function __main__.jmp>, [-4])],\n",
426 "execution_count": 43,
428 "output_type": "execute_result"
432 "program = \"\"\"\n",
440 "# m = new_machine()\n",
441 "# program_from_listing(program, m)\n",
443 "execute(program, initial_state={'c': 20})"
448 "execution_count": 44,
456 " 'instructions': [(<function __main__.set_literal>, ['a', 10]),\n",
457 " (<function __main__.dec>, ['a']),\n",
458 " (<function __main__.inc>, ['b']),\n",
459 " (<function __main__.sto>, ['b', 1]),\n",
460 " (<function __main__.jpz>, ['a', 2]),\n",
461 " (<function __main__.jmp>, [-4])],\n",
467 "execution_count": 44,
469 "output_type": "execute_result"
473 "program = \"\"\"\n",
481 "execute(program, initial_state={'c': 20})"
486 "execution_count": 45,
495 " 'instructions': [(<function __main__.cpy>, ['c', 'a']),\n",
496 " (<function __main__.set_literal>, ['b', 0]),\n",
497 " (<function __main__.dec>, ['a']),\n",
498 " (<function __main__.jpz>, ['b', 3]),\n",
499 " (<function __main__.dec>, ['b']),\n",
500 " (<function __main__.jmp>, [2]),\n",
501 " (<function __main__.inc>, ['b']),\n",
502 " (<function __main__.jpz>, ['a', 3]),\n",
503 " (<function __main__.jmp>, [-6])],\n",
507 "execution_count": 45,
509 "output_type": "execute_result"
513 "program = \"\"\"\n",
524 "# m = new_machine()\n",
525 "# program_from_listing(program, m)\n",
527 "execute(program, initial_state={'c': 5})"
532 "execution_count": 49,
541 " 'instructions': [(<function __main__.cpy>, ['c', 'a']),\n",
542 " (<function __main__.set_literal>, ['b', 0]),\n",
543 " (<function __main__.dec>, ['a']),\n",
544 " (<function __main__.jpz>, ['b', 3]),\n",
545 " (<function __main__.dec>, ['b']),\n",
546 " (<function __main__.jmp>, [2]),\n",
547 " (<function __main__.inc>, ['b']),\n",
548 " (<function __main__.jpz>, ['a', 2]),\n",
549 " (<function __main__.jmp>, [-6])],\n",
553 "execution_count": 49,
555 "output_type": "execute_result"
559 "# b holds parity of number in c: (c % 2)\n",
560 "program = \"\"\"\n",
571 "# m = new_machine()\n",
572 "# program_from_listing(program, m)\n",
574 "execute(program, initial_state={'c': 5})"
579 "execution_count": 52,
585 "'10: 7, a: 0, b: 1, c: 3, pc: 11'"
588 "execution_count": 52,
590 "output_type": "execute_result"
594 "# c holds floor(a/2)\n",
595 "program = \"\"\"\n",
608 "# m = new_machine()\n",
609 "# program_from_listing(program, m)\n",
611 "show_machine(execute(program, initial_state={'a': 7}))"
616 "execution_count": null,
626 "display_name": "Python 3",
627 "language": "python",
635 "file_extension": ".py",
636 "mimetype": "text/x-python",
638 "nbconvert_exporter": "python",
639 "pygments_lexer": "ipython3",