Skip to main content

Full text of "Forth Dimension Volume 14 Number 1"

See other formats


Volume XIV. Number 1 



May 1992 June 



FORTH 

DIMENSIONS 




mWm 



SILICON COMPOSERS INC 



Announcing the SC/FOX DRAMI032 Board 



lllll) U4 RS232 
yS UIO PARA UU PARS g U17^ HIPAR 




U3 RS232 




Xi^SC/FO! DRAHIDSa (?) 1992 SAlcon Conpoj«i~«. tnc PaLo Mig CA USA 



SC/FOX DRAMI032 Board (actual size) 



■ The DRAMI032 is a piuq-on daughter board which 
attaches directly to either the SBC32 stand-alone or 
PCS32 PC plug-in single board computers. 

■ Up to 16 MB on-board DRAM. 

■ 5 MB/sec SCSI controller supports up to 7 SCSI 
devices. 

■ 1 6-bit bidirectional parallel port, may be configured as 
two 8-bit ports. 

■ 4 Serial ports, configurable as 4 RS232 or 2 RS232 
and 2 RS422. 

■ Each serial port is separately programmable in 33 
standard baud rates up to 230K baud. 

■ 4 input handshaking and 6 output control lines. 

■ 7 general purpose latched TTL level output lines, 

■ 11 general purpose TTL level input lines with 
interrupts available on either transition. 

■ 2 programmable counter/timers, may use internat or 
external event Irlgger and/or time base. 



■ Wristwatch chip keeps correct time and date (battery 
included) with or without system power. 

■ 24 bytes of keep-alive CMOS RAM, powered by 
wristwatch battery. 

■ Source code driver software and test routines for 
SCSI, parallel and serial ports, DRAM, timers, CIVIOS 
RAM and wristwatch chip included. 

■ Interrupts available for all I/O devices. 

■ No jumpers, totally software configurable. 

■ Hardware support for fast parallel to SCSI transfer. 

■ Multiple boards may be stacked in one system. 

■ Two 50-pin user application connectors. 

■ Single +5 Volt low-power operation. 

■ Full power and ground planes. 

■ Input for external -h5 volt supply to keep DRAM data 
In case of loss of main power. 

■ 6 layer, Eurocard-size: 1 00mm x 1 60mm. 

■ User manual and interface schematics included. 



See application article in this issue. 
For additional product and pricing information, please contact us at; 
SlUCON COMPOSERS INC 208 California Avenue, Palo Alto, CA 94306 (415) 322-8763 



May 1992 June 



2 



Forth Dimensions 



Features 



6 A Single-Step Debugger Rick Grehan 

& Other tools for the SC32 

The lechnical dirctlor of HYVE Labs produced a "niassivc amount of code" on Silicon 
Composers' FCS32 system. Here he shares Lhe debugger he wrote to speed development. 

12 Designing Softwate^ontrolled Devices Carol Goldsmitit 

'I'hG Sales Manager of 'lhe Saclig Company explains Fonh's advantages when doing product 
development, and describes llic use of two nn-lx)ard-Forih controllers offered by that firm, 

14 JForth— 32-bit Forth for the Amiga PhiiBurk 

The co-author of JForth advocates big Forth for big niiaoconipuler systems, and his company's 
Forth offers such an alternative applications-development environment. Also discussed is 
HMSL, the 'hierarchical music specification language" extension. 

16 Object-Oriented Foiih MarkusDahm 

From a European group that devclofM workstations for medical imaging comes this 
description of their Forth, 'I 'he principles and benefits of its object-oriented design are 
discussed, including performance considerations, 

23 The Curly Control Structure Set Kourtis Giorgio 

Searching for a set of control struaures with good performance, ease of use, generalization, 
flexibility, and teachability without sacrificing /oo much historical continuity? The code, 
examples, and text given here conclude the discussion begun in our last issue, 

35 Working with Create ... Does> Leonard Morgenstem 

'[his word pair trips up many who arc learning Forth, The basics of writing a new defining 
word are <k;monstrated for the hesitant, more-advanced uses for the bold, and a caution is 
given lo the over confident. 

42 Space Application of SC32 Forth Chip Silicon Composers 

Developing, acquiring data from, and conuoliing a suborbital solar telescope via a system 
configured around Silicon Composers' SC32 Forth RISC chip. Using a single on-board 
ccMnputer reduces complexity and development time. 



Departments 




4 


Editorial 


. . New in PD, call for tutorials, time of renewal. 


5 


Letters 


No commerce, no Forth; ideal lime for an 'end run*; ten Forth 






commandments. 


27 


Advertisers Index 






Fast forthward 


..Promoting trade, product watch, vendor spotlight. 


40-41 


resource Listings 


Revised and expanded "On-line Resources" — extensive listings 






for RIME network Forth access to appear soon. 


43 


On the Back Burner 


, , Demonstrating competency. 



Forth Dimensions 



3 



May 1992 June 




oJnflcd 



So What's New? 

Welcome to a new vol- 
ume-year oS M>f0 Dimen- 
sions. To commemorate this 
new beginning, we have 
been preparing — in con- 
junction with our talented 
lindciedkatedcont^KwtSr^ 
an infusion of fresh material. 

"On the Bacii Burner," a 
new department, is engineer 
liusseill Ifenis' forum for 
iminiMescSc^/Am projeas 
that readers can build and 
pEcg^ram. Icsicueni, aportfrom 

inherent in building pro- 
grammable devices thai 
work, is to offer proof (e.g., 
to prospective employers and 
projea managers) that Forth 
and tlie programmer can gel 
the job done. (Tlie clever 
'gj^snia? gom &}is World's 
Fastest Programmer contest 
several years ago is but one 
example of the genre.) 
Russell's first installment, 
"Demonstrating Compe- 
tency,' explains the raison 
for the departmem, 
and keiiXes yeas sijtb- 
missions from readers — the 
success of tJiis undertaking 
will rely greatly on the re- 
sponse aod paitieipatfon of 
you, the iea<i^. 

"I'asl I'onhward" is an- 
other new feature to appear 

product news and ail- 
nouncenienls, short profiles 
©f Forth companies, and es- 
sxys about what makes a 
Forth business/programmer 
successful and about the 
nature of Forth. This synergy 
usefSi'^'ejidors, snd 
developers .<!hou Id he! pus to 
to collaborate more closely, 
to communicate about Forth 
more effectively with the rest 



of the wnrld, and lo focus 
5(x-c i a I a t ten! i on oi 1 1 he ll li ngs 
Forth dcx;s well. 

We are doaigoyr be^t to 
erKDurageFoiaiwMKtorsand 
developers to participate in 
FD in other ways, too. Add- 

our adverriscrs, thi.=; is'oje 
welcomes editrjrial contri- 
butions Erom three busi- 
nesses. A number of readers 
requested this kind of f:>er- 
specUvc in FD, and the Forth- 
business community has le- 
Spoeded wdi. t^e loeae in- 
ward to hearing from other 
companies about their Forth 
products and their experir 
ences in the commeFdal 
world. If your firm would 
like to participate, get in toucti 
with me. soon to discuss the 
optiofis. Arkl ismendicr tb 
.send us your press relea.scs 
about upgrades, new prod- 
ucts, and your company's 
background Our readers 
want to tear from you! 

Tutorials Wantedl 
Some iihifig^ bear lepeat- 

ing, like the basics of CRE- 
ATE ... DOES>. Leonard 
Morgenstem's aitide in this 
issue uckles. 4]ijtt perennial 
nightmare of Fbrth neo- 
phytes. If someone once 
helped you by explaining a 

not return tliat favor for the 
up-and-coming ge ncratioi i of 
Forth programmers? 

I recently got a phoiE^ call 
from a gentleman In the 
Midwest; he appreciates 
Forth over other language 
but hasnY yet adhletred the 
degree of proficiency re- 
quired to benefit from many 
of FD's intermediate and 
advanoedarticles. Would we 



! ever, he asked, be puMish- 
ing more tutorials? I told him 
tfie truth; we'd love to, but 
thejF are too racely seen 
crtsssinfg ^ e£Bt6r*is desk. 

Please consider this a call 
for tutorials. Perhaps a topic 
Spi^ y<eur JoiM 
now — chance&lKg>aome of 
our readers tt^Sisd to hear 
about it Attd aFfG SSiiaptef 
liCioiaQg f&t « 0mp iHOfea 
shoflijJd (seriijtdes' potflng Its 
collective genius to work 
developing a list of such likely 
lopg^andibihttfd^'^Gfiihg 
a series of short, written iii- 
U)rials wiUi succina coded 
examples. 

As many of you have 
noifiddvef Sie years, there is 

I a dearth of Fonli learning 
resources. Won't you help to 
li^lisve tiife need? ASer all. 
Forth 's success will ultimately 
dt;|')Cfid on new people 
learriing to use it. (And if you 
know of any Forth dasses 
and woricshops, let us know 
so we can add them to our 
"resource Listings.") 

Have You 
Renewed lately? 
As a fin^ note, dieck to 
be sure you have retsewed 
your FIG membership re- 
cenLly. This issue may have 
been sent as a courtesy even 

with ilic last issue. \X'e value 
you r continued panidpatiori 
and arc loc^ut^g forward to 
an exciting year ahead. So, 
please, don't let Ibis issue be 
yOUit^st... 

— MariUi Ouverson 
Editor 

PS. See our call for papers 
md^ontestannouni^ment 
on page 22! 



Forth Dimensions 

VohKlwXIV.NumiX^t 

Fortli Interest Gee^ 



Circulation/OrcSor Dosk 
Anna Brerelon 

Forth Dimensions welcomes 
editorial miteria], teoers lo the 
cdUor, and coounenis from as 
readers. No responsibilliy is as- 
^mcd for accuracy of su Ismssions. 

Subscription to Forth Dimen- 
sionsit included with inemt>ership 
in ihe Forth Intctcsl Croup ai $40 
per year C$52 overseas air). For 
membership, change of address, 
and to submit items fof publication, 
thcacklrtss is.- Forth Interest Group, 
P.O. lU>x ft.^Sl,SanJose,CjiIifornia 
9S155 .'Vdmlnisirativc ofTices: '108- 
277-t)668. Fax: -108-286^988 

Copyrigta © 1992 by Forth In- 
»?fcst Group, Inc. Tiic materia] 
contained in ttiis periodical (but 
not the code) is copyrighted by the 
individual authors of the articles 
and by Forth interest Croup, inc., 
respectively. Any rcproduaion or 
use of this periodical »S it is com- 
piled or the aidiih;4^ :<^ieq» repro- 
ductions for non-commercial pur- 
poses, without the written per- 
missi0n of Forth lAetesC Gixup, 
Inc. b » vieMoa (^th£ Cqpfdg^ 

Laws. Any code bearing a co^^r^bt 
notice, however, can be u$e<£dn^ 

with pennteajon of the cc^yj^^ 

The Forth lntmmst:<SSikip 
The Forth Interest Croup is the 
a$$oci»tioa of pcogrammers, man- 
agers, and ertgioeets wbo etegfa 
practical, Forth-bued SdlutidBS to 
leal^wortd needs. Many researdi 
haidwaie and softwatetlesiffas that 
wffl adwmce the geneiat sate of 
the an. ftC provides a dknaie of 

iif*jj]ffjt»M-.<'yrNpjgi^*iyt.^^ 

ii^ieK^eA^m^iai^i^is mem- 

area dutj^er med&igs are among 
its amfima. 

'Forth DimmskMS <0Sm <iB84r 

bfeim Gita^, ^iS S. Baseom 

Jose, CA.f0§tf4^^$it^^S^^ 
drew<^tfi|;i^jiii^M»jiifM^ 



May 1992 Juna 



4 



/L( 




L etters to the Editor— and to your fettow readers— are always welcome. 
Respond to articles, describe your latest projects, ask lor input, advise 
the Forth community, or simply share a recent insight. Code is also 
welcome, but is optional. Letters maybe edited tor clarity and length. 
We want to hear from you> 



No Commerce, No Forth 

Dear Editor, 

If there is no commercial Forth, no commercial hype, and 
no commercials, there is no Forth, I would like to liear aboul 
the acLiviiies of ilie rirnis who use Fortii for their livelihood 
or who provide Forth development systems for a fee. If such 
firms succeed, Forth will also; if FIG's aim is to promote Forth, 
llicn it must promote; those who use it. Forth Dimensions Ls 
a bit of a bore, lots of articles on ideas that have little to do 
with commercial reality. 

Charles Esson 
CVS 

11 Park Street, ISacchus Marsh 
Victoria 3340, Australia 

Ideal Time for an 'End Run' 

Dear Marl in. 

Forth does what no other language can do. It allows the 
user to map his or her working environment to a computer 
in a direct and consistent fashion. 'ITiis allows the user to 



10 Forth Commandments 

by Tom Napier • North Wales, PA 

1. These commandments are not caived in stone; thou mayst 
change them if thine application demandeth. 

2. He who changGth these commandments shall not do so lightly, 
and shall document the change in his prog ran. 

3. Thou Shalt putthineapplication Into words, and these words shall 
be thy program. 

4. The lord Moore has given thee many of 
the words of thy program, and the re- 
mainder shall thou create. 

5. Thou Shalt use no wcrd in thy program 
before that word has been defined. 

6. Thy parameters shall precede thine op- 
erations, and thine operations shall 
remove their parameters from the stack. 

7. Thou Shalt be sparing in thy use of the 
return stack and shdl at all times keep it 
balanced, lest thy program depart for 
the land of thy fathers. 

B.Thereshallbenogotofoundinthy code . 
Thy program shall use if-else-endif, 
counted loops, repeat-whiie. and re- 
peat- until. 

9. If thine application needeth a structure 
or adatarype which does not exist, thou 
mayst create anewstructureordata type . 

10. Thou shalt tell thy fellow programmers 
what new structures and data types 
thou hast created, that the wheel shall 
not loo often be invented. 



solve problems using familiar models and terms. 

'ITiis is of little or no value to professional programmers, 
Tlicy prefer C and C++ because they rccogni?jc this language 
no matter what the environ mentor problem. That is why they 
da not and will not use Forth. I lowcvcr, ming familiar terms 
in a famiiiar environment is very valuable to everyone else. 
Therefore, I propase that the Forth community do an end run 
around other programmers. 

lliis maneuver would have two stages. In the first stage, 
using ANS Forth, we build a graphic, and possibly object- 
based Forth. Instead of using graphics to hide tlie machinery 
of Forth, we use tlie graphic interface to make the simple 
Forth machiriery visible, accessible, and understandable. 
Users will be able to as.se mble small F~orth pieces into their 
own applications and will learn to modify their environment 
as they get more comfortable. This environment is ported to 
-Macs, DOS, OS/2, and Unix machines, allowing the user to 
operate in ttie same way and with the same environment on 
all of tlie Ofx: rating systems. 

ITic second stage builds on tlic first stage, using the Forth 
chips now available to build expandable Forth computers 
tliat run this environment quickly and more efficiently than 
existing machines can run it. Since Forth lends iLself to 
multitasking and multiproces.sing, a basic unit with one Forth 
chip could be bumped to, say, four or eight chips as more 
power became necessary. TTie additional chips would be- 
liave as coprocessors or as dedicated I/O devices. They could 
be botli, since tliey can be switclicd from one type of task to 
another by changing the software tlicy run. 

Now is an ideal lime to [Xirsue this approach. The new 
wave of consumer electronics provides a lot of opportunities 
to make inroads into the non-programming world. The 
multimedia devices that arc being introduced this year 
require simple, easy to use, low-memory metliods of pro- 
gramming. Sounds like Forth to me. 

So let's get started. I've been playing around with ways to 
do what I've proposed and I'm eager to take it further. 
Remember, "the Future starts tomorrow." 

Regards, 
Mark Marti no 
170-1 1th Avenue 
Seattle. Washington 981 12 



MAKE YOUR SMALL COMPUTER 

THINK BIG 

(WftVe baar doin;g i1 sine* 1977 for IBM f^C. XT, AT, PS2, 
and nt&tfeJs i, 3, 4 & 

FOR THE OFFICE SfmplilyflfwJapoed your wot* 

with OUT Qutslanding word pfoc^mg, database handlers, 
and ^eral kitiger software. Tiney are eas/- to use, powertui, 
■ftith exEKUiivei-look pifnt-oiits. reflKJiiabie site Jfcense tosts 
and comf^matJe. refiawe wppofl Raiph Afvsnst, autw 
nistorian, saya 'FWTWWRrrE lets me iv0rii:enlr5te on rry 
Ptianuscrlpf, noi thfl coFTBtjieA'' Stawart Jo^Fl5^>^T, BosEon 
Maifmg Co , says; We jseDATAHANDLER-lH.US beiauwifs 
tlie beat we vis seeor 

MMSFORTH SyMWR Om (rom $ 1 7895 

ModiHw pddng — Infegrate with Syafem DhSt anly wr\ki 
you n&&d' 

FOHTHWBITE - V/(jrdprcn:«$£K m 95 

OiATAHAM?t£fl-QaiabaEie t&99a 
DATAHWJDLtn-KUS - D&tabase 
FOflTHCOH - for Corriitiuntcstipns S49.SS 
GENERAL LEDOEB ■ Accoursliiig Gystem 00 

MILLER HICflOCOMPm-ER SERVJCES 

61 LaX^ Shofa Road. Nat^ck, qv/So 



FOR PROGRAMMERS — Build programs FASTCR 
and S WALt ER wi rii gur - 1 nteHigenr ' MMSf OHTH System and 
rjpplicAtions modufes, plus the famous MMSf 5RTH conlinu- 
ing support. Ur»t rnoduJe^ include ^urcd. code. Ferren 
Wacfntyra, &treaT.O'graph€f. says ' FofWi is the' language thai 
mJcfocompuEers were inwentea to tm " 

SOFmARE MANUFACTURERS— Eiffflentsoft- 
'*3ie lools KS'-'e lime aitd moftey. MMSFORTM's ffexUb'Nit/, 
compactness ant! .spee<l fiave rgsnjlte^l t»tter pri?ducts Iti 
'tas time [pr s wide range of soit*Sr& d'eweiopef^ mcludiog 
Asmofi-Taie, Ejfcaiibur TectTftoJogies, Lm^befgh Syaiems, 
Locitheecj Mi^siSe and Space Div«s<cin. and NASA-Goddard. 

H¥BF0iaT«Va.4SyrtemtMik ^fTiom;$l7M5 
,Nwd9 only 241^ RAM compafiad tp tOCK far OASip, Ch 
' PastaJ and othsra. Convert ydor computer iftto a Forttr virtual 
machine wtEhsoptiJsticdted l^orth >9dilortir^ lekaEed tools. This 
car^ fesjit in 4 ti^ 10 times gfearer productivity. 

Modular prtcJrig - inissrafg with System Dsk oitly what 

yiiufte&d. 

EXP£RT-2 - Experl' System Devetopniem i6595 
FORTHCOIil -Fieitibte data tran^^ £4035 
UTlLirniS - GrapNc5, 8037 S'jppon end otti^f fijciiitiea. 

and a little motel 

THIRTY-DAY FREE OFFER — r<tt HMSFOHTH 
GAMES DISK wnnh %i9.n. Willi puicnsse 0l MUSFORTH 

Syiion GHYPTOQlJOli HELPER OTHELLO BREAK- 
FCRTN ana olhere. 

Ctf for Inc/iVfW, Mehnfevt M> or piMfv 



Forth Dimensions 



5 



May 1992 June 



A SinglO'Step 

Debugger 

and Other Tools for the SC32 Processor 



Hick Grehan 

Peterborough, New Hampshire 

T\\c SC'52 is a 32-bit, stack-bascd processor designed 
spctiJically for executing liigh -level, Torlh-likc languages, ft 
can directly execute two gigabytes of code memory and l6 
Gb of data memory. Good ck-scriptions of the SC32 can be 
found in the March- April 1990 i.s.<;ue of Forth Dimensions 
CSC32: A 32-Btl Forth Engine" by John Ilaycs) and in Philip 
J. KoopmanJr.'sb(X)k StackCotnptUers, The New Wcwe09^, 
Ellish I lonvood Ltd., Chichester, West Sussex, England). 

Silicon Compasers' SC/FOX parallel coprocewing .sy.stem 
CPCS32) offers an SC32 on a PC XT/AT-compaUbJe plug-in 
card. The PCS32 runs tlie SC32 at 10 MHz, achieving 
execution speeds of 10 to 15 MIPS, Thanks to the SC32's 
pipelined design, the system can execute an instniClion per 
clock cycle. Furthermore, since multiple Forth primitives can 
be combined into a single SC32 Lnstruciion, a PCS32 oper- 
ating with a 10 MHz dock can hit "burst" execution speeds 
of up lo 50 MIPS. 

On the software side, the PCS32 is supported by Silicon 
Compasers' SC/Forth32, a Forth-83-compliant system with 
32-bit extensions added to harness the capabilities of the 
SC32. The PCS32 uses the host PC as an elaborate I/O serverj 
the host PC gives the PC32 disk storage, keyboard, and video 
I/O. 

Woricing on a recent project, I produced a massive 
amount of code on the PCS 32 system. As the number of 
words and their interactions grew, it became obvious to me 
that some sort of debugger would sp>eed the development 
process. In spite of all my Forth coding abilities, bugs 
inevitably crept into my work and the system would crash 
during a testing cycle. A debugger would help me home in 
on the crash site more rapidly. Unfortunately, SC/Forth32 
included no debugger, 1 had to build one. (The source code 
for the debugger is shown in Listing One.) 

Requirements 

My needs were not extravagant; 1 didn't require breakpoints 
or multi-step executions. 1 simply wanted a way to single- 
step through a word's component i nstmctions and watch the 
stack effects. I also needed to be able to exit to Forth to check 
the states of variables. 

I wanted the debugger to display, at each instruction step, 
llie name of the word it was about to execute. In some sense, 



j you could say that tlie SC32 supports subroutine- tlircadcd 
Forth; tlic SC32's "call" instmction (which works much like 
any other CPU's subroutine call) docs tlie nesting job of the 
trjner interpreter. 'Ihis meant the debugger tiad to extract llie 
call's destination address — which pointed to the body of the 
word being called — and "back up" to the name field addres.s. 
This is handled by the word MISNAME in Listing One, 

Debugger Internals 

The main debugging loop is within the word DLOOP (see 
listing One). DLOOP is simply a large BEGIN „, AGAIN 
struaure that endlessly fetches instruaions and executes 
them in a controlled fashion. The only way out of DLOOP is 
when the debugger executes the final instmction of whatever 
word is Ixiing debugged. Fxccution of the final instruction 
will inevitably cause the return stack to be popped, which has 
the effect of exiting DLOOP and llie debugger. 

Wliile 1 have some complaints about the SC32's cell-based 
archi tectu re (it makes stringhandlinganightmare),itlx!came 
a real blessing as I stmggled to build the debugger. Unlike 
processors willi I nstmctions of varying Icngtti, tlie SC32's 
instructions are all 32 biLs Cone cell) long. 

ITie SC32 instruction tyjxw fall into eight categories (see 
Figure One on page 1 1). 'I"he lop three biLs of an instruction 
determine its rype. It turns out ihal it was sufficient to have 
the debugger treat instructions as though they fell into one 
of four categories: call, unconditional branch, conditional 
branch, and everything else. Although the debugger handles 
several different instruction types identically, the system will 
nonetheless tell the user what the instruction type is. 

CaU 

To handle call instmaiorLS, the debugger first fetches the 
Lnstmaion that would ordinarily execute. It masks out the 
upper three bits, leaving the destination address in that 
instruction's lower 29 bits, lius value is placed on the 
parameter stack, and the debugger can simply use the Forth 
word EXECUTE ID go where llie call would have gone. 

'Ihe debugger keeps track of where it is inside a word 
being debugged via the global variable HIS IP (short for "his 
instmction pointer"). H I S IP serves as a simulated instmction 
pointer; upon each loop through the debugger, the system 



May 1092 JunB 



6 



Forth Dimensions 



lliitiHBJPii» .i 

< ** ) 

( ** single-step debugger f&r Sd/Foxth35j ) 
( ** Copyright, 1991 ) 
( ** Rick Grehan ) 
( ** Hancock, m ) 
( ** ) 

{ ** ) 

( ** stora^ 

( ** ) 

VARIABLE HISIP 
VARIABLE HISFLAG 
VARIABLE HERELOC 
CREATE NUMBUF 4 ALLOT 

HEX 

6008242C uCODE GFL&G 



( His instruct ioa jpfQiot6x ) 
( His FL bit ) 

( Location for inline execution ) 
( Buffer for aundbter input ) 



{ Put FL on stack } 



( ** INSTRUCTION TYP 



00000000 
20000000 
400WtOtt 

60000000 
80000000 
AOOOOOOO 

cooooooo 

EOOOOOOO 



CONSTA.\T 
CONSTANT 

CONSTANT 
CONSTANT 
CONSTANT 
CONSTANT 



ES ** ) 
IS CALL 
IS^IUVN 

IS ALUS 
IS LOAD 
ISSTORE 
ISLAL 
I3LAti 



( Call } 

( yncoBfJiitipiigil t>r40cti ) 

i e&ndirtiongO. i&jra»#f !■ 

( ALU/shift ) 

( Load ) 

( Store ) 

( Load addr low ) 

{ l^oad adde higb ) 



( ** Impjseved dun^ ) 
( ** J 

( Dump 16 fc^^es in hex starting at bjiife address baddi: ) 
; IJJBKKYTiES ( badd« ) 
eCff 8 HEX .8 MCl*IkL : " 

16 DO 

I OVER + Ce 2 HEX .R DECIMAL 

SPACE 
LOOP 
DROP ; 

( Dump 16 bytes in ascli starting at byte address baddr ) 



— ) 



IfASCiiBYtCES ( ba<Mr 
16 DO 

I OVER + C@ 
AND 

Jim M < 

IF DROP ASCII 

THBK 

EMIT 
LOOP 
DROP ; 



( Supee Jb^fte dian^ tricm. i^tm- address baddr ) 
: SDXnte ( baddr n J 
CR 

BEGIN 

OVER 16HEXBYTES 4 SPACES 
OVER XgASGIIBiraES CR 
16 - DUP 

(i> 



forih^tnenskim 



uses the addiess stored in 
HISIP to detenaine the k>- 
catton the neact hstsK- 
lion. 

of Ltic debugger handling 
call iniiruciioos inaements 
aiSlPb^one b^oieexUit^ 

Unconditional Branch 

the i.i(.-!.iiiggc!" L;ik care 
of luicondiiional branch tn- 

ing out tJic; high ihrce bits of 
the instruciiori, thereby 
leaving only tJic jump's d^S^ 
tination address, lite unt- 
condilionai brandi handler 
then places this address in 
HISIP ^d passes back to 
die^siitoftfieioop. 

Conditional Branch 
CM "Sen SC^ a essidt- 
gi^sd branch tnstmction wSH 
take the branch if the FL bit 
is set to zero. This is a proces- 
sor fla^that <i:mbe motiiSed 
by ALU ^M. rtmafl&tsr^. 
Consequently, for the 
debugger to know whether 
a conditicKial brandi^QciM 
be taken or stepped over, it 
has to simulate the setting of 
the processor's FL bit. 

I accomplished this by 
creating a madlin&<X>de in- 
struction called GFLAG (for 
"get ilag'J dial places the 
ccHiimtS bPttie f i bk OR the 
parameter stack. After the 
debugger exccxitcs any in- 
struction in tire target code 
du^ may aOba FL,. it calls 
<3eWB tnd SSdltes pit 
rameter stack in HO&yiB^M^ 
HISFL6G. 

So, >when the debagjger 
encounters a conditional 
branch, it simply examines 
the contents of HISFIAG. If 
HISFLAG is zero, the 
debugger treats the instruc- 
tion as an unconditional 
brandi and the branqh is 
taken. Otherwise, the 
debugge r merely in ere me nLs 
HISIP by one to skip to the 
next linStm€^Qfeu 



Tim 4i^^bufg^ ^umim 

i^etk^lll^teal, shift, and load/ 
jStaK^-ps. £s. Ii does this by 
^Etdi^tg^jeinsUuction pointed 
10) by HISIP and placing that 
instruction in-line. The fol- 
lowing is ihe SC/l-orlh32 code 
fragment for doing this: 

( piafe tfee iiistriKstion 

( in-l.ine ) 

[ HERE HERELOC ! 



The word IFETCH re- 
trieves the instruction pointed 
to by HISIP. The debugger 
stores that instruction at the 
address stored in HERELCK:. 
As you can see by the code 
between [ and ] , hereixX 
is set to point to an inrtially 
crnply cell within the debug- 
ger's stream of execution. 
Stmpty put, the d^bv^^Sg 
patches iiscif on the fly, the 
patch lx;ing the instnicUon 
fetched from the loQtCton 
^en by mgiP. 

I'inatly, after flie Iri-line 
instruction ha.se xcaucd, the 
d^>ugger uses the gflag 
wic8d maalSsitedl to 
$ave the siate ctf die fl Wu 

While you're in the 
debugger, the system gives 
you the option of emering a 
iradei^ of sin^jjer^hantcter 

slep; llie$e <xxnmafids aie: 

F Momtheteertotexn- 

poiarily suspend the debug- 
ger and go to Forth. Ihis 
^oittiimliQd mai^ mS^ the 

SC/Foi^2 word INTER- 
PRET. The d^xjggierdeiines 
an additional wqtd, BEStJMBt 



SWAP 16 + SWAP 
REPEAT 
2DR0P ; 

< ** > 

( ** Debugger ) 

( ** ) 

HEX 

( Fetch his next inst3?uct±on } 
: IFETCH ( — n ) 

( Mask out jump address for calls and hraapi^^ ) 
: JADDR ( — n ) 

IFETCH IFFFFFFF AND ; 

IFETCH %@mwm im t 

DECXtflAL 

( Siefifity fritft jsta<;k . th-ts, won' t boafa ±£ the stack 
( has U£ide£l0wed. ) 
: SSTAjCK 
DEPTH 0< 

IF ." Underflow " 

ELSE .S 
THEN ; 

{ GiveA th^ l>jrte address of a xisxtusi flsld^ j^ri^nt It ) 
: SHOHflME I baddr -- ) 

DUP CS 12.7 ANO ( Get count ) 

?DUP { Anything there? ) 

IF 

DO 

1+ DtJP m 1^7 EMIT 

LOOP 
SPACE 

THEN 

DROP ; 

( tSiven the cell addr. of a code field, do youi; best to locate ) 
{ the associated name field and print it , Works in most cases . ) 
: HISNAME ( addr — ) 

BYTE ( Convert to byte address ) 

< Start a cou&t€sjr ) 

wmm 



SWAP 1- Mxss (?# If 7 mas 

DUP 32 <> 



IF 



32 < 
IF 



DUP CS 127 AiSB; 

2PICK = 

IF SWAP 0RQP 

SHONAME 

EXIT 

IBEN 



THEN 
SWAP 1+ 

ELSE DROP SWAP 

THE» 

DUP 33 ^ 

UNTIL 

2BRQr ; 



< Feteh a dhataCf^j^ % 
( Null? y 

( Printable? > 

( Fetch it again ) 

{ Equal tS owe count? ) 

t W® got it ! ) 
( Go home ) 



{ Increment counter } 
( Don't increment ) 

( Name can't be this big ) 



{ t^he eusr^nt insfcruet ion type } 

: SHOTYPE 
ITYPE 
SELECT 
CASE 
CASE 
CASS 
CASE 
CASS 
CASK 
CASE 
CASE 



ISCALL = OF 
ISBRAN - OF 
IS?BRAN = OF 
I S IOra S =^ OF 

ISLOAD = OF 
ISSTORE = OF 
ISLAL = OF 
ISLAH = OW 



." CALL: " 
." BRANCH: 
7BRANCH 

mu/ mt 

LOAD: " 
.'■ STORE: 
LAL: 
LAH: 



BREAK 
'■ BREAK 
" BREAK 

: " Bmm 

" BREAK 
" BREAK 
BREAK 
BREAK 



( Get a Tiexadecimal nmnts^i; £m0tt( the keyboard ) 



NUMIN { — n ) 

NCJMBUF ! 

NUMBUF BYTE 10. EXFEiKE 
BASE @ HEX 

NUM8UF BirfE 1- UfflffiER 
2I3R0P StfJte BK$E ! 



{ Clear receiving buffer ) 
( User inputs number here ) 
( Set base Co hexadecimal ) 



( Exit to forth fcom detm^er ) 
: TOFORTH ( — ) 

." TO FORTH ■ CK 

INTERPRET 

BACK m DBBD6 " CR ; 

{ Return to the debugger ) 
: BEiSljEtiJE R> DROP ; 

( Get user lijjput at each ^^buggeir step ) 
: USERIN 
BESIH 




SEX^CT 

CASE ASCII F = OF ( Shell out to Forth ) 

TOFORTH BREAK 
CASE ASCU Q = OF ( Abort ) 
1 ABORT" ** Rmm^l P^ESSE 
C&SE ASCII I = OF (: isAspl^y cuxreiit instrustion 1 

BASE e TFETCa .*« (* MK 
. BASE ! ." )" BREAK 



CASE ASCII D = OF 

ADDR:" NUMIN 
." LEN:" NUMIN 

NOCASE mtde i bbesk 

U>JTIL ; 

( Main debugger loop ) 
: DLOOP 
BEGItr 

SHOTYPE 
ItYPE 

ISCALL = IF 

J7VDDR HISNSME 

SSTACK 

CSERIN 

J%DDR 

laCECUTE 

1 HISIP +! 



( Dump ) 
( Address ) 

( Number of bytes i 

( Anything else continues ) 



C ^ow instruction type ) 
( Fetch it and select ) 
( ** CALL * ' ) 

( Show word's name if pessible ) 

( Show the stack ) 

{ Get aaer iitt|>at j 

( psail'f ^jfeatijiation aMreisa } 

t ^c^^eiite tlie wo£<i ) 

{ Btatg? ia«fcrucJt£©n pointer ) 



Por^ DSnemions 



& 



that returns the user to the 
debugger where he left off. 
Currently, these words make 
noaitmi^tpsavieandrestore 
tt& panuttetef r^arh 
stacks. It's up to you to make 
ajre ilic stacks arc In ihe 
^meaalewhcii you execute 
RESUME as when you left the 
debugger. 

I t^splstys in hfeJKdeci- 

mal the instruction the 
debugger is about loexeoite. 
I kAOti&M^im^lbrM^/ 
shift iasirucUons, since the 
debugger simply announces 
them as "ALU/SH." With the 
I command, you <an 4iS!^ 
semble an in^iticdt^^h^ 
operation you arc unsure of 
Cprovicled you have the 
n&md''^-''^^' ihsmjcdon 
Ibtm^ handy). 

D Provides cpiidk access 
to a memory dump. The de- 
bugger will prompt you for 
the Starting cell addtess and 
ihenun)b^ofcaQs tpditt^ 

Bxeaites an ti^Si^ 

quilting the deliugger Hid 
returning lo Fartli, 

Entering any other charac- 
ler al llm: (:.\t:cution steps will 
cause the detx^ger to proceed 
with tite next instmaion. 

Problems and 

Primitives 
SEctee ihe SC32 was de- 
Agin the ground up 
toesseaite Perth (aniidKarUffl 
to the optimi/alion of (he 
SCyForth32 compiler), some 
of fee more compli^ Fotcdi 
primitives are compiled into 
a series of obtuse SC32 In- 
^TUdiGm For example, if 
you encounterthe Forth word 
DOin the debugger, you wont 
see a call to the location of 
DO, you '11 see a series (;^S<32 
itistrad^ Asa: ^ re- 
turn aad£ iMKh Mtlal and ler- 
minal loop ia&ex. values. 



die iGtumstadc aie rKXlheinjM 

and final loop values. 'Iheeffea 
is [he same, hgrweverj) 

Step Into 
In its current incarnaiion, 
#e j^nSbf^^l^ handles call 
fil^ctiqns using the SC/ 
Foith32 word EXECUTE. 
Consequently, there is no 
vtzy to "nest down" at level 
and step into a W0r4 In 
order for the debugger to 
perform that feat, you would 
lita?K:(o fl<4d kept 

fltevsuriablc HIS IP prO[x;rly 
cracking the instruction 
pointer of the debugged 
code. The debuj^isr would 
aifeo Wift^ io W£ dvet tfJe 
responsibility of managing 
the letum stack. Spedflcally, 
whenever the ddnigger 
coiintered a call instmction, 
it would push the 
taeijeiB^nted value of HISIF 
onto the return stack, extract 
the destination address from 
the iiislruciion, and store tJut 
address into KISIP. 

Ibndlii^ a return from 
subroutine is more diffi- 
cult, since the SC32 actually 
embeds the return operaticHi 
in ALIVshift or load/store 
instructions. Bit 28 of such 
fnsimciions is called the 
"next" bit If it is set, it loads, 
the top value on the return 
stack into the instruction 
pcdaier. Bits 16 throtj^ 19 
ii^i^ tile *^imB^ liSss- 
They determine whether the 
parameter and return stacks 

next bit is set and the stack 
bits specify tlui the return 
suck is to be popped, the 
is it lebxOi operation. 
So, for flie debugger to 
manage a return, it would 
have to watch for a set "next" 
bitwifiiinAUZ/ehiftandload/ 
jsore instructions. Whenever 
ttsees a sctbit, itivould mask 
^lebjtouti trauas^the topoT 
tiieietum stack into HISIP, 
and execute the modified 
instruction. 
May I WSJune 



ISBRAN = IF 

S STACK 
USERIN 
JADDR 

ITSPE 

IS?BRAN = IF 
SSTACK 

IP 

1 KISre 

ELSE 

JADDR 
HISIP ! 

THEN 
USERIN 

IFETCH HERELOC @ 
[ Hrli-^K HiLKilLOC ! 
GFLAG HISFLAG ! 

I mmm *! 

THEN TlffiN TB^ 

ca 

A€I^IN ; 



( The outermost word. To unleash the dt^ugcfer on a word/ ) 
( siiiply enter DEBUG <worctnaine> ) 

BL WORD CELL FIND NOT 
IF ." ** NOT FOUND **" CR QUIT 
ELSE HISIP ! 

." WORD AT;" HISIP g HEX . 

DLOOP 

THEN 



( ** UNCOND. BRANCH ** ) 
( Show the stack ) 
( Get user input ) 
{ Get jump address ) 
i tarn ±R»££i. |!©:it5iter ) 



( ** COND. BRAKCK ** ) 
( Show the stack ) 

< Get user input ) 

< Get his FL bit ) 

( BEaaoh rxo% taken. ) 
( Branch tiaken > 



( :** aLL OTHERS ** ) 

( Shew the stats* ) 
( Get user input ) 
( Put instr. inline ) 

< Save flag after opetatien } 
( Xncr. his ^(^teess ) 



( Is word in dictionary? ) 
{ Bail out if not ) 
( Set instr, pointer if so ) 
( Show word' s body address ) 

( Ejffter the lOipp y 



Listing Two. Execution trace. 




: TRACE 
R@ 1- 

HISNAME CR ; 


( Back up t& cod^ fi€tld ) 
( Display waffle ) 


: >>TRACE 

[ ' ] TRACE , 

IccaseijiE] ] ; 


( Cort^tile TRACE into dictionary ) 
{ SSa^ke ec(l©n happy ) 


: TRACEON 

L'} »TRACE 
t'l i 
8 + 
! 


( Address where ] was ) 
( Overwrite it ) 


; TRACEOFF 
t^J 1 

8 + i ! 


( Put ] 


back where he was ) 



10 



Oimen$k>m 



Hn3%; you wxiU want Id add an additkxial user-input dK^ioe 
diutwodd allnwifaeusertDseleawbdberliie debugger stepped 
ii^ tfae csSJed wm^ m es&^mikis a «ho]e, as it does now. 

Last Calls To fim^ 

SC/Forth32 is an optimizing compiler. Among other things, 
diis means thattfie fioosiinbr is intelligent enough to recog- 
nize that if the last iristmction in the definition of a word is a call 
instmction, that call can be converted to an unconditional jumpL 
This saves return stack space, as wdl as nsdudng some execution 
time that would ordinary be unnec£$^arily con^med moving 
addresses between flie lesiirfi stadt and tfie instmction pointer. 

From the debugger's point cirview, the iump instruction 
is just a juir^; there's no indicati on that this was a aiU optimized 

that you have nested down into a word, and in some severe 
cases this nesting can go on tor several levels as you lepeaiedly 
exrvinei' tile last instmdion of each wad. UlUm^^dy, oT oourse, 
you vM eiKJOunter a Foriii primitive arid pop outtiie end. 

Trace 

based tSm &&((i!iS^ tm^ tr^ tasmsamis 



Mgure One. SC3? i[iSlruc:io[i Sypos 



Instruction 
Type 



Top 3 bits of 
instruction 



CaU 



CoEuiiiiaiMtl 
branch 



Sims 



Load Address 
low 



Loadacisin^ 



000 



mx 



oil 



100 



101 



110 



111 



Description 

The SC32 places the return address on the leium stzcis., 
and jumps to ^ ]£tead<piv|^v^ l^ 
le&miniQg^ bits, 

S.1 me as a call instruction, only the SC32 dO^sn^ 
place ns^^iiAg Qn Uie mtuin s^dc. 

If the SC32's I"L flag is zero, this insiniciion porri>rms 
a branch. Otherwise, the processor proceeds to the 
nextlnstrutdion. 

c^iejsatfom. (£e{3end{ag oa the remaMn^ 1$ bits, 

Adds an offset (encoded in the lower l6 bits of the 
instruoipn) K> the ooiuietws of a desig[Jia?je4 soucee 
m^sm^ Wb &ssmM & fim T^i^^!^. iti^ttm are 
loaded into a de$i£iRa£6d <|^scinatioh ixigisti^. 

Adds an oflsei CenoQde«i in &m l&mx IS ^ o£ tl$e 
jnstnt(^0>a) the c^i^W^aL:'ie^^g!i^^mm3i 
iegi^r> ^ (seinte^tts «iPa designated ^bs^uaEttiOtt 
tiegisii^ are stoGsd at {h^ addr^ 

Adds an offset (encQjfed |tt the lower l6 bits of ijie 
instruction) to the contents of a designated soiu^ 
register. -The result ]& placed in a designated 
^stinaSoa fej^ister. 

Adds an offset (enodidi^ iia the lower l6 bits of th^ 
insfructiocQ lo the contents of a designated source 
lei^steF ^^l^shifcing that oSset \o the left l6 bits. The 
ffistttt is ift s d^sj^^iaied 4e^Kte4ti^ le^^stec, 



Forth W^er^sm 



11 



found in old, reliable, interpreted BASIC. To le&esh your 
memory, executing TRACEON in BASIC wcftilii otuse 8ie 
system to display iJie number of the current line BASIC was 
exeoiliiig. This was handy for locating exactly where the 

wanted a similar construct formy Fonli work. I wanted words 
to tell me when ihe>- %%ere about to execute, and i wanted to 
be able to turn tliis tx'havior on and oil. As in BASIC, this 
would make it easier lo pinpoint where the pro-am died. 

My solution was a pair of words — TRACEON and 
TRACEOFF — that you couid use as brackets. Thai is, words 
compiled after TRACEON would display their names when 
emamd. THACEorr would dlisil^l^ trsebitg; ^bisie^iui^ 

words would act normally. I was .sausficd to have only colon 
words ! )o affected by TRACEON and TRACEOFF. (I could have 
extended the trace word to ccwer dsfltiUng'swsr^, bull #^0*1 
need thM i^rtioil;^ feamiej! 

Trace OjioraUon 
TR^EOK works by patching the : (colorO word. The last 

in^CDrripiling:$tat&TheSC32 instRiction ihaE calls ] is located 

eight cells into the dcllmtion 
of : . TRIMUION overwrites that 
location with a call to the 
word »TRACE. 

So, after you execute 
TRACEQtji wt^Qev<!er ; ex- 
eowes, ft cais »Tia«^ as 
its last instruction. »traCE 
will compile the word TRACE 
into the dictionary. Hence, 
TRACE becomes the first 
word executed by whatever 
word : has just defined, 
»TEACE thene»eajt^ ] so 
that ^ cothpiiei' erttm the 
proper state at the end of : 
CA side-effea is that words 
ccHtip^ed aiiSe^^M^sdlNr:^ 

one cell longer than they 
would ordinarily L>c,) 

Now, whenever the co- 
lon-defined word executes, 
it immediately calls TRACE. 
TRACE fetches the return 
address from Che returnstadc 

by one cell. The resulting 
cell address points to the 
body of IfeSs ealBiSg word, 
and TRACE can unleash 
H I SNAME (described above) 
to prim tlie name field. 

TRACEQFF Simply un- 
patches overwriting the 
call to »TRACE widi a call 
to 1 . Thesouice to the TRACE 

May tSSBJum 



Designing Software' 
Controlied Devices 



Carol Goldsmith 
Victor, New Yoria 

When soflware is involved in product development, the 
step of inicgraiing hardware and software is fraught with 
difficulty. Sophisticated development systems, emulators, 
and logic analyzers exist to help the debugging process. In 
ihe conventional approach to embedded system design, a 
PC is used to write, cross -com pile, link, and load code into 
emulation memory on the target system. One iteration of 
the laborious and oft- re pea ted edit, compile, link, and load 
cydc can easily take ten or 15 minutes for a complex 
project. This sequence must be enacted for one error in one 
line of code or many. The agony really begins if the errors 
are interactive with the hardware — the correction of one 
exposes another. System debugging is often done via an in- 
circuit emulator (another expense) that provides breakpoints 
and other soflware debugging support. F.ver wonder why 
project managers go gray at an early age? 

Forth to the Rescue... 

The solution — familiar to most readers of this magazine 
but largely unknown to most designers — is to include Forth 

Embedded control Is a place 
where Forth can make a 
significant impact and become 
more widely known. 

on the controller card, giving users tlie ability to deal with 
code on a word-by-word, or line-by-line basis interactively 
with the target system. Forth's primary benefit for the 
developer is that it eliminates the middle- man. Both a 
language and a programming environment, Fortli can be 
developed and executed directly on the target system, so 
there is no need for tlie traditional cross-development 
system required by C or assembler. Forth is interpretive and 
highly interactive, giving developers ihe ability to proto- 
type applications swiftly. It offers the designer the unique 
opportunity to write, test, and run software in real time and 
avoid the time-consuming steps of the edit, compile, test, 
debug loop for each single modification. On-board Forth 
offers in one entity a real-time programming language, an 
operating system, and a development environment. The 



natural extensibility of I'"orth leads lo application-specific 
words that are self doc-umeniing as they arc used. Engineers 
using Fortli can design words to suit dieir specific work. 
F.mbedded conuo! is definitely a place where Fortli can 
make a significant impact and become more widely 
known. 

Compilation occurs one word at a lime on the target 
system itself. Each Forth word can be tested as soon as it 
is entered; if it docs not produce the desired result, you can 
quickly change the word and recompile. This encourages 
thorough testing of each piece of code as it is written. In 
contrast, C and a.s,sembler have long edit, compile (or 
assemble), link, and load cycles that make it difficult to test 
fragments of code. Debugging can't start until most of the 
framework is in place. Incremental testing speeds project 
development, because there is a higher probability that the 
design will work the first time. 

Not at aU Tedious... 

Two economical and easy-to-use controllers which 
offer extensive on-board Forth are the TDS2020 and the 
TOS9092 from Tlie Saelig Company (Victor, NY). Well- 
known in EurofM, and becoming recognized in the U.S.A. 
and Canada, these boards from Triangle Digital Services 
Ltd. of London (U.K.) have been sold worldwide in their 
thousands. Both of these near!y-pin-compatible 4" x 3" 
boards provide a complete Forth design environment — the 
TDS2020 operafing at 20 MHz comes complete with eight 
channels of A/D, and the slower and cheaper 1T>S9092 
runs at 1 MHz, more suited to simpler control situations. 
The TDS2020 is a powerful CMOS controller card, based on 
the Hitachi 1 6-bit H8/532 microprocessor, and runs at 
about 3 MIPS. It has I6 Kbytes of Forth as well as a full 
symbolic assembler, eight channels of ten-bit A/D, three 
channels of D/A, .serial RS232 and 1^ protocols, too. There 
i.s 45K for program storage, and up to 512 K NVRAM spae^ 
on-board, as well as timers, intermpts, and 33 I/O lines. 

lite Programming 

Programming is accomplished by downloading suitable 
words from the PC soflware provided with the boards. 'Yhe. 
TOS2020 starter pack includes lots of utility routines to 



May 1992 June 



1 



2 



Forth Dimsnsions 



make life easier for the designer. Included are serial input/ ! 
output, timer, IX^,D/keyboard driver, memory test, and j 
many other routines. Also available are string- handling \ 
routines, trig functions, graphics LCD display, intermpl- j 
driven serial I/O, and round-robin muluiasking. | 

Embed the '1052020 in a product, talk to il from a PC- 
compatible down an RS-232 se"':.! line, dcbuggiiig each 
segment as you go, and ilie final code can be stored in 
NVRAM, with no need for I'liOM burning. You have very 
fast development time with no need for in-circuit emulators 
or tesi stubs for developing fault-free code, 'Hie application 
also ruas ai full speed, and the full resources of the 
development environment arc available for use in debugging 
the application. In the Fortii environmeni, any (xinion of j 
the code can be exercised ai full speed, and breakpoints 
can be introduced for snapshots, or single stepping. 

"Advantage TDS" 
When you have developed your produa using the 
TOS2020 or TDS9092 and arc now manufacturing it, that is 
not the end of the stor)' for Forth, It can be used for repair 
and maintenance because the language is on-board, A 
connector can t>e built into the product which gives serial 
access to the TDS board in your instrument. With a PC or 
hand-held terminal, you can now gain access to the system. 
The command ctrl-C allows you to break out of your 
program and individually exercise all the procedu res that 
make up the software. For instance, you can drive the 



printer, LCD, keyboard, or A/D routine to determine fault 
conditions. On-board Forth is very useful during design 
and debugging, but the ability to access individual software 
procedures in a finished product is invaluable, 'Ihls also 
saves writing lots of "service rou fines," often requested by 
servicing departments, and frcquenfiy some options gel 
forgotten, requiring new routines to be written. With on- 
board ForUi, it's all there anyway. 

Thaiiks for llie Memory... 

'llie 'l'DS2020CM is a useful module which sandwiches 
on lop of the TDS2020 and allows storage of up to 8 Mljytes 
of non-volatile data on industry-standard JEIDA/PCMCIA 
card memory, including Flash types. In an applicauon, this 
removable card can be brought back to base from field data 
collections and read in another TDS2020 or by a PC with 
a card memory drive. Meanwhile, the datalogger is storing 
informafion on a new card. Datalogging for over a year or 
a single 9-vo!t battery is possible, since the TDS2020 only 
draws 300 |ia in standby mode. A complete datalogging 
program is included with 'rDS2020 starter pack. In addition 
to standard fig-Fcrth, 200 words are supplied with the 
TDS2020 for simplifying tasks such as data-logging, key- 
pad and LCI) control, stepper-motor driving, interrupt 
control, etc. The TDS2020 starter pack is and fiie 
TDS9092 starter pack is S249, in stock from The Saelig 
Company (716-425-3753; fax 716-425-3835). 



Carol Goldsmilh is Ihe Sales Manager for Tile Saelig Company. 




20MHz Forth Controller 

le-bit ftp, 8ch 10-bit A/D, 3ch 8-bit D/A 

TDS2020 

CONTROLLER 
AND DATA-LOGGER 

4" X 3" board uses Hitachi 
i6'btt H8/532 CMOS 
Screams along at SMtPS, but runs on SOma. On- 
board FORTH and assembler - no need for in-circuit 
emulation! Up to 512K NVRAM. 45K PROM. Attach 
keyboard, lea, liC peripherals. Built-in interrupts, 
multi-tasking, watchdog timer, editor and assembler, 
33 t/0 lines, two RS-232 ports. 6 - 16 volts SOOfjA 
data-logging: on-chip 8-ch 10-bit AID, 6 ch D/A. 
Date/time clock ■■ low-power mode lasts over a year 
on 9v battery ! Lots of ready-made software 
solutions free. Program with PC. Many in use world- 
wide for machine control, data-logging, inspection, 
factory automation, robotics, remote monitoring, etc. 
Specials: ■40°+8S''C; or 1 IXHz - full functions - 4ma!! 

STARTER PACK $499 
CALL NOW FOR DETAILS I 



Sale-or-return. 




Saelig Company 

"European Tecknoh^tj 



tel: (716) 425-3753 
fax: (716) 425-3835 




7 making a DATALOGGER ? 




TDS 
2020C 

CONTROLLER 
& DATA LOGGER 

. 8ch 10-bit 20 MHz 3 MIPS 

• Store data on 4M JEIDA cards. 

• Easy-use keyboard I led. 

• 33 X I/O, 2 X RS-232 ports. 

• 300^A data-logging! 

• Lots of ready-made software 
solutions free. Program with PC. 

CALL FOR DETAILS ! $369 (25's) 




Saelig Company 

tel: (716)425 3753 
fax: (716)425 3835 



Forth Dimensions 



1,3 



May 1992 June 



JForth 

A 32^bit, Subroutine'Threaded 
Forth for the Amiga 



Phil Burk 

San Rafael, California 



JForth falls into iJie category of "big Forths." Wc ai IX;Ua 
Rescarcli believe thai Forth development systems should 
offer the same facilities that C programmers enjoy. While 
minimal Forths arc perfect for small embedded systems, 
ihey are inappropriate on larger computer systems. Wc feel 
thai one of the reasons Forth has not sold as well on large 
systems is because many Forths adhere to a minimalist 
philasophy. We feel that Forths for large systems should 
have all of the file I/O routines, memory allocation, floating 
point, complex data structures, and other tools that are 
standard in competing languages. We applaud the ANS 
standardization efforts thai include these facilities. 

One of the areas that Fonh does not usually compare 
well with C is in the generation o( small executable images. 
We, therefore, added clone which can generate standa- 
lone images as small as 3K. Clone starts at tlie top word 
in an application and disassembles its 68000 machine code, 
then disassembles all the words called by that word, and 
so on. It then reconstructs an image without headers and 
with only the words and data needed by the application. 



We wanted JForth programmers 

to be able to call 

Amiga system libraries 

as easily as C programmers. 



It also performs some optimizations made fxjssible by the 
smaller image, such as converting absolute subroutine calls 
to PC relative. An executable image is then written to disk 
with an icon. Clone-able programs have a few restrictions 
related to storing addresses in variables at compile time. 
These are easily handled, however, by using run-time 
initia!i7ation, or by using DEFER for vectored execution. 

We wantedJForth programmers to be able to call Amiga 
system libraries tis easily as C programmers. To call Amiga 
system routines, JForth uses a simple CALL by name syntax 
that automatically builds code to move parameters from 
the data stack to the appropriate 68000 registers. 

Since the Amiga relies heavily on passing structures, we 

Phil Burk is a co-aulhor of JForlh and HMSL His current inlerosts inclucle 
aleclronic music, animalion. and 56000-bas(3d digital signal processing. 

May 1992 June 



implemented a C-like structure facility that automatically 
handles variously sii;ed structure members, Tlius, one can 
fetch a signed byie member or a 32-bii-iong member using 
the same S@ word. Signed versus unsigned members and 
address relocation is also handled. Here is an example 
structure definition plus some code to access it: 

\ Define structure template 
: STRUCT FOO 

LONG FOO_SIZE 

APTR FOO_BUFFER 

LONG FOO_INDEX 

SHORT FOO_SCRATCH 
.-STRUCT 

\ create a FOO structure 
FOO MY-FOO 

: TEST, FOO ( — index scratch ) 
MY-FOO S@ FOQ_INDEX 
MY-FOO SS FOO SCRATCH 



If we use the JForth disassembler to examine TEST . FOO 
we will see that it built the following code: 

BSR.L MY-FOO 

MOVE.L $8 (A4,D7.L) ,D7 

BSR.L MY-FOO 

MOVE.W SC (A4, D7 . L) ,D7 

EXT.L D7 \ sign extend 

RTS 



Notice that it used MOVE . L for the long member, and 
MOVE . W and a sign extension for the short member. 'Ihc 
top of the Forth data stack is cached in D7, so ilic results 
of the fetches are left there. A4 is a register tliai points to 
the ba.se of the Fortli dictionary and allows us to build 
relocatable code. 

JForth provides other tools, including a Source- f-ttiel 
Debuggerwith single step and multiple breakpoints. The 
debugger also works with doned images. A code peifor- 

14 Forth Dimensions 



mance analyzer in JfFonh will periodically interrupt an 
executing program and gather statistics on where it is 
spending its time. JToftli also provides local variables th^t 
use the following style; 

; TYPE/2 ( addr cnt — ) 
CNT 2/ -> CNT 
ADDR CNT TYPE 

r 

A new feature of JForth is support for IFF AXIM and 
ANIMBmsh files. This utility lets you load animation 
images from other programs to create animated displays. 
The output of the Amiga can be plugged directly into a VCR 
for simple home video. 

These, and other features, combine to create a powerful 
Forth-based application development environment tliat 
offers a real alternative for commercial developers. 

MMSL 

HierarchJcal Music SpecJflcaUon Language 

HMSL i>s an extension to Forth that provides MIDI 
support, and object-oriented compositional tools. The 
object classes include Sbaf^es which are a general purpose 
array of N-dimeasionai points. The data can represent a 
melody, a tuning, a trajeaory, or any user-defined parameter. 
AnoLlier clas-s, called Players, schedules the conversion of 
Shape data into musical or other forms of output. Jobs 



schedule user-written functions for repeated execution. 
Collections can contain Players, Jobs, or other CoUectioris, 
and allow you to create a complex hierarchy of music 
objects. 

HMSL supports standard MID! files. Thus, you can use 
HjMSL to algorithmically create sequences for use with 
other commercial music programs. An event i>«^Tprovidcs 
low-level scheduling of MIDI events and supports a text- 
based Score Entry System. Here is an example of a simple 
score; 

1/4 C3 F# 1/8 20 /\ A A A A 
1/2 _mf CHORD! E4 G B )CHORD 

HMSL provides a toolbox for building interactive screens 
out of control grid objccLs tike check boxes and faders. 

'ITie Amiga version of HMSL uses JFonh. 'Ihe Macintosh 
version has its own built-in I'orih. IIMSL pieces are 
generally portable betwcx;n the Amiga atid Macintosh 
versions. 

A numtjer of the other features of Jl-orth and IIMSL are 
mentioned in the accompanying advertisement, .so I won't 
list them here. If you are interested in JForth or HMSL, give 
us a call and we can direct you to a discount retailer. 



Tap the Power of Your AMIGA ® 




Forth 



a 32 bit Subroutine Threaded Forth 
generates small, royalty free applications 
complete Amiga DOS 2.0 toolbox suppon 
simple IFF, ILBM and ANIM tools 
source level debugger with breakpoints 
object oriented dialect, ODE 
hashed dictionary for fast compilation 
local variables for more readable code 
integrated, file-based, text editor 
ARexx suppon for inter-application I/O 
FVG standard floating point support 
Profile - code performance analyser 
global, register- based optimiser 
integrated assembler and disassembler 
numerous examples and tutorials in manuals 



JForth was created by Delta Research; 
serving Amiga developers since 1986. 



Hierarchical 
Music 



Specification 
Language 

Experimental music for Macintosh and Amiga 
HMSL is an object oriented extension to Forth with: 

• extensive MIDI toolbox, MIDI File support 

• tools for building your own user interfaces 

• Markov chains, 1/F noise, graphical shape editor 

• hierarchical schedtiler for playing abstract data 

• tools for complex algorithmic composition 

• support for Amiga local sound and samples 

• complete source code provided with manual 

If your music is too unusual to create using 
u*aditional music applications, write your own 
using the tools HMSL provides. HMSL is being 
used in hundreds of studios and colleges worldwide 
by some of the today's most creative composers. 
HMSL was developed by Frog Peak Music. 



Find out more about JForth or HMSL by calling or writing: po Box 151051, San Rafael, CA 

Amiga i."! a registered U'ademark of Commodore Business Machines 9491 5-1 051 USA (41 5) 461-1 442 



For&\ Dimensions 



15 



May ^ 992 June 



Object'Oriented Forth 



Markus Dahm 
Aachen, Germany 

Ai ihc Institute for Measurement Tecfmiques at ihe 
University of Tedinology RWI"H Aadien, we have used 
Forth since 1987. Our tnterdisdplinary workgroup has 
developed medical image works laiioas. We have written a 
lot of software including memory management, Image- 
processing algorithms, fibre optics network coupling, and a 
graphical user inierfacc in our proprietary 32-bit Forth. The 
psychokjgisis in our workgroup conduct experiments con- 
cerning the software- and hartlware-ergonomical aspeas of 
the design and functionality of the workstatioas using the 
prototype image workstation. 

Some of the student laboratory work in image processing 
is done in Forth, which Ls picked up by the students usually 
within half an hour. Within this short amount of time, they 
learn enougli to program image -processing algorithms. 

So, for varioiis reasons, the ease of understanding and 
getting access to a complex system is of high priority for us. 
For this purpose, our existing 32-bit Forth did nrx provide 
enough programming support and traasparency, so we 
conceived a new and object-oriented Forth. 

Within one-half hour, 
students learn enough Forth 
to program image-processing 

algorithms. 

The work was funded by the derman Ministry for 
Research and Technology, grant no. BMFT/AuT-01HK577- 
03, as part of the DIBA-project. Thanks to Maria Irene das 
Reis Lourenfo-Kaierle for her work on the implementation. 

An Object-Oriented Forth 

The paradigm of ciijecl orientation has been around for 
quite a while but has recently received a lot of attention. Apart 
from the hype — it was even called the "silver buOet" to shoot 
al! programming troubles — itis a real advance for programmers 
in terms of structure, darity, readability and, thus, useability 
of both ilie programming approach and tlie program code. 

Forth's advantages arc tlie interactivity of tlic interpreted 
language and tlie oticasibilily wliich allows llie language to 
be fitted to a .spedal application, which make it suited for 
non-expert users. Moreover, it enables you to lest everything 
May 1992 June 



easily and directly via the keyboard, which makes debugging 
easy. Forth supports — almost forces^ — tlie method of faaoring, 
which greatly enhances the darity of programs and thus the 
programmer's productivity and content. 

Our main interest is to work with a programming 
language that supports fast and easy understanding and 
debugging, and thus allows rapid prototyping of user 
interfaces by botli engineers and, on a higher level, by 
psychologists, 

OOl' strives to achieve tliis by combining the best of both 
worlds by extending Forth following the paradigm of object 
orientation in a strict sense. It provides all its amenities, such 
as security, inlieritance, and late binding, Tliis is adiicved by 
strictly adhering to the concepts f>f data encapsulation, strong 
typing, and message passing rather than direct procedure 
calls. The system still has a small kernel that performs 
everyihing from interpreting to compiling the source cotlc in 
a simple but smart fashion. 

The principles of OOF and their con,sequcnces are best 
explained by examples. The use of OOF is therefore 
described step by step, from simple definitions of objeas to 
the creation and extension of classes and methods, explaining 
the nomenclature and buzzwords of object-oriented lan- 
guages en passant. 

Here's How 

Everytliing in OOF' is an object. Every objca is an object 
of some ckiss(fi-%., integer or character); it consists of a data 
field and a set of methods to manipulate the data. For 
example, when you want to create an integer object start 
or two character objects cl and c2, you writer 

integer : start ; 
character : cl , c2 ; 

This shows one of the basic syntax elements, the colon 
declaration, which in Forth only declares words. According 
to one my favorite guidelines, simplification by generali- 
zation, the colon is used in OOF as the general method of 
declaration. It can be applied to any class that is known in 
the system in order to create objecLs (or instance.^ of this 
class. If you want todeclare more than one object of the same 
class, the names of the objects separated by commas form a 
list of objects to be dedared, terminated by a .semicolon. 

Forth Dimensions 



Figure One. Deflning an Instanoe method. 



im : size 

( ( image : i ; — integer : s ; ! I integer : pixels ; ) ) 
i -> xdim i -> ydira * pixels f 
i -> bits /pixel pixels * s ! ; 



Figure Two, Using individua! instance methods. 

ob jecL subclass : state ; \ define class state 

state iim ; keypressed ( ( state : s ,* — ) ) 

" A key was pressed" print ; \ define default-reaction 
state : idle , input ; \ define states for state-machine 

idle iim : keypressed ( ( state : s ; — ) ) 

" Idle state: key" print ; \ define individual reaction 



Actually , tlie comma is exactly the same method as the coloa 
In some cases, the colon me^Kxl needs scxTie more paranieteis; 

e.g., when defining a string, you want to give Am tnaxinuiin 
number of charades in the string: 

30 string : text I 

If, as a more elaborate example, you want to handle 
images in your system, you define tlic new class image. You 
do noE want to invent the meiliods anew for creation, 
deletion, or debugging methods of objects every time you 
define a new class. So you let image inherit all these prop- 
erties by declaring image a subcbss of objcCL, ihc most 
basic class of all classes, which already provides these 
properti^: 

object subclass : image ; 

image is now defined as an objea of the dass subclass 
I and, at this moment, tm exactly the same properties as the 

class object, 'llic !iubd;iss image is now going to tx: 
extended in order to fulfill the purpose we defined it for. For 
every image, you i»ed to know, Ux eicample, its dimension 
in X and y and how many bits are in a piwi. Hicsc ibta are 
part of every objea of the class image, i.c,,Lliaiis:jn imlance 
of image. Thus, we have to define instance variables (i.e., 
instance ot^eos, but "instance variables" in the typical 
nomendature of object-oriented languages; in OOF it is 
abbreviated as IV*) of linage: 

image IV Integer : bits /pixel ; 
iniage IV integer : xdim , ydim ; 

Whenyou wantto declare two new images iml and im2, 
you write: 

image : iml , iin2 ; 

using ^ general colon dedaratioa Now you have two 
image objects .eachcontainingonesetofthe above-defined 
instance variables. In order to adiicve die desired security 
and consistency, the instance variables of any object may 
only be modified by the methods that have been declared for 



I its dass, the instance methods (abbreviated as "im"), No 
method defined fear any other dass may alter, or even read, 

I these instance variables. One method for the dass image 
might, for ex ample, compute tlie siix; of an image in bits. You 
can define this method as in I-'igure One, 

So size is defined as an object of class im. What is known 
as the stack comment ( — ) in Forth, has evolved to a full 
declaration uf input and output parameters as well as local 
variables in OOF: ( ( — 11 ) ) . 

The parameters are defined in the same way as any object 
by the colon dedaration. The method size can refer to the 

I object that was passed to it on TOS as i, the object that is to 
bf} passed as Ltic result c:an Ix' referred to as s, and pixels 
is a local objecL It goes without sayii^g that you can define 
as many of these temporary Objects (here: s, i, and pixels) 
as you like. Their scope is only within the definilinn of this 
method, they cannot Ix; accessed from outside the method. 
They make possible clear and readable programming witliout 
stack juggling, and they ensure that only the values dedared 

i are popped off the stack and only the values dedared are 
I^ij.stiL'd onto tlie stack as results, 'l'hi,s is performed auto- 
matically when entering and exiting the method according to 
these declarations, thus enhandng security. 

'Hie instance variables xdim, ydim, and bits /pixel of 

I the image object i are acees,sed by the method ->, which 
may only be called inside an instance method for that 
particular dass (here: image). This is called data encapsu- 
lation and ensures that these operatiorts can only be 
performed c)n object data that you have explidtly allowed 
and defined to do so, again enhandng program security. 

Note that, in order to push the wiue of, for example, 
pixe Is onto the stack, there is no method @ involved (and 
thus cannot be forgouen any more). Every object lays itself 
onto the stack when invoked. The low-levid diffeienoe 
between the ot^ect's value and Its location is no tonger 
visible — there are only objects. 

Making Passes 

The above-defined method size for the class images 
ca n now be applied to the previously dedared image-object 

iml by: 

iml size 



Forth tXmensions 



17 



May 1992 June 



Ffflum HirMt. U^ng shallow object. 



state ^ : active 
iidle active <- 



\ creates the shallow state-object "active" 
\ maJces the shallow state -object "aetlve" act 
\ #8 if it the attat-^-obiffet "iaie" 



UtelhQ i^iattow objects in iftdlvidiiat trance mettiod$. 



i(ile iim : keypressed ( { state : a ; — ) ) 

" Xdle states entsatiag ii^ut state 



print 



Flsura FiiiF«. Uslh0 the Bo ... Ljosp- 


im : looptest 




( ( integer : from , to ; — | | 


integer : end , run ; ) ) 


from run ! to 1 + end 


! \ set limit and index variables 


end run do 




run print 


\ print the index value 


loop ? 





Non-objcci-orienicd languages, such as Forth, call nxshods 
dircaly: they compile the address of the code to be executed. 
OOF instead sends a message to the objeaon top of the stack 
(TOS). In its essence, a message is the name of a method to 
be called. When a message is passed to the object o on TOS, 
a method of tliat name is searched at mn time in the list of 
aiiinBediods awailaiile^^ie^^^ 

the method is executed; if nnt, an error methodic ca|li3d,TIi is 
ensures thai only valid code meant for objects oif the given 
dass is nm. 

1^ mediaDism also rnakes it possible to have the 
message sent to cijjects of different classes, wheic different 
methods of the same name are called, 'lliis property is called 
pc^pmorpbism. It saves Inventing new names (e.g., 
printjnteger, print_string, etc;) for the same function (print 
an object) applied to i jbjecLs ofdlfTcrent da.sses. In partial lar, 
it enables you to send the same messages that can be sent lo 
objects of class C, to objedB of aU subdasses of C ^t in- 
h^ited the methods fiom C. 

Methods for Indlvldiials 

Instance methods of adass haveilesaineeEfeaoD every 
dbjed of Ifiaf dasS, whteh fs ve^y di^liiatrle ife? aanSIKfiBicy. 
Rut someiimes you want to have different objects of the same 
dass to leaa difleiently to the same messa^^. This is very 
tisej^ ti^hffls '^ wSinf ^isi^^, a finite sta^ 

machine. There are a number of states the machine can enter 
and a number of possible events that can occur. This can be 
'i&^^k^mise^ ^■m^x&aSSSi^ state as an ikpjsxt of dass 
iSt^t^ lilliem each cbject is supposed to react spedlically 
td a Itsessag^, such as 'a key was pressed." 'Iliis behaviour 
OpuMbe achieved by means of a reaction table, but there is 
a more elegant way whidi is an evolution of the concept of 
message i:»ssing. OOF provides you with individual instance 
ni€^jEKK&(iiiri). A default iim for all instances (objects) of the 
dass is defii^ whipn the dass is declared For every 
inidMidual c±j^a[;spie<dfic: iim caa otitic! dedaue^IwM^ 
Ala/ tQSSJm» 



will be the individual response to slil! tlic same inc^sage. 
OOF code for this example might look like in l-igure Iwo, 

Shallow Objects 

In almost every language, there is the notion of pointers. 
A pointer is not an objea it.sclfbut kccj^w only a reference to 
an c^|ecL In Forth, every address can be interpreted as a 
pointer to a data field, the. syntax fear desaltig'w^i pfeiktters 
can become very cnnfusing (just think of C pointer puzi^les) 
and error prone. 1 abandoned the idea of a ctas.s pointer for 
these rea.sf)ns. In.stead, Smalltalk inspired me to define 
shallow obJ&^ They are diSfgpised as nqtmal c^^jects of a 
da^ but only bear a refercnoe to another ohfect. They be^ 
baoeexa^e^iftb^ were the (Ejects they keep the refemwe 
to, you do nqulttit^ne to wpct^ aboftit th^ shaUov/ nal^jue. Aa 
example isa st^ttowd^^gdi^da^ state^^^a^NQ^ that 
rcpresenui the active state nf the slate macliinei It b GCealed 
and handled as shown in l^igure Three. 

Now, in order to s^od file m^s^aigie^^^^^ 
momraitarily ac^ve stette^ you wn^ 

active kH&jnpx^seol 

which, at this point, sends ll« message keypressedtoSie 
.state object idle. Note that you need not perfomi some soli 
of poinier-indirection-qperaiion, the shallow objea active 
autoim^di&y jii^n^ the rdereniQed scaieHsb^ idle (xm 
the stack. The iim keypressed of idl# n&fi^ cao be ex- 
tended, as shown in Figure Four. 

Looping 

The control stmctures are quite the same as in Forth. The 
do . . . leave . . . loop, however, was modified it still takes 
limit and index as parameters, but they must be gi\^ in the 
form of local integer variables. This offers you the opportunity 
to name Lire "function.s" tliat access the index and limit of the 
loop (the former i and j) the way yqu like Ouid spares the 
toe^eitiewatipii to ck^:^ die trntm scadE with loopiqg 
18 Forth DmmTsions 



'iflure Six. Header o( an objectTI 



iiame 



link 



time 



owner 



module 



module-offset 



flags 



size 



class 



self 



body 



offset 



name of object, tcmriinated by 0, followed by a count-byte 
object number of next objcci in list, e.g., vocabulary, etc. 
object number of next object in list of ail objects 
object number of owner-object, e.g., owner of instance object 
object number of module-object - vocabulary + source file 
offset in source file 

e.g., shallow/deep object, private/public, ailocaied/deleied 
body size of object 

object number of the class the object belongs lo 
object number of the object il.self 
object nu mbcr of the object that holds the object's body 
ofisei within the body 



information). The example in Figure Five shows how to use 
this feature. 

Implemc ntation 

OOF is not implemented by extending an existing Forth. 
It is not based on clever use of vocabularies and create . . . 
does> constructs. I did start defining it thai way, since it Ls 
the first and obvious way to any Forth programmer. But it 
soon turned out that, if 1 u.sed a standard I'onh as a basis to 
program OOF, the underlying Forth would cither not be in 
use any more when mnning OOF or it would induce 
intolerable s(x;ed penalties. So the variety of new conccjxs 
forced an entirely new kernel for OOF. In the process, some 
wrinkles in Forth were ironed out by s trial y adhering to the 
paradigm of object orientation. As with any Forth, the kernel 
consists of some assembler primitives for arithmetic, I/O, and 
special kernel functions^ — comprising the virtual machine 
(VM) of OOF — and the lion's share of the kernel is written 
in OOF itself. This OOF source code is translated by a 
metacompiler into the kernel's tlireaded code. 

To make porung as fa.st and easy as pos.'iible, C source 
versions of all functions exist. F.xisting programs (e.g., 
image-pr(x:essing librarte.s) written in C or other languages 
can easily be linked to OOF. The metacompiler itself is 
written in C as well. So, in order to pon CK>F to another host, 
all you need for the beginning is a C compiler for that 
machine. 

In the following sections, I will desailJC in detail the 
stnicture of objects, the concept of object storage, and the 
consequences concerning access by the virtual machine of 
objects, the stack, and the execution of secondaries. 

Handle wi th Care 

Each object consists of a header and a body. Tliestmaure 
of the header is shown in Figure Six. It contains various 
information about the context and nature of an object, as wcD 
as information for debugging and the source of ifie definition 
of die object, 'llie body of liie object dial contains its data is 
located anywhere else in memory, in a contiguous memory 
block. The body of a compound object thai is built of instance 
objects consists of the bodies of its instance objects. As an 
Forth Dimensions 



example, the body of an 
image object is shown in 
Figure Seven. 

Objects may not be ac- 
cessed directly by an ad- 
dress, only via Cl6-bit) objea 
numbers Csomeiin>es called 
bandies). An object number 
can be convened into a 
memory address via the 
Objea Table, an array that 
holds the memory address 
of every object that exists in 
the system. The address of 
an object is determined by 
using the object number as 
an index into the Object 
Table. Thus, it is passible to 

relocate an objea without having to change every reference 
l{} this objea; only the entry in tlie Object Table must be 
updated. 'Ibis is very iniportant in an fJ^ject-orienicd system, 
where objects are constantly aeated and deleted at mn lime, 
causing the need for garbage collection and relocation of 
objects. 

Every objea has a unique object number. The corre- 
sponding address from ihc Object Table points to the header 
of the object, and the nature and slate of the ofjject can now 
be deduced. However, since the body of the objea can be 
stored anywhere else in memory, we need more information 
in the objea's description: a further object numter gives the 
address of liie memory block where the body is located. An 
ofTsei within the block must be added to this address to arrive 
at the complete body address of the object. 'Ibis process is 
shown in l''igure Fight. 'Ibus, a complete description of an 
object consists of a reference to the header and a reference 
to the body of the object. 

This concept has great impact on ilie format of stack 
entries. It makes sense to push onto the parameter stack not 
only an address, as in Forifi, but a complete object descriptor. 
In order to speed up message passing, tfx: objea numterof 
tlie dass of the object is added. When primitive arithmetic or 
logical functioas are executed, it would cause an enormous 
overhead wlien a new object would have to be created each 
time a result is returned. So, in the stack entry, there is a 
value field tfiat can hold the result of operations on basic 
classes, such as integer, character, or even float. 'Ihe com- 
plete format of a stack entry on the parameter stack is shown 
in Figure Nine. 

Because ifie desaipiion of an objea is divided into a 
reference to the header and a reference to the body, orie 



Figure Seven. Body of an image object. 



offsets 

+0 

body of instance-object 
body of instance -object 
body of instance-object 



bits/pixel 

xdim 

ydim 



19 



May 1392 Jung 



Figure Eight. Accessing the body of an objectTj 

object-table 



object number of body 
= index in object table 



header can be used to de- 
scritie many bodies. ThLs Is 
the case for instance objects, 
E.g., every time an image 
ob|ect is creased, its body 
coniains the bodies of its 
three instance objects; bits/ 
pixel, xdim, and ydim 
CFigure Seven). But a new 
header is created only for the 
new image object — there is 
no need to create a new 
header for each instance 
object. Tlic one header that 
was buill during the dcfiitilion of the class image for cadi 
instance object, describes tlic nature of the instance objects 
completely. OUT and LOCAI, objects of a secondary arc 
treated similarily: every time a secondary is entered, only 
space for the bodies of these objects is alicKsited on the 
parameter stack, no new header is created. So, in most cases, 
no new header i.s constructed for new objects. This saves 
considerable amounts of both time and memory space. 

Additionally, tt turns out, access to the body of an object 
LS accelerated a great deal because there is only one 
mechanism to arrive at the body address. No testing of (lags 
or considering of special circumstances at mn time — which 
takes longer than it takes to actually access the Clbject 
Table — are necessary. The latter is especially important for 
the primitives, which should be as fast and elTident as 
possible. 

Once again, the principle of simplification by generaliza- 
tion proves useful. Here, it saves space and lime when 
creating new objects, and simplifies and, therefore, speeds 
up access to the body of an object. The next paragraph 
describes how the appropriate stack entries are composed 
according to the spedal nature of each objea. 

The Virtual Machine 

'ITie virtual machine (VM) of OOT consists of a number 
of Body Evaluation Codes (BECs), the inner interpreter, the 
primitives, internal regi.sters, and the available RAM. It is the 
machine-dependent part of an OOF .system. 

A BFX' is a piece of a.s.sembler code that performs a basic 
function, such as pushing an object descriptor onto the stack, 
sending a message to the objea on TOS, and calling or 
returning from a secondary. They are the counterparts of 
North's CfA primitives, 

'I he inner interpreter works similar to most Fortfis' inner 
interpreters: a register of the vinual madiine called OOF PC 
points inside the body of a secondary, wfiere the next entry 
shall Lx; interpreted. liadi entry in a secondary consists of ifie 
object numlxr of a BliC followed by parameters for the DEC. 
In order to speed up the inierptciation, GO I- compiles 
references to the codes that evaluate tfic entries of tlie body, 
directly into the body rather dian just storing a reference to 
the object. Everytiiing that is known at compile time about 
an object to be compiled is stored as tf le appropriate UEC and 
thenecessaryparameieis;soihai, at run time, a BEG does not 



array of memory addresses 

start of block 




Figure Nine. Format of a stack entry. 



class 


sdf 


body 


offset 











value (64 bit) 



L 



J 



object numbers 
I 



short 



J 



object descriptor 



have to test fiags or search for its parameters somewhere el.se. 
Since lots of kilobytes of memory are no big deal anymore, 
space is no problem in most development systems. OOF 
makes inaemental development and compilation possible, 
so compilation speed is not critical. The emphasis in the 
design of OOF's kernel is on execution speed, which is 
always a critical issue in object-oriented systems. So, in OOF 
compilation takes a bit longer and the code size grows, but 
execution is sped up a great deal. 

One by one, each entr>' of a .secondary is evaluated by 
calling tfie DEC thai the OOFPC points to. At the end of every 
BEC;, tlie OOFPC is set to the next entry, the processor jumps 
back to the inner interpreter, and the next entry in the fxKly 
of the secondary is evaluated. 

The execution of a secondary shall now be explained in 
detail. When a secondary is entered, the VM registers 
SDELTR, SFRAME, and OOFPC, and the objea number of llie 
secondary are .saved on the return stack. Then SFRAME is set 
below the first input parameter witiiin the paranxjter .stack; 
now the stack frame .starts with the stack entries of the input 
objects for the secondary. 3DELTA is calculated as SFRAME 
- S BOTTOM (bottom of stack), and space for the bodies of the 
OUT and LOCAL object-s is reserved on the stack by 
decrementing TOS. After OOFPC is .set to the first en uy in the 
body , theinnerinterpreterisreadytointerpretthesecondary. 
Figure F,leven shows the contents of the parameter stack at 
that time. 

To explain the (unctions of the BECs, the evaluation of a 
sample part of the .secondary that was called when the 
message size was sent to the global image object iml, shall 
now be traced Figure T en shows both a sample of the body 
of the method size and the appropriate contents of the 
parameter slack after tlie execution of each BEC. 



May 1992 June 



20 



Forth Dimensions 



Figure Ten. Body of a secondary and parameter stack during execution (extract from 
the method size sent to the global object im1). 



BEC IN 



offset " 



BEC IV 



offset = 4 



integer 



bits/ pixel 



integer 



BEC IM 



BEC EXIT 



class self 
image | imT" 



body 
I iml 



offset 



value 



biis/pixel 



BEC loc;al 


pixels 


integer 


bits/ pixel 


iml 


4 




offset = 20 


integer 


pixels 


SBOTrOM 


SDE[,TA-20 


1 


integer 
pixels 






BECIM 




integer immediate SBOTI'OM SDIiLTA-32 | product | 


• 




BEC OUT 


s 


integer 


immediate 


SBOTfOM 


SDEI.TA-32 




offset = 16 


integer 


s 


SBOTTOM 


SDl-LTA-16 


product 1 



BEC IN lakes the offset parameter as an offset into the 
stack frame and copies the stack entry at that location to 'I'OS, 
effectively pushing the current input parameter iml onto the 
parameter slack. This is an example of the behaviour of 
shallow objects: they do not appear on the stack themselves, 
only the object they refer to. 

BEC IV manipulates ihe stack entry on TOS as follows; 
it adds the offset lo the offset on TOS, replaces class with 
integer, and self wilh bits /pixel. Tlie body object 
remains the same, as explained above. Now the instance 
object bits /pixel of the input object is on TOS. 

In order to push pixels onto the stack, BEC LOCAL 
creates a new stack entry. Tlien it takes tlie parameter offset 
as an offset into the stack frame, sublraos it from the contents 
of the VM register SDELT A (equal to tlie stack frame - bottom 
of stack) and places ihe result as the offset into the new 
stack entr/. The pseudo-object SBOTTOM (bottom of pa- 
rameter stack) becomes the new body, class is .set to 
integer, and self is set to pixels. 

The parameter of BEC IM is a token that represents the 
message *. The message is sent to tlic object on TOS, which 
is now pixels. In the list of instance methods of the class 
of the object on TOS (here: integer), a method is searched 
that matches thLs token. In order to speed up the search, this 
list is 32- fold hashed. When the method is found, it is called; 
if not, an error message that is guaranteed to be unrterstood 
by all objeos— since it is defined in the kernel — is sent to the 
objecL 

The primitive for integer multiplication takes the two 
integer objects off the stack and pushes an integer object wilh 
Forth Dimensions 



the product in the value field of the stack entry. Self is set 
to Ihe pseudo-objca-number iitmediate, indicating ihat there 
is no valid header available for this object, 

'ITie OUT object s is pushed by BEC OUT the same way 
pixels was pushed. 

The result of the mu Itiplicaiion is stored in s by the method 
that was found when BEC IM sent tfie message ! lo s, 

f "inally, the secondary s i ze is exiled by BEC EXIT, which 
cleans die parameter stack by setting TOS to S frame, ef- 
fectively freeing the space of out and local bodies in the 
stack frame and taking the IN objects off the slack. Then il 
pushes the OUT dajccts (here: s) onio the stack, restores the 
VM registers SFRAME, SDELTA, and OOFPC from the return 
stack, and resumes where size was called. 

Experiences with OOF 
and Future Work 

OOF was utilized lo write a lcx)lbox for graphical user 
interfaces for image workstations. Since llic CX)F kernel will 
be finished real soon now, we still have to gain experience 
about how the system behaves in terms of speed. However, 
early experiences about the impact on the style, clarity, and 
ease of writing programs in OOF arc promising. 

A very important lesson is that the way you tackle 
problems changes when using OOF. You no longer think 
about some data siaiaure in the beginning and then write 
loB of code manipulating it independently. After having 
analysed yourproblem, you try lo build a hierarchy of das,s&s 
that can represent the solution. Here you use the well-known 
techniques of factoring and decomposition, which are 

May 1992 June 



Figure Eleven. Parameter stack at entry of secondary size. 



SBOTTOM= botiom of Stack - 
not reachable by size 

SFKAJaE= stackframe ■ 
stackentries of INPlfl' objects 

reserved space on stack 

TOS = lop of stack 




free stackspace 



body of Oiri' objerE 



body of LOCAI- object pi:^el?i> 



SDFXTA 



16 
20 
24 



already recognised good style in Forth and elsewhere. Data 
structures and methods working on the data are tightly 
coupled now. When you write a function in OOF, first you 
have to consider lo which objea you will be sending a 
message to do tfie job. 

Since OOF does a lot for you in terms of factoring or 
deciding wliat to do in special cases, which is done by 
inheritance, polymorphism, and message passing, code 
Lends to Ixj tighter and more to the point. You have more 
control over what is going on in your program and you don't 
get !osi in an unordered heap of data and words. Last but not 
least, it is more fun! 

Some words concern i ng sta nda rds: we have worked with 
morc-or-le.ss standard Forihs and were less tfian happy with 
the environments and the support for n on -trivial programs 
written by more than one engineer, CX>I'' might not be 
suitable for tiny target applications or not fast enough for real- 
time applications (which is stiti to be decided, there is enough 
room for optimization). However, OOF pwinis out how to 



tackle problems differently 
but ,stil! in the good nl' Forth 
style of writing and testing 
small chunks of code incre- 
mentally and interactively. It 
support.s the programmer by 
providing the integral order- 
ing mechnisms of objea-ori- 
ented languages and by 
adding security— by means 
of strong type checking and 
local parameters — to the ad- 
vantages of Forth. Ihus, OOF 

j could show a way towards a 

nKxlernized, extended, sup- 
portive Forth living side by side with the current standard, 
minima listic, compact Fortli. 

'the future will see an OOF system running all described 
features, with optimized code for ihe kernel, more classes, 
ported versions on hrxsis sudi as J'Cs, Macs, and Unix 
machines, and a full debugging environment lo make life even 
easier. We wiU run laboratory work for image processing and 
protoyping of medical image workstations using OOF. ;\ny 
conuncnis, annotatioiis or additioas are welcome, Slav turied. 



We hc^xi (Mr mark wiU nol be misaseci for milUary jmrposm. 
We will not take pan in any military projecis. 

Mafkus Dahm recoivcd his Dipl. Ing. tdcclrical ongineoring) in 1987 al RWTH 
Aachen, University o) Technology. Aachen, Gormany: abd his M.Sc. (Computer 
Science) in 19&S at Imperial College, London, U.K. He has been A research 
assistant since 1989 alLehrsluhl fuef MdSlcchnik, RWT>H Aachen, DIBA-projecl, 
working on user interlaces for medical imaging workstations. He can reached at 
the tdkiwing: 

Lctirstutil (uof Mcsstochnik, RWTH Aachen. Temptergrabon 5S, D-SlOO 
Aachen, Germany Phone: +24 1 -80 78 64 Fax: +241 -60 78 71. 
E-mail: SE©DACTH5 1 .BITNET 



$ Contest Announcement $ 

Call for Papers! 

Forth Dimensions is sponsoring a contest for articles about 
"Forth on a Grand Scale" 

Write about large-scale Forth applications, systems, or ... 



This theme applies equally to projects requiring multiple 
programmers, and to applications or systems consisting of 
large amounts of code and/or of significant complexity.' 
("Editorial," FD XI 11/6) Papers will be refereed. 

Mail a hard copy and a diskette (Macintosh 800K or PC 
preferred) to the: 

Forth Interest Group 

P.O. Box 8331 - San Jose, California 95155 



Cash awards to authors: 

1 St place: $500 
2nd place: $250 
3rd place: $100 

Deadline for contest entries is August 3, 1992. 



May 1992 J una 



22 



Forth Dimensions 



FIG 

MAIL ORDER FORM 



HOW TO USE THIS FORM: 11<:ise enter your order cm Ihe back page ofthi-'i form and se:nti wiih y<.>ur paynicni to die T'orth Interest Group, 
Most iicms list ihrrsc different price C4)iC£<jric;s^ USA, Canada^ and Mexico / Other counirics via surface mail / Other cfHintrics via ui mail 

Nt*c; Where only two prices arc lifted, surface mail is noi available. 



"Were Sure You Wanted To Know..." 

Forth Dimensions, Article Reference 1 51 - $4/5 

An iniicx of Forth anitlcs, by keyword, from Forth Dimensions 
Volumes l-l2(197S-yi). 

FORML, Arlicic Rtirvrcnci: !52 - S4/5 

An index of Forth articles by keyword, author^ and date from The 
rORMI. Conference Proceedings (iy80-89). 



FORTH DIMENSIONS BACK VOLUMES 

A volume consists of ihe six issues from tha volume year (May-April) 

Volume 1 Forth Dimensions (1979-80) 101 -St3/l6/!8 

tntioduetion lo FIG. threaded cade, TO variables. fig-Forth. 

Vcdumel Forth Dimensions (19S0-S I) KCSIS/WIS 
Recursion, file naming, Towera of ITanoi, CASli coinest, input 
number wordsel. 2nd FORML report, TORGF,'!', VIEW, 

Volumes Forth Dimensions (1981 -S2) 103 • S15/16/18 

l*OfTh -79 Slanda rd.Slacks.HKX, database, musie.mcmoryman- 
agcment. high-level intermpu, string stack, BASIC compiler, 
recui^ioti, 8080 assembler. 

Volume 4 Fkjrth Dimensions (1982-S3) 104 -$15/16/18 

Fixed-point trig-, fixed-point square rool, fractional aiithmctic, 
CORDIC algorithm, interrupts, sicpper-mottir control, source- 
screen documentation tools, recursion, recursive decompiler, file 
systems, quick text fomiatter, ROMmablc Forth, indexer. Forth- 
83 StandanJ, leaching Forth, algebraic expression evaluator. 

Volumes Fonh Dimensions (1983-84) 105 - $15/16/18 

Computcrgraphics, 3Danjmation, dcxible-precision math words, 
overlays, recuisive sort, a simple multi-iaskcr. metacompiiaticii. 
voice output, number utility, menu-driven software, vocabulary 
tutorial, vectorerd execution, data acquisition, fixed -point 
togarithms. Quicksort, fixed-point square rooL 

Volume 6 Forth Dimensions {1984-SS) 106 - 115/15/18 

Interactive editors, anonymous variaHes. lisE handling, integer 
solutions, eontrt^ structures, debugging techniques, r^trsion, 
Eemi[>hcircs, sirtiplc I/O words. Quicksort, high-ievel packet 
commurtications. China FORML, 

Volume 7 Fonh l>imcns(ons (1985-86) 107 • S20/22/2S 

Generic sort. Ft>rth spreadsheet, control stmcturcs, psuedo- 
interrupis, numbw editing, Atari Forth, pretty printing, code 
mixlules, universal stack word, polynomial evaluation, 1^83 
strings. 

Vol tim e « Forth I>im ension s ( 1 986-87 ) 1 OS - S20/22C5 

Interrapt-driven serial injiut, data-base functions, 1'] 99/A. 
XMODiiM, on-line documentation, dual-CFAs. random 
numbers, armys, file query, Bateher^s sort, scrceoless Forth, 
classes in Forth. Brescnham line-drawing algorithm, unsigned 
division, DOS file VO. 

Vmumc 9 Forth Dimensions (1987-88) 109 • STaniOS 

Fractal landscapes, stack error chocking, pctpenial date routines, 
headless compiler, execution security, AJS'S-Fonh meeting, 
computer-aided instmctioo, local viiialiles, Iranscetiduiilal func- 
tions, edueaticn, relocatable Forth for 68000. 



Volume 10 Fonh Dimensions (1988-89) 1 10 . $20/72/23 

dUase file access, string handling, local variables, data stntcturcs, 
object -<>rientE:d F(>rth, linear automata, sEandatonc apj^cauons, 
8250 drivers, serial data comprESsion, 

Volume 1 1 Forth Dimensions (1989-90) 1 1 1 - S30/22/25 

Local variables, graphic filling algorithms, 80286 extended 
memory, expert systems, quaternion rotation calculation, 
inukiproccssor Forth, double-entry bookkeeping, binary table 
search, phase-angle differential analyser, sort contest. 

Viilumil2 Fonh Dimensions (1990-91) 1 12 - S20/22/25 

Floored division, stack variables, embedded control. Atari Forth, 
oplimixing oom|Mler. dynamic memory allocation, smart RAM, 
extended-precision math, inlcmipt handling, neural nets. Soviet 
Forth, arrays, melaccanpilati on. 

FORML CONFERENCE PROCEEDINGS 

l-OR.Ml. (Forth Modification l^boratoiy) is an educational 
forum for sharing and discussing new or unprovcn proposals 
intended to benefit Forth, and is an educational forum fordlseus- 
sion of tlie technical aspccEs of applications in Forth. Proceedings 
an^ a compilation of the papers and abstracts presented at the 
atmual conference, FOltML is pan of the Fonh Interest Group. 

1 980 FORML I'ROCKEl)! NGS 3 10 - $30/3 1/40 

Adiittss binding, dynamic metnor>' allocalion, local variables, 
ctx>cUTTcncy. binary absolute & relocatable loader, IJSP, how lo 
manage Forth prtvjccls, n-level file system, documenting Forth, 
Forth structures, Fonh strings. 

1951 FORML PRtK-EEl)!NGS 31 1 - S4S/48/35 
CODE-less Forth machine, quadruple-precision arithmetic, 
overlays, executable vocabulary stack, data l>ping in Forth, 
vectored data structures, using Forth in a classroom, pyramid 

files, BASIC, LOGO, autixnalic cueing language formulumcdia, 
NliXOS — a RO.M-based multitasking c^rating system, 

1952 FORML PROCEEDING.S 3 12 - 530/31/40 
Rockwcl lF"ortliprocessor,virtualexecution,32-bitForth, ONLY 

for vocabularies, non-lM.MFDIA l'F, kxiping words, number- 
input wonlsct, I/O vectoring, recursive data s irutiu res, program - 
maWe-logie compiler. 

1 9)i3 FOR M L P ROC EEDl KGS 3 1 3 - $3 0/32/40 

Non-Vort Ncuman n^achincs. Forth instruction set, Chinese 
FtKth,F83,conipilcf& interpreter co-routincs,log& exponential 
function, rational arithmetic, transcendental functions in 
variable-precision Forth, portable file-sysiem interface. Forth 
coding conventions, expert systems, 

1984 FXJRML PROCKEDINGS 314 - $30/33/40 

Forth ex(5crt systems, consequent -reasoning inference engine, 
/£.r\ floating point, portable graphics woiJset, 32-bit I^nh, 
11P7111 Forth, jNHON— objea-onented pmgranuning, decom- 
piler design, arrays and stack variables. 



198S FORML PROCEEDINGS 



313 -$30/32/40 



Threaded binary trees, naiural language parsing, small learning 
exjieir system. LISP. LOGO in Forth, Prolog mteipreter, BNF 
parser in Forth, formal rules for phrasing. Forth coding 
conventions, fasi high-level floating point. Forth component 
library. Forth &. artificial intelligence, eliK:tiical network 
analysis, cvenl -driven multitasking. 

1986 FORML PROCEEDINGS 316 - $30/32/40 

IhiBading techniques, Prolog, VLSI Fonh microprocessor, 
natural -language interface, expert systt^ shell, inference cn^e, 
multiple -inhcntance system, atttomalic prtjg ramming environ- 
ment. 



1987 FORM L PROCKKDINGS 317 - $40/43/50 

includes papers f ruin 'S7 ciifnI-ORMt. Conference. 32-bit l^anh, 
ncur^ networks, a^ntro] slrjc Lures, AI, opLiini/ing compilers^ 
hypeTIexL^ field and record slAJcturcs* CAD command language, 
ubjcd-oricntul lisu. LrainablciMllrtW*I> <S!^P<*i^'yft™^' 

19»Hn>KMl. PROCEEDINGS 318 - $24/25/34 

lliiitrin inlcrraccs, simpk robotics kemd^MOSTOI, ^qitb. 
Unguageiofxcs, hiidwaic.Wil't workup A'QiKVphikW) 

f oRb-luutiiMre ifldiMitiQn*,. ANS ppnb senaf^n^waam mi 
in Altqcfiiksttkm. 

I988AUSTRAMWSPROCEEDINGS 380 - Jai^fliSS* 

Proc^iSlSDgt frocn the finl Au^lnilian Horth Symposium, held 
May 1 988 at ihc UniversiEy ofl'cchnology ill ^mey, Stllwctl 
include training, parallel proccuing, pmgjmamiii^pattaBe^ 
Prolog, siinulalLons, and appliciiiion^. 

198!> FORM L I'KOC KKDINGS 3 1 9 - S 10/43/50 

Includes paficrs from '89 euroFORML. Pascal to Forth, 
extensible op<imii';erforcompiliQgi SDn^suiEm ent with objea* 
Oiiaited Forth, CRC polyiMliMi. F-PC, Harris C aaw- 
coiinpilcr,nKi4uWappnwcblof«!i>alicmu^ lecompiler 

1»0 FORML PROCEEDINGS 320 S4O/43/S0 

Forth in indiuiiy, commumcations monitor, 6805 dcvelopmenL 
3 -key keyboard, documentation techniquci, object-onuited 
pl<ogramiTun^ simpleai FonK decomptlcr, crior lecoveiy. stock 
opcavons, pcoccts cownd event management, control 9iiuaiu« 

BOOKS f^mmwrnm 

AU. ABOUT FORTH, 3[d cd., Jum: 1 990, Glen B. Hq^ m -^^e^iCtS 
Amiotaled gtossaiy of most l^rth words in coaHOm 'HH^^I^ 
bidudingFo)th-79,Forih-!t3,F-PC,I^P-F<xlh.Ii^leaia|liui9lt 
examples in high-level Fmh an(W jOS^SS membler. IJleM 
cccnmenta^ given for each entry. 

THE COMPLET^POKTH. Alan Winfield 210 



eFORTH IMPLEMENTATION GUtDE, C.H, Tmg 215 - S25C6/3S 

eFonh is the name of a Fofdi modd designed to be portable to a 
lar|e nimdier (tf Ibe iiewqr, nofc powetfid [Hoceaim avai^ 
aawmdbe«nAtBW«iti^ibi!iB;BenliitsiiE. Cw/^) 

FK3 SOURCE, Henry LitWK&Mkhtel Peny Zlf-S^i0S 
A cunplcte listing of Pg3, including source i^jtfHKlQW tOeen). 

hicludts inlruduction on getting started. 

FORTH; A TKXT AM) KlireRENCE 219 -$31/32/41 

Mahlon G. Kelly & N^icholas Spies 

A tcAibouk appK^flch to Forth, with c<wnprehenslve referenccito 
MMS FORT it ami the ■?<) and '83 !-urth sundanls. 

THE I-OR'1'H COURSE, Richaixl R Haskell -tW^ 
This set (]f 11 lessons, called the Forth Course, is detignedtoimlie 
it easy for you to leain Fonh. The malerial was devdopcd war 

scvetdl years of Teaching Forth as pan of asenior/gmdjnlieoODi^ 
in dc^s^n ernbcJJed >oriware computer systemS' M Oal^and 
University in Rochester, Michigan, (w/disk) 

FORTH ENCYCLOPEDIA, Milch Oeikk & LtatdaB«ker 

A detailed look at each fig-Fortb t 



FORTH NOTEBOOK, Dr. C.H. Ting 232 - £15/26/35 

Good esianiplex wd if^Eatiotu. Great learning aid. puiy- 
PORTH is the dialect used. Some convenjan advice it indtided. 

Code is well docunientcd. 

TORTH NOTEBOOK 11, Dr. CH. ling 232a - $25/26/33 

CoUeoion of rcscardi ptqiers on vaitiMt::neietini^:; 
processing, parallel processing, anditdi<sdH|Eomi 

LNSlUE F-83, Dr. C.H. Tin^ 33S-&fi%WS 
Invaluable for those iiang F-83. 

LIBRARY OF FORTH ROUHNES AND UnLITIfS, 

lames D. Terry 237 ■ S23/2S/35 

Comprehensive collection of pnifestranal qualtty con^HUer code 
for I'onh: offers louimes ibatcanbeptKlotiteiiialiniii^any Fonh 
application, ineliu^ «X{)«lt cyAttttt «^ OitlSniHHgMlgb 
interfaces. 



OIUECrORIEmXD FORTH, Did[Piiln«!ia Z«-S2C/29/34 
Irni^onemiiten. of i*f» ttnicUinix. bMik urate objecl- 
Diicnted prop wnl i > ingfwD)ifcMiMCTcfCTmi^«i»^ 

cocnputcis. 

STACK COMPUTERS, THE NEW WAVE 244 - J62/65/72 

Philip J. Koopman, Jr. (hardcover only) 

PrrienEs an alu^niauvc lij Ciirnptc^ Iiislnjctiisi Set Ct>mp( iters 
(CISC) and Reduced InjWJCUon Set Qwtpiteis (RISC) by 
showing the itiengll^ wd wetlowages of itadit naicldiiji^ Onri- 

cover only). 

STARTING t"ORTH (2od ed.), Leo Brodie 24S - S29/30/3S 

In this edition olSlaning Forth — die most popular and complele 
introduction to forth— ^iJiEtllMbW IWpiltndtid to 
honh-83 Standard. 

TOOLBOOK OF FORTH, VI 

0>.D<)bh's) Edited by Marfin Owverson 

Fspndcd and revised versions of die best roilhailkleac<d1ccti.-d 

in die p^igc.-^ of LV.Dobb's JoLtn^al. 

TOOLBOOK, VI vm DISK [MS- DOS) 2S7t. - S4<V42/50 

TOOLBOOK WFORTH.VZ, {ft. Do«>-*) 268 - 330(O2W> 

Cnmtetc anthology of FORTH pngrammiitmg techniques atvd 
d^vdie^ncnts, picks up where V,l left off. Topics include prog- 
nutmiing windows, extended oonuol suuctuies, design of a Forth 
tanet eompiter. aiMl mote. 

TODLSOdl^ VZwilii DISK (MS-DOS) 25ga - S«V4S/56 

WRITE YOUR OWN mOGBIAIitiHJNG LANGtlAlGE; USI.vr, C-,*. 

Nqtman Smith 270 - S ) 5/16/1 8 

liui boot; IS about an appucatjioa Jingiiagc. More speojically, it 



isaboutbow towriteyouTownci]Stomat]pUc^o<il^gii4ge. The 

book contains the toils necessary to begjt) the HQcess.aad a 
cntnplete sampklanguageiin ptenientatton. KIOCsi wbatlangaagell 
hicludes disk with ceinplete source. 

REFERENCE 

FORTH-sa STANDARD 30S-MS/l(fW8 
AntbmicRiiwdein^piictatf Ft>(Qit-S3 &aaibnl> fis'ii^u^ac«,nat 

SYSTEMS GUIDETQ f^VOXm 308 • $2Sl2S/3a 

How's an d ^'sjc^ Ael|g'P<«blii3d4ty&QUl|iB>M^ 

BIBLroaR/ffSVOF^tHITH REFERENCES m-tiSmtSS 



foPai^aiti^lfaniiy^Kiilt coinpnter liter- 



F-PC USERS MANUAfejPil#t«|4iS 350 - mi2l0 

Users manual to thtpiti^iaBifSS^ WMH ajnten opdmi^^d for 
IBM PC/XT/AT computeis. A fal. fast system with many tools. 

F-rC TFXIINICAL REFERENCE MANUAL 351~$3(^£NQ 
A must if you need to know the inner VTOddngi of F-PC. 

MORE ON FORTH ENGINES 

ymm 1ft iumaiy tm 8 1 - sisimu 

RTX i^HinU from 1988 Rochester Fordi Conference, object- 
oriented cmFonh, lesser Forth engines. 
Volume II July 19S9 31 1 - S15/W!g 

RTX supj>lemeni lij FtioisLepx in an Empry Vtilhy, SC32, 32-bil 

Fonh Engine, RTX interrupts utility. 
Volume 12 April 1990 812.StSa<lSfl|' 

ShBotiin Oiip architecture and ioittiKwm, Neiiiil Cqmpuimg 

.Module SCM3232^BigiF^tsiig(yndixs^^^ 

and RTX2000, 

Volume 13 October 1990 8l3'S15/16nS 
PALi of the RTX2000 Mini-RfiE, ^Fbilb. AZJWh, ^IX- 
2101, 8086 cForth, 8051 cFocth. 

Volume u m>^)^sm: 

RTX Podtei-Scopc, cFoith for mnT^, ShBboiiri, e^)^ fotCPl' 
M & 7K0, XMODEM for eHonh. 
Volume IS 815 - $15/16^8 

Mooic ; New CA D System for Chip Design , A portrakof the F20; 
RsUk QSl Foftb Procesaor, <^ RJS^s it )«; m CFMiti 
Software StDubtor/Debaggcr. 

MtSCELLANEOUS 

T-S FIIRT "Maj the Forth Be With You" 601 - $12/13/1 5 

f^pecify size: Small, Medbmi, Lngs, Eiiim-I^tg<;oiiaiilcrforni ) 
White design on a dark blue diut. 

POSTER fflrTEcovert 602 - $5/6/7 

FpilTH-»HAWI>¥KE|iE^i)e£<CAKD 



DISKS: Contrlbuttons from the Forth Communily 

'I'hu "Omributiuns Trom ihc I'orlh Conuntmity" disk libraiy coatiutt 
author- submitted donations^ generally tncluding source, for a varic[y 
of turn pullers & iliik fomiau. IZuch file is determined by the author as 
public riooiain, sharrwart, or use with socne Ttslriclions. 'I'his library 
dtjgs no*, cxtntain "Kor Sale" applicaliorts. To auhnUyour own conirt- 

Priees: Each ium below cooks cm oiwcvmoreduk^ indkaled in 
paTEntheses after (he item ntimbcr. The price of ycatot6whS6(9 per 
disk, or $25/37 for any five disks. 



n.OAT4lh.III.K VI A Robert I. Smith COOl - (1) 

Software floaliiig-poin! for fig-, poly-, 79 Si J., R3 Sni, 
I'tJrths. IKiill shod 32-bit, four standanl functions, square 
root and log. IBM. 



Oamo,s iit Forth 

Misc. games. Go. TEmA, 1Mb.. 



Sfmm. DM 



C003-(l) 
C003-C1) 



AFortb Spreadslieet V2, Craig liEidley ^ 

Tins model spreadsheet first sppeued in Forth X^inwnriiM* 
VH, 1-2. Those issues contain docs & source. IBM 

Aulomatic Strudure Charts V3, Kuii Harris C0Q4 -(t). 

Tools for analysis of large pmgnmi, SrstpicKoied at 

"Pitic^edlii^. IBM 

A S 1 1 1 ! p I r 1 ri f tre ti t e E ti (; i » e V 4 , .M J n in Tracy CCX15- (IJ 

3aKcd on inf. engine in Winslun £l Horn's book on LISP, 
t^kcs you front pattent vaiiaUct to ceMirijie.igrafifflWiCi^ 
algorithm, with runninE comrnctitaiiy'f)aBanh|iwi£^&i^.A 
style. Iitcl. source. IBM 

The Math Box V6, Naihanid Grossman CO06 - (1) 

Routines by foremost math author in Forth. Extended double- 
pr^dsion ariihrnctie, aymplete 32 -bit fixt^d-jxjint in:ith. & 
auto-ranging text. Inch graphics. Ulililics for rapid 
D0^!i|aaMal ewaluattooi cwaimi^ 
mSt>iiai6oti, Bid. sooice & doo. IBM 

AstniFcirth & A?ilrt>()KO Demos. I.R. Agumirsian COOT - (IJi 

Astiol'onh is the R3-Stil. Russian version of I-otth. Incl. 
window iiutrtao;, full -5Cn;cn editor, dynamic assembler & 
a great demo. Asln>OKO, an astronavigation system in 
AsuoFcHth, calcidates skypositirai of several objects front 
^fi^«lstt^^$(liilAilt|^P^^ 

Forth List Handler VI. Martin Tracy CO(SS- (lS 

listl primitives extend Forth to provide a flexible, high- 
speed environment for AI. Incl. EUSA and Winston A. 
liom'smiero-LISPas examples. IntiwaioeAdqcs. IBM 

8fl.^ I Em t) td ded Forth , Wil I iam I'ayne CC50 - (4) 

Wi^l Rr)MTii:ili!i: r-onh operating system. 80S&-t(j-ffl5l 
[jirgci compiler. Ind. source. Docs arc tn the book£m6«t!fe<f 
Cimlri'Utr Forth for the 805} Family. IBM 

FitJVZ.Ol, Mike Perry & Henry Laxcn ClOO-(l) 

The newest version, ported to a variety of machine i. i editor. 
issen)i^cr« deeompiler, metacompiler. Souroe and shadow 
tcnsens. Manual available sep«tat«^ ^ 
Baseffvoiher FS3 afptications. lBM, tl3. 



F-PC V3.53^ Tom Zimnier C2TO - (5) 

AMI For^ lyAemmibpciU-dawiiiiie^^ 
forwud asaemHer, mctacoaijnler, floating pdnL Cbm^oe 

350 & ^1> Ear «tber F-PC ■p^sMkna. leq^ laid &k, 
IBM, 83. 

F-PC TEACH Less<Mis D-7 Jack Brown C2»\i - Q) 

VP-PIanncr Float for F-PC.Vl.OUack Brown C2C2 - ( 1 ) 

Software floating-point engine behind the VP-Pianner 
spn»dsheet. SO-bilTtempcHaty-reat) toutines with tranncendental 
functions, mmilKir sifppfiiv 'vec to support ninntak 
processor oivoliy & tuer KAN checking. IBM, F-PC. 

F-1«C Graphics V4,2f , Mark Sni Ucy C2(Ba - p) 

I'he latest versions of rtew graphics routines, including CGA, 
i!GA, sod VGA siqjppon. wilh lunneipus 'nnptCf<f^ioial»S^ 
earlier vcFstoni created or aupponed by Mark Siiiui^.l IbM^ 

^KketFortb VI .4, Chris Heitoian OtKl - {1 ) 

Smallest cOTDplcie Forth for the Mac. Access loall Mac functions, 
filetj graphics, floating point. ma;;ros, L-r^ati: standalone 
ai^ieaiions and DAs. Based on &g & Starling Forth. bicL source 
tDtdttnKul; 

Yeritcs Forth V3.6 C350 - (2) 

Comp [etc object-oriented Forth ffw the Mae. Object acec^^ to 
Mac lunciiuns, files, graphics, floating point, macros, citrate 
Jt and atona aBcBcaliona. Ind. xouFCe, tutorial, a«iemUler & 
msnul. MAC, System 7X>10»>pataUe; 

JUSPV1.0, Nick Didkovsky C40I - (1) 

USP interpreter invoked from Amiga JFonh. The nucleus <^ the 
inteipreier is the rcsull of Martin Tracy *s work. Ejilended to allow 
the OSP interpreter to link to and execute JForth words, k can 
communicate with JForUi's DDE (Object* Development 
Rnvironinenl). AMKfA,^ 

PygmjfVl.3, Frank Sergeant C500 - { 1 > 

A lean, fast I -01111 witji Ml iiHjrct: CivJe. Ind fuU-serBcn editor, 
assembler and metacompilet. Lp 10 15 Ides t^?cn at a time. IBM. 

iCForth, Guy Kelly OSOO - (3) 

A toll Forth syaicai windows, ntousci, drawing and modem 

ForST, John Redmond C700.(1) 
I'onh for the Atari ST. Ind. mmtoc A docs. Atari SiT. 

Mops V2.0, Michael Hom C7 10 - ( I ) 

Close ooutintoYctlcN andNeon. Very fast, comj^les subroutine- 
thieaded & native eod«. Qtyect Qri«itted> Uset F-P coprocessor 

7(<bg., Apple£yatHt>. aigI. tssaablcr.i&Gi Atemdet, mkC 

BBL & Abundance. Rocdy Green C800 - (4) 

BBL pu bli c-domain. 32-bii Forth wiih exten s ivc su ppoit ofDOS, 
melii.ulously optimuced fur execution speed. Aiiundanoe u a 

Eublic-domain database lattEuagc written in BBL Req. hatttdidc 
id. source & doca. IBM HO iard diidt reequlred 



ACM-SIGFORTH 

The ACM SfGFonh Newsletter is published guarleily by the 

Association of Computing Machinery. Inc. StCtFonh's focus is 

on the development and refinement of conoe^, m^boda, and 

leehniques ne^^deii by Tortii professiionais. 
Vnlumel Spring 1989 900-56/7/9 

I'-rc, g[ot,sary uiihty, Euroforih. SIGFonh 'S9 WoiJalKlp 

summary (real-time software engineering), Intel S0x8x. 
VultiiDc 1 Stninner 19S9 901 - )6/f/9 

Metacompiler in cmFonh, Forth exception handler, string case 

statement for l.;F/Fonh. 
Volume I, S3 1-aIl Vm 902 -^Jft 

1 802 simulator, tutorial on inuluple threaded vocabularies. 
Volume 1, #4 Winter l9Ky 903 • S6/7/<J 

Suck franies, duals: an altciriu^WVIliljbfe^PQckelFurih. 
Volume i#Z December 1990 904 S6/7/9 

raiF^««a, td>itiaai 19^K»d«aarGiUiif^ F^'BM& 



Volume I, «3 V^i-WtS 
Tethered Eonfa model, abstracts 1990 SlU Forth conf. 

Volume 2, #4 906 -$6^7/9 

Taiget-meta-cross-: an engineer's viewpoint, single- mstmaicn 
ctifuptJTcr. 

Volu me 3, « 1 Sii mm e r ' ') 1 907 - Sf i/7/y 

Coroutines and lecuision for tree balancing, convenienl number 




IJSg^^Mift WMM^ PrKPftflncs 931 ■ S20/2 1/26 

multitasking, intcrnipt ilriVL-n systems, 
oopsi^iaftenlul^itttil, error recovery and control, virtual memory 
«i|p<M; I^Nit p)i^e^rii^ 



MEMBERSHIP IN THE 

The Fonh Interest Group (FIG) is a world-wide^ ncfi-piofit^ rnanbcr- 
suppori^ organizaiion wiih over 1 .500 rncmbcrs and 'lO chapters. Your 
membership induiJcs a subscripiion lo the hi -monthly magaTine Fonh Dimension.;. 
HG also offers ils members an on-line data base, a large selceiion of Koith 
Ijccrswre and other services. 

Cost is S40.00 ptf year for U.S. A, & Canada surface mail; $46.00 Canada 
air mail; all other countries S52.00 per year. No sales (ax, handling fee, or 
discount on membership. 



FORTH INTEREST GROUP 

When you join, your first issue wiU arrive in four to six weeks; Stibsequcni 
issues will boniiail(^d lo you every oihtrmonih as they are published— six issues 
in ali. Yoo willaUu receive a mcmbcTship tiard and number ^vhi<i) tntiilcji you 
lo a 10% discouni on publica;ions frwn RG, Vout mcaribcr nunr^bcr will he 
required lo receive the discount, so keep it handy. 

Di>cs sxt not dcdudibje a£ 3 chaiiiable con liibu lion for U.S. federal incoisic 
Lax purposes, but may be dcxluciible a^ a buiiiJitsAS expense where applicable. 



P.O. BOX 8231 



FORTH INTEREST GROUP 

SAN JOSE, CAUFORNIA 95155 408-277-0668 



408-286-8988 (FAX) 



Kamc 



Company 
Sireci 



City 



Slate/Prov. 
Country 



Zip 



Daytime phone_ 



OFFICE USE ONLY 




Bv Date 


. - .. Type. ... 


Shipped bv 


Date 


L'PS USPS 


XRDS 


Wt. 


AmL 


BO Bv 


Date 


Wt. 


Ami. 





Item# 



Title 



•MEMBERSHIP 



Qiy. 



Unit Price 



Total 



SEE BELOW 



□ CHECK ENCLOSED (Payable to: Fonh Inlerest Group) 

□ VISA □ MasterCard 

Card Number 



Expiration Date 
Signature 



(S 15.00 minimura on all VISA/MasteiCaril orders) 



Sub-Total 



10% Member Discouni 
Member # 



Sub-Total 



*Sales Tax (CA only) 



Mail Order Handling Fee 



♦Membership in the Forth Interest Group 
□ New □ Renewal S40/46/52 



* Fji closed is S40/46/52 for 1 full year's dues. 
This includes S34/40/46 for I'orlh DimensUins. 



$3.00 



MAILORDEHS 

S*ncf to: 

Fonh imflraet Group 
P.O. Bom B231 
San Jos«, 

U.S.A. 



PHONE OnDEnS 
Caw 4Gft-277-066a 
ta pldca crocTit ca/d 
ociJam or ittf cuBt- 



Hours: Mor.-Fri,, 
BiLm,-5pjn.PST. 



PAYMENT MUST ACCOMPANY ALL ORDERS 



PRICES POSTAGE h 

M ordATS must be pfepaid, Prtc« ars HANJ^UMG 

subbed to diange without notDca. Ct&6\\ Pricos indui^o 

card crdfirs nvitt bo sent and bittad al cur- (hipping. Tho 

rem prices. SI 5 rnmirrHjm on charge or- $3.00 handling 

ders. Chechz musi be In U.S. dollars, lee tfl reQuired 

drawnonaU.S.bank. AStOchargewiHbe wiEh alJ orders, 
added for rolurnod cl>dcks. 



SKIPPING T1M£ 

Soohs in stock are shipped 
within ssvon days of roce^i qI 
the ordaf. P!sa$e aikow 
wooke lor out-of &lock books 
(delrvorlee In mo&t casefl wilt be 
niuch eoorw). 



" CALfFOflNIA SALES TAJC BV COUNTY 

7.5^: Sonoma; 7.7S%: Fresno, Imperitit, Inyo* 
Madera. Vonrerey^ Orange, Riverside. Saera- 
mentg. San Qanflo, Santa Barbara.. San B^irnar- 
dloo, &M S^n ioa^uin^ 525%: Alameda. Contra 
C«ta, AngeliA. San Diago. San Maieg, 
San Frandsco. Sanla Clara, and Sania Crui; 
7^S%: othw counUsfl. 



XIV-l 



Part T'mo of Two 



The Cutly Control 
Structure Set 



Kourtis Giorgio 
Genoa, Italy 



[Continued from the previous issue,,.] 

Create a tJery large table. 7he available memory could consist 
of a non-integer pan of cells. Nevertheless, the definitums 
work correctly and do not corrupt unavailable metnory (this 
depends on the choice mmes:=diff/sl^). 
MaxAvailableChunk (addr size ) 
constant LogosSize constant Logos 
: Logoslnit 

Logos LogosSize Cell SIZE 

LOOP! I off LOOPl ; 

: LogoBackSearch < logo — false I addr true) 
Logos LogosSize cell SIZE BACK 
LOOP{ 

dup 10= 
WHEN{ 

drop I true 
WHEN 1 

(COMPLETED! drop false 
LOOP } 

Sinif)le examples 

10 19 3 End LOOP{ I . LOOP} 

types (19-10)7+3 = three numbers. 'Itiese are: 10 13 l6. 

19 10 -3 End LOOP { I . LOOP) 

types C10-19)/-3 = three numbers. These are: 19 l6 13. 

10 20 3 LOOP{ I . LOOP) 

types C20-10)/+3 = three numbere. These are: 10 13 l6. 

20 10 -3 LOOP( I . LOOP) 

types C10-20)/-3 = ihree numbers. These are: 20 17 14. 



Stibtle exercise 

What gets typed by this phrase: 

10 20 3 END BACK LOOP { 1 



LOOP) 



(Soluiion — the same numbers, bul in reverse order, as 
10 20 3 END LOOP( I . LOOP). That is, 16 13 10.) 

Implementation Preliminaries 

It's possible to implement llie above set of control -n<)w 
words in at least two ditTcrent ways. First is by using the usual 
Forth Dimensions 



words like BRANCH, TBRANCH, FBRANCH, and similar tech- 
niques. 

Additionally, an excellent idea appeared in the articJe, 
"LEAVl^able DO LOOPs: a return stack approach" by George 
Lyons ii'ORMl. l-^eedings 19S2, page 132). it is a pity that 
such a good idea hasn't lx;cn considered modi i n. subset |u em 
works. Briefly, tliai idea con.sisus of compiling after the 
beginning of the control struaure a pointer to the end of the 
control structure (and to other relevant poinLs, like ) LEAVING ( , 
etc). Afterwards, at mn lime, when we enter a control 
structure we have to push the address oftlie beginning onto 
the return stack, along with other things like tte index and 
step values, where applicable. 'Ibcn any word, without need 
of pointers compiled later, can jump lo the tx^gimiing of ihe 
control structure or, hy using the pointer compiled at the 
beginning, can jump to the end or to other reicvant points. 

'ITie above solution, a little mrjre refined, is very powerful 
and provides really new possibilities, like the words AG A INS 
and LEAVES. 1 LEAVES is like LEAVE, 2 LEAVES leaves two 
levels of nested control structures, 3 LEAVES leaves three 
levels, etc. The concept of what is structured and what is not 
is cleaned up and some clarity is achieved. 

Pascal, C, and standard Forth do not offer such possibili- 
ties. Besides (although the code i.sn't actually provided), ii is 
passible to defined "named" control staictures like LEAVE - 
TO and AGAiN-TO. So the sequence abort-CS again- to 
would mean ABORT, while COLd-C S agAIN-TO would mean 
COLD-START. Additionally, OUTMOST-CS LEAVE-TO would 
mean BYE. 

t-or efficiency purposes when programming in machine 
language for typical processors like 68xxx and tJ0x86 and 
using a.sscmbler control structures, it may be necessary to use 
the usual xBRANCH words, providing a less powerful set of 
control structures (but probably more llian enough for 
assembler needs). 

Forth processors, on the oilier hand, are easily adaptable 
to variations of the more powerful solution, sometimes with 
gains in efficiency. 

In this anide, 1 provide two implerneniaiions. One is a 
68xxx implementation of the more powerful solution for 
Forth control struaures. IJecausc the code presented must be 
readable by people using other processors, (iscudo-a.ssem- 
bler code is given where appropriate. So if you are interested 
23 May 1992 June 



please don't panic. found T am able to read 80x86 
assembler easiiy without knowing the processor.) 

Due &> lack of tiine, I have been uiuUe to present code 
for the less powerful solution. For a preview, please refer to 
the code provided in the article "Slack Variables (>Z?XU/1). 

tmpWmeiii&S3.tm 'BxphmaAtm 

The generic conuol slruciure has the following fGi'flB^fe. 
Kx;ipc( MainCode )pppp3-l someCodel 



J]^E$*'Sf someCodeN 



structure 2it^ 1st t CO tfHg filst yi^Otd ^ 

beginning, 

. We have to pii* fheiold oattents of tfteGSP reglstK-onto 

the return stack. 
. We have lo push the contents of die adjusted IP to mark 

the address of die beginning of liie control structure. 
. Haviiig completed the control stmaure stack frame, we 

ism to sEcae iiaa CSf flie awiests of the register, 

teuir% CSP pc»fiE to (he liew ^idti]*©! fama 



xxxx may be any one of CONTROL, REPEAT, CASE, FOR, 
TINES, LOOP, and RECOVERABLY while ppppl, pppp2, etc, 
0a.fcie.afly pcie of LEAVINQ, CQMPLETP?,, QilERp^ etc, 

llot eveiypp^X is applicatfe to every sosda 

So only some comb ina lions are valid. Actually, the 
maximum number of pppp's is two (LEAVING and COM- 
mM^mto^sB&m or LEftVUNS aBrtJ ^^Mmm b^effife^; 

The position of reference points (pppp's) must be re- 
corded at the beginning of itie control struaure, along with 
the position of the end of the structure. 

The controlsiructures CONTROL, REPEAT, CASE, and FOR 
C2n only use LEAVING, while TIMES and LOOP can also use 
COMPLETED. The RECaVERABLX SllUCtlUlfe Caii VMS liEAV- 
ING and ONERROR. 

So wfli cdNTftQli, £^^<3l',^J^, andl^two pointers 
are necessary — fine for the optional LEAVING point (if the 
LEAVING point doesn't exist, a - 1 is stored in the pointer) and 
another for ^^id of the contti^ seucture. See F^iure Two 
to understand the compOatiiW ieEfe<X$.of COl^TROIi, REPEAT, 
CASE, and FOR. 

In TIMES and LOOS', three pointers are necessary — one 
for \be lemttisgpoati, one to the etidof the control structure, 
m$ one to fte completed point (see Figure Three). 

Upon entering a control structure, a 'control-stmcture 
r@tum-stack frame" is generated, A ncQoessor renter CSF 
Ccx%ttro! stm(Siii& framed tes/m&i ^ p6lnr iO) wmii 
frame, allowing access to index values from secondaries 
called within the control structure or, more generally, while 
OSti^ Ihe return stack. ITie ooiitioi-<structure return-stack 
iams is composed of both necessary and optional items, the 
latter depending on ttie control structure. See l-igure I'our for 
a description of the return stack frame in various cases. 

The exact actions we have to takeypon eateiH^ a control 
structure are: 

1. Depending oftthe:flUinberof cxu a values needed (index, 

step, and badscounteir; or index only; or notliing), we 
liavetoad^ttheienimstadc pcAsilitTlxsTessetvespict for 
them. 

2. We have to push onto the return stack liie address 

return stack isx^/mHHskm i^gSERiKsel (ie9l!fedt&ttte control 
struaure. 

3. We have toadyan^e dieiQslcu^ctMim poii^ 



1. Using ihe CSf register, recall the saved value; Ji^.ttss IP 
pointing to the beginning of ihe control structure. 

2. Fetch the pointer compiled at the beginning of the control 

stniOure that points to the end, 

3. $et the IP res^r tp ppitit t<a ibe fm^ wqrI jifier thie end 
#tfetoiiitird stmdSBe 

4. Use the addre,ss pushed onto the return stack diaxpf^iihts 

to the deallocating routine, and jump to th^J foutine. 

that deallocate the space used into the return stack, along 
with the space occupied for extra data like the index, step, 
and badcGOunter. Other control steio^t^mes may have 
much more complicated un-framing actions, (ihe Dex- 
ibWi\y provided by pushing an address of an un-framing 
routine, rather tlian a numter of cells to deallocate, is 
absolutely necessary for other control stmctures Ulce 
RBCOVER|j^,ifl^M{, aM LOCALS J 

Batiotiale for 

The need lo extend the set of control .structures has been 
described In many previous articles. Wliat I'll desaibe here 
are the choices peculiar to set of controi structt^es 
pipposed in this article. 

The idea of iastfig^hesiafte nawie attfiet>eginning andend 
of a control stnicaire simplifies both the choice of names 
when inventing conlrolstructuF^ and their memorization 1^ 

I could have chosen, as in other languages, tO yttiis 
REPEAT ( , . . } or REPEAT begin . . . end without USiQg a 
REPEAT before ^ dosii^li^b^eit 'Si^Me this is possible 
with very .slight mcxlificatBsilsiQ the presented code, I found 
that readability and compBe-diiie error checking are greatly 
enhanced by sjx;cifying what is be^^^fit^a^ and what is 
endii^ instead of asking the programmer to stadc this in his 
brain. If you try to program in C or Pascal, you'll soon realize 
what I mean. 

lliereisntanyrealmasonfor selecting {and \ foropening 
iaiid de^sing symbols ihstmd of ( and ) , or [ and J , or < and 

>, The motivations arc mainly aesihclical or practical ones 
dependitttg on the keyboard used: American, French, Italian, 



Tbe choice to write xxxx { ... xxxx ) in.siead of xxxx [ 
... ixjtxx, or {xxxx ,,. xxxx^, or £xxxx ... }xxxx 
d&j^iods m'^ Uct &m the wend mm^t mMM^^^i^tm 



as xxxx. CSbegin and ihat xxxx ) could be written as xxxx 
In fad, I amttncasin of whliii to 

TIMES ( .„ immi 

TIMES { } 
TIMES { ... } 

Actually, the {xovided code allows TIMES I lUP^S ) 
buial$o,whiled±socuragcd,TIt^S{... }and,stnttia%»f#!^{ 
... WHEN) a$ weU as wssnii ... ) (psesbte ft» weiy short 
vamis). 

§en^{ sndf af&eead as "begtci^ and '^&a4,' 

tlie spelling used is postfix. 

When ycHJ indent vertically, in my opinion 
TIMERS i 
TIMES) 

reads better fliaa 
TIMES) 

Furthermore, locating the braces at the end of each word 
helps indicate that (Jft bfeglnniitigGf (b& GontrQl stmcture is 
really outside the structure, so that in a loop it is only 
executed once. Likewise, it helps indicaie that the word 
cmipiied at the end of the control stniaure is ism^ the 
CDBtreil ^nictui!^ m k is e^maed repeatedly. 

Aboutthe laiffe cKofiaSS, T ha*ertT: fotlnd anything better 
for CONTROL Cany ideas?), repeat and CASE are needed to 
maintain historical continuity. FOR has been borrowed from 
•ffiiif e iaY^pa^ ft slaw^ 

and the execution of any operation. The name FOR cc^^^ 
with the established use of FOR NEXT, but 1 don't think thai 
U-.-i^m^'^&m CPawtdaa^i iSS.aa;^ appropriate as count 
BACK or FOR PREVIOUS, etc.JjNe^theless.if spiiieQnehss 
a better name to propose, it is welcome. 

TIMES is obvious, and reads well. WHILE has the same 
meanitig as tjefore (and gains more flexibility). WHEN is short 
and could be renamed as ?LEavE for darity — but onceuised, 
it i.s a good name. 

In particular, I think WHEN( ... HHEN) read very well. 
1<^P^1®T^{ is long and wo@M he Clearer if named 
lOSOaiiltETIONI, but I don't like typing so much. 
1 LEAVING { means "while leaving.,," and sometimes, but 
not always, could be named } 

Name choices depend mainly on personal taste, and the 
discussion could gotxi forever without being really construe- 
iSsf&SQ here ft ends. 

Forth's main control structure hasnt been ehaitged for 
several reasons: 
Efficfesncy. 

Code simplification (if the TF THEN staicturc generated a 
return .slack frame, a LEAVE embedded in it would iiavc 
the effect of leisvi% IP THEXtitisteadof ^ outer cc^trol 
strudure). 

Presumed psjrchologfeal resistaficse fiiMi iadS^Sd^ 



included) to so radical a change. 

The main reason for leaving IF THEN ufli^hiiaged is the 
efficiency preserved Nevertheless, many complaints have 
be^ raided about its counterintuitive syntax. WMg any 
syntax becomes intuitive onoe it is learned, the time needed 
to memorize asymax depends cm its relationship to previous 
use (usually spoken language). New names for if then that 
follow the presented ^xuax guidelines are THEN { and THEN}, 
wifh the word IF acting like an optional comment word that 
doesn't compile anything. So we could wolsK 
IF 3 X e > THEl^t ... THEN } 

'which is equivalent to 

3 X e > THEN! ... THEN) 

e^j#ad^ tp the classic 
3 if > fp ^msejy 

The syntax shown is probably more teachable than the 
old one. But I resisted ^ WfttiSfegen to rename i, is^me 
my goal wasn't to offer new names for old words bEtlttO a^r 
new possibQities in a coherent, unitary frame. 

Future Dlrecdoiis 

I already have some ideas of how to expand the presented 
control structure set, but I am still experimenting with these 
extensions. When they become more stable, 1 win ptesent 
fifem. MsaofwWte, here are sohie ideas jfe ^irik about. 

RECOVBiiABLY 

code . to . execute 

}ONERRQR{ error. handler 
RECOVERABLY) 

igee piwided code for wiCBs eluddati^^ 

MUniLOOF 

( ( startO stepO startl ateipl .- stiartN stepN ) } 
#t^iRie'3 

multiijCxdp{ ... lO il i2 ^te. 

MULTILOOP } 

Iie^a k>@ptbattak^a vaiiaMe nuir^ers^^aits anii:^^||jp 
and, aiany iteration, moves all the indices together, eachWlh 
its own step, 'Ihc loop must tx; executed #times, 

7JSACK 

Every wOTdtfat allocates a resource (e.g., files, memory, 
windows, hardware, etc.) must place into a stack variable or 
onto the stackanidcntifierfor the allocated ob)ea and ibr the 
deallocating routine. "Leaving tfie TRACK Structure fdr any 

rea,son must have the cffct.l (ifdeaiiocaiing, in acidiiion to the 
return stack, all tfie resources allotted within the above 
stfuctune. 

Tine l.FAVF aaion may be exeaited as the result of a 
LEAVE, WHEN, WKi LE, or similar word, or due to an error that 
happened iaside a word called directly or indirectly withth 
the TRACK structure. (Pay attention to the implementadoci of 



ilrtlelM on Gontrol Structures 



Fori}; Dirriensions 
Vd. 1 No. 3 "D-Chads," Kim 1 [srris. 
V<^. 1 No. 5 Case .siaiemcni ronio.st 
Vol. 1 No. 5 Toiih-85 Case Siaiemeni," Richard B. Main. 
Vol. 2 No, 2 "A Generalized LOOP Oposlnia fat Fonh," BrxsB^ 

KcHnusin Cmultiple WIUL^. 
Yti. 2 No. 3 (^se coiȣSL 

Vol. 2 No. 3 The Kin Peak CODO Con^nKt," David IStsidge. 

Vol. 2 No. 4 'Case StaiemcDt,' Bob Giles Oetter). 

Vol. 2 No 4 "The C*^ SEL, and COfOSi SnKSlwes," PelW H. 

1-lelmcrs. 

Vol, 3 No. 1 "Compiler iiecurity," George W. shaw. 

Vol. 3 No. 3 'Mu%»le 'WHILE* Scriution," Jultm Hayden Qeuer). 

v<4. 3 N(>. 6 ''©Qies ioeiaib]^ 

VbJ. 3 Na ^ "atea^^^l^lQiS^I^ Cassady, 

Vol. 3No. (5*GeneraH2e«lti^SiRStm H.Jr. Fey. 

Vol 3 No, 6 "CA.S1- as 3 D<Aii-:mg Word," Dan I/^mer. 

Vol 3 No, fi "Eakefs CASH AugiTtcntfd," Alfred j. Monroe, 

Vol, 3 No. 6 Tran^rtable Control Structures wilii Qom^lN 

Security,* Marc Perkel (LEAVE discussion). 
Vol. 4 Na 3 ^orfli-83 DO LOOP," Robert L Smith. 
Vdi, 4 Ko. 3 *Toith-'^><ompataMieLEAl^ for Poitlv€3 OQ IQOPs," 

Klaxon Sural te. 

Vol. 5 No. 3 "Yet Another Case Statement," Marc Pejkel OetCer). 

Yd, 5 No, 3 "RPN Blues—Revisited," Horsi G. Kroteer. 

Vd, 5 No, 3 '■Fonh-83 Standard," Robert L Snjjtb. 

Vol. 5 No. 3 'Forth-83; a Minority View." 

Vol. 5 No. 4 "Fofth.j^ loop a3SiaW»i» BUI StcxWard. 

Vol. 5 No. 5 "^IRtfiki "^SI^CTOlf 

Vof^ 5 No, 5 *A More Gettera! Sc&nf d!elM>^ 

Vd, 5 No. 5 "Just One Exit in &se," Ed S^lfpiiKfi OaVSr^. 
Vd. 5 No. 6 "Do.,, When., . Loop Construct," K.'W', Gia.y. 

Vd. 5 No. 6 "DO... LOOP 83 tjution," Nitiiolas PappaS. 
Vd.6No. 1 "Pamas' jt,,..tiStruaurc,° Kurt W, Luoto (subcases iCXJR 
CAND). 

Vei. 6 Nq. I "Mcne oo WITHIN," Bicb QmeO, 

Vol. ^6. 'ZlPtWIf CiOli^SBM^^ Hartalsdn. 

Vd. 6 No, 4 «ANDIPl^il^*EW»nLE," Wendall C. Gates. 

Vd. 6 No. 6 "Enhanced DO tOOP," Michael liore (falltliroughi); 

Vd, 6 No, 6 Techniques TutoriaL YAC'i,' Henry taateo. 

Vd. 7 No. 1 "VACS, part two," Henry Laxcn, 

Vd. 7 No. 1 "Another Forth-83 LEAVE,' John Hayes. 

V(rf, 7 No. 3 "fayjfcivecl FotHaSS, DO LOOP," Dennis VeudA. 

Vd). 8 No. 4 "S^botid Takfe MalHfjIe ti>3^ 

Miller (letter), 
Vd. 8 No. 5 "Lritimate Case Sutement," Wil Baden. 

VdL. 12 No. 2 'immaivs Gocml smxtms,' jobn r mj^- 

FORML Proceedings 
1981 "Unravel and Ahprt Improved Error Handllt^ for Forth," 
DaiM'^ndtoa. 

1981 "A Generalized Poith Loof^ StracUre," Itobfert Berkey 
CCOUNIS RANGE). 

1981 "ConiprehenslUe Conbot Stnictuw^* HOH^Jr. Goodell 

(new syntax). 

1982 "Non lriimi.-di,iif l.tjopin^; Word';.'' 

1^ "LEAVEabje JDp LOOPs: a Eetwn Stack Appioadi," George 

1983 "Modem CScntrol Logic," \Pit Badsa 



1983 "Error Trapping, a Median i.sm Tor Resonnqg Esecotton at a 
Higher level," Klaus Sehlei.siek. 

1982 "Proposed Kxioiisinns to Standafd Lpop SQtKttif*^* Kim 
Harris and Michael McNeil. 

1983 "User-Specified Error Recovery in Fonti," Don Col burn. 

1984 "OouUiqg ifae Speed of IndeOoite Loc^' Michael McNeil. 
1984 ltq>iow«iKflt Prc^io^ f<»^ DO -i-IjDoP StnictUfl%* John 

Bowling. 

1984 T« Another CASE," John Rible. 

1984 "Error I rappinR and l/x-al \'ariables," Kkus-ScUelSk*. 

1985 "Interpretive Ixsgic," Wil Baden, 

1985 "Improvements in Error Handling," Loring Cramer, 

1985 "EiTor llandiiag Using Standard Compile Oitoctives," Frans 

19H5 "Exte^niyi^ ^(tfiV CQiatti@l Stfo^^ ims l«3rg!tiage 
Hcqufi»b!t&ils of the 90^5 * Da^ W, flarials^^ 

1986 'Charting, Escaping, Harkini^, Leaping Forth," Wil Baden. 

1986 "Extended Forth C^ontrd Slnjclures for the Languages Re- 
quirements of the 1990''5,° David W. Harralson. 

1987 "Loops and Conditionals In LaForth," Robert L. Smiib. 
1987 "imorpretiag GontK>l Smtctores the JSlj^'Wafy," Midi Bra- 

dley. 

1987 "Ftarth Cootrd Structures for die Language Requirements of 

the 1990's," I")avid Harral-wn. 

1988 "GOTO: A Proposal," CH, Ting. 

1989 "Have Dot-if tJot-i^l.'^e Llot-then," Klaus Schleisiek-Kem. 
1^ Contrcd-How Words from Basis 9," WU Baden. 

1989 'PaitM^yiitdiing fti Iferthj" Bnad Rodriguez (interaction 
between oontR^ stracxtBe^ aiid^ttetti matdilnig). 

Roche^tatPotA Conference Proceedings 

1981 'Transportable Control Structures," Kim Harris, 

1982 "*lhe Importance of the lioutineQUIT," Hans .N ieuweahn^en. 
1982 'Techniques Working Group," Uieks J<Lx«*en. 

1984 "Hello, a Hcplil I AM," Israd Uriel i, 

19?S "KEvised BEcursive AND? 'SEPHL OS* Israel UtidU. 

IS^ "Do-Loop Exit Addrc.'vs Id Return Stack and ?leave." 
1988-89 not available to author 

1990 "Non-Local Exits and Slacks Implemented as Trees," R.J. 
Brown (abstracO- 

1990 "Gryptic GMiamet^" Bob Spwfc 

Dr Dnhh'^ Journal 
9/83 "Non-dele rm in istic txxitrol 'tf'ords in Forth," Louis L, Odette. 
1/84 "N on -determinism Hcviiiied," Kurt W. Luoio. 
11/86 'Extended Control Stniaures," Wil Uaden (letter), 

"Adding (jdSUB to Bbtth,*Mk^iadTTam. Computer language 4/ 

86. 

"A b'asL and Versatile Control System Using High-Level Program- 

luing," I Ohel. Molorcon 81 Conf. 
"Exiensibilily wiili l-ortli," Kim R. Harris. lYoceedings of the West 

Coast Comljuter faire (date n/a). 
"Dau Structures Issue," James BasQc.Jwmai<^ForAA0>lkafion 

oadMeseoft^ vdL 2 No. 1. 



Ji4ay 199?J!iJm 



2$ 



Figure Seven. 



xxx^ ( S ome C ode 1 WHEN 

SomeCode2 WHILE 

SomeCode3 WHEN { SomeCodeS WHEN } 

SomeCode4 WHILE! SomeCode6 WHILE} 

SomeCodeV } LEAVING { CodeToInsert xxkx} 



Figure Eight. 




xxxx [ SomeCodel 


WHEN{ 


CodeToInsert 


WHEN} 


SomeCode2 


WHILE { 


CodeToInsert 


WHILE} 


Some Code 3 


WHEN{ 


SomeCodeS 


WHEN } 


SomeCode4 


WHILE { 


SomeCode6 


WHILE} 


SomeCode7 


xxxx) 







Such an error, besides resuming exeaition at tlie level of 
the first enror handler above the TRACK structure, will also 
have the automatic effect of deallocating the resources 
allotted within that structure without leaving open files, 
unused memory, etc. In addition, if the TRACK} word is 
reached, resources still left intact will be deallocated auto- 
matically. 

LOCALS 

Tlie locals solutions can be viewed at the internal of tlie 
control structure frame. The syntax could be; 
( X 1 o ) 

L{ ABC — ... code ... L} 

Conclusions 

I hope to have shown that liie presented control structure 
set is easy to use and tea rn, powerful, expandable, uniform, 
and unifying. More work has to be done on the RECOVERABL Y 
and TRACK structures, and on the parte m-matc hi ng problem 
that is related lo control structures. Is anyb(xly willing to 
implement the above structure set for tlic 8086 processor on 
anotlier system (F-PC, for example) and to present the 
developed code? Does anybody have any new control 
stUJCCurc? 

Has anybody encountered inconsistencies in the above 
set of words? I would be very glad to discuss the positive and 
negative issues of this wordset and any problems thai remain 
unresolved. 

Speculaiing on the struaure of Forth engines, 1 believe I 
have found ways to render these control structures "pipeline- 
able" and as efficient Cor more so, due lo pipelines) as normal 
brandi words. If fact, variations of the above scheme arc 
easily adaf^able on some Forth engines to mn a.s fast as their 
branch cquivalenL*;. For stmctures like BEGIN WHILE RE- 
PEAT in particular, pushing the address of the beginning of 
the structure onto the return stack meaas that, without 
compiling offsets, the code is relocatable automatically while 
given the efficiency of subroutine return (or better program 
cou nter load from the top of the return stack); and we are able 
with "slight" processor modifications to execute an AGAIN 
concurrently with some other data stack manipulatioa 



Does anyone have the ability to do benchmarks of various 
solution.s? Are modifications needed to achieve maximum 
performance? 

How does this wordset compare to other solutions in 
Forth or, more generally, to the control stmctures of other 
languages? Are there ideas to borrow from other languages? 

If, as is the case, flexibility and freedom are the best 
characterisitcs of Forth, let's use them to our best advantage. 

And yo conclude our story: 

AUIKOR 
(tired, observing the reader) 
Do you like all this? 

READER 
(thinking) 
Hmm! Have you got the code for this? 

AlJ'mOR 
(serious) 

Sure, on the following pages!. (Becoming impatient) But 
tell mc, do you like iL' 

READER 
(smiling) 

Let me try, my friend. I'll try the code and tell you. 

AUTHOR 
(thinking silently) 
. . Forthcrsarc never salLsfied. . . very, very strange [X^ople. . . 



ADVERTISERS INDEX 



Delta Research 15 

Forth Dimensions 22 

The Forth Institute 44 

Miller Microcomputer Services 5 

The Saelig Company 13 

Silicon Ctom posers 2 



Forth Dimensions 



27 



May 1992 June 



\ When tfe size is uci^aBcifipd iJefauit is ipng* 

\ V& O mem' tt^^ase'tiwljy '^tf^-'immf'* ^'itiot^roeim^t'^' "leng. meive," 
\ The assBmblmr chooses a 1 Nays tiest -form for ins.tnjc'bian ^ 
\ That means that add, rr^y compile 

\ addg ( add general ) addq ( add quick ) addi ( add imrnediate ) 

\ and move may compile tnoveq ( move general ) moveq ( move quick to data reg ) 

\ Or movei ( move immediate ) . For address registers , size is ininf luent 

V so a long inviri^Mte .nmtst cmif4^Xf^ ss,. w^iCf i.qi0pjdi!att{^ mr^: 

\ md a IctnQ ^^^'^ i Adl^ ^iiici#«issf -reft^jtar" i ■imsjf' 'his- jcanpilfiKl :«».>v«3rd 

\ imnecliate adda t i'f the imrediatie valtn is smal l errau^ K 



s 03deActctraf ( "naiiie"lri|3atstmam 









m 




macro: 


OldCSF 


en esF 






macro: 


releaser 


619 CSF 


I) 


isacro; 


fflaeroi 


index 




i> 


mat:riQ| 


macro; 


step 


BE CSF 


I) 


macro; 


macros 


Counter 


12 CSF 


I) 


macTOj 


macro 1 


OldErrorCSF 


BE CSF 


I) 


macro; 


macro; 


□IdSP 


12 CSF 


n 


macro; 



Pfa ) ' cfa ^compile] literal ; 

immediate 
\!S$mer^^'Wstam -S- ism m^mmistsM 
\. --v#t#ti 'flitake reference th# sitieiim' mit^' 
\ if means in forth pseudoccxtej 
\ "CSF 1 +" 

\ Step and cpunter are used by the 
V laap structi«re. 



\ by the recoverably strucfa^^. 



variabl e 1 astErrorCSF 



macro: IPtoBegJLn&ngi 

CSlsegterSfig'. JP l>- 
CSF RP 1> 



lastErrorCSF off \ Contains the value of the CSF of the 
N last RECOVERAa_Y structure- 
\ Set the instruction pointer to point to the 
\ laeyxmng of the oantrol slanjEttire **taie 



macro: 



\ reseting the return stack to be as Mhen the 
\ control structure was entered. This is necessary 
\ to al low an AGAIN beeing executed by a 
\ secondary called within the control structure. 
\ without filling the (i^g^itac:!^ wl^ urmecesssary addrssBe^, 
IPbeg>end, -2 IP 1} iP w. add„ ftmrm 
\ Assuming the Instruction PctinidR^ ( tP } pioin'^ Is the begining of th& control 
\ structure roaKp St point af ter the end of tJie control stmcturw i figurs 3 ) 



macrdl unframe, ( *tof __extra_cells_onRS — ) 

(31tESF CSF 1> S Bestore the pld contents oi the CSF register 

■cells SSft + ^at RP ad^V V't^SflB ft^tt^ Ihff i«(^S3trn Siack space 
macrtti \ iised ?e»" the contrcfi structure^ 



create releasers 
code Bun frame 
code lun frame 
code Siinframe 



B LBiframe, rts, 
1 unfrane, rte, 
3 ynf rame, rts. 



code RECXfcOV^BLYrelease 

LastErrorCSF fifxiiy aS lea, 
oldError-CSF a0 t ) IJ- 
3 unframe, 
rts, 

\ code otherl^leasers . . . 



e-id-ccide \ LJnfr=mB a return 5tack frame 
end -code \ where the 5p.ace occupied by 



«nd-cade 



\ extra values ( index S^p ecc ) 
\ is of , 1 or 3 cells. 
\ More elaborate behaviour to 
\ unframe a recoverably control 
\ structaire frame. 



end-code 
€nd— code 



macro: frame, [ releaserAddr ttextra eel Is onRS *tof _coiT)piled pointers ) 
>r ( tteKtra_cel lB_anRB ) cells tttt RP w. sub, \ Reserve space on RetStack for Extra cells 
{ releaserAddr ) releasers - 4Mt w, rpush, \ push offset of un framing routine. 

\ Make the IP point to the first Mord 
% after the control structure start. 
RP ^SF l> 
set new CSF 



r> ( tof^compiled^pointers ) 2* ## IP w. add 

1^ :'»T3!JSihjj, 'IP ^rmsm*- 
\ push:' mitS 'iSS^ f*iKsti sl^arir- fP 'adt^ 



May 19^ Jung 



m 



(nitcroi Rescxirces8f?Sre lease, N execute the unframing routine 

releasers Ape I ) A(S lea, \ Load A0 with the base addr of unframinq rcxjtines. 

releaser w. add] \ Add the unfrantxng routine offset to the base addr, 

fiB ( } J'sr, \ Juitp suisroutlhie to ttie raut^nB. 

ccxie LEAVE IPtoBegining , IPbeg>end, Resource^&PBre lease, next, end-CQde 
\ (iiDve IP to begining. Move it to end . Execute unframinq routine. 

code f ramBeginirv^eave IPbeg>end, Resources&RSrelease, next, end-code 

\ spHifiAl casB fnore efficient LEi^ytE 

\ jieeing at ilhs begining of the cmtrDl structure vm wsfit to junp ^ 
\ tlie LEAVING a3*PLETED or similar points if they eKist. 
S Other wise LEWE the control structure directly. 

macro: f romBegl^EXTtoRef erencePoint, ( of fset_af_pQin ter_tD_ref . point — } 
( offset = -2^-4,-6 i IP I) d0 w> \ offset IP @ + w@ dB w! 
GK', CddeAifiSHIIf' fmtkeiiSSsrtfr^lUeiscim' C3Q^^h', m pitm:iiiW^. f^ i^emm 

\ or CQ-PLETEB. UStM OUt dlrsctly. 
d0 IP w, add, \ move to the referenee point: d0 w© IP +! 
next, \ airvd continue exetitititin. 

macro J 

macroi frtxn^ieigly^irrtdLeaving, ~4 fromBegNEXTtoRefer^nc^bint, maerDj 
(liDcm: f rdiTOegfCXTtttDsinplet^ , --6 fromBegNEXTtoRef &-encePtiint , macro; 
inacro: f ^□mBeg^EXTToOnError , -6 f romBeqKEXTtoRef erencePoint , macro; 

\ Seeing at the begining of a control structure go to a specific reference point. 

code NegError error" , Mtimes is negative" end-code 

\ from assanbly xssub an error message. 

macros NqNeQativeTimes, B<, CodeAddrOf Ne^rror CX^atn^anch, macro; 

\ if t*(B conditidn code flags sigrial a negative value issue an error tapssagie. 

macro: OnlyPositive, NoNegativeTimes , if, next, then, macro; 
\ If the Ccnd pode f lagis js^^i^gn^l a n^Sf^tiye tymtil^Br issmef ^an error « 

code LEAVES { tttimesToLeave — ) 

dl pop, Onlyfositive, \ continue only if the tttimes is positive 
dl Mtimes<, IPtoBegining , IPbeg>endp FiesourcesfiJ^Srelease, Mtimes>, 
\ Uhframe the retMm stack for ^tiinesToUeaye times • 

encH:oeie 

code AGAIN ( — I IPtoBegining, next, end-code \ Continue from the begining 

\ of the control structure, 
code AGAINS ( 4ttimesToAgain — ) \ Resume execution from the begining of the 

cEt :0apf ' tlntyPBeiti^w*', %. i». lea. mMk nH#T efciiiaf .con*if©,l .iStructure. 

{^i j^times< , Resnurces&RSreleasier wtim»> , \ So izjinS^ftJ^. #l^%tc^re frames 

IPtsBegining, next, \ fnust be unframed. 

end'^ode 



code iSIM=LJEt) ^ — ) \ It gets compiled by CO^fTROLt or REPEATC - 

GddeAddr^^ aanfFame ( releaser ) { extra v*lt»s > Si (; fpiaintsarw ) fr^We^ 

next, \ vihen we enter C0N1H]L or REPEAT we have only ho make a eontnal structure franie. 

^nd-code 



Mety 1992 June 



code (INDEXEDO ( value — ) \ It gets compiled by FORi or CASE( . 

CodeAddrOf lun-franie ( rele=3&er ) 1 ( extra value ) 2 ( ^pointers ) -fr-ame, 
index pop, \ when we enter FOR dtnd CASE besides making a control structure frafTie 

next, \. rismr^itig ^pace for tihe iXTX^n ms have to oet aiie Xirtitlal iivie^ yalyfe, 
end-code 

macro; TConpIeted, ( — ) a<, if, f rofnBeqNEXTtoCompleted , then, next, macroj 
\ if the backcounter is negative the Loop must go to the COfPLiiTED clause or 
\ ii CXfPLETED doesn' % exist it must i£ftWE the control structore. 
code (TimSi,) 

'C^xtef^iddrdf iiiTifj^^ttne i ■t&lmas^ ) t f \^i;tite' 1 3 t' iiaeinters } frame, 

index pop, NonegativeTimes, \ issue error if negative Mtinies. 
1 #M index sub, TCompleted, \ predecrement ths backCounter and if it is 
end-code \ go to EOffLETEO i of leav« if CSMFISED is absieit ) 

code (Tir-ESJ) 

IFtoBeginirMgi^ \ set the IP to ttie begining of the control structure* 

end-oode \ to ca3*VETBD t or tesvie if CCHJt Ftt* doei^i't ^ist ) 

code (LOOP() ( beqininq tttimes step — ) 

CodeAddrQf 3unframe ( releaser ) 3 ( extra values ) 3 ( ^pointers ) frame. 

Step fiEpi -smmtm- pop, NdNegatlveTime^:,, irtden pop, 

X m-^^iamtBr- sub, TCsmfUm^t 
end-^dcfe 

\ iiiake the control structure return stack frame reserving space for 3 extra 

\ values. Bet the step value set the backCounter value ( checking that it isn't negative ) 

\ set the index starting value), piriedeerement the backcounter valu# 

code (LOPPJ) 

1 ## catnter sub, ^(jampleted^ \ Add the step to the index , decrement 

end-code \ the backCounter chieck it ecc. 



code (RECOVERABLY( ) ( — ) 

CodeAddrOf REaavERAHLYRe lease ( releaser ) 3 ( extra values ) 3 ( painters i fraBie,, 
lastErrorCSF Ape I) A0 lea, V Save the old value of the variable oldErrorCSF 



SP oldSP l> 
CSF AB () 1> 
index clr, next, 
end -code 



^, ism,. *#l3yrrt; s*^*-, m Wi -m^^- value. 

\ iet t»*. heM value of the otdErrorCSF poinft to the aetuat 

\ return stack frame. Set the initial value of the index 
\ to . The index cconts the tttimes an error occured Luitil 
\ now* 



code ERROR 

repeBit< , la^tErrOrtSF 

Resou rces&RSre 1 ease , 

1 4»# index add, IPtoBegining , 
end-mde 



CSF cmpi <>, while, 

repeats, 
fr□mBBg^EXTto□nwrar, 



% XMi^f^. stack to 

\,.fHj0aph' ^^Nb mi^Hre- ' recently' 
\ set error 'handler 
\ start executinS- the 
\ OvERROR clause. 

code imfW t flm — J is '$rmr if the flag is 

d(3 pop, thd^itidrOf m<m CCabranch^ m»t^ \ true. 

end-code 



code ErrorPropagate 
nesourcesSRdreltense, 
code 



alnayS) GgdeAddrOf 



\ BackPropagate the error to 
GSaarar«b,\ the preNfiauB errtsr hsnctler. 



code Stac knar k ( 
code StackRestore { 



) SP oldSP L> next, end-code 
) oldSP SP L> next, end-code 



\ reset the stack to the level 
\ It had when the ferro*" handier 
\ had been set. 



May 1002 Jam 



code 14-EN ( flag — ) 

end'-eode. \ if -fcte fiag i« ^^vm ga t© 'tfl© t#iifiBNIi! t^aima tsr !%■ .ifeiean*'!- w«iftt ^tl^iME -lifcie 

code WHILE ( flag ~ ) 

d0 pap, 0=, if, IPtoBeqxrjing, froriBm^tCXTtdLeaiVings then, nextj 
end-code \ ^ame as "B= UMEN" 



2 «» TP ada, " compxles addij. 



maicrt)^ "Spiti^, t ccndition — ) 

if, 2 *» IP add, nent, 
IP )+ IP w. add, next, 
macro; \ a word pair beginner ( like Ul-EN{ ) has to decide if the code between 

\ the word (Dair has to be executed or skipped. If the qonditton is true 

\ we execute the code between the word pair, 
code (M-ENC) ( flag — • ) dB pop, 0<>, Tenter, end-^ode 
cadB (WHILEO < flag — ) dSi pap, Q>=, '?m*m't end-ca^ 



dQ pop, 



( number _ta_cofnpare_aqa ins t_ index ) 
index dB cmp, =, Tenter, \ execute the pair code if the index 

\ equals ttie stacM argument. 

\ Forth definition of IffipiN Ist 

\ t WITHIN ( value lower Misuser > I3(*er - >R - R> U< j; 
\ That means: rieailt =* ft^libw) IK W^ly^-l^J 

\ If you design numbers on a circle in a cot!n.^P*5clockwise nvanner 
\ value is WITHIN lower and upper IF PND CttJif' IIP starting from lower 
\ and moving on the circle in a caunterclockMi^ iftaiTHer yoii find Value 
V strictly before then Upper. 

\ ( the starting position must be checked first } . 

\ So lower=^ value=10 upper=23 is c^acy 

\ lower=23 value=23 upper=3GJ is dkay 

\ lower=10 V3lue=30 upper=30 isn't okay 

\ Iower^321 valuer- 10 upper=-l is okay 

\ lower=34 value=-3a uppBr^30 is okay 

\ iQwerHS value=~4 upperN3 isn ' t pkay 

code (WIIHINC} < lower upper ) ( d0:=lower, dl:=indeX» d2t=^i^er ) 
index dl 1> d2 pop, ( upper ) dO pop, ( loMer ) 
d0 dl eub, d0 d2 sub, \ subtract lower from both index and upper. 

dl d2 U<, compare, Tenter, 

\ above line is efqui talent toi dl d2 cmp, CC, Tenter, 

V That means in fc)rth pseudocode s dl @ d2 @ - U< Ifenter^ 

\ Wm esMj^ ^^,m^ ■i^.ysuSstFm^^fm i'^^ -PScte is unne^i<g^t tut dae^""1|: nptter)':. 
code rawtN { numl nuRiS ... numN PI — } A subject on SKl result en dl. 

a0 pop , \ keep in a0 the return address . 

#tt dl 1> d2 pop, C d2 contains the counter ) 
\ Loop on register 0Z:,. If at start d2 is the Loop isn • t done* 



\ d2 e Umes< 
\ IP & 9 m ® - 4 3=' + i 



d2 wtime5<, 

3i+ m e«p., 

a=, it, -I m dl L> then, \ jSSM i# -i dl 1 then 
>^mes>, A. ^tiSne^ 

a0 () iwip, \ r^tMm from subrpatine. 
end-code 



dpde back IN ( numl nun^ ... nunW N subject — flag W group subject — flag ) 

dia fisiPj CDcteAddrOf rawIN iPibsr, push, neK%, 
end-ccxJe 



31 



May fSiSiSJans 



; IN ( subject numi num2 ... nufrivj N — flag ) ( subject group — flag > 

dup i+ pick back IN riip ; S Daing FO_L wcAjld hiavi? fcx^c^ i unef f icienl.. 
code ( INt ) < numi nuni2 . . . nunW N — ) 

index rf0 1> CodeAddKlf rawIN Absr, dl tat, BO, Tenter, 
STVi-cocie 

\ To use irM( IN) ecc zonsd.dmr to define C ( and ) ) . 
\ They may be defined as 
\ Svariabie QidDepth 

\ ! ( ( ( — } depth QidDepth puaf* | 
N s } ) ( — ) d^th QidDepth pop ^ { 

\ dr ydu aren't familiar with Stack Variables as described in RJ XII nisnber t 
S ycxi may thi^ alternative def initicxt ( that alloHS fpr riested (( and )l t 

\ vmiABLE O-DDEPTH 

\ s ( ( ( — X ) DldDepth & depth oldDepth ' ; 
\ t )) ( X ni n2 ... rtSf — nl n2 ... nN N ) 

\ dHpth oldflefttt* e - {*ufi 1+ mil OidDec*h ! ! N "l RQU-" hwmib swflP 

code I t — IndexValue ) index pu^h, next, M^dHEddit 
ccade TO-I ( newvalue — ■ ) index pop, next, ertd-cdde 
code STEP ( valueToAdd — ) \ "STtP" or ■'+Ta"I" 

d0 pop, dO index addf next, end'^ede \ add to the index a value 
code J ( — IndexValue ) 

0A as I) pMsh) \ Attention no information localisation, 
next, \ Value OA is that of the "index," macro. 

V Better hut unef "f icient definition is; 

S CSF a0 1> QldCSF CSF 1> index, push, a0 CSF 1> next, 

end~code 

S Full compile time error checking is provided. 

\ iKt iMKy syrfiax ii> f;^^ided to cons^truct new cmti^l stryctunss. 

structureC BegStructure 

cell: >BegToken \ the words >begToken >BegStarter 

cell; >BBgStarter cell: >BegEnder \ >BeqEndBr are equivalent to: 

ceil: >Beg4tpointer5 cell: >BBgAppl icableMidS \ CELLS + 1 CELLS + 2 CELLS + ecc 

structure) 

S. the abqwi} stTMcture is tipd to structure beginer words liK? CfiSE^L TifE5(, ecc. 
\ tfe f^jeid >'SBqfdH.en contains the token of CSftSEC or TtHfeSf or vhsti: is the tase. 

\ the field >BegStarter contains thie token of the word to ccDmpile at the m'trufetw*^ 
\ begining ( (Sir^EO ( INL>EXED) (TI^ES{) ). See figures 3 and 4. 
\ Ttie field >BegEnder cofi tains the token to compile at the Caantnol strucixire and 
\ C words like LEAVE A6AIN (TIMES)) (LOOP)) ) 

\ The fSmM ^^^e^SPi^^mr^S'^smii^i^ Wm' # lof pointers. tcJ .reference points, to 
\ 'poptil^ at t^. ism^re^. ^trtic^tur^ iet^iiii^^* 

\ the 'field ^jiEaig^ipp-iis^itilMicte isf a bit ietrr^ thail^ -^aeCM^em wiislt etaOBes 

\ like LBfSMINB EJWPLETED eec ana applicable to the cxmsidet^ aantrol structure. 

structuref mid){Structure 

Gellt >iiiidl1ask cell: >midPointerOf fset celli >mic^ider 
structure;]' 

\ The above structure is related to the clause words ( like )LEAVING{ )COm_ETED{ ecc ) 

\ the >micfl1ask field contains a bit Arrs.y with the bit associated to the clause 

V word on. The field midPointerOf fset specifj.es the offset ( --4 for LEAVING 

\ and --6 for COMPLETED ) of the pointer at the begining of the control structure. 

\ See figure 3 and 4 

variatile Seg v^isiHAm CSbegining variable trader 

\ Tree variables *B hOld the token of the start word of the last 
\ control structure under construction, the address of the begining of the 
\ control structure and the token of the word to compile at the end Of the 
\ eoitrol structure ( like LEWE AGAIN (TirtSJ) ecc ) . 



M0y I^S Jtim 



32 



: BegAdttr ( — Adclr ) Beg @ >ixMy-' } \ 'BSa/m 'tti»' ^/tS^^maim- 'of 'BHistnicture assaciatecf 

\ ¥iiih tHe last controi ^tructn^. 

: I<!jeep8c! ( Ne^alue acktr - — OldValue ) dUp @ >r I r> ; V Store a new value into a variable 

\ holding the old one on the stack. 
! of Spain ts ( a#fSSii;^of_pointer addr_to _point ) N Set the painter compiled at the start 
CSbegining Q — SMap CSbegining @ + w! | \ of tine control structurw to point to 

\ the sjp^ified address. 

: ofspoints? ( of f5et_Df_po inter — flag ) \ Does tt^ specified pointer point 
CSbeginirig 6 *• wi -1 <> ; \ already soniewhere? 

I tSSsegiflt ( BsgTokiBn — ) \ given the tokerv of Uie control strxcttw^ beginner 
>body >r 

r© >BegToken <S Beg KEEP&! \ set the Beg variable accordingly 

rS >BeqStarter 3 token, \ compile the Associated starting Mdfd 

r@ >Begttpointers @ DOold -1 w, LOCFold \ set to -1 the initial pointers 
here CSbegining KEEPSt'. \ set the CSbegining var to point here. 

r@ >BegEnder 3 ender KEEP&! S set the ender var lattle. 

r> drop ; 

: CSend ( — ) ender @ token, \ Ckampile the ender token 

-2 ( end of structure ) here ofsPoSntS \ make the painter to end point point to the end. 
ender i CSbegining ! Beg ! | \ Restor the old values of the 3 variables. 

t &s^lm,t t yaltMB^; , . y&Hi^. ttcel l^To^tampile — } V coffliif^lP # certain niimber of cells> 
hsm- swap &ei\& alio*, here cell- DDold laid ! -tis^t -fUDOPold ; 

\ The use of this subsequent word like: 

\ create CONTRQL{ ' CXJNTROLt ' (BirPLEl) LEAVE Midsl ' >LEAVire( Mids) Begls 

: Begls ( dataToFi 1 IBegStructure ) 

5 cells, imnediate doee> TCocnp >BegTol^en @ CSbegiji ; 
\ compile the 5 structure parameters declare inntediate the structure beginer 
\ previously created* and declare it to □□ the code after dams> 

: ender Is ( corresponding Beg — // "name" -IS- ) 

create , i(«i»diate does> ?co«np @ Beg S <> ?abart" Ender doesn't maches Beg" CSend i 
\ dedans a jcontrol stnictiure ender Mord associated tP the beginner. 

t 1 ^^comp @3end ; iamaiia^ \ Ssnoric ending Micirid to be 'usiiii. Witb artV 

\ cdrttpol stFuctaire start Or lediv^ig pair. 

Clause words ( as )LEAVING{ and >COHPLETED{ ) have a certain bit number associated. 

When we define a CLAUSE word we must "allot" the next fn(» bit nu*nber for the clause. 

vmm m^ti^W^ ^ pi-mme' ^aur'it:^^ .cipin^l.atli3rf' mimek^ tt4a% 'm$ tare; ;£ni^ cipfflpiie' 

stat^^ ctieisk. t^t' the ;cy!|j9E %•» a^lieaibAia to. -tiin: ad^i cqntroi structure^. 

check that it hasn't been already used , it must compile the endi^ token set 

by the control str-ucture beginni^r , it rrny^vt the associated pointer compiled at 

tl-e control structure beqining (.xDint to HERE and finally it must set it s CMfi ender. 

variable midFreeflasK 1 midFreeMask i 

: mid>(Is C midPointerOf fset midender //IS "name" ) 
create midFreeMask dup , 2# midFreieMask '. 2 cells, immediate does> ( addr ) 
?comp S check campilation state, 
dup >midmask @ begaddr ' >BegAppl icableMids @ and \ is it applicable to this CS ? 

0= Tabort" midEnderBeginer isn't applicable to that control structure" 
(kip >(iiicFointeraffset e ofsFtoints? ?abort" mid>t already applied." 
dhder et token , 

dup >midpointerOf fset @ here ofsPoints \ set tJ» pointer point here 
dup >midender S ender i \ set new ender 

mm I 



33 



May 1902 Jam 



-4 ( midpointerOf fs^, Jf ' tljsi^ ( midermsir ) ni^diMfe ^LmMmt 

-6 ( inidpointerOffset !f * liMl^ ( midencfer ) midJtls >tXm.£TED{ 

( midfxjinterOffset f ' SESCFPFiGPAGATE ( midander ) iiiid>CIs >a>£PFiQR< 

: hidBf ( — 0)0; 

: Mids) ( a nl n2 . . . nN — ) 1 ( #pointersUt_least_cne) applicableMask ) 

BgSlNQld rot rt^p WIL-Bgld >bqdy >midMask @ or st^tap Si+ swap REPEATold drop ; 
\ . i * ^Sdsi J.*i i^t^ *p ei3n?s%nti£;t the mask ;pf #w cantrol structure applicable 



create QQNTiP-i * CCI41Ba4 ' (SI|-PtE{) ' Uafm. MidaC ' JUB^JNBt MidsJ Begls 



create REPEAT( ' REPEATC 
' RQSERtTt Ehderls FJEPEPfT} 

create ' 

' CASEC Ertc^ls e«SE> 

create FOR( ' FORf 

' FDRC Enderl^ FOR} 

.c^mam. TIMEaC ■ TlFIESt 



create LOQP{ 



LCOPi 



(Sin=LE() ' AGAIN Mids( ' }LEAyI^G^ Mids} Begls 
iltHDmsmi ) ■ imJE mdst ' JL^/INBC Mids> Begl* 



i litcfej BaglS ' tidteSt eider Is TirtS> 



(LOQPO 



(LODPl) 



create WI-EN( ' WHENf 

' WHEN{ Enderls WHBJl 

create UHILE{ ' I*H1LE( 
' WHILEt Enderls WHILE) 

create ONt ' 0P*{ 

' mi epKtBTis mi 

creatte %m ' IN{ 

' IMC EnOtsttn im 

create WITHIN( ' WITHINt 
* WXTHINt Enderls WITHIN} 



Midbit V&dSki Begils 



(tMIL^i ) ' um/E MidsC Mid5> Stsgls 



(INC) 



LEf^ Mid5( Mids} Begls 



' r€dsC M£d5> Begls 



CWITHINC) ' LBPtM MidSC MidBj Bt^# 



m 



Tutorial 

Working with 
Create ... Does> 



Leonard Morgenstem 
Moraga, California 

II has been well said that programs arc not written in 
Forth, Raificr, t'orth is extended to make a new language 
specifically designed for die application at hand. An 
imponani pan of this process is the defining word, by which 
one can combine a daia structure with an action, and create 
multiple instances that difTcr only in detail. One thinks of 
a cookie-cu tter- all the cookies are the same shape but have 
different-colored icing. 

The Basics 

Defining words are based on the Forth consmict 
CREATE ... DOES>. Beginners quickly learn to apply the 
method mechanically, using two familiar steps: 1) Start a 
colon definition, write CREATE, and follow by the actions 
that lay down data or allot RAM. 2) Write DOES> and follow 
by the action to be performed on the body of tlie word, the 
address of which has been put on the stack by DOES>. 
(Experienced programmers will please forgive certain 
oversimplifications.) Although the Create ... does> pair 
is easy to use at this basic level, understanding the details 
is hard because there are no fewer than three phases of 
action. Words compiled in one are executed in another. 

A simple example is 3 CONSTANT, which creates the six- 
byte analog of CONSTANT, (Screen One) It has two stack 
diagrams; the first for creating an iastance, and the second 
for executing iL The first phase is in effect when 3CON- 
STANT is defined (Line One). It is a colon definition and 
works in the usual way; that is, : sets up a header, after 
which the CFA's of ordinary Forth words are compiled, and 
immediate words such as DOES> are execuied. 'I'he pro- 
cess is ended by the semicolon. 

In the second phase (Line 'Iliree), 3CONSTANT creates 
an instance named 3 FOG. The CFA's tiiai were compiled in 
the first phase are now executed one at a ume, as follows: 
create picks up the next word in die input stream, wlrich 
is 3F00, and makes a header from it. The commas lay 
down the top three words from the stack; they become the 
body, D0ES> stops the action and sets die CFA of 3F00 to 
execute the Forth words that follow it al Point A, These are 
not executed until pha.se three, in which 3 FOG is cxcicuted 
(Line Four); the address of its body is put on the stack, and 
the Forth words at Point A are executed, moving three 



Forth words from the dictionary to the slack. 

Using iCODE 

Just as it is possible lo substitute assembler for high- 
level Forth by starting an ordinary definition with CODE 
instead of :, one can do ilie same for defining words by 
substituting ;CODE for DOES >. In the alternate definition 
on Screen One, 3CGNSTANT is rewritlcn in this way. ; CODE 
is followed directly by the necessary assembler words, and 
the definition is terminated by NEXT and END -CODE with 
no semicolon (Line I'ivc), 

As another example (Screen Two), we constmct number- 
machines. The real ones look like rubber stamps, but print 
sequence numbers. Their Forth equivalent simply puts the 
ncxl number on the stack. Note that commands can 
precede CREATE. We can specify that the machines reside 
in a vocabulary named #MACHINES. We could make al! of 
them immediate by writing IMMEDIATE just before DOES>. 

What CREATE Does 

In the Forth-83 Standard, CREATE will "define a word 
that returns the address of the next available user memory 
location." Hence, if we write CREATE FOO and then ex- 
ecute FOO, an address is returned. .Mo.st existing Fonhs (fig- 
Forth is the important exception) follow this rule, as does 
the ANSI draft standard. Differences derive from the fact 
that each implementation interprets "the next available 
memory location" in its own way. For example, in F83 the 
dictionary is confined to a 64 K space, and the address 
returned by FOO immediately follows the CFA. in F-PC, 
header and body are in separate spaces called the head 
segment and die code segment respectively, and FOO 
returns an address in the latter. The ANSI draft standard 
adds specifications as to alignment. 'Ihe casual user need 
not be concerned wiili tiiosc details because words tliat 
allot memory, such as , (comma), C, and ALLOT itself, 
automatically do so in the proper place, namely, at the first 
1 available memory location. 

U is worthwhile to comment here dial one should not 
use 2-t- lo go from the code field to the body of a word, it 
will work in F83, but may not in other versioas. Porting 
from one Forth to another is never easy, and a shortcut of 



Forth Dimansions 



m 



May 1992 Juna 



ihis kind merely aggravates the problem. The correct word 
is >BODy. 

CREATE em stand alcne^ eicber in^de or outside a 
ebloft d^^tdSm, without an 3(ss6(MtM'M0s$>, and is so 
used when the word to be created leiurns the 

address of its body, for example, vari^lJlies and noii- 

follow it with , . Wlieti FOO is executed, the address of 
the zero will be returned, so the aoioii is the same as a 
variable. Or, we can the preidefitaed VftRl A^lii -w^iich 
is defined as 

: VmXfiBlM CRE&TS , ; 

mi FO@^ tilie ftist mediod ts preferred ' 

when only one instance is wanted, as it avoids the 
overhead entailed in writing a defining word, while the 
second is bettsi iKAien fliultiple instances are Cof might be) 
needed. 

What DOES> Does 
E©ES> is imroediate, and is executed duritiig phase one 
of ia defSMfi^fti tt tejs dewH flie wtasd ( I'cmii m^soass 

assembler instructions. Therefore, ifyou decompile a Forth 
word that includes DOES>, you will sec (;CODE), fol- 
lowed by the passibly undcciirapiiable assembler in- 
structions. These will be followed by the address tob^eiies of 
the Forth words that are to be executed in phase three, 

( CODE) is actually executed in phase two. Ii sets the 
Q'A of the most-recently created header to point to the 
assend)1er instructioris. At this point, we can darily tite 
imprecise Statcmcnt.s made in earlier paragraphs. As a kind 
of shorttiand, it is convenient to attribute to DOES > actions 
llat ai« aewally executed by ( ; CODE) . We also say that 
DDES> ^kes the CFA of the word toeing defined point to 
the Forth words that follow DOES>, when it actually points 
to certain assembler instruc^ons that precede them. 

Don't confuse ;CODE and (;CODE) . The latter is a 
■primitive" laid down by bc^ DOES> aiiid rCXsiM. ft ts 
conventional in Forth to name a primitive by enclosing in 
parentheses the name of the word ttiai compiles iL Otiicr 
©Bunples iadude (LIT!. (."I, etc 

Sei>aratlng CREATE and DOES> 
CREATE . . . DOES> are nearly always seen together, but 
unlike the tM.lves of a pair of scissors, they can be useful 
when separated. It is not well known that DOE s> can stand 
alone although it cannot be employed outside a colon 
definition. Wh0a ^ word ^at conuins DpES> is executed, 
i^rcfless ofw^tttertt^ past ol^a dellraln^ word ot not, 
the CI-A of the la, St- created header is set to execute the Forth 
words that follow DOES>, Screen 'Ituee shows how to 
define an indexed anay wtih 12$ ^}it-bit elements by 
using an "external" DOES>, 

This trick Is not often used because it is noi often useful, 
although Laxcn aini Pcrr>' did employ it in F83. It makes it 
possible to define words in groups, for example, pairs that 
vary sllghtlir in i^eS^% or words with the same name in 



different vocabularies. This can be done in Forths (for 
example F83 and F-PC) that f3acff'GS^iSt1^£ into two parts, 
one CO get ^ string from the inpiu soeam, and ihe other to 
ati!&&'dnsm^m^&mtM. In fisir example, CRBAi^B is 
defined as ficillows: 

• CREATE BL ffOItD ?WPERCASE "CimA^TE ; 

BL WORD gels llie string and places it at HERE, leaving 
its address on tlie stack, ?UPPErcase c( in verts it to 
capitals if die variable caps is set, and "CRiyVTE (a — ) 
uses the result to form a new word. 

Supjxwc we :ire writing an advcntuiB game in 
which we want compass directions to have CwQ different 
actioos. to BiB ^iSME *ocabo1aff , tl^Rfft wiB fsme the 
advcntufiBlCf:^s^le in the FORTH vocabulary, tho same word 
with an appended twill act as a constant and put a number 
on the stack. With conventional methods, each direction 
wcxild need two definiqg ^rds, one for MOi^ and the 
other fof Mblif ftf . Screen Fburshbws how a Stagle difTriing 
word, DIRECTION, ran crca;f (he iwo at the same lime. 

The first Step is to factor out the DOES> action of all but 
one rfthe wonls to be eri^tfed. IWs iS 
the nan-time action of (;CODE) which is laid by 
DOES> is to exit from the word that ii is in, after$etdng the 
CFAint^most recently laid-do wn header. In pur example, 
the game-word actiofl is f^ctpfed out intp move, which 
fetdies the direction number from the body, and moves the 
adventurer. 'Hie defining word DIRECTION gets a string 
from tlie input stream, converts it to upper case, and places 
it in the bufferDBtJE" iQEiiie One). In line Two, the resulting 
string is used tocreatc NORTH i n the GAME vocabula ry . DUP , 
lays down its parameter field, and MOVE executes DOES> 
to si^ #ti «<^oa tines f'iyai and Hve append a # to the 
string in DBtJF, and Line Six uses the modified string to 
create NORTHS and set its action with DOES>. 

Nested Defining. Wofds 

SeasSirtaflFOrth prograrrafKiJSfciew^sSdg^ 
can create defining words, which in turn can create other 
defming words, llie nesting can, in theory, be continued 
indeftiiteijfi SiiippiSse (hn we want ^i^few isol©irS as a 
series of arbitrary constants, numberedJQiJf2, etc., and that 
we also need shapes and other attributes defined in a 
similar way. Wc proceed as on Saeen Five. Here ATTRI BUTE 
defines a word that contains the create ... PQES> 
sequence, and is therefore another defining word, this 
idea is not merely a clever trid^- ftiS;fhebasi$ofl££>8t object- 
oriented Forth systems. 

B^Si^ and @t{^ti^we^ el^eiNtSf with 

the valueis (j^ i,,and 2, andB3@pd^^@;gQfARE, and oval arc 
constants the same sei^ C^A^t$es. I leave it to the 
leacter to wotk out the defiuled actions of tte various 
words. 

Some R^dom Thoughts 
Why is there a ri^ an^e-biacket in doesH-R origi- 
rtated with cetb^is^tA^ '^e^^yitfi^'GiiSK'fS Md down 



May 1992 June 



36 



Forth OimBusi^ 



a header whose code-field 
contained a pointer to the 
next byte in memory instead 
of an execuUon token. To 
set up i idd£ej^i%^Kroid, it 
was necessary to follow 
CREATE by the pair, 
<BUILDS ... DOESX 'Vbe 
Forth-83 Standard changed 
the aaion of CREATE, so lhai 
<BUILDS was no longer 
needed, but did ooi chan^ 
the origina] sc&&h and 
spelling orDOES>. 

The action of defining 
VfMs Mr stoipie 

Hi complex. Simplest arc 
those that lack does > . At ihe 
opposite pole are highly 
Specialized words, for ex- 
ample, iMi and lAMi, \jsed 
by the F-PC as,st:mlilcr to 
generate 80x86 commands. 
B^inners, carried away by 
a sense of power and free- 
dom, often create too many 
defining words. Although 
there is little cost in memory 
or execution speed, doing 
this can result in hard-to- 
read source files. Most pio- 
gieams seed bxtilt- 
insetofdefiiEiui^^Anci^ and 
a few oovettii&s. 

Conclusion 

'ITie easy formation of 
defining words is one of the 
features that makes Forth 
powerful and enjoyable. At 
the basic level , the technique 
is easy to learn and apply, 
but pm^^ains aie atmcf$ 
better- written when a pro- 
grammer is aware of what is 
going OTL A de&per under- 
stauicling is also required to 
cmaie specialized exten- 
sionsi which, thcaigh not 
ofien needQcl, am be very 
use&l. 



Laonard Morgenstem is a retired pa- 
IhoiogisL and cofnputer hobbyist. His 
irvlerest in Forth goes back over tort 
years. Cta FOTtly. ha is a sysop of the 
R;>rth. RpundTsbIa on GEiw- His 9on, 



SCRSEN 1 

: 3C0NSTAm: I n3 a2 nl — ) t — n3 n2 nl) 
CI^ftTE , , , 

DOES> ( Point h ) DUP 4 + § SWAP 2:S 
12 3 3C0NSTANT 3FOO 

3S*dQ .S ( FQxth will display 1 2 3> 



( Line 1) 

( Line 2) 
( Line 3) 
( line 4) 



: 3C5C5NSTANT { tt3 ti2 nl ~ ) ( — n3 ti2 nl) 
CREATE , , , 

?eOOB ( Point A ) WtJSH 4 [SXl PraSR 2 [BX] 

PUSH [BSC] m,m EHDKiODE ( Line S) 

SCREEN 2 

: NUMBER-MACHINE ( — ) ( — n) 

DC^BS> PUP 8 1 +1 f 

\ First alternate definition uses sOOSB 
: NUMBER-MACHIKK ( — ) ( — n) 

jCODE pop B3C W0V AX, IBX] JNEJ 6 [8X3 IP^SH EKTOHSOHE 

\ Second alternate definition putis all nmitm: machines iM 
\ a special vocabulary 

vocAeuiiABar l^i>iUK::B£Er£s 

: NOMBERi-iCACHlSiE { — I < ~ n) 

ALSO fMftCflXNlS EBFINITIONS CREATE , PREVIOUS DEFINITIONS 
DOES> PUP e 1 ftpT +! ; 



: tiAItE-8 { i — a) sw&p iS * + ; 
^lEATB INDEX! 1000 ALLOT MftKE-t 



\ 125 8-bit elraoents 



VOCABULARY GAME \ Flayer's vocabulary 

CREATE DBUF 33 ALLOT \ A buffer to hold the name 

: MOV:-^ DOES> Q (Write fSKse .etCti-O'Q hJ^XB ) 1 

: DIRECTION { n — J 

SL WORD ttJPPERCASE ©©SOKE DBUF PLACE ( Line 1) 

GAME DEFINITIONS DBtJF "CREATE DUP ,f MOVE { Line 2) 

FORTH DEFINITIONS ( Line 3) 

ASCII > DBUF COUNT + C! ( Line 4) 

fiBOF ce 1+ oaaiF Cl ( Line 5) 

mm "CREATE , DOES> f ; ( Line S) 

DIRECTION NORTH \ Create game word NORTH and constant NORTH* 
|: ©llaECTION EAST 

• test [ f oxth ] north . t newstuf f ] north t forth ] ; 
SCREEN 5 

\ Nested defining words 

DOE5> CREATE DUP g 1 liKJT +! , 
DOES> e ; 

ATTRIBUTE COLOR ATTRIBUTE SHAPE 

cQLOiiL wm <^Q%m mm 'Qmm m^m 



37 



way i93Sji0ei 



A Forum for Exploring Forth Issues md Prtmroting Forth 



In vdume 15 of Forth iXmenshflS; many FIG members 

requested more promotion of Forth. Here and cLscwIiere, we 
should tout tlie advantages of Forth. Fvery cause has 
benefitted from promoiioci a I times. I think you'll agree that 
the promotion of Fcxth and FIG should extend to several 
areaa 

One area is the promotion of trade or commerce. For- 
pt^ Activ'ny is ultimateljf what has kept us fed, dodied, and 
sbdfiaied. A2 sbtnte peiht fliie dev^opnfie^ ^'SttindMtY, 
commerce also .spawns "trade magazines" directed ai fostering 
better-informed trade amongst the producers and consumers 
in a particular industry. Ofien user groups soe bom because 
of the widespread sale of one product. 

Unfortunately for Forth, the trade magazines do not serve 
Forth adequately (although they seek an occasional Forth 
ailid^. Worse, the number of people who are buying and 
selling Forfli-i)ased goods and services is probably too few 
to fund a Forth -dedicated trade magazine. Nevertheless, FIG 
can help promote trade by making sure vendor names and 

Jd^^ifcpi^ I liope we wjib^ jbj^feliitg^^^^^^ 

FIG can help promote trade by 
making sure vendor names and 
product information appear in 
ttie pages of FortK Dimensions. 

in "Fast FORTHward," not as a means for them to provide 
product-spedfic information, but as a way for them to help 
promote Forth generally. Beyond that, the Board of Directors 
of the Forth Inieiest Groyp wants to try to maximize the 
advertising space ££»t3 <ti{> tb j^ei^ liffil^^^ihis type of 
journal). FIG intends to play its.f^Ultf6 p(ioiiS^ trade. 

hope that other parts of Tii&imi^^^^ic^Mcion feature 
atffdei a3i6t^%aEriigttii^^^^ 

or software. We have taken steps to help ensure that this 
takes place appropriately. Such article,-! should serve the 
higher purpose of educating our reader; about important 
prc^rarrmung techniques, about praoical ways to develop 
successful applications, and so forth.) 

Professional sodetJes and standards efforts can promote 
Forth in ways that would be difficult for individual veiKtors. 



I They can hdp ensure that corisuiners cif a proAict or se rvioe 

are gf^tting the Ixisi tliat ran 1 x: made available. TTic ACiVI and 
ANSI organizaliorw arc wel I known for tlicir seivice in such 
arca.s. Thanks to the dedicated efforts of Forth vendors and 
enierprisiqg Forth activists, Forth coniingenLs have been 
ihstaltedin each of those oiganizations, ACM SigFORTH and 
ANSI X3J14. I expect "Fast FORTHward" to offer es,says 
descrihinig standards and 'open systems," and bow they 

ers as wel! as prcxjiicers of Forth prodnas, 

(One related activity that FIG has supported is the China 
Forth Eme&smm p^f^ it Iielp^ ictetei^ifflie die 
level of conr^setency of Forth programmers and it brought 
guaranteed employment lo the top performers on the test 
Dr. C.H, Ting will be translating portions of this test into 
English so that "we are better able to appredale iO 

Publidty is another isna of promotion that help 
further a cause. It aiso takes many forms. For FIG purposes, 
publidty should hel|) create visibility for Forth in as much of 
iSi& trade atndgaieM Anathetv^^ 
can help publicize %lffe: is to make sure educational 
materials arc readily ^lafs^^^ie to anyone who is curious 
alx)ut Forth. I promise tG^ia^e "Fast FORTHward" as a fomm 
lo publish analytical essays regarding the nature of Forth. 
Such explorations can help educate newcomers — and they 
can hold the interest of the Forth pros, ion [ will quote 
liberally Cor reprint where appiof»iate) tiie materials from 
vendors, statidafds committees, Forth books, artides, and 
just abfjut any source that can help shed light on this thing 
we call i'orth. If Forth is a philosophy besides a language, 
then words must be found to express it adequately. 

A valuable marketing exercise is to consider a market- 
place without regard to existing products. Wliat does a 
market composed of software and hardware developere 
need' Once that is known, pediaps we can state how Forth 
uniquely meets thcMe needs. A market study should show 
how orte's own product has a place among existing products 
serving the same customer base Along these Mass, "Fast 
FOiEilt«sS«r' Invito the <fi^^fse custratier laSI 

including laboratory researchers and med^a^dtliei^gLtteeiS, 
to write about tficir ideal Forth system. 

Ttie type of short articles, leCQSici^ Gi« ^^^tfHit I expea 
to appear here should heip foster communication among iIk 
Forth user, developer, and vendor communities. As your 



May 1992 Jww 



newly appoinicd FIG Publicity Dircaor, I also need review- 
er who caxi help noe d^crnuije; vrtat Fqith-i^ioinotipaal 

have the interest and-'or background to help develop and 
review sudi materials, please contaa me, in care of the I'lG 
office. V foa -wish to write material for thb department, send 
your ideas or finished work to me by way of Mariin 
Ouverson. fFortfo Interest Group, P.O. Box 6231, San Jose, 
California 95 J 551 

Please do your part to help forth and FIG by renewii^ 

support our worthwhile cause by coasideririg l&Sr Jffiu 
might contribute to this deparlnicnl. Of you received tfiis 
issue as a complimentary gift, 1 hope you will sec that Forth 
Dimensions is becomirig a more broadly informaUve 
ms^azine, wich monspoti^tialbenefU for everyone &)cvat«<ed.) 



from the company ilseif— see "Product Watch'X 

Version 2,0 of DataScope featmes;ikn SAA CUA-compIiant 
(Systems Application Architecture add Common User Ac- 
cess) user interface oiMion. It includes user-alterable 
rau I ti tasking window displays and a "Windows-Uke" pull- 
down raemi inter&oe. It silso provides search tools^ttiaf €aii 
find data that is ordioanty an invisible part of a transmit! on. 

Since 1982. Paladin Software, Inc. has written a number 
of software applications for a variety of clients, including 
General Motors C&ttwra (riant HYAC cluster-interlink pro- 
tocoD, Eastman Kodstk (!Tn88 DieiflsitbiiseterX Miaaorirtell 
Douglas Electrophoresis Operation in Space Ground Data 
Systems, Lockheed, ITT (Power Systems SUPERVISOIO, 
and I^deialBf^eHS^K:^ protocol andAjfcalab^S^tem 
for the Super Tracker), 

The company's founder is James Dewey, He has 
implemented X.PC, SKCS-U, DDCMP and a variety of other 
protocols, primarily for applications invcdving single-chip 
ntitrocoinpuiers. He tiaspiffiigraittii^WPt.1, fei?- 
poly FORTH, and Fortran, as well as various assembly 
languages. Before founding Paladin Software, Inc he 
ytfS^iSsA as an Electrical Engineer and was a senior pro- 
grammer with Forth, Inc He holds degrees in Electrical 
Engineering and Psychology from Cornell University, 



May 1991 

Orion Instruments revealed a bStife^p pS^lfam tor 

converting from the UniLab/UDL microprocessor 
emulator-analyzer to a more powerful UniLab 8620 
microprocessor emulator-analyaet Ctbe dte^Qsunt oBer 
ended S^jtember 30, 

July 1991 

BDS Software announced Q'83, a 1983 Standard Forth 
for the Radio Shade OqIqf Computer lunnbig SS^XSS^ 

September 1991 

Pabdto SoftwOTe aniioaneed t)as®eE^je^ Vfeisfem 
a serial-line monitor and protocol analyzer sporting a 
windowed GUI and lequiring MS-DOS 2,1 or higher 
niiiniiigoiia.PC». 

Forth, Inc. ann<»lS|SM0*e<hipT-OKTl ! 68:^.^2 Software 
[>;velopment System, 'B^ch includes onc-ycar telephone 
support, uses an MS-DOS PC host, and includes a 68332 
set.known a$ the Motorola Evajtuaticm Kit CEVK). 

October 1^91 

Forth, Inc. announced a newi^ease of EXPRESS Event 
MariageiiieiK and Control SifSi^^^ a. pt&s^ss-^sSisW^ 
software }»dka^ 



Companies MenUonwl 

BDS Software 
P.O. Box ^5 

Glenview, Illinois 60025-04^ 
Phoi*5: 708-998-1656 

Forth, Ittc 

111 RS^xilveda Blvd. 

Manthailan B^ch, Oalifbit^ WM^l 

Phone: 310-372-849S 
Fax: 310-318-7310 

Orion Instruments 
180 Independence Dr. 

Menlo Park, California 94025 
Phone: 415-327-8800 
Pso: 415-327-5881 

Pahdin Software, Inc, 
3945 Kenosha Avenue 
San Diego, Califomia ^117 
Phone: 619-490^6^ 
Fax: 6l^9CH>177 



Paladin Softwate, Inc- 

ScaiiGsd fn 1S62, Qiis software con^tflittg firmi wrote 
custom software for a wide variety of indu.strics, providing 
^tems and applications software in projccis ranging from 

implementarions. ^^Bcieapfl^,, the company released 
DaiaScope™ version t.6, the hiesi in a family of PC-based 
software products that lets PCs replace much more expensive 
qannjmunica#on det7u|gei5 and serial-line monitors. 

Ifersiori l .ifSi dF DataScope was brou^ out in 199!. 
Version 1.4 is available as shareware (on CompuServe, 
FIDONET, EXEC-PC, and utlter bulletin boards as well as 



Forth Dimensions 



m 



On'Une Besourcesn 



message bases of several bi^etia boards and inTonnation semces 
ill an auempt to provide greater distribution of Forth -related info. 

ForthNf't provttiod murtcsy of the SysOpsof iLs various links, 
who shutil appropriate mcssafies in a manual or .semi-manual 
manner. 'Ihe current branches of ForthNet inclutie L'.scNet's 
comp.lang. forth, BiiNet's FlGi-L, the bulletin board systems KCFB, 
ACFB, LMI BBS, Grapevine, and FIG's BoufKTTaUe on GEnie. 
Qtilprm^t^ on tDodem^t^oe^^sibie systi^QS isJfidu4ed below^ 

very chatty and cbrtdiilh srame personal 1 aTSO 

contain blatant commercial advert L-^ing. Most comp.lang.forlh 
posts are iiol like that. I-'ortiiNtit mesiiagci tiiar are ported into 
comp lang fonh from the re si of ihc Forth Nel all originate on 
GCnic, w, hicli i.-i a l( ttid of iic/jfto FofthNet message hub. Ail such 
messages a re ported to co m p . 1 a ng . forth "Wiftf a ft6m4lQ,e^S>e GSM; 
From; ForthNet® willett.pgh. pa. us ... 

Most messages ported to comp.lang-forth also contain some 
tiaiJer infonnatiqa to wbe;re tb^ ^^sti^Ujr oc^inated, if it was aot 
on GEnie. 

There is no e-maO link between the various braiidies of 
ForthNet. If you need to get a message through to someone on 
another branch, please either make your message general enough 
to be of interest to the whole net, or contact said person by phone, 
U.S. Mail , or some oilier means. 'iTioughlfu! njcssage authors place 
a few lines at the end of their messages describing how lo contact 
^letD Celec^cMiiically or o^i^wise>. 

Phone fatfonnatkxi for the diai-to seivleesi iceniiaDed ^b&ws 



RCFB (Real-Time Controt'feilhSew^' 

S^sOp: Jack Woehr 

UxaHon: Dtsmvet. OObrddia, USA 



303-278-0364 
SprintNet node cpden 



(Australia Connection Forth Board) 03-809-1787 in AustralSa 

SysOp !_ance Collins 61-3-B09-1787 IntemStbnai 

Location: Melbourne. Victoria. AUSTRALIA 



LMI BBS (Laboratory Microsystems, Inc.) 
SysOp: Ray Duncan 

Locstlon: Marina del Ray. Catilomia, USA 

Grapevine (Grapevine RIME hub) 

SysOp: Jim Wenzet 

Location: Utile Ftock, Arkansas, USA 



213-306-3530 
Sipnntftot node e^ffli 



501-753-8121 lo register 
S01^^»«859thw»aftef 



800 -638-963S for into. 



efiiHii (General QecM6NeifM6rk %>r 
irtfoimaOcn Service) 
S^C^i Osnnte Ruffw(D.RUFFER) 

Leonard Morgenstem (NMORGENSTERN) 

Gary Smith (GARY-S) 
LoGatton: Forth RoundTable— type M710 or FORTH 

exccutabies, and so oi. TTiesewious repositories are xof kientkal 
copies of the same things. Material is available on an os-ft basis due 

to the charity of the people involved in maintaining the Itteari^ 
■["here are several ways to access Forth libraries: 

FTP 

Note: You can on ly use FTP if you ate on an Imemet site which 
supports FTP (some sites may restrict OB[^ia classes of user^. If 



foe iafonnation. Yotsr^q^^tSOl stdinioistrator should always be your 
(tt^iesort if you bammtf^SSStSill^iXi^^ 

Fat MS-DOS-related files, th^e are currently two. siliK from 
which you can anonymously FTP Porth'related matejfafej 
WSMR SIMrrEL20.ARMY.MIL CSiimel20 for short) 
mJARCHIVE.WUSTL.EDU CWuarchive for short) 

Wuarchivc inaintains a "mirror" of the material available on 
SiiiiLell'O. Simtcl20 lia.s a Ijitiitcd amount of material, [iiost of it 
' binaries ft^r MS-IXIS computers T he- I'orlh files on Simtel20 arc in 
director)' PDl:<MSDOS.FOirri l>.Thc Forth filcson Wuarchivcarc 
fa direck^/mirroi/nisdo^/forth. For detailed infoim^icxi on bow 
^fil^^id!]gSiattd2Q8n:jifve (ft is tdoiimchto indtKis here), 
see the text Sles In: 

PDl:<*lSDOS.STAfiTER>SIMTEL2CUNF or 

An FIP site containing a mirror of the ITt". library on GHnie is 
"under construction" and will be announced wfwn is ready. 

FIGI-L Gaieway 
For those who have access K> S1'LM1£I/C9^ but not Usenet, 
compjimg-fofth is echoed m PICI-L. Tlie iiiaii^lia^ <^ the 
Intentet^nNBT g^ttev»y sltice flist q[uaiter 1992 fs as fbltows: 

Pedro Ltrisl>ro5pefD Sanchez intefnet: pJOIst.usp.br (PREFERRED) 
llniversily of Sao Paub uunet: uunet!vme131 !pl 

Dept. o( Bectronk: Engineering hepnet; psanchezSuspifl.hepnei 
phone:(055K11)211-«74 
hoim (055){11)914-d7S8 
fax: (C]6gX11}B15-4272 

Mociem 

P^dioee desiring to use Cor stuck with) modems, the disl-in 
systems listed above also have Forth libraries. 

Msdar If you are unable to access SIMTEL20 via Internet FTP or 
through erne of the BrrMnyi-.MJN file servers, most SI\rm, 20 MS- 
DOS files, indudi[)g the I'C- network at 313-885-3956. DI5C has 
multiple lines which suppon 300/1 20<V2400/960(VlH 00 bps 
(I ISTA'.32A'.42A'.'i^bLs/MNP5). TTtis isa subscription system with 
an average fiourly cost of 17 cents. It is also accessible on Telenet 
via PC Pursuit, and on Tymnet via StarLink <»jtdial. New files 
U[joade4 SIMI^ELap ai^ ije^dt^k on POQ witihin M 

hotm 

Infommtbn provkled by: 

Keith Petersen Maintanerof SIMTELSO's MSDOS, 
MISG & qp/M ar^lv«s IIP a^^dms 26.2X).74] 
Intemdi: ««sdzeTOMK-StMTEL20.ArTriy.Mit or 

w8sdz@velaacs. Oakland, edu 

Uuep: utjnet!wsmr-simlel20 army .niflt«[il$<te 

BITNET: wSsdzOOAKLAMD 



This list was compiled 20 February 1992. While every attemftt 
was made to produce an accurate list, errors sm tlwaye 
possible. S>/fls are aiso subject to mechanica) pn^iterrts or 
SysOpbumout Ptease report any discrepaiKi^, additions, or 



Gary&nith 

P. O. Drawer 7Sm 

Little Rock.An 72217 

U.SA. 



ULmtlddftHra^lglsrk'gais 
rruu(ip%dcS1@uuneWU.NEr 
GEr7ie Forth RTS Unb( WS^^<^ 

ph: 501-227-7817 
fax: 501-223-9374 
8-5 Cen^^. M-F 



May l&S2June 



40 



Forth Omertsions 



posts frofn PonbMet ported intocotnp.ki^ Jofth sometimes advet- 
tjse Files being availaUe on GEnie, Those messages also cental 
informalioo on how to get UU encoded e-mail copies of the same 
flics. There is an automated e-mail service. The entire FIG library 

on GEnie is avail.ibk- via c-niail, but no [H.istcr index or catalog Ls 
ycl available. The file MM:.'?. ARC contains a fairly recent lisl of the 
files on GEnie, and filcji; added ."iincc then arc only documented for 
comp. tang, Forth readers by way of the "Files On-line" mes&ages 
potted through ForthNet. 

If have any questions ^x>ut FoxthNet/comp.lang.forth or 
ftiQr^ennatfon to adtl/dekts or cotrea In this me^^e, or any 
stiggesti9ns on fotmsS^Obg ot prescotation, pieast contact either 
DQtig FlijlipeorGarr&iiSiCjE^efierably both, bU oae is okay) via 
die feUoning addresses: 

• Internet dwp@wille».pgh.pa.U3 

ortlditlllBrk IgarsSuunet. uu.net 

• Usenet: ...!uunet!ddil!lrark!gars 

or ...luunetfwiltett.pgh pa uslciwp 

• GEnie: GARY-S or D.PHILIPS3 

• ForthNet: Grapevine, Gary Smith 

leave mail in Main Conference (0) 



To communicate with the following , sot your modem and commu- 
nication software to 300/l200/P400h.-rud with eight bits, no parity, 
and one stop bit, uf^ess noted otheiwise. GEnie requires local 

GEnie* 

For informal ion, call SOO -63 3-9636 

• Forth RoundTabie (FonhNef) 
Call GEnie local node, then 
type M710or FORTH 
SysOps: 

Dennis Ruffer (D.RUFFER) 

■.^onstd Morgenstem (NMORGENSTERN} 

fitlott C^^f^aJLlStT.e) 

BIX (Byte Information eXchange) 
For Information, call 800-227-2983 

• forth Conference 

Access BIX via TymNet, then type j lorth 
1 y!:ie FOFfTH at the : prompt 
SysOp: PWIWasson 

CompuS«ve 

For Information, call 800-848-8990 

• Creative Solutions CoW. 

Type I Co FORTH 

SysOj is Don Col bum Za!::h Zscr-.arla, Ward MtFaitand,. ©fag 
Guerin, Jotin Baxter, John Jeppson 

■ iCompiiter Language Magfofhe 
typft I Go CUM 

SysOpsr Jim Kytd, J«ljf 0rM:>n. Chrp RiibimMiltZ^ Ite^ Eto 

Ridley 

The WELL (Unix BBS with PicoSpan frontend) 

• Forth con'orence 

Access WELL via CPN (CompuServe Packet Net) 
orvia SprintNetrKKfe: casta 
or4t5-332-«1C)6 

Forth Fdrwitness: Jadf VUbalw ^} 
Type ! j forth 

Citadel Network - two sites 

• Undermind (UseNet/Ciladel bridge} 

At'anta. GA 
404-5210445 



'GEnie is tber^iosUory o/ihe l-'orih Interest Group "i 



• !rtt*rface {formertif KSSfiCXiiO 

SysOp: Bob Lee 
Napa. CA 

N on- Forth-specific BBS's 
with exlenvlva WatXtk 

• DataBit 
Alexandria, VA 
703-719-9548 

SprlntNet node dcwas 

• Programmer's Comer 
Ballirrvore/Columbia, MD 
30 1-596- 11 80 or 
301-99S-3744 

Sprint Net node dcvuas 

• PDS'SIG 

San Jose. CA 
408-270-0250 
SprinlNet node casjo 

Ititanutioiia] Forth BBS's 

Mt^bouriie AusEt^ In Fortf1^tBt ndde IM sfeovs 

■ ^tim^im 
Pfaffe, R^hCd 

From Germany add pfsfet O^S 

From other counl«1eS:add33 

(1)4108 1175 

3<»baud (8t\Jl)iSf 

1200/75 E71 or 

(1) 41 OS 11 11 

1200 to 9600 baud {8N1) 

For delails aboot high-speed, 

Minite!, or alternate carrier 

contact: SysOp Mart; P^emanh 

1 7 rue de la Lancette 

Per Aim Sweden 

46-8-71-35751 

• I^EXUS Servieosde IntortitaGfen. Si„ 
Traveserads Ddt, f04>106 

Enllo, 4-5 

08O24 Barcelona, Spah 
+ 34 3 2103355 (voice) 
^3<(#214?^ aetata) 

• Max BBS (ForthNet*) 
United Kktgdom 

Sy^s^p; Jijn Bro^ 

• Sky Port (ForthNet*) 
United Kingdom 
44-1 -294-1006 
SysOp: Andy Brimson 

• Art of Pfog ramming 

Mission. British Cotonnt^, Cfanada 

604-826-9663 

SysOp; Kenneth O'HesKIti 

• The Forth B^itl 
VancouvervBrM Ckiltnil^ iSsiada 
60mi32S? 

Fbrth-6G Cbmputsr ^i^ 

U'NI-nel/US 

• The Monument Board (U'NI-net/RIME ForthNet bridga) 

Monument, CO 

Jerry Shifrin (ForthNet cinarter founder) 
719-48&947C> 



Forth Dfmen^om 



41 



May 1993 Jum 



A Space Application for the SC32 ForOi CMp 

fay Silicon Composers, Inc. 



^|jUefi0i3as leqtiii^ hlgh-^ieed 

sofiwaie 4^ilttIC||Uieat is especially important to 
pragraim deal be easily tested with applicatlDtf fiStiJiiiiie 
shorten develDpinent schedules. What Mlows is an minpfe Gfa 
space application involving solar astronomy that m^ts this piofile. 

Sun spots, flares, and granularity are solar phenomena of 
interest to scicniisis since a good theory of solar dynamics must 
take them inio uccount, 'I lie gmnulartty of the sun is caused by 
convection cells, which appear over the eniirc surFnce of the sun. 
To some extent, ihe sun's surface is similar to a pot of boiling 
oatineal with the bubbles of oatmeal paralleling the convection celts 
on the sun. Although convection cells are about the si;ie of the 
state of Tracas, high resolution visual imaging of individual cells 
from earth-based solar telescopes is difficult to at^tieve beeatise of 
tbe distortion due to the earth's atmosphere. 

Scdai t^tesoopes opetattng Erom suborbital flights have tbe 
advantage of tieing atx^ve the atmospfaere, wbidi ^lows tbem to 
ffixjuire higb resduiion images that ^ow more detail of coovectiot- 
oen c^^naiaics. For this type of mission, using a stn^e on-board 
computer to control sub^tems and data services can reduce 
sj'stcm design complexity and development time. This single 
embedded computer ain perform tasks ,5uch as telescope pointing, 
optics filter control and experiment sequencing as well as image 
acquisition, data storage, and doun-Eink communications. 

Hardware 

A g^od ODbedded system lor this type of application is 
tbe SBC32 single board computer (using the SC32 Forth RISC 
cWp) and tbe DRAMI032 board. Together, these provide a large 
a0lid-«tate rnepKn; spvee. bigh-perfonnance M>, mi » 




board shadow £PROM, which is loaded on power ^ buo ott 
zero wait state SRAM (maximun) of 512KB). 

The DRAMI032Board is designed for u.-^c in applications 
requiring high-speed data acquisition or control ca pa N lilies. The 
DRAM1032 has up to 16 MB of DRAM, a l(>-liit bidirectional 
parallel port, 4 serial ptirts, SC:SI port, 2 timcr/eoiinri;!:;, uiisi watch 
tiap and CMOS RAM. 

For the solnr telescope application, the UUAMl().12's four 
serial ports arc used to acquire control data from and send scrvo- 
eonirol commands to the telescope pointing, optics filtering and 
coniroi, and mirror adjustment subsystems. The observation light 
beam is reflected to tbe teiesc^'s CCD camera via servo coalicH 
u^g paam handshake ^ m$ i ^atefi/timer on the 
DRAMIQi^ bpaiKt Solar-image c^paiHm ttttated at pre. 
progr^iKBs^ l^lnxii. ScAat-im^ & m0 fitHS the 16-btt 
j)9[fUei|!iirt itao t6 MB of G»-bcxtrd battery-backed 

l3It4iSt blice tbe rodltet telescope payjoad is recovered, mission 
data can ix transferred from the DRAM to a second 
SBC32/DRAMI032 system or other system by way of the 
l)KAMI032's ports. Alternatively, image data can be down-linked 
from the DRAM to a GST: (Ground Sup|xiri Fquipmeni) stiition. 

Up to 48 MB additional DRAM can be added with the 
DRAMEXP plug-on board. A 64 MR .sy.stem can hold 1,024 gray- 
scale (uncompressed) 64 KB images formatted as 25^256 8-bit 
pixels. An application specilic im;igc comprcsaon routine can be 
used to incrca.sc storage capacity. 

SC32 technology can also be used in the staUoru 
Bttta Seem ibe ro&set telescope tan be dOwn-tinlaed to a PG based 



CSE ^stem using the PCS32 (Parallel Co-processor Sysiem32), a PC 
plug-in coprocessor board v/tkh uses the SC32 chip and supports the 
PBMaCt32. Deis from lbs dicj«iMtDlE Is xout^ HffiODgi^ tbe 

accessed by at^ SCM bsied a^nim ftir ma^^ 

Software 

During project developmenl, the S13C32/DRAMI032 flight 
hardware can serve as a development system by connecting it to a 
host terminal or PC for 1/0 services, Wien developing applications 
such as instrument control, programming in Forth on 32-bii Forth 
hardware with high-speed L/O is a major advantage over other 
development methods 

Creating software in high-level interactive Forth significantly 
speeds up development, while running the application on a 32-bit 
Forth chip |»qn&tes bigb resolution and perfbnaance. High-speed 
VO p&caml^Mimt signal filt«iiig, data conpiessiaii and enayption 
as data is acquired or transferred. Tbe code it tested aadtiten placed 
in (Hi-board EPROM for the spae^ mis^ffii. 

Sample Prcsram 

The following code fragment shows how straightforward it 
is to use this board set. ?UBW returns a flag showing that the next 
CCD data is available on the parallel port. Direct manipulation of the 
hardware is possible, .such as %J'ARRD @ to read memory mapped 
parallel port data. CCD data is collected 16 bits at a time and placed 
in 32-bii wide 0-ws SRAM, where it Ls pr(Kes.sed at high speed before 
being stored in slower DI^AM. Acees.s to driu'rs is shown in the call 
to SCSIVVil. whicb takes {block number, address, numttcr of blocks} 
to write ]aip ibitdks of data to a SCSI device. COMPRBSS- 
B4A<^.ismj^^&^:^.^ ffmj^^^ im^ ^ QSy^. attd 

msti bim$ii ^ik^t!&^ l^BI^Qi^CtMSlli^ time until the 

next picture. After the solar bnq^ng pbase k o^cnplete, additional 
data is collected untU meoicay is faJL This data is tben unloaded to 
a SCSI device afi^ pa^ital reoiweiy. 



Code cjcimple - SBC32 
CREATB PIC 32768 AIXOT 
IIFRE CONSTANT KNDPIC 
VAfUABLE NEXTIMG 
: COLLECF-IMAGE ( -) 
ENDPIC PIC DO 
BEGIN ?UBW UNTIL 
%PARRD@ I! LOOP; 
: RELOAD-HMER (-) 
NEXTTMO @ ^ 256 /MOD 
%eTURl ! %CrLRI ! 
t NEXTIMG +! ; 
: ROCKET ( ~ ) 
INIT-COI.LECT 
BEGIN ?MORE WHILE 
POSmON-CAMERA 
mMB4I'IC IF 
COIJ.OCT-IMAGF. 
COM PRESS-IMAGE 
RELOAD-TIMER 
THEN REPEAT 
COLI£Cr.REENiaY * 



RQCICET data collection 

{ alloeaie pie SRAM buffer) 
( and mark end) 
( pointer to image time array) 
( CCD parallel -> SRAM) 
( FOR size of f^ure DO) 

I pit^ to SSAi^ 

( get time tiU next inu^) 
( set hardware tinier reg) 
( advance picture pointer) 
( Turnkey task for launch) 
( Set pointers,! imcr) 
( Outer Space loop ... ) 
( adjust camera if needed) 
( time for nth picture?) 
( CCD image into SRAM) 
( compress, move to DRAM) 
( wakeup call fot ned pki) 

( Save damM SCSI ^ivi^ 



42 



Demonstrating 
Competency 

Conducted by Russell L Harris 
Houston, Texas 

Perhaps I tie most ba.sic prnblem facing a Forth program- 
mer is that of obtaining, from a client unfamiliar with Forth, 
authorization to use Forth on a particular contract. The 
situation has been exacerbated in recent years by the 
unquestioning and near-universal acceptance of C along 
Willi tlie mcUiodology of ubjcci-oriented programming. A 
secondary problem !s that of convincing the client tliat the 
programmer has the expertise to successfully complete the 
a.ssignmcnt. The following paragraphs present one approach 
to surmoimting these barriers. 

Better vs. Safe 

Programming assignments and contracts are not always 
won by the most talented programmer or by ilie one having 
the best tools and expertise. 'I'he factors which typically 
weigh most heavily in the choice of a programmer are the 
language in which lie programs and his previous perfor- 
mance. The faaor typically of greatest import in tiic selection 
of a programming language is code maintainability. Predict- 
ability of completion date is a factor which influences 
seletnion of both language and programmer. 

Clients tend to view code maintainabilily as a function of 
the language in which the program is written, and the nK;asure 
of maintainabilily as ttie relative abundance of programmers 
claiming proficiency witfi llie language in question. 'Iliey 
ap[x;ar to give little, if any, consideration to iJie relationship 
between programming teclinique and maintainability. 

ClicnLs frequently value predictability of completion date 
over minimization of programming time. A program may he 
only one element in a complex system involving many 
components and the services of many vendors. With the 
inierde pendency of schedules, a missed deadline may have 
consequences which gready outweigh die expenditure for 
prograunning. Likewise, once a budget has been autliorized 
and a schedule lias been set, tlie programmer rnay receive 
iillle, if any, reward for early compleu'on. From the standpoint 
of the client, the l>^t insurance agaiasi a missed dcatlline is 
to ."w^lcct a programmer and a language, both rjf which he 
personally knows to have produced serviceable crxie within 
reasonable time on a project of complexity comparable to 
that of the project at hand. 

Shock Therapy, or Back to Reality 

Sometliing more tiian a resume listing past projects is 
required if thc^ Fonh programmer is to overcome the 
contemporary mind-set of C and object-oriented program- 
ming and bring his client back into a state of objectivity 
regarthng Korifi. He must convincingly demonsLrate liie 
capabilities of Forth, the maintainability of programs written 
in Fort! t, and liis mastery of tlie art of prograiiiniing; and he must 



do so in a manner which will profoundly impress his ciienL 

A demonstration may take any of several forms. One 
could, for example, quote statistics, studies, or respected 
autlioriiies regarding tlie matter in question. However, one 
of tile more effective means of demonstrating the efficacy of 
a product or a technitjue is through tlie use of apparatus. In 
the fif.st place, apparatus — be it basically mechanical, elecm- 
cal, or virtual (i.e., a screen image) in nature — almost always 
draws attention. In liie .second place, apparatus provides a 
concrete example of technique. Finally, functioning appara- 
tus proves capability. 

Computerized apparatus programmed in Fortli can attract 
arid hold the attention of a client, thereby affording the 
programmer opportunity to demonsu^te his own elTcctive- 
ncss and llie effective [X;ss of Fonh. Source listings which 
exhibit orderly arrangement, functional grouping, and intui- 
1 live names can dLspel qualms regarding code maintainability, 
i The overall appearance of ttie demonstration is perhap'? the 
I best indication loaclientoftheprogrammer'sabilitytobring 
i to completion on schedule tJie project under consideration. 
, Attention to detail is vital. Confidence in the progratiimer's 
reliability can be severely eroded by poor workman.ship, by 
program bugs or quirks (no matter how minor), and by 
source code whidi is abstru.se. 

*iTie apparatus need not relate to the project under 
consideration. It should perform an obvious funaion of 
some complexity. Ideally, it should allow demonstration of 
; itie manner in wtiidi tlie interactiveness of Forth facilitates 
tlic development cycle. 

Effective Yet Practical Mcdianlsms 

A demonstration mechaiusm, for maximum effectivc- 
I ness, .should be elegant, functional, and attractive; yet 
practicality usually demands that it be both simple and 
economical to construct. Ideally, the complexity of tlie 
mechanism (including the electronics) should be no greater 
than neces.sary tosuptxm the programming demonstration, 
so that the mechanism spotlights the code rather tfian 
I overshadowing it. 

Although demonstration apparatus frequently has no 
intrinsic usefulness, it should be pawible to devise a number 
of useful mechanisms which are simple enough to be 
practical in this role. 

A Clear! ngliouse 

This is the first appearance of what i.s intended to be a 
regular Forth IMmensiom column serving as a clearinghouse 
for the exchange of ideas and technical assistance regarding 
computerized apparatus for demonstration or other purposes. 

Ttie continuation of ttiis undeilaking will depend largely 
ufxjn reader response. What 1, as editor of this column, hope 
to receive is a variety of submissions, ranging from verbal 
descriptions and conceptual sketdics to dimensioned draw- 
ings, schematics, source code, and photos of working 
I devices, together with suggestions, criticism, and feedback 
regarding specific devices and the column in general. 

Material for publication may be sent direcUy to me at 8609 
Cedardale Drive, Houston, Texas 77055. 1 can be contacted 
by phone at713-46i-l6l8 durii ig normal busij less hours and 
on rnost evenings, or on CEnie (RUSSELL-H), 

nus^HIL.Iiaiii&isabuiibutiiiiUeMyiii(^ivi^ihiiywllla-iiiLiL'OOL.'J^y^!urii;iiiillKJ 
I fields oJinsl/'jmonlalion and machinocontrd. Ho programs in pdyFoflti, lyposon 
a Duorak keyboard, and keeps his wristwatch set !o Greenwich lirrxj. 



forth Dimensions 



43 



May 1992 June 



tddi ^oi^hester Forth Conf^r^iee 
BiomedlGal Applicaitions 

June17-20tli, 1992 
University of Rochester 



Call for Papers 

There is a call for papers 
on alt aspects of Forth f0ch> 
nology, its application and 
implementation, but espe- 
cially as relates to biomedical 
appiications. Other sessions 
include standards and em- 
bedded languages including 
Q, Mumps, /«^mJt4 F©?8% 
and Open Boot. 

Please submit 1 00 word 
^Detracts by May 15tli and 
papembf Jttne lj^ IMl^i 
pages, 10 point size. Gal) for 
longer papers. 



Invited Speakers 

Dr. C.H. Ting, Applied 
Biosystems, Inc. 
HamM WBmfn0m& 
AutomaUon 

Dr. Steven Lewis, 

Aerospace Corporation 
Hhinosoft: Design of A 
Bhmedicsd Product 

Mr. Jack Woehr, Vesta 
T^tinotogy 

ANS Forth as a Componerjt 
of Advanced Programming 
Environments 



The Conference 

•Forth seminars, 

beginner through 

Wivanced 
Demonstration of 

siate-of the-art- 

commer&al 
•ASYST seminar 
•Stack computers 
•Forth in the post-USSR 
•Poster sessions 
•Working Groups 
•ANS Foith StarKteu^ 
•Vendor Exhibits 
•Forth vs. C vs. C++ 
•Obj. orients tec^liOliGii' 
•RHd time extents 



Registration 

$450. Attendees 

$300. Full Time Students 

$200. Spou» 

Rooms 

$150. Single, 4 nlgms 
$125, Double per/person 

Tal(e advantage ot lovim mgis^mtion 
fees tfiis year! 



For More Information: 

Lawrence P. G. Forsley 

Conference Chairman 

Forth Institute 

70 Elmwood Avenue 

Rochester, NY 14611 USA 

(716)-235-0168 (716>-32M426 ^ 

EMail: Genie L.Forsley 

Compuserve....720S0.21 1 1 

...„.Ta6S0.21 i1@cmnpu9eivexoni 



Forth Interest Group 

P.O.Box 8231 

San Jose, CA 95155 



Second Class 
Postage Paid at 
San4©setC!A