compilationforth

How CREATE and buffers works?


This code create a buffer:

: bytes create allot does> + ; 

When you execute

10 bytes a

create first create the header for the definition, and then insert one operation that pushed next address into the stack.

Then allot allocates 10 bytes, and then the rest of the instructions (whatever they are).

enter image description here

My question is How the execution jump around the 10 bytes buffer?


Solution

  • How the execution jump around the 10 bytes buffer?

    It does not jump, and there are no instructions after the buffer.

    For better explanation, let's break your bytes definition into a few words:

    : create-bytes ( u.size "name" -- ) create allot ;
    : bytes-action ( u.offset addr1 -- addr2 ) + ;
    : alter-bytes-latest ( -- ) does> bytes-action ;
    : bytes ( u.size "name" -- ) create-bytes alter-bytes-latest ;
    

    Thus, 10 bytes a is equivalent to the following commands sequence:

    After the command 10 create-bytes a you will get a definition for a that conceptually looks as:

    At this point, each of the commands a ., ' a >body . and here 10 - . prints the same addr5.

    After the subsequent alter-bytes-latest command execution, the definition for a will conceptually look like this:

    Now we must pass an offset to a. The command 0 a . prints addr5, 10 a here = . prints -1.

    So alter-bytes-latest just modifies the behavior of a (that is the latest named definition at the moment). Formally, it replaces the execution semantics of the most recent definition (that shall be created via create), see 6.1.1250 DOES>.

    See also my illustrative portable implementation for create, >body, and does>.