Search

mercredi 8 février 2017

Self-interpreter: fetch instructions (3)

Context

Now that our instructions are read correctly, let's implement a fetch loop.
Given an instruction pointer, the fetch is an operation that gives us the operation to implement.
This is globally similar to a random access in array, but the fetch loop should be executed again and again. Then, it's simpler to ave a one-based index: we can loop on fetch pointer in this case.
And access an element in this case is not complex either, the pointer value just need to be decreased by a given offset

Initial state

  • Memory: 0, 0, 0, instructions, 0, IP
  • Cursor: on instruction pointer (initially 0)
  • Input: any

Process

  • Set pointer to 1
  • While pointer is not null
    • Decrease pointer
    • Copy pointer
    • Use pointer copy to get instruction
    • Copy current instruction outside array - the instruction copy will be placed just beside the instruction pointer cell
    • If instruction is not null
      • For test purposes: rebuild original value and print it. This part will be later replaced by instruction processing, of course
      • Increase pointer back to original value
      • Increase pointer (move to next instruction)
    • Otherwise, break the loop

    Code 

    fetch loop
    +[
      get current instruction
      -[->+>+<<]>>[-<<+>>]<[-<<<[<]>[-<<+>>]>[>]>>]<<<[<]>[-<+<+>>]<[->>[>]>>+<<<[<]<]<[->>+<<]<[[->>+<<]<]>>>[>]>>

      parse current instruction
      >+<[>-<
        rebuild and print (test)
        >+++++[-<+++++++>]<.[-]
        increment instruction counter
        <++>
      ]>[-<<[-]>>]<
    <]

    Code (minified)

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

    Final state

    • Memory: 0,instructions, 0, IP
    • Cursor: on IP
    • Input: unchanged
    • Output: unchanged (except for test purposes)
    Note: when direction_flag will be available, the <++> line will be replaced by
        increment or decrement based on direction_flag

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

    Example

    Live 'Instruction reader / fetcher / printer' example, that reads code to execute until it reaches separator, then display the code using the fetch loop.

    Back to previous step
    Go to next step

    Aucun commentaire:

    Enregistrer un commentaire