Search

Affichage des articles dont le libellé est memory. Afficher tous les articles
Affichage des articles dont le libellé est memory. Afficher tous les articles

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

Self-interpreter: Memory map, left and right (5)

Context

Here is the final memory map will be
0 0 0 {instrs} 0 inst_ptr 0 0 0 inactive_flag direction_flag memory_ptr  0 0 0 0 0 {mem}
The inactive_flag will be updated by both '[' and ']', and used by the global instruction processing to do execute or not instructions.
The direction flag will be used by the fetch to move on left, or right, and updated by ']' instruction when active, or '[' when inactive.

Let's now implement < and > operations.

Initial state

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

Process

  • Increase or decrease memory_ptr

Code for >

  >>>>+<<<<

Code for <

  >>>>-<<<<

Final state

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