TweetFollow Us on Twitter

Forth Structures
Volume Number:2
Issue Number:9
Column Tag:Threaded Code

Adding Record Structures to Forth

By Jörg Langowski, EMBL, c/o I.L.L., Grenoble, Cedex, France, MacTutor Editorial Board

Records with local field names

Data representation is a field that is neglected by many Forth dialects. Basic Forth-83 doesn't even provide for simple one and two dimensional matrices, neither are more complex types of data supported, such as Pascal records or C structs. These latter forms of data representation play a most important role in Toolbox programming, since very many traps expect pointers to records as parameters.

A letter received through BITNET from a reader who was wondering how to install a way to handle such data structures in Forth got me started on this month's column:

"I posted the following article to the USENET, but got little in the way of a response. Any help you can give will be much appreciated. By the way, I know that the rectangle definitions given below are inaccurate for the Mac, but I was trying to be machine independent in posting to the Forth language newsgroup.

From postnews Thu Jun 12 15:23:34 1986

Subject: Defining a structure in FORTH?

Newsgroups: net.lang.forth

Distribution: net

I am very much a novice FORTH programmer, and I don't even have a good textbook to go by. I recently purchased a FORTH for my Macintosh at home (MACH1, distributed by the Palo Alto Shipping Co.), and would like some advice. Professionally I do a lot of work with LISP, and I would like to implement something similar to a `DEFSTRUCT' package in FORTH. In other words, I'd like to be able to do something like:

           TOP    2
           LEFT   2
           BOTTOM 2
           RIGHT  2 ]ENDSTRUCT

Which would automatically define the following:

    : RECTANGLE-TOP@ ( a - n ) @ ;
    : RECTANGLE-TOP! ( n a - ) ! ;
    : RECTANGLE-LEFT@ ( a - n ) 2 + @ ;
    : RECTANGLE-LEFT! ( n a - ) 2 + ! ;
    : RECTANGLE-BOTTOM@ ( a - n ) 4 + @ ;
    : RECTANGLE-BOTTOM! ( n a - ) 4 + ! ;
    : RECTANGLE-RIGHT@ ( a - n ) 6 + @ ;
    : RECTANGLE-RIGHT! ( n a - ) 6 + ! ;
    : MAKE-RECTANGLE ( whatever code
 necessary to allocate 8 bytes of variable storage and assign a dictionary 
entry to the word which follows.This I guess would be implementation 
specific. ) ;

While I'm sure that this could be done by defining 'DEFSTRUCT[' so that it constructs all of the necessary dictionary headers etc. at the bit and byte level, this would doubtless be complicated and not very portable. I wonder then, if there is a higher level method of defining such a beast? Any help (even "no that can't be done") would be appreciated."

--Bruce Florman florman@rand-unix.ARPA

Since I think the question put forward by Bruce Florman is of very general interest to Macintosh Forth programmers, I'll try to show a way how such data structures may be implemented in MacForth or Mach2.

Structures in MacForth (CSI method)

MacForth (Kernel 2.4) provides a simple and effective way to implement structure definitions. A structure definition is a way to assemble information about a data structure (the lengths of the various fields and the total length of the structure). Example:

structure testrec
 long: ^date
 long: ^time
 byte: ^flag
   20 string: ^description

defines the data structure testrec with four fields, date, time, flag, and description. testrec is not a defining word. When executed, it merely leaves on the stack the length of the structure that is going to be defined; this number can then be used to allot an appropriate number of bytes in the dictionary. So, creation of a testrec would be done like:

create myrec testrec allot

The words that are used to access the field, ^date, ^time, ^flag, and ^description, simply add an offset to the number on top of stack. If this number is the address of a valid structure, like myrec,

myrec  ^flag

would indeed yield the address of the flag field in myrec. [Note that the circumflex in front of the field names is purely a MacForth convention, you could name the fields as you like].

This solution is beautifully simple and helps very much improving the readability of your program text if you are working with lots of structured data types. There is one drawback, however, that the field name definitions are global to the program and therefore violate the conventional definition of a Pascal record, in which field names are always local to the structure.

This means you have to exercise a lot of discipline when you work with structures defined in this way. On executing a field operator, it is not checked whether the address on top of stack is really the address of a structure, so bugs that leave unexpected values on the stack would be harder to detect. Furthermore, since all the field names are global, they may not occur in several different structure definitions in different contexts.

Therefore, I'd like to present an alternative to CSI's implementation of structures which uses local field names. This is slower during compilation, since every structure definition will have its own local dictionary that has to be searched, but in most cases has the same speed during execution. It offers the additional advantage that by a very simple modification, a rudimentary NEON-like class behavior may be built in.

Record definition with local field names

From now on, we'll call the type of data structure dealt with a record, to emphasize the similarity with Pascal records. A record definition will be a template from which an arbitrary number of instances of this record can be built (note that this already strongly resembles NEON's terminology). Each instance will consist of a reference to its template and the data fields as defined in the template (Fig. 1).

A record definition (Listing 1) then consists of:

- the word :record, which sets up a defining word for the instances and initializes the stack for the field name definitions following;

- field name definitions (>long, >word, etc.), which add names to the record template and store (after the name) the length of the data field and its position within the record;

- ;record, which closes the definition, stores a 16-bit zero and the total length of the record at the end of the template, and checks for completeness of the definition.

An example definition is given at the end of Listing 1.

Run-time behavior of records

The run-time behavior of a record template defined through :record is given by the word do.record. This word scans the list of field names in the record template and creates a new instance of the record with a pointer to the template in its first four bytes and space for the data fields following it.

The run-time behavior of the record instance is just to place its base address (the pointer to the template) on the stack. Access to the record fields is provided through ^field, which expects an address of a record instance and a string address on the stack. ^field will search the record template for the field name and leave the (absolute) field address on the stack or abort with an error message if the string does not match any field name in that particular record.

The operator ^ is provided for readability; executing

r1 ^ date

will give the same result as executing

r1 " date" ^field.

So far, we have only talked about execution time behavior of records. However, most of the times one would want to compile references to record fields into Forth definitions rather than execute them directly. For inclusion into Forth definitions, one way is to write

: test1 [ r1 ^ date ] literal ....... ;

which compiles the address of the date field of r1 into the definition as a literal. If a run-time reference to an arbitrary record is to be made, one can either write

: test2 ( record addr -- addr of date field )
  " date" ^field ;

which also checks at runtime for the validity of the date reference (something like 'late binding'), or, for faster execution, one writes

: test3 (record addr -- addr of date field )
  [ r1 dup ^ date - ] literal + ;

which assumes that the record address passed at run time refers to a record of the same type as r1. But in that case, CSI's structure definition is, of course, equivalent and easier to read.

From record to class definitions - using record fields as vectors

A simple, again very rudimentary, implementation of a NEON class like structure can be obtained using the record definition given here. If the data contained in a >long field (lets say with the field name print) is the cfa of a Forth word, writing

r1 ^ print @ execute (Mach2) or

r1 ^ print @ make.token execute

will execute the word that the print field of r1 points to. (In MacForth, one might also reserve a >word field and store a token there, then say r1 ^ print @ execute).

Vectors within records are very similar to methods associated with objects. Of course, method inheritance from superclasses has not been implemented here, so the resemblance to 'real' object oriented languages is not very strong.

Some extensions to Mach2 for MacForth compatibility

At the beginning of Listing 1 I have included some definitions for MacForth words that are not included in Mach2. Those are the words =cells, needed, and -string. The latter, a string comparison operator, has been implemented in two different ways; in both cases, the top two stack items are string addresses, and the flag returned is 0 if the strings are equal and 1 if not. =string uses the IUMagIDString routine from the international utilities package, which does a better job in comparing name strings that contain umlauts, diacritical marks etc., but is slower. -string uses the _Cmpstring trap, which is much faster and the recommended one to use for applications like this one.

MacForth Plus - no more Level 1,2,3

Readers of the CSI newsletter might have received an announcement of their latest update to MacForth by the time this is in print. Anyway, I'll tell you a few things about it that I was told in a letter at the time I wrote this (June).

• MacForth Plus, to be released at the end of August, will supersede all previous versions and levels of MacForth. Its version of the kernel will "...execute considerably faster than K2.4 It will execute faster than Mach1."

• Normal text file editing will be supported, as well as block file editing.

• Multitasking, which was undocumented, but in principle possible with MacForth, will be fully supported in MacForth Plus.

• The documentation will contain in one single manual the Level 1,2 and 3 informations, as well as the new features.

• Stand-alone applications can be produced by a built-in turnkey mechanism.

• The upgrade from Level 2 will be available for (scheduled) $49 upgrade fee, which includes the manual. Level 3 users will receive a free upgrade.

This sounds very interesting. I hope I'll soon have a test copy to write about.

Listing 1: record structures in Forth
( Structures, Mach-2 version                  
Adding a structure compiler to Forth. JL 26.6.86.
This file defines a Pascal-like 'record' structure;
a record is a template for instances of the structure.
:record a
    >long field1
    >word field2

myrec r1 \this creates an instance r1 of myrec whose fields
          may be accessed through myrec ^ field1 etc..

for 'late binding' usage, the word ^field is provided)

only forth also assembler
( some MacForth definitions that Mach1 is missing )
: =cells dup 2 mod + ;
: needed depth 1- > abort" NEEDED- not enough stack items" ;

CODE =string 
      count rot count rot swap  
      MOVE.W    #0,-(A7)
      MOVE.L    $C(A6),-(A7)
      MOVE.L    $8(A6),-(A7)
      MOVE.W    $6(A6),-(A7)
      MOVE.W    $2(A6),-(A7)
      MOVE.W    #12,-(A7)
      ADDQ.L    #8,A6
      ADDQ.L    #8,A6
      MOVE.W    (A7)+,-(A6)
      MOVE.W    #0,-(A6)

CODE -string 
      count rot count swap  
      MOVE.L    (A6)+,A0
      MOVE.L    (A6)+,D0
      SWAP.W    D0
      MOVE.L    (A6)+,D1
      MOVE.W    D1,D0   
      MOVE.L    (A6)+,A1
      MOVE.L    D0,-(A6)

( do.record, creating one instance of a record )  ( 062686 jl )
: do.record  ( addr of master | -- )
    create  dup ,
        begin dup c@ dup while ( not zero, i.e. end)
            1+ =cells 4 + + ( next field in template )
    drop 2+ w@ ( length stored here ) allot
    does>  ( nothing special )

( :record ;record and friends)                    ( 062686 jl )

:  :record  create 13579 4 does> do.record ;

:  ;record  2 needed
    0 w, ( end of list) w, ( total length )
    13579 = 0= abort" ;record without :record"

:  put.fieldname
    32 word here over c@ 1+ dup =cells allot cmove ;

( field defining words )                          ( 062686 jl )
: >long ( addr | addr+4)
        put.fieldname dup w, 4 w, 4 + ;
: >word ( addr | addr+2)
        put.fieldname dup w, 2 w, 2+ ;
: >byte ( addr | addr+1)
        put.fieldname dup w, 1 w, 1+ ;
: >bytes ( addr \ n | addr+n )
        put.fieldname over w, dup w, + ;
( ^field, addressing a field within a record )    ( 062686 jl )
: ^field ( addr name | address of field )
    over @ ( addr name master )
        begin 2dup -string while ( no match )
            dup c@ 6 + =cells +
            dup c@ 0= ( end of list )
                abort" RECORD- specified field does not exist"
    ( match found )
    dup c@ 1+ =cells + w@ ( start within record )
    swap drop   +  ( address of field )

( ^ )                                   ( 062686 jl )

: ^   32 word ^field ;

( example of a record structure )                 ( 062686 jl )
:record testrec
    >long date
    >long time
    >byte flag
    >word counts
 30 >bytes description

testrec r1
testrec r2

Community Search:
MacTech Search:

Software Updates via MacUpdate

Notion 2.1.3 - A unified workspace for m...
Notion is the unified workspace for modern teams. Features: Integration with Slack Documents Wikis Tasks More improvements to editing Browse through a page’s images from one place Choose a type... Read more
Cocktail 15.3.7 - General maintenance an...
Cocktail is a general purpose utility for macOS that lets you clean, repair and optimize your Mac. It is a powerful digital toolset that helps hundreds of thousands of Mac users around the world get... Read more
Dropbox 158.4.4564 - Cloud backup and sy...
Dropbox is a file hosting service that provides cloud storage, file synchronization, personal cloud, and client software. It is a modern workspace that allows you to get to all of your files, manage... Read more
WhatsApp 2.2236.10 - Desktop client for...
WhatsApp is the desktop client for WhatsApp Messenger, a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS. WhatsApp Messenger is available for... Read more
VOX 3.5.2 - Music player that supports m...
VOX just sounds better! The beauty is in its simplicity, yet behind the minimal exterior lies a powerful music player with a ton of features and support for all audio formats you should ever need.... Read more
TeamViewer 15.34.4 - Establish remote co...
TeamViewer gives you remote control of any computer or Mac over the Internet within seconds, or can be used for online meetings. Find out why more than 200 million users trust TeamViewer! Free for... Read more
ClamXAV 3.5 - Virus checker based on Cla...
ClamXAV is a popular virus checker for OS X. Time to take control ClamXAV keeps threats at bay and puts you firmly in charge of your Mac’s security. Scan a specific file or your entire hard drive.... Read more
Ableton Live 11.2 - Record music using d...
Ableton Live lets you create and record music on your Mac. Use digital instruments, pre-recorded sounds, and sampled loops to arrange, produce, and perform your music like never before. Ableton Live... Read more
Viber 18.5.0 - Send messages and make fr...
Viber lets you send free messages and make free calls to other Viber users, on any device and network, in any country! Viber syncs your contacts, messages and call history with your mobile device, so... Read more
CrossOver 22.0.1 - Run Windows apps on y...
CrossOver can get your Windows productivity applications and PC games up and running on your Mac quickly and easily. CrossOver runs the Windows software that you need on Mac at home, in the office,... Read more

Latest Forum Discussions

See All

TouchArcade Game of the Week: ‘Tallowmer...
With its pre-determined launch date of September 30th it didn’t quite make it in time for our weekly round-up of new game releases, but darn it, I just don’t care. I’m not letting that technicality keep me from picking Tallowmere 2 as our Game of... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for September 30th, 2022. In today’s article, our pal Mikhail has another review for us. Gosh, that guy needs a day off! He’s taking a look at Let’s Build a Zoo, and it’s not exactly the... | Read more »
Seven Knights 2 recieves global update i...
Netmarble has announced the latest global update for mobile role-playing game Seven Knights 2. The update will bring brand new characters, some very rewarding events, and reworks to a few old favourite heroes. [Read more] | Read more »
‘GRIS+’ Is This Week’s New Apple Arcade...
Nomada Studio and Devolver Digital’s brilliant GRIS+ () has joined Apple Arcade today as an App Store Great. If you’ve not played it yet, GRIS debuted on PC and Nintendo Switch before seeing PS4 and mobile releases later on. I reviewed the iOS... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for September 29th, 2022. In today’s article, we have a bunch of new releases to check out with the spearhead being The Elder Scrolls V: Skyrim Anniversary Edition. There’s a little here... | Read more »
‘Residual’ Controller Fix Update Release...
A few weeks back developer OrangePixel released their newest game on mobile called Residual. This is a roguelike survival game where you play as a pilot who crash lands on a procedurally generated planet, filled with all sorts of crazy creatures and... | Read more »
‘Queen’s Wish 2: The Tormentor’ Launchin...
We learned back in July that Spiderweb Software’s latest game Queen’s Wish 2: The Tormentor would be heading to desktop platforms in August, which is exactly what happened, and at that time we were guessing that the iOS version of the game would... | Read more »
‘Kingdom Rush Vengeance’ Primal Ravage U...
Ironhide Game Studio’s Kingdom Rush Vengeance ($4.99) has gotten quite a few updates over the years on iOS, Android, and PC. | Read more »
Interactive Film The Gallery screens at...
The FMV/interactive film hybrid video game genre has been around for a while but doesn’t seem to have that many games out there, but they just might get some more exposure as The Gallery has landed a spot in the Dinar Film Festival 2022. [Read... | Read more »
Terraria’s Massive Labor of Love Update...
Re-Logic’s action platforming sandbox game Terraria ($4.99) has just been updated on mobile and console platforms with its newest major update titled the ‘Labor of Love’ update. | Read more »

Price Scanner via

Apple has M1 Mac minis in stock again startin...
Apple has restocked a full line of M1-powered Mac minis available in their Certified Refurbished section starting at only $589 and up to $140 off MSRP. Each mini comes with Apple’s one-year warranty... Read more
13″ M1 MacBook Airs with 16GB of RAM availabl...
Apple has 13″ M1 MacBook Airs (8-Core CPU/7-Core GPU) in stock today with 16GB of RAM for $190 off MSRP, Certified Refurbished. Apple includes a standard one-year warranty with these models, each... Read more
Update: 13-inch Apple M2 MacBook Airs now on...
Amazon has 13″ MacBook Airs with M2 CPUs in stock today and on sale for $150 off MSRP. Shipping is free. Their prices are now $150 off Apple’s MSRP, and they are the lowest prices available for these... Read more
Save $240 on a 14″ 8-core CPU M1 Pro MacBook...
Apple has the 14″ M1 Pro MacBook Pro with 32GB of RAM and a 512GB SSD (Space Gray) in stock for $2159, Certified Refurbished. Regular price for this configuration is $2399, so their savings amounts... Read more
Save $170 on this 13″ M2 MacBook Pro with 16G...
Apple has 13″ M2 MacBook Pros with 16GB of RAM and 512GB SSDs in stock today for $170 off MSRP ($1529), Certified Refurbished. These are the cheapest 13″ M2 MacBook Pros with this configuration... Read more
This Apple retailer is offering a $350 discou...
Apple retailer Expercom is offering a $350 instant discount on select upgraded 16″ Apple MacBook Pros through October 4, 2022. Shipping is free. Their sale price applies to the following... Read more
Clearance 27″ 5K Apple iMacs are on sale star...
Other World Computing has dropped prices on Apple refurbished, factory-sealed, recently-discontinued 27″ 5K iMacs with models now on sale for up to $950 off Apple’s MSRP, starting at only $849. Their... Read more
Get a new Mac for up to $400 off MSRP at Appl...
Need a new Apple Mac for school? Whether you’re a student, teacher, or staff member, you can use your .edu email address when ordering at Apple Education to take up to $400 off the price of a new Mac... Read more
13-inch Apple MacBook Airs with M2 processors...
Amazon has 13″ MacBook Airs with M2 CPUs in stock today and on sale for $1099. Shipping is free. Their prices are $100 off Apple’s MSRP, and they are the lowest prices available for M2-powered Macs... Read more
AR Glasses That Work With Apple’s Hardware? T...
NEWS – Lenovo has created quite the spectacle(s) with its latest product. “Apple Glass” — the purported name of Apple’s forthcoming AR glasses — is not expected to be released until 2025 (at the... Read more

Jobs Board

*Apple* Electronic Repair Technician - PlanI...
…a highly motivated individual to join our Production Department as an Apple Electronic Repair Technician. The computer repair technician will diagnose, assemble, Read more
( *Apple* ) Production Designer/Artist - TEKs...
…Art Ops team supports production, asset management, quality control, and global publishing for Apple Media Products, like Apple Music. The Art Ops team is Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States ( - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States ( - Apple Blossom Mall Read more
Sephora Beauty Advisor - *Apple* Blossom Ma...
Sephora Beauty Advisor - Apple Blossom Mall Location:Winchester, VA, United States ( - Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.