Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(GNU) Forth Local Variable Behavior

I was just learning about local variables for word definitions in Forth. I happen to use GNU Forth (gforth). I was looking at the question and answer, Forth local variable assigning variables and was struggling with the behavior of the given answer. When I tried it, I was getting an underflow unless I had four cells on the stack.

Consider this simple example:

: foo { a b } a b + . ;

This word will take the top two stack cells, store them in the local variables a and b, put a and b (in that order) back on the stack, add them, pop and display the result, and emit a carriage return. It works as I would expect, leaving nothing on the stack when it completes:

: foo { a b } a b + . cr ;  ok
1 3 foo 4
 ok
.s <0>  ok

Now I'd like to try a local variable which is not taken from the stack originally:

: foo { a b | c } a b + to c c . cr ;

I would expect this to behave similarly but use the local variable c. This word would take the top two stack cells, store them in the local variables a and b, put a and b (in that order) back on the stack, add them, pop the result and store it in c, push c back onto the stack, then pop and display the top stack cell and emit a carriage return.

This one doesn't work as I would have expected. Here are my results:

: foo { a b | c } a b + to c c . cr ; ok
1 3 foo
:3: Stack underflow
1 3 >>>foo<<<
Backtrace:
$7F2B572EA1F0 >

Hm, ok, why is there an underflow? Let's try an additional cell on the stack:

1 3 5 foo
:4: Stack underflow
1 3 5 >>>foo<<<
Backtrace:
$7F2B572EA1F8 >l

Still an underflow! Let's try another:

1 3 5 7 foo 4
 ok
.s <0>  ok

No more underflow. The word foo has consumed all of the cells, but the top two don't appear to be used anywhere. The result 4, which is the sum of the first two cells on the stack, is what I would have expected when I originally tried 1 3 foo.

I have been trying to find some good documentation regarding the local variable behavior, but the manual is very terse on this topic. Can someone explain what is happening here?

like image 231
lurker Avatar asked Mar 20 '18 12:03

lurker


1 Answers

Per the comment thread to the question, there is a bug in local variable handling in the "current release", version 0.7.3 (7/9/2014) which has been resolved in a later development release. Downloading, building, and using version 0.7.9_20180319 indicated that the problem was resolved. Thanks to Lars Brinkhoff for pointing out the resolution.

like image 102
lurker Avatar answered Nov 11 '22 16:11

lurker