Search

mercredi 8 février 2017

Self-interpreter: memory access, inc, dec, print and read (6)

Context

As a reminder, here is the final memory map
0 0 0 {instrs} 0 inst_ptr 0 0 0 inactive_flag direction_flag memory_ptr  0 0 0 0 0 {mem}
Let's now how to access a value in memory and implement '+', '-', '.' and ',' operations.

Initial state

  • Memory: see above
  • Cursor: on instruction, next to inst_ptr
  • Input: any

Process

  • Access memory value
    • Copy memory pointer, and add one to copy
    • While copy is not null
      • Move through the first memory array (initially: none)
      • Move second memory array (initially: whole memory) first element to end of first array. Init / reinit first cell of the block to 1.
      • Decrease copy
      • Loop invariant: target item is Nth of second memory array, where N is the actual copy value (1-based index)
      • When copy is null: N is the last element of first memory array
    • Go to last element of first memory array
    • Execute instruction
    • Move array back to initial position

Code - generic

duplicate memory pointer and move to copy
>>>>[->+>+<<]>>[-<<+>>]<+
[
  -
  go to next memory cell
  >>>>[>>]+>>
  (re)init/copy memory indicator
  [-]>[-<<+>>]<<<[<<]<<
]
go to current memory cell
>>>>[>>]<
do somethingmove array back to initial position
<[[->>+<<]>[->>+<<]<<<]
<<<<<<<

Code (minified) for inc

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

Code (minified) for dec

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

Code (minified) for print

>>>>[->+>+<<]>>[-<<+>>]<+[->>>>[>>]+>>[-]>[-<<+>>]<<<[<<]<<]>>>>[>>]<.<[[->>+<<]>[->>+<<]<<<]<<<<<<<

Code (minified) for read 

>>>>[->+>+<<]>>[-<<+>>]<+[->>>>[>>]+>>[-]>[-<<+>>]<<<[<<]<<]>>>>[>>]<.<[[->>+<<]>[->>+<<]<<<]<<<<<<<

Final state

  • Memory: see above
  • Cursor: on instruction, next to inst_ptr
  • Input: unchanged
  • Output: unchanged

Aucun commentaire:

Enregistrer un commentaire