/ structure2 /

STRUCTURES, very simple

description:


: ^FIELD CREATE , DOES> @ + ; ( offset "name" -- offset )
( name: addr -- addr+offset )

\ base stricture
0
^FIELD mst^x CELL+
^FILED mst^y CELL+
^FIELD mst^a CHAR+
^FIELD mst^b CHAR+ ALIGNED
^FILED mst^z CELL+
CONSTANT mst-size \ mst for "My STructure"

\ derived structure
mst-size
^FIELD mst^u CELL+
^FIELD mst^v CELL+
CONSTANT xmst-size

: foo
...
( addr ) mst^x @ ( val )
...
( val addr ) mst^y !
;




More complex:


: @FIELD CREATE , ( offset "name" -- offset )
DOES> @ + @ ; ( name: addr -- val )
: !FIELD CREATE , ( offset "name" -- offset )
DOES> @ + ! ; ( name: val addr -- )
: C@FIELD CREATE , ( offset "name" -- offset )
DOES> @ + @ ; ( name: addr -- val )
: C!FIELD CREATE , ( offset "name" -- offset )
DOES> @ + ! ; ( name: val addr -- )

0
^FIELD xyz^c C@FIELD xyz.c C!FIELD xyz!c CHAR+ ALIGNED
^FIELD xyz^x @FIELD xyz.x !FIELD xyz!x CELL+
CONSTANT /xyz
\ Slash "/" stands for "size-of"


or

<spanforth>: word: ^FIELD @FIELD !FIELD CELL+ ;
<spanforth>: byte: ^FIELD C@FIELD C!FIELD CHAR+ ;

0
word: smp^x smp.x smp!x
byte: smp^a smp.a smp!a
byte: smp^b smp.b smp!b
ALIGNED
word: smp^z smp.z smp!z
CONSTANT /smp



Explanation:

to be written


Page written by:

mlg


Notes:

GuidoD most likely would say that ^FIELD should be called +FIELD
and that the field selectors must be of the form ->structname.fieldname
rather than structname[operation]fieldname . It's a matter of taste.

Anyway, to add structures to Forth you need one line of auxiliary code.


guidod comment:

to give you an idea of the look with using +FIELD to declare an
offset-constant, here is an example


0
+field my.x+ cell+
+field my.y+ cell+
+field my.a+ char+
+field my.a+ char+
aligned
+field my.z+ cell+
+field my+ drop

0 my+ buffer: my.buf
42 my.buf my.z+ !

0 my+ \ extends
+field other.w+ cell+
+field other+ drop


note that only a single word +FIELD is needed to build a complete
series of structure accessors and declarators. Since the words CHAR+
and CELL+ are part of the ANS Forth standard, no other word is needed
unlike the case of /FIELD where the usual but not-required words
/CELL and /CHAR would be needed, as this:


0
/cell /field ->my.x
/cell /field ->my.y
/char /field ->my.a
/char /field ->my.b
aligned
/cell /field ->my.z
constant /my

/my buffer: my.buf
42 my.buf ->my.z !

/my \ extends
/cell /field ->other.w
constant /other


however the latter is a bit more readable and has references in
the openboot standard where the simplefield declarator was just
called FIELD (which some forth system tooks for another meaning).


generated Wed Jul 23 02:53:36 2003mlg