Search

mercredi 8 février 2017

Self-interpreter: load code (2)

Context

Let's now implement the first part of our interpreter: read code to execute - and code only. The part dedicated to execution's input should remain unread for now.
Here are the characters we want to read. First value is the corresponding ASCII code, second is 35 below those values (35 is ASCII code of #, our separator.
  • # separator 35/0
  • + inc 43/8
  • , read 44/9
  • - dec 45/10
  • . print 46/11
  • > left 60/25
  • < right 62/27
  • [ while 91/56
  • ] loop 93/58
Our goal here will be to
  1. Read character
  2. Subtract 35 to check if character is the separator, or not
    1. If separator: stop reading
    2. If not: store instruction value (even the -35 one, it doesn't matter as long as '+' is now defined by 8, ', ' by 9, ...)

Initial state

  • Memory: empty
  • Cursor: first cell
  • Input: any

Process

  • Read char
  • While current char is not null
    • Decrease by 35, set else bit
    • If value is not null, read next char
    • Otherwise, stop reading

Code

>>>,
leave some cells for future use and read char
[
  >+++++[-<------->]+
  subtract by 35 and set else bit
  <[>,>]
  if not # then read next char
  >[[-]>]
  otherwise do not read and back to same position in both cases
  <<
]>

Code (minified)

>>>,[>+++++[-<------->]+<[>,>]>[[-]>]<<]>

Final state

  • Memory: 0, 0, 0, instructions, 0, IP (=0)
  • Cursor: on IP (instruction pointer, currently 0)
  • Input: remaining is interpreted code's input only
  • Output: unchanged

Example
Live 'Instruction reader' example, that reads code to execute until it reaches separator, then display the code (add 35 to each char and print).

Back to previous step
Go to next step

Aucun commentaire:

Enregistrer un commentaire