stackforthgforth

Restrictions on stack use when defining words?


I was testing the use of [] inside a definition, I got an error:

: x [ here ] ;
:2: unstructured
: x [ here ] >>>;<<<

I understand that the cause of the error is having grown/decreased the stack while compiling. The culprit can be any "immediate" word:

: y + ; immediate  ok
1 2 y . 3  ok
4 5   ok
: x y ; 
:4: unstructured 
: x y >>>;<<<

My question is: is it part of the standard or just the gforth implementation?

Are there any other restrictions on the use of the stack?


Solution

  • is it part of the standard or just the gforth implementation?

    It is a part of the standard.

    The word : leaves colon-sys on the data stack: ( -- colon-sys ).
    The word ; consumes colon-sys from the data stack: ( colon-sys -- ).

    colon-sys is a system-compilation data type. The size of colon-sys is implementation dependent. It can occupy 0 cells in the data stack, or ten cells, or more.

    The following line, when run with the empty data stack, will output the colon-sys tuple.

    : x [ cr .s cr ] ;
    

    In turn, the word ; throws an exception if it does not encounter colon-sys at the top of the stack (for example, if you put something on the stack over colon-sys). Throwing exception in this case is not obligated, but allowed by the standard due to an ambiguous condition.

    Therefor, doing compilation of a definition, it's not easy to consume something from the data stack or leave something on the stack. You can use variables, or a user-defined stack, or, if creating a definition programmatically, the return stack.


    Formally, colon-sys is placed on the control-flow stack. But the control-flow stack may be implemented using the data stack. Anyway, the result is that colon-sys may occupy 0 or more data stack cells.