sábado, 4 de dezembro de 2021

FORTH stack notation in code could be better

Consider the following WORD called TABLE for accessing entries on a table (all examples from: The Complete Forth, by Alan Winfield, Sigma, 1983): First, let's create the table:

CREATE MYTABLE -10 , -5 , 0 , 5 , 10 ,

This, of course, used the comma WORD "," (reserve one cell of data space and store x in the cell). Now, we can define a TABLE@ WORD:

: TABLE@ 1- 8 * MYTABLE + @ ;

We'll explain this shortly. Now, a cell, in Forth, is a one 8-bit byte on most systems (here, I'm using gforth). So, if we're advancing on the memory layout of the table, we'll be moving 8-bits at a time. Here's what using TABLE@ looks like:

5 table@ . 10  ok
4 table@ . 5  ok
3 table@ . 0  ok
2 table@ . -5  ok
1 table@ . -10  ok

Now, the usual way to document the stack notation would be:

: TABLE@ 1- 8 * MYTABLE + @ ; ( n1 -- n2 )

which is pretty much usual in what regards us gaining insight in how the thing works. Winfield proposes a better notation:

: TABLE@

     1-       ( n -- n-1 - subtract one from index )

     8       ( n-1 -- n-1 8 - push cell size value onto the stack )

     *       ( n-1 2 -- offset - multiply to give offset )

     MYTABLE      ( offset -- offset addr - fetch start address of MYTABLE )

     +       ( offset addr -- offset+addr - add offset )

     @       ( offset+addr -- n - fetch value required )

;

Let's face it, that is a much better way of documenting the stack effects on Forth code. You can see that it begins with a number, and ends with a number, but simply documenting it as "( n1 -- n2 )" says nothing about how the code works. In this Winfield notation, the 'stack after' becomes the the 'stack before' in the next line. He defined his experienced on using this way of notating Forth code "invaluable" for complex stack manipulations. It's pretty clear why, and it makes for very understandable Forth code.

Nenhum comentário:

Postar um comentário