You are on page 1of 198

Programming Forth

Revised May 2011


Stephen Pelc

Programming Forth
Copyright
Copyright (c) 2005, 2006, 2007, 2011 MicroProcessor Engineering Limited
For further information
MicroProcessor Engineering Limited
133 Hi L!ne, "o#th!mpton
"$15 5%&, '(
)e* +,, (0)23 -063 1,,1
&!.* +,, (0)23 -033 /6/1
e0m!i* mpe1mpe2orth3com
tech0s#pport1mpe2orth3com
4e5* 4443mpe2orth3com
i
Acknowledgements
Acknowledgements
6 4o#d i7e to th!n7 the 2oo4ing peope in p!rtic#!r 2or their in8o8ement in the
content o2 this 5oo7*
Peter (n!ggs, Chris E3 9!iey, 9i "todd!rt, 9o5 M!rch5!n7s, H!ns 9e:emer
)hese peope h!8e in2#enced ;Progr!mming &orth< !nd contri5#ted to it, !nd their
inp#t is 8!#ed3 % 2!#ts !re my o4n3 M#ch criticism !nd proo20re!ding 4!s
pro8ided 5y the re!ders o2 the comp.lang.forth ne4sgro#p, especi!y*
"te2!n "chmied, =ii!m Coo7, %nton Ert
$ther peope h!8e in2#enced my progr!mming stye !nd gener! !ttit#de to i2e3
&o77o 8!n >#in, =iem 9oth!, Ch#c7 Moore
Progr!mming &orth
Copyright ? 2005, 2006, 2007, 2011
MicroProcessor Engineering Limited
ISBN 978-0-9525310-5-0

ii
Contents
Table of Contents
Copyright33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333i
&or 2#rther in2orm!tion33333333333333333333333333333333333333333333333333333333333333333333333333333333333333i
%c7no4edgements3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333ii
1Introduction.....................................................................11
%5o#t this 5oo73333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333311
=h!t &orth is3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333311
(ey concepts 3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333312
6nter!cti8ity, >e8eopment !nd )esting333333333333333333333333333333333333333333333333333333333313
Ho4 to >e5#g333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333313
=riting progr!ms in &orth33333333333333333333333333333333333333333333333333333333333333333333333333333315
Editors333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333316
&orth 6mpement!tion3333333333333333333333333333333333333333333333333333333333333333333333333333333333333316
MPEisms33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333316
2Architecture of Forth......................................................1
&orth @irt#! M!chine33333333333333333333333333333333333333333333333333333333333333333333333333333333333331-
"t!c7s !nd post2i. not!tion333333333333333333333333333333333333333333333333333333333333333333333333333331/
>!t! types333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333320
=ords !nd A#m5ers333333333333333333333333333333333333333333333333333333333333333333333333333333333333333321
6nterpreting !nd compiing33333333333333333333333333333333333333333333333333333333333333333333333333333321
>e2ining =ords !nd 6mmedi!te 4ords33333333333333333333333333333333333333333333333333333333333321
&!ctoring33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333322
!"ow Forth is documented..............................................2!
Comments333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333323
"t!c7 comments333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333323
Aot!tion333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333323
#First words in Forth........................................................2$
$Components of Forth......................................................2%
>!t! st!c7 oper!tions333333333333333333333333333333333333333333333333333333333333333333333333333333333333332/
Bet#rn "t!c7 oper!tions333333333333333333333333333333333333333333333333333333333333333333333333333333333330
M!ths oper!tions33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333330
Comp!risons33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333331
=idey !8!i!5e3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333332
9it4ise ogic33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333332
Memory oper!tions3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333
=idey !8!i!5e3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333
Const!nts !nd 8!ri!5es333333333333333333333333333333333333333333333333333333333333333333333333333333333333,
C$A")%A)s33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333,
@%B6%9LEs333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333,
@%L'Es3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333335
Contro str#ct#res 333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333335
6& 333 )HEA333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333335
6&333EL"E333)HEA33333333333333333333333333333333333333333333333333333333333333333333333333333333333333336
EC6)3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333336
>$ 333 L$$P !nd >$ 333 n +L$$P3333333333333333333333333333333333333333333333333333333333333336
D>$ 333 L$$P !nd D>$ 333 n +L$$P 3333333333333333333333333333333333333333333333333333333333-
i
9EE6A 333 %E%6A333333333333333333333333333333333333333333333333333333333333333333333333333333333333333-
9EE6A 333 'A)6L3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333-
9EE6A 333 =H6LE 333 BEPE%)33333333333333333333333333333333333333333333333333333333333333333333/
C%"E 333 $& 333 EA>$& 333 EA>C%"E33333333333333333333333333333333333333333333333333333333/
MPEisms* C%"E e.tensions33333333333333333333333333333333333333333333333333333333333333333333333,0
Best!rts !nd errors333333333333333333333333333333333333333333333333333333333333333333333333333333333333333,1
)e.t !nd strings33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333,1
Co#nted strings3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333,1
Ch!r!cter "trings33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333,2
Ch!r!cter Liter!s3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333,2
)e.t !nd "tring inp#t33333333333333333333333333333333333333333333333333333333333333333333333333333333333,2
Print &orm!tting3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333,3
@oc!5#!ries333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333,,
=ordists333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333,6
&'(ample) *ate +alidation................................................#%
>!te @!id!tion* the reF#irement33333333333333333333333333333333333333333333333333333333333333333333,/
>esigning the so#tion333333333333333333333333333333333333333333333333333333333333333333333333333333333333,/
Coding the so#tion3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333350
P#tting it ! together33333333333333333333333333333333333333333333333333333333333333333333333333333333333333351
Lessons 2rom this e.!mpe33333333333333333333333333333333333333333333333333333333333333333333333333333352
,-imple character I./.......................................................$!
$#tp#t333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333353
6np#t333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333353
"tring $#tp#t3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333335,
"tring inp#t !nd the inp#t stre!m3333333333333333333333333333333333333333333333333333333333333333333355
A#m5er o#tp#t33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333356
A#m5er inp#t3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333356
Bedirecting (EG !nd EM6)33333333333333333333333333333333333333333333333333333333333333333333333333357
*efining with C0'AT' ... */'-1...................................$%
%rr!ys333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333360
"tr#ct#res3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333361
%*iary and Phone 2ook '(amples..................................&!
>i!ry333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333 63
"peci2ic!tion3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333363
6mpement!tion333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333363
%n 6ntern! Phone 9oo7333333333333333333333333333333333333333333333333333333333333333333333333333333333367
"peci2ic!tion3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333367
"ome design notes3333333333333333333333333333333333333333333333333333333333333333333333333333333333333336-
6mpement!tion33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333336/
13'(ecution Tokens and 4ectors....................................,$
E.ec#tion 8ectors3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333375
E.ec#tion !rr!ys333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333377
11'(tending the compiler................................................,%
6mmedi!te 4ords3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333337/
C!#tion!ry notes33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333-1
%ccessing the compier33333333333333333333333333333333333333333333333333333333333333333333333333333333333-1
"tr#ct#res re8isited333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333-3
C!#tion!ry notes33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333-,
v
Contents
12'rrors and e(ception handling....................................,
%9$B), H'6) !nd %9$B)<3333333333333333333333333333333333333333333333333333333333333333333333333-7
C%)CH !nd )HB$=3333333333333333333333333333333333333333333333333333333333333333333333333333333333333-7
>escription33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333-7
"!mpe impement!tion3333333333333333333333333333333333333333333333333333333333333333333333333333333--
&e!t#res3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333-/
"t!c7 r#es 2or C%)CH !nd )HB$=333333333333333333333333333333333333333333333333333333333-/
"ome more 2e!t#res3333333333333333333333333333333333333333333333333333333333333333333333333333333333333/0
Error codes !nd ret#rn res#ts33333333333333333333333333333333333333333333333333333333333333333333333333/0
%4!ys ce!n #p3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333/1
1!Files................................................................................%!
%A" &ie %ccess =ordset3333333333333333333333333333333333333333333333333333333333333333333333333333333/3
"impe 2ie toos3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333/5
1#Common e(tensions.....................................................%,
M#tit!s7ing3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333/7
Cooper!ti8e !nd Preempti8e t!s7ers33333333333333333333333333333333333333333333333333333333333/7
'"EB 8!ri!5es3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333/7
"impe &orth t!s7s333333333333333333333333333333333333333333333333333333333333333333333333333333333333333/-
6I$ !nd P%'"E3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333//
Error chec7ing333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333//
&o!ting point333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333100
Loc! 8!ri!5es3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333101
C!#tion!ry notes333333333333333333333333333333333333333333333333333333333333333333333333333333333333333101
$5Ject oriented progr!mming33333333333333333333333333333333333333333333333333333333333333333333333103
6ntegr!ted !ssem5y333333333333333333333333333333333333333333333333333333333333333333333333333333333333333103
"o#rce oc!tion3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333103
Mi.ed !ng#!ge progr!mming333333333333333333333333333333333333333333333333333333333333333333333310,
P!r!meter p!ssing333333333333333333333333333333333333333333333333333333333333333333333333333333333333310,
>LLs !nd sh!red i5r!ries3333333333333333333333333333333333333333333333333333333333333333333333333105
"t!tic in7ing333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333105
K#mp t!5es33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333105
1$'mbedded -ystems....................................................13,
>e2ining !nd #sing memory33333333333333333333333333333333333333333333333333333333333333333333333333107
H!r8!rd t!rgets333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333310-
Compier !nd 6nterpreter e.tensions333333333333333333333333333333333333333333333333333333333333310/
>e2ining 4ords333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333110
Compier m!cros333333333333333333333333333333333333333333333333333333333333333333333333333333333333333111
6I$ ports33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333112
6nterr#pt h!nders333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333113
%ssem5er interr#pt33333333333333333333333333333333333333333333333333333333333333333333333333333333333113
High e8e interr#pts333333333333333333333333333333333333333333333333333333333333333333333333333333333311,
6nteroc7s33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333116
'm5iic! "ystems3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333117
>e5#gging Em5edded "ystems33333333333333333333333333333333333333333333333333333333333333333333311-
9!sic r#es333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333311/
M!7e 2!#ts 8isi5e33333333333333333333333333333333333333333333333333333333333333333333333333333333333311/
Chec7 t!s7s33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333120
Beco8er 4e333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333121
)!7 to the h!rd4!re peope3333333333333333333333333333333333333333333333333333333333333333333333121
9oc7 6I$3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333121
"o#rce in 5oc7s3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333123
v
1&Forth Internals.............................................................12$
%n!tomy o2 ! &orth system333333333333333333333333333333333333333333333333333333333333333333333333333125
A!8ig!ting the diction!ry str#ct#re333333333333333333333333333333333333333333333333333333333333333127
"tr#ct#re o2 compied code333333333333333333333333333333333333333333333333333333333333333333333333333127
A!ti8e Code Compi!tion (ACC)3333333333333333333333333333333333333333333333333333333333333312-
"#5ro#tine )hre!ded Code (")C)333333333333333333333333333333333333333333333333333333333333312-
>irect )hre!ded Code (>)C)3333333333333333333333333333333333333333333333333333333333333333333312/
6ndirect )hre!ded Code (6)C)333333333333333333333333333333333333333333333333333333333333333333312/
)o7en )hre!ded Code ())C)33333333333333333333333333333333333333333333333333333333333333333333130
$ther 2orms33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333131
&orth engines !nd st!c7 m!chines33333333333333333333333333333333333333333333333333333333333333333131
Commerci! de8ices3333333333333333333333333333333333333333333333333333333333333333333333333333333333132
Prototype !nd rese!rch m!chines33333333333333333333333333333333333333333333333333333333333333132
Aotes on em5edded re!0time33333333333333333333333333333333333333333333333333333333333333333333133
1,5sing the Forth interpreter.........................................1!$
Con2ig#r!tion e.!mpe3333333333333333333333333333333333333333333333333333333333333333333333333333333333135
%ppic!tion !nd design333333333333333333333333333333333333333333333333333333333333333333333333333333135
6mpement!tion33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333136
Phone 5oo7 re8isited33333333333333333333333333333333333333333333333333333333333333333333333333333333333331,0
>esign33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333331,0
6mpement!tion333333333333333333333333333333333333333333333333333333333333333333333333333333333333333331,1
>e8i!tions, iss#es !nd essons33333333333333333333333333333333333333333333333333333333333333333331,2
1Code 6ayout................................................................1#$
=hy ! st!nd!rdD333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333331,5
6mpic!tions o2 editors333333333333333333333333333333333333333333333333333333333333333333333333333333333331,6
)!5s33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333 1,6
Hori:ont! !nd @ertic! !yo#ts3333333333333333333333333333333333333333333333333333333333333333333331,7
Comments333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333331,-
&ie !yo#t333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333331,-
He!der "ection3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333331,/
Code sections33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333150
)est "ection33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333151
9!se !nd n#m5ers33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333151
@oc!5#!ries !nd 4ordists333333333333333333333333333333333333333333333333333333333333333333333333333151
L!yo#t o2 ! de2inition333333333333333333333333333333333333333333333333333333333333333333333333333333333333151
He!der comments33333333333333333333333333333333333333333333333333333333333333333333333333333333333333152
A!me !nd st!c7 comment3333333333333333333333333333333333333333333333333333333333333333333333333152
6ndenting !nd phr!sing333333333333333333333333333333333333333333333333333333333333333333333333333333153
End o2 de2inition333333333333333333333333333333333333333333333333333333333333333333333333333333333333333153
Comments333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333315,
>e2ining 4ords3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333155
Contro "tr#ct#re !yo#t33333333333333333333333333333333333333333333333333333333333333333333333333333333155
&!gs !nd imits33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333155
6ndenting333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333156
"hort "tr#ct#res33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333156
6L8e ch!nged my mind3333333333333333333333333333333333333333333333333333333333333333333333333333333157
L!yo#t o2 code de2initions33333333333333333333333333333333333333333333333333333333333333333333333333333157
Const!nts, @!#es !nd @!ri!5es333333333333333333333333333333333333333333333333333333333333333333315-
9#22ers333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333315-
>!t! )!5es33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333315/
C!se F#estions3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333315/
v
Contents
1%'(ercises.....................................................................1&1
"t!c7 oper!tions33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333161
%rithmetic33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333161
6np#t, o#tp#t !nd oops3333333333333333333333333333333333333333333333333333333333333333333333333333333333167
Memory33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333316/
>e2ining 4ords3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333172
Misce!neo#s33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333173
23-olutions to '(ercises................................................1,$
"t!c7 oper!tions33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333175
%rithmetic33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333175
6np#t, o#tp#t !nd oops33333333333333333333333333333333333333333333333333333333333333333333333333333333331-2
Memory3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333331-5
>e2ining 4ords33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333331-7
Misce!neo#s333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333331-/
21Adopting and managing Forth...................................1%1
6nter!cti8ity !nd e.por!tion33333333333333333333333333333333333333333333333333333333333333333333333331/1
E.tensi5iity !nd not!tion3333333333333333333333333333333333333333333333333333333333333333333333333333331/2
Limited memory333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333331/2
=hy not the common !ng#!geD33333333333333333333333333333333333333333333333333333333333333333331/3
=e #sed &orth 15 ye!rs !go, 5#t 3333333333333333333333333333333333333333333333333333333333333333331/,
M!n!ging &orth proJects33333333333333333333333333333333333333333333333333333333333333333333333333333331/6
M!n!gers3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333331/6
Progr!mmers3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333331/6
)r!ining333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333331/7
Port!5iity33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333331/7
Li2ecyce3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333331/-
226egacy issues..............................................................1%%
&orth "t!nd!rds3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333331//
A!ti8e Code Compiers333333333333333333333333333333333333333333333333333333333333333333333333333331//
Con8erting 2rom &orth0-333333333333333333333333333333333333333333333333333333333333333333333333331//
"creen 2ies3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333200
&ies3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333200
2!/ther 2ooks and 0esources......................................23!
"t!rting &orth M Leo 9rodie33333333333333333333333333333333333333333333333333333333333333333333333333203
)hin7ing &orth M Leo 9rodie3333333333333333333333333333333333333333333333333333333333333333333333333203
&orth Progr!mmerLs H!nd5oo7 M Con7in N B!ther3333333333333333333333333333333333333203
&orth %ppic!tion )echniF#es M B!ther33333333333333333333333333333333333333333333333333333333320,
$ther Beso#rces3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333320,
&orth 6nterest Ero#p333333333333333333333333333333333333333333333333333333333333333333333333333333333320,
'senet ne4s gro#ps333333333333333333333333333333333333333333333333333333333333333333333333333333333320,
Con2erences333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333320,
%m!:on3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333320,
2#Inde(.............................................................................23$
v
6ist of Tables
)!5e 1* &ie !ccess d!t! types3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333 /3
)!5e 2* Cross Compier se!rch orders333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333310/
)!5e 3* Eeneric &orth registers33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333 127
)!5e ,* A!ti8e code register #s!ge33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333312-
)!5e 5* "#5ro#tine )hre!ded Code register #s!ge333333333333333333333333333333333333333333333333333333333333333333333333333333333312-
)!5e 6* >irect )hre!ded Code register #s!ge3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333312/
)!5e 7* 6ndirect )hre!ded Code register #s!ge333333333333333333333333333333333333333333333333333333333333333333333333333333333333333130
6ist of Figures
&ig#re 1* >e5#gging3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333 1,
&ig#re 2* &orth !nd C @irt#! M!chines33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333331-
&ig#re 3* "EA>6) @M !nd registers3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333331/
&ig#re ,* 'm5iic! &orth mode333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333311-
&ig#re 5* 9oc7 5#22ers3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333 122
&ig#re 6* "o#rce in 5oc7s33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333 12,
&ig#re 7* )ypic! &orth memory mode333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333125
&ig#re -* >iction!ry entry33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333 126
i
Introduction
1 Introduction
About this book
Progr!mming &orth introd#ces yo# to modern &orth systems3 6n 1//, the %A" &orth
st!nd!rd 4!s ree!sed !nd #ne!shed ! 4!8e o2 cre!ti8ity !mong &orth compier 4riters3
9ec!#se the %A" st!nd!rd, #ni7e the pre8io#s in2orm! &orth0-3 st!nd!rd, !8oids
speci2ying impement!tion det!is, impementers too7 2# !d8!nt!ge3 )he res#t h!s
5een 4h!t 6 choose to c! modern &orths, 4hich !re !8!i!5e 2rom ! r!nge o2 so#rces
5oth commerci! !nd open0so#rce3
)his 5oo7 concentr!tes on introd#cing peope 4ho !re!dy 7no4 some progr!mming to
%A" &orth systems3 6t is not ! tre!tise on %A" &orth itse2 M i2 yo# need the gory
det!is, the !st p#5ic (2reey distri5#t!5e) dr!2t o2 the %A" st!nd!rd is inc#ded on the
C> s#ppied 4ith p#rch!sed copies o2 the 5oo73 Copies in P>& 2orm!t !re !8!i!5e 5y
do4no!d 2rom http*II4443mpe2orth3comI!ren! !t no cost3 62 yo# !re ! no8ice
progr!mmer (or indeed !t ! interested in the cr!2t o2 progr!mming) re!d this 5oo7
!ongside ;"t!rting &orth< !nd ;)hin7ing &orth< 5y Leo 9rodie3 Ho4 to get them is in
the ch!pter on other 5oo7s !nd reso#rces3
%p!rt 2rom the introd#ction o2 %A" &orth itse2, Progr!mming &orth inc#des e.!mpes
o2 8!rying si:es, e.ercises, some !d8!nced topics, ho4 to t!7e 5est !d8!nt!ge o2 &orth
!nd proJect m!n!gement3
)he m!teri! is deri8ed 2rom co#rse m!teri! 2rom MicroProcessor Engineering !nd
te!ching 4or7 !t )eesside 'ni8ersity 5y 9i "todd!rt !nd Peter (n!ggs, p#s ne4
m!teri!3 9oth the printed !nd the P>& 8ersions !re #pd!ted 2rom time to time to
incorpor!te ch!nges reF#ested 5y re!ders3 62 yo# 4!nt to comment on the 5oo7 pe!se
send 2eed5!c7 to progr!m2orth1mpe2orth3com 0 6 !ppreci!te ! yo#r comments !nd
contri5#tions3
7hat Forth is
&orth is ! mem5er o2 the c!ss o2 e.tensi5e inter!cti8e !ng#!ges, 4hich inc#des
c!ssic! impement!tions o2 "m!t!73 Extensible me!ns th!t there is no distinction
5et4een the 7ey4ords (core 4ords) !nd the ro#tines th!t yo# 4rite3 $nce ! ne4
de2inition h!s 5een compied, e8en 2rom the 7ey5o!rd, it is immedi!tey !8!i!5e to
yo#3 Interactive me!ns th!t yo# c!n t!7 to it 2rom yo#r 7ey5o!rd3
&orth is ! di22erent sort o2 comp#ter !ng#!ge3 &orth code is e!sy to de5#g 5ec!#se &orth
is inter!cti8e, 2!st 5ec!#se &orth is compied !nd po4er2# 5ec!#se it is e.tensi5e3 &orth is
! !ng#!ge 4ith ! de2inite stye3
&orth 4!s de8eoped 5y Ch!res (Ch#c7) Moore in the e!ry 1/60s3 MooreOs 4or7 4ith
comp#ters !t M6) !nd the "t!n2ord Line!r %cceer!tor Centre e2t him diss!tis2ied3 )he
t#rn0ro#nd time 2or editing, compiing !nd r#nning ! progr!m #sing the then c#rrent
gener!tion o2 %LE$L !nd &$B)B%A compiers 4!s too so43 His so#tion to this 4!s
to 4rite ! simpe te.t interpreter in %LE$L 4hich re!d in 4ords (!ny print!5e
ch!r!cters e.cept sp!ce) !nd per2ormed !ctions !ssoci!ted 4ith them3 =ords 4ere either
11
Introduction
prim!ries (i3e3 P#nderstoodP 5y the interpreter) or second!ries (i3e3 de2ined in terms o2
other 4ords)3
%2ter his initi! s#ccess 4ith !n %LE$L 5!sed interpreter !t M6) !nd "t!n2ord, Moore
mo8ed on to 4or7 4ith 9#rro#ghs eF#ipment3 )his h!rd4!re 4!s strongy oriented
!ro#nd ! st!c73 )his in2#enced the 2#rther de8eopment o2 &orth3 6mpement!tions 4ere
4ritten in 9%LE$L, C$9$L !nd "9$L (the 9#rro#ghs "ystems Progr!mming
L!ng#!ge)3 )hese pro8ided m!nip#!tion 4ords 2or the st!c7* DROP, DUP, SWAP, etc3
4hich !re sti 2o#nd in modern &orth systems3 )he 2irst tr#e &orth system 4hich
resem5ed 4h!t 4e no4 percei8e !s &orth 4!s then cre!ted 5y Moore on !n 69M 11303
)he 4ord si:e o2 this m!chine imited the #sers to h!8ing n!mes o2 not more th!n 2i8e
ch!r!cters3 H!d it not 5een 2or this 69M imit!tion the n!me Q&orthO 4o#d h!8e 5een
Q&o#rthO 0 st!nding 2or &o#rth Eener!tion L!ng#!ge3
)he 2irst &orth !ppic!tion 4!s ! B!dio )eescope >!t! %cF#isition Progr!m 4ritten 2or !
Honey4e H316 !t the A!tion! B!dio %stronomy $5ser8!tory3 )his impement!tion o2
&orth #sed ! diction!ry to store 4ords de2ined 5y the #ser3
8ey concepts
)his te.t is deri8ed 2rom ! posting on comp3!ng32orth 5y >4ight E8ey3
Like many programming languages, Forth has an eecution model or virtual machine.
!nlike many languages, Forth eposes this to the programmer.
)he &orth 8irt#! m!chine is disc#ssed in more det!i in the ne.t ch!pter3
"ll source code elements are either num#ers or words. $ords are %hat are called
functions, procedures or su#routines in other languages. $ords can #e either user
defined or part of the Forth core and are entered as a dictionary. $ords are composed
of other Forth elements and&or true machine code.
"ll elements are eecuted in se'uential order, left to right, top to #ottom. (e'uential
order is only #roken #y flo% structure %ords.
)ormal input and output of %ords is #y the data stack, return stack, varia#les *values+,
or arrays.
)esting is maintained #y a return stack. ,ecution of %ords implies nesting, ecept at
the lo%est levels of true machine code.
-he programmer is responsi#le to maintain stacks.
Forth can #e either compiled or interpreted. -hese can #e selected at %ill #y the
programmer #ut is usually done in an orderly fashion.
"ll the rest comes from the a#ove..
$ne o2 the 7ey portions o2 &orth is its inter!cti8ity M yo# sit in 2ront o2 the 7ey5o!rd !nd
p!y (e.pore) 4ith yo#r !ppic!tion3 >!nie Ciesinger 4rote*
Further, / use Forth to test 0 li#raries. ,perience is that this finds errors %hich are
not found #y 0 test procedures. / even prefer it to Rational -est Realtime %hich is too
indirect for my taste. -akes eternities to %rite test cases. /n Forth, you 1ust test
12
Introduction
interactively and cut and paste your test cases into your favourite editor after%ards, so
you can run the same test again..
Interacti+ity9 *e+elopment and Testing
Ei:!5eth B!ther 4rote this posting !5o#t 4or7ing 4ith Ch#c7 Moore (the origin!tor o2
&orth) on comp3!ng32orth*
"ny given pro#lem has a certain intrinsic level of compleity. /n the solution of the
pro#lem, this compleity %ill #e conserved2 if you dive in %ith too little advance
thought, your solution may #ecome very comple #y the time it3s done. 4n the other
hand, if you invest more in thought, design, and preparation, you may #e a#le to
achieve a very simple solution *the compleity hasn3t gone a%ay, it3s #ecome em#odied
in the sophistication of the design+.
/n connection %ith our recent discussion, that investment certainly can take the form of
prototyping. $hen / %as %orking %ith 0huck, he3d typically go through the follo%ing
process2
1. Read the spec. "ssert confidently that it really isn3t as complicated as that, and %rite
a very clever program that solves the essence of the pro#lem.
2. ,nter a phase in %hich the customer repeatedly points out aspects of the spec that
have #een ignored or omitted5 in fiing these, the code gets more and more complicated.
6. "t some point, a full understanding of the pro#lem emerges. "ll the previous code is
thro%n out and a ne% program emerges %hich represents a simple, elegant solution to
the whole pro#lem.
Ei:!5ethLs notes i#str!te th!t coding is not the m!Jor p!rt o2 dei8ering so2t4!re3 6 !m
8ery r!rey gi8en ! 2orm! speci2ic!tion 2or ! ne4 piece o2 so2t4!re, despite the e22ort,
time !nd cost0s!8ings th!t ! good speci2ic!tion pro8ide3 =riting ! piece o2 so2t4!re is
mosty !n iter!ti8e process in8o8ing e.por!tion, design, coding !nd de5#gging3 )hese
re!ities o2 the so2t4!re engineerLs i2e e!d to techniF#es 4hose 5#::4ords inc#de
;r!pid prototyping< !nd ;e.treme progr!mming<3 6n s#ch !n en8ironment, de5#gging is
2!r more e.pensi8e th!n coding in 5oth time !nd cost3
"ow to *ebug
6nter!cti8e testing !nd de5#gging is ! 7ey 2e!t#re o2 &orth3 B!pid de5#gging c!n 5e
!chie8ed 5y the !ppic!tion o2 2orm! scienti2ic method3 )he side 5eo4 is t!7en 2rom
one o2 o#r co#rse present!tions3
13
Introduction
)he di!gr!m !5o8e sho4s th!t de5#gging consists o2 t4o nested oops3 Ho4 2!st yo#
c!n go !ro#nd the inner oop determines ho4 2!st yo# c!n de5#g ! system3 6nter!cti8e
de5#gging is the 2!stest ro#te 6 h!8e 2o#nd3 )he st!ges o2 de5#gging !re*
1) M!7e the pro5em repe!t!5e3 )his #s#!y in8o8es 2inding o#t 4hich inp#ts c!#se
the pro5em3
2) E!ther d!t! !5o#t the pro5em3 )his o5ser8!tion is cr#ci!, so t!7e this st!ge so4y
!nd c!re2#y3 6 h!8e seen peope immedi!tey dismiss e.ception disp!ys !nd cr!sh0
d#mps 4hich cont!in 8it! c#es3
3) &rom the d!t!, 2orm ! hypothesis !s to 4h!t c!#sed the pro5em3
,) >esign !n e.periment 4hich tests the hypothesis3 )he import!nt p!rt in designing
the e.periment is to ens#re th!t it gi8es ! yesIno !ns4er3
5) B#n the e.periment3 62 the hypothesis is incorrect, go 5!c7 to st!ge 23
6) &i. the pro5em3
7) 62 yo# h!8e more 5#gs to 2i., go 5!c7 to st!ge 1 2or the ne.t pro5em3
&orth is ! 4onder2# too 2or de5#gging systems !nd their so2t4!re3 E22ecti8e de5#gging
in !ny progr!mming !ng#!ge reF#ires #s to #nderst!nd the techniF#es reF#ired 2or
e22icient de5#gging !nd ho4 to !cF#ire the reF#ired in2orm!tion3
14
Figure 1) *ebugging
10
>e5#gging 2
Formal scientific method
applied to software
Debugging is not an art -
Debugging is a method
S upport it at the lowest
level
Methodologyis important
1. There is a problem
2. ather D!T!
". Form #$%&T#'S(S from D!T!
). Design '*%'+(M',T
-. %rove #$%&T#'S(S with '*%'+(M',T
.. Fi/this problem
0ntil you believe you have tested everything
Debuggingis the problem
Spec 1 22-2-3
4ode 1 22-2-3
Debug 5 (ntegrate 1 6-23
Introduction
7riting programs in Forth
&orth o2ten t!7es ! itte onger to e!rn th!n other !ng#!ges3 K#st i7e spo7en !ng#!ges,
there !re m!ny 4ords to e!rn in &orth 5e2ore yo# c!n #se it 4e3 6n &orth p!r!nce, 4h!t
!re c!ed 2#nctions, proced#res or s#5ro#tines in other !ng#!ges !re c!ed words3 &orth
is ! !ng#!ge in 4hich 8ery itte is hidden 2rom yo#3 Ae!ry e8ery 4ord th!t 4e #sed
!ong the 4!y to some other 2#nction h!s ! n!me, !nd is doc#mented in ! glossary3
%s ! res#t o2 this openness there !re m!ny 4ords in the diction!ry (type WORDS to see
them)3 &#nctions in &orth !re c!ed 4ords in &orth J!rgon3 )hese 4ords !re stored !s !
dictionary, !nd the gro#p o2 4ords 2orming yo#r !re! o2 interest 0 the conte.t in 4hich
yo# 4or7 0 is 7no4n !s ! vocabulary3 &or e.!mpe, 4ords #sed to de2ine the !ssem5er
!re o2ten 7ept in ! 8oc!5#!ry c!ed ASSEMBLER3 %s in ! comp#ter !ng#!ges, there is
! J!rgon to &orth3 6n this inst!nce the J!rgon is ! technic! !ng#!ge, !nd ser8es !s ! set o2
comm#nic!tion toos so th!t 4e c!n e.p!in o#r ide!s to e!ch other 4itho#t 5eing 5ogged
do4n in the min#ti!e3 Perse8ere, &orth is not ony 4e 4orth the e22ort, 5#t is ! too o2
spect!c#!r prod#cti8ity in the right h!nds3
)he &orth r#n0time p!c7!ge is !ct#!y ! comp!ct com5in!tion o2 interpreter, compier,
!nd toos3 % comm!nd or seF#ence o2 comm!nds (4ords) m!y 5e e.ec#ted directy 2rom
the 7ey5o!rd, or o!ded 2rom m!ss stor!ge !s i2 2rom the 7ey5o!rd3 6n hosted 8ersions o2
&orth (!nd some em5edded systems), yo# c!n !so t!7e inp#t 2rom ! norm! oper!ting
system te.t 2ie, cre!ted 5y ! norm! (non0&orth editor)3 Progr!ms in &orth !re compied
2rom com5in!tions o2 e.isting 4ords (!re!dy in the diction!ry), ne4 4ords !s de2ined 5y
the #ser, !nd contro str#ct#res s#ch !s IF ... ELSE ... THEN or DO ... LOOP3
$2ten, ne4 4ords !re de8eoped inter!cti8ey !t the termin! 5e2ore the 2in! (!nd tested)
8ersion is then entered #sing the editor !nd s!8ed on disc, 4here it c!n 5e in8o7ed 2rom
the 7ey5o!rd or #sed 5y !nother progr!m3 62 yo# !re te!ching yo#rse2 &orth, get ! yo#r
5oo7s re!dy in 2ront o2 the termin!, !nd try things o#t !s yo# go !ong3
)he 5e!#ty !nd po4er o2 &orth ies in inter!cti8ity, e.tensi5iity !nd 2e.i5iity3 Ae4
4ords c!n 5e !dded either !t high or o4 (!ssem5er) e8e3 &orth is one o2 the 8ery 2e4
!ng#!ges 4hich c!n de2ine ! d!t! str#ct#re !nd ho4 it is #sed inside ! singe de2inition3
)his !5iity to cre!te ne4 4ords 7no4n !s defining words, 4hich c!n !dd ne4 c!sses o2
oper!tors to the !ng#!ge, is one o2 the 7eys to the e.tr!ordin!ry po4er o2 &orth in the
h!nds o2 !n e.perienced progr!mmer3 % 5!d &orth progr!mmer is J#st !s m#ch ! dis!ster
!s in !ny other !ng#!ge3
62 yo#r e.perience o2 progr!mming h!s 5een in tr!dition!y org!nised !ng#!ges s#ch !s
C or 9%"6C, yo# 4i 2ind re!ding !nd 4riting progr!ms in &orth some4h!t 5i:!rre !t
2irst3 P!tience 5rings rich re4!rds3 &orth 5ecomes m#ch e!sier to #nderst!nd once yo#
h!8e m!stered ! 2e4 ide!s !nd p!yed 4ith the !ng#!ge3 %mong the most import!nt !ids
in #sing &orth is the choice o2 4ord n!mes3 )hin7 !5o#t the n!me o2 ! 4ord in !d8!nce3
Poets m!7e good &orth progr!mmers3 @er5s, no#ns, !nd !dJecti8es ! h!8e their p!ce in
good &orth progr!mming stye3 Eood choice o2 4ord n!mes e!ds to 8ery re!d!5e code,
!s does the #se o2 4hite sp!ce in so#rce code3 Go# c!n #se !ny ch!r!cter 4ithin ! 4ord
n!me 0 the #se o2 print!5e ones is sensi5e3 =ord n!mes c!n 5e #p to 31 ch!r!cters ong
(more in some impement!tions), !nd ! the ch!r!cters !re signi2ic!nt3
&orth progr!ms 7eep most o2 their 4or7ing 8!ri!5es on the st!c7, r!ther th!n in n!med
8!ri!5es, so re!ding some sections o2 code c!n 5e ! itte mind05ogging 0 e8en 2or the
e.perienced3 )he secret is to 7eep de2initions short !nd simpe3 L!:y progr!mmers o2ten
15
Introduction
m!7e good progr!mmers 5ec!#se they m!7e i2e e!sy 2or themse8es 0 !nd p!rt o2 m!7ing
i2e e!sy is m!7ing s#re th!t yo# c!n 4or7 o#t 4h!t the code is doing ! ye!r 2rom no43
)he !ng#!ge ends itse2 4e to 5ottom0#p coding3 Li7e the choice o2 4ord n!mes, this
c!n 5e ! do#5e0edged s4ord3 )here is no s#5stit#te 2or good o8er! progr!m design,
4hich c!n ony 5e done propery 2rom the top do4n3 9ottom0#p design !nd coding is
e.ceent, ho4e8er, 2or e.poring the n#ts !nd 5ots o2 techniF#es, !gorithms, !nd o40
e8e inter2!ces3 )he !5iity to inter!cti8ey cre!te, test, !nd prod#ce 4or7ing code e!ry in
the de8eopment cyce is in8!#!5e3 E!ry 4or7ing code !so heps to 7eep yo#r 5oss o22
yo#r 5!c7, !nd it en!5es c#stomers to m!7e sensi5e re!ctions !nd disco8er speci2ic!tion
errors 5e2ore it is too !te3 C!re2#y #sed this 2e!t#re c!n s!8e yo# ! gre!t de! o2 time3
9ottom0#p coding h!s !n !ddition! !d8!nt!ge in th!t it is e!sy to test 4ith the &orth
interpreter3 "ince yo# c!nnot #se ! 4ord #nti ! its components h!8e 5een de2ined, yo#
simpy test !n !ppic!tion in the order o2 the so#rce code3 E!ch component th!t yo# test is
then 5!sed on pre8io#sy tested code3 )his is ! much more rei!5e str!tegy th!n testing 5y
r#nning the competed !ppic!tion3
Go# m!y 4e 2ind it pro2it!5e to st#dy the so#rce code o2 the progr!ms s#ppied in the
2ies 4ith yo#r &orth !s ! g#ide to stye3 )he stye is the one 4e #se, !nd h!s e8o8ed o8er
! n#m5er o2 ye!rs, r!ther th!n thro#gh !ny theoretic! !rg#ments3 =e 2ind it #s!5e 5y
5oth the !#thors !nd those 4ho h!8e to re!d other peopeOs code3 Be!d the goss!ry
doc#ment!tion, !nd spend ! 4hie trying o#t the 2#nctions, !nd o5ser8ing their !ction on
the st!c73
'ditors
&orth so#rce code is #s#!y hed in reg#!r te.t 2ies3 Go# c!n #se yo#r progr!mming
editor o2 choice3 &orth synt!. coo#ring 2ies !re !8!i!5e 2or m!ny o2 them3 )he MPE
&orth !yo#t st!nd!rd disc#sses MPE pr!ctice 2or !ying o#t so#rce code3
)he e!rier RscreenL or R5oc7L !yo#t o2 &orth so#rce code is no4 o5soete e.cept 2or
speci! #se, mosty on em5edded systems or 2or eg!cy re!sons3 9oc7 editors !re
disc#ssed in the ch!pter on eg!cy iss#es3
Forth Implementation
%s 4ith ! comp#ter !ng#!ges, &orth h!s e8o8ed o8er time3 )his 5oo7 !ss#mes the #se
o2 !n %A" &orth 4hich con2orms to the %A" &orth st!nd!rd p#5ished in 1//,3 %t the
time o2 4riting in 2005, the %A" &orth st!nd!rd is the most 4idey #sed3
Modern &orth impement!tions #s#!y gener!te optimised n!ti8e code, !nd the good
ones prod#ce code o2 the s!me F#!ity !s the good C compiers3 &or those CP's in the
em5edded 4ord 4here code density is more import!nt th!n per2orm!nce, thre!ded code
(interpreted code) impement!tions !re sti #sed, o2ten 4ith imited peephoe
optimis!tion3
)he di22erent impement!tion str!tegies !re disc#ssed in the &orth intern!s ch!pter3
:P'isms
9ec!#se this 5oo7 4!s 4ritten !t MPE #sing MPELs @&C &orth 2or =indo4s 2or testing
the code, it ine8it!5y s#22ers 2rom the #se o2 ! 2e4 idioms 4hich !re speci2ic to MPELs
16
Introduction
impement!tions3 6 h!8e tried to !8oid these !nd 4here !ppropri!te they !re m!r7ed3 &or
e.!mpe,
MPEism: M7, implementations of Forth do not care a#out the case of characters in
Forth %ord names. CAT is the same as cat is the same as Cat. ,m#edded comments may
#e as long as you %ish %ithout a space or speed penalty in the compiled code.
17
2 Architecture of Forth
Most progr!mming !ng#!ges, inc#ding C, h!8e !n #nderying !rchitect#re or mode
o2 the comp#ter3 )his is o2ten c!ed the !ng#!geLs virtual machine (@M),
reg!rdess o2 ho4 the 2in! 5in!ry code is prod#ced3
)his ch!pter inc#des some det!is 4hich yo# do not need to !ppreci!te 2#y to #se
&orth, 5#t !re descri5ed here 5ec!#se they !re ! conseF#ence o2 the !rchitect#re o2
&orth3 Go# c!n !4!ys come 5!c7 to these !ter3
Forth 4irtual :achine
C!ssic! or c!nonic! &orth 8ie4s the 4ord !s ! CP' connected to m!in memory
!nd t4o st!c7s3 )he st!c7s !re not !ddress!5e, !nd !re F#ite sep!r!te 2rom m!in
memory3 C 8ie4s the 4ord !s ! CP' connected to memory, 4hich inc#des ! ist o2
2r!mes (#s#!y ! st!c7 o2 2r!mes) 4hich must 5e in !ddress!5e memory3


MPEism: 8y adding the necessary registers for the frame stack to the canonical
Forth machine, %e can support local varia#les in Forth and 09isms needed to
interface efficiently to operating systems %ith 0 and 7ascal calling conventions. -his
model is called the (,):/- virtual machine after the pro1ect %hich developed it.
)he "EA>6) @M oo7s rem!r7!5y simi!r to other st!c7 m!chine CP's deri8ed
2rom ! &orth !rchitect#re !nd designed to e.ec#te C e22icienty3
18
Figure 2) Forth and C 4irtual :achines
CPU
Main Memory
Data
Stack
Return
Stack
CPU
Main Memory
incluin!
"rame Stack
"ort# $M C $M
Introduction
"e8er! impement!tions o2 d#! st!c7 !rchitect#res h!8e 5een prod#ced in siicon 2or
#se in h!rd re!0time em5edded systems, 2or 4hich the 5est de2inition comes 2rom
9ernd P!ys!n 0 ;L!te !ns4ers !re 4rong !ns4ers<3 $n some occ!sions e!ry !ns4ers
!re !so 4rong !ns4ers3
9ec!#se d#!0st!c7 processors h!8e 8ery 2e4 registers, interr#pt response is
e.ceent3 % 10 MH: B)C2000 h!s !n interr#pt response o2 2o#r cyces, ,00ns, !nd
4e h!8e seen ! 8ideo !ppic!tion 4ith ! 1 MH: (not ! typo) interr#pt r!te3 9ec!#se o2
this, st!c7 CP's 4ith !pp!renty o4 coc7 r!tes !re #sed in speci!ised !ppic!tion
!re!s3
-tacks and postfi( notation
&orth cont!ins t4o st!c7s, one 2or storing ret#rn !ddresses (4h!t 4!s 6 doing
!stI4here do 6 go 5!c7 toD), !nd one 2or storing d!t!3 )he 2irst st!c7 is c!ed the ret#rn
st!c7, !nd the second is c!ed the d!t! or p!r!meter st!c73 =here 4e J#st re2er to ;the
st!c7< 4e ne!ry !4!ys me!n the d!t! st!c7, !s this is the one the progr!mmer #ses
most3
)he ret#rn st!c7 hods the ret#rn !ddresses o2 ! the 4ords th!t h!8e 5een c!ed, 5#t
h!8e not yet 5een e2t3 )he ret#rn st!c7 is !so #sed 2or storing tempor!ry d!t! th!t
4o#d ony get in the 4!y i2 7ept on the d!t! st!c73 )his sort o2 d!t! inc#des oop
imits !nd indices, !nd d!t! t!7en o22 the d!t! st!c7 to red#ce the !mo#nt o2 st!c7
m!nip#!tion th!t 4o#d other4ise occ#r3 )here is ! set o2 4ords #sed 2or tr!ns2erring
d!t! 5et4een the st!c7s3
)he d!t! st!c7 is !n e22icient method o2 p!ssing d!t! 5et4een the 4ords th!t m!7e #p !
&orth progr!m3 %ny 4ord th!t needs d!t! t!7es it 2rom the top o2 the st!c7, !nd p#ts
!ny res#ts 5!c7 on top o2 the st!c73 )he 4ord .S c!n 5e #sed to disp!y the contents
o2 the st!c7 4itho#t destroying them3 6t is ! #se2# de5#gging too3 Ae!ry ! modern
processors pro8ide 2or the #se o2 st!c7s, so st!c7 oper!tions !re 8ery 2!st3
1%

Figure !) -';*IT 4: and registers
CPU
Main Memory
incluin!
"rame Stack
Data
Stack
Return
Stack
S&'D() $M an re!i*ter*
PC + ,ro!ram counter
PSP + ,arameter *tack ,ointer
RSP + return *tack ,ointer
"P + -rame ,ointer
"&P + -rame en ,ointer
Introduction
9y 7eeping p!r!meters !nd tempor!ry d!t! on the d!t! st!c7, the ret#rn st!c7 is not
!22ected 5y the n#m5er o2 items p!ssed into or ret#rned 2rom ! 2#nction (4ord)3 )his
me!ns th!t the C eF#i8!ent o2 varargs is e22icienty h!nded, !nd !so th!t ! 2#nction
c!n e22icienty ret#rn more th!n one item 4itho#t resorting to pointers !nd tempor!ry
d!t! str#ct#res3 ConseF#enty, 4ords th!t ret#rn more th!n one item !re common in
&orth3
9ec!#se st!c7s !re #sed 2or d!t! h!nding, the #se o2 post2i., or Be8erse Poish
Aot!tion (BPA), is 8ery s#it!5e3 6n this 2orm o2 4riting !rithmetic e.pressions,
oper!nds (the d!t! #sed) come 5e2ore the oper!tors (ho4 yo# #se the d!t!), 2or
e.!mpe*
)he norm! !ge5r!ic not!tion *0
at**2 + bt + c
is 5etter e.pressed 2or comp#ter e8!#!tion !s *0
(at + b)t + c
4hich is then e.pressed in Be8erse Poish Aot!tion (BPA) !s *0
a t * b + t * c +
Aotice th!t the #se o2 5r!c7ets 5ecomes #nnecess!ry3 )his is 5ec!#se o2 the #se o2 the
st!c7 to hod intermedi!te res#ts3 %tho#gh the #se o2 ! st!c7 is intimid!ting !t 2irst,
!2ter ! 4hie it 5ecomes n!t#r!, !nd e8ent#!y it is ony notice!5e on r!re occ!sions3
Bemem5ering th!t the 4ord . is #sed to print 4h!t is on the top o2 the st!c7 yo# c!n
try ! 2e4 5its o2 !rithmetic3
1 2 + .
4 5 * .
9 3 / .
1 2 + 3 * .
1 2 3 + * .
1 2 3 * + .
Ae!ry ! &orth 4ords remo8e their d!t! 2rom the top o2 the st!c7, !nd e!8e the res#t
5ehind3 =ords i7e + !nd * remo8e t4o items, !nd e!8e one 5ehind3 )here is ! &orth
4ord .S 4hich prints o#t the contents o2 the st!c7 4itho#t destroying the contents3 'se
it 4hene8er yo# 4!nt to see 4h!t is on the st!c73 "o 2!r, 4e h!8e e.ec#ted 4ords 5y
typing their n!mes !t the 7ey5o!rd3
*ata types
&orths !re o2ten ch!r!cterised 5y the si:e o2 !n item on the d!t! st!c7, 4hich is
#s#!y 32 5its or 16 5its3 "e8er! 6, !nd - 5it &orths !so e.ist, !s 4e !s ,, 20 !nd
2, 5it systems3 &orth is !n #ntyped !ng#!ge, so there is nothing to stop yo# !dding !
ch!r!cter to ! n#m5er3 Ao c!sts !re necess!ry3 )he !mo#nt o2 memory needed to
store ! st!c7 item is c!ed ! cell3
=ords th!t oper!te on st!c7 items 4i J#st !ss#me th!t the d!t! is !ppropri!te3 Most
&orth compiers do not chec7 the d!t! types !t !3
%n integer occ#pies ! singe ce on the st!c7, !s does !n !ddress3 62 yo# need !rger
integers, #se ! do#5e integer 4hich occ#pies t4o ces on the d!t! st!c7, most
signi2ic!nt h!2 topmost3
% ch!r!cter is sm!er th!n (or the s!me si:e !s) !n integer, !nd is :ero e.tended to
2i ! ce3
20
Introduction
)4o di22erent 2o!ting point impement!tions !re descri5ed 5y the %A" st!nd!rd3 6n
one, 7no4n !s ! sep!r!ted 2o!t st!c7, 2o!ting point n#m5ers !re hed on ! sep!r!te
st!c7 reser8ed 2or 2o!ting point n#m5ers3 &o!ting point oper!tions th!t reF#ire
integer p!r!meters t!7e them 2rom the d!t! st!c73 )he second 2orm #ses ! com5ined
st!c7, in 4hich 2o!ting point n#m5ers sh!re the d!t! st!c73
7ords and ;umbers
% te.t entered to &orth is tre!ted either !s ! n#m5er (iter!, e3g3 123,) or ! 4ord
(2#nction)3 % #nit o2 te.t is sep!r!ted 5y sp!ces or ine 5re!7s3 )hese #nits !re either
interpreted or compied3 )h!tLs !3 %tho#gh this is ! 8ery simpe process, it is ! 7ey
to the #se o2 &orth3
Interpreting and compiling
&orth cont!ins 5oth !n interpreter !nd ! compier3 6nterpreting me!ns t!7ing the te.t
2ed in, con8erting it into ! 2orm the m!chine c!n e.ec#te, e.ec#ting th!t 2orm, !nd then
disc!rding the e.ec#t!5e 2orm3
Compiing me!ns t!7ing the inp#t te.t, competey con8erting it into ! m!chine
e.ec#t!5e 2orm, 7eeping the e.ec#t!5e 2orm, !nd disc!rding the te.t3 )his c!n
prod#ce ! progr!m th!t r#ns 8ery 2!st, 5#t yo# c!nnot ch!nge !nything 4itho#t 2irst
editing the so#rce te.t, then compiing it (#sing ! sep!r!te progr!m c!ed ! compier),
!nd then o!ding the e.ec#t!5e code 4hen yo# 4!nt to r#n it3
%ny te.t 2ed to &orth, either 2rom the 7ey5o!rd or 2rom m!ss stor!ge, is e.ec#ted or
compied3 Bemem5er, ! comm!nds to &orth !re pre0de2ined O4ordsO in its
O8oc!5#!riesO, conseF#enty &orth c!n oo7 #p the !ddress o2 ! gi8en 4ord 2or !ter
e.ec#tion3 "ome 4ords in &orth ch!nge the 4!y the compier section de!s 4ith te.t3
&or inst!nce 4e co#d de2ine ! 4ord th!t sF#!res the 8!#e gi8en to it3
: squared ( n1 -- n1^2 )
dup * ;
)he !ddress o2 the 4ord : is 2o#nd !nd : is e.ec#tedS the !ction o2 : is to te the
compier section to st!rt de2ining ! ne4 4ord 4hose n!me comes ne.t, squared, !nd
then compie into the ne4 4ord the !ctions o2 the 4ords th!t 2oo43 )his 4o#d c!rry
on 2or e8er #ness 4e h!d ! 4!y o2 stopping it, !nd this is pro8ided 5y Oimmedi!teO
4ords s#ch !s ; 4hich !re !4!ys e.ec#ted, reg!rdess o2 4h!t the compier 4o#d
other4ise 5e doing3
)he !ction o2 ; is to stop the compier compiing 4ord !ddresses, !nd ret#rn it to the
mode o2 e.ec#ting the !ddresses inste!d3 )here !re other 4ords (de2ining 4ords) 4hich
!re #sed to cre!te 4ords s#ch !s : 0 these !re one o2 the 7eys to !d8!nced #se o2 &orth3
%t ! times remem5er, ho4e8er, th!t the 5!sis o2 &orth is !4!ys 8ery simpe3 &orth is
! !ng#!ge 5#it 2rom ! n#m5er o2 8ery simpe ide!s, r!ther th!n one 2o#nded on ! 2e4
compe. systems3
*efining 7ords and Immediate words
"ome 4ords s#ch !s : in the pre8io#s section, !re c!ed de2ining 4ords, 5ec!#se they
!re #sed to de2ine ne4 4ords (squared in the pre8io#s section)S these 4ords !re one
o2 the 7eys to the po4er o2 &orth3 )he 4ord : cre!tes ! ne4 4ord in the diction!ry !nd
s4itches &orth 2rom 5eing !n interpreter to 5eing ! compier3 %ny 4ord n!mes met
2rom no4 on 4i not 5e e.ec#ted, 5#t 4i 5e 2o#nd !nd compied into the diction!ry3
)his process repe!ts #nti stopped, 5#t it c!n ony 5e stopped 5y the e.ec#tion o2
21
Introduction
!nother 4ord, !nd ! 4ords !re 5eing compied, not e.ec#ted3 )his pro5em is de!t
4ith 5y immedi!te 4ords3
)he so#tion to the pro5em o2 the pre8io#s section is to h!8e ! c!ss o2 4ords 4hich
!re !4!ys e.ec#ted, reg!rdess o2 4hether &orth is s#pposed to 5e compiing3 "#ch
4ords !re c!ed immediate 4ords3 )he 4ord ; #sed to termin!te ! high e8e
de2inition, is !n e.!mpe o2 s#ch ! 4ord3 =hen it e.ec#tes it s4itches &orth 2rom 5eing
! compier 5!c7 to 5eing !n interpreter, !nd !so compies the !ction o2 the 4ord EXIT
4hich per2orms the 2#nction o2 ret#rning 2rom ! high e8e 4ord3
Factoring
&!ctoring is the term &orth progr!mmers #se 2or spitting compe. 2#nctions into
se8er! sm!er ones3 6t is ! 7ey !cti8ity in 4riting good &orth3 6t is !so ! 7ey re!son
4hy 4e04ritten &orth progr!ms tend to 5e sm!er th!n those 4ritten in m!ny other
!ng#!ges3 &orth promotes code re#se !t ! 2ine0gr!ined e8e3
9ec!#se o2 the t4o0st!c7 8irt#! m!chine, the per2orm!nce !nd code si:e o8erhe!ds
o2 2!ctoring !re 8ery o43 )hey !re o#t4eighed 5y the 5ene2its o2 e!sy code re#se,
4hich impro8es code si:e, rei!5iity !nd m!int!in!5iity3 Code si:e is red#ced
5ec!#se code is c!ed r!ther th!n repe!ted (c! 5y te.t editor)3 Bei!5iity is
impro8ed 5ec!#se sm! code is e!sier to test i2 it ony occ#rs once3 M!int!in!5iity is
impro8ed i2 code is simpe !nd ony occ#rs once3 62 code ony occ#rs once !nd h!s no
side e22ects s#ch !s modi2ying 8!ri!5es, it c!n 5e competey re4ritten 4ith
con2idence pro8iding th!t the st!c7 e22ect rem!ins the s!me3
&rom the point o2 8ie4 o2 C progr!mmers e!rning &orth, this emph!sis on 2!ctoring
!ppe!rs str!nge3 =hen 6 go 5!c7 to progr!mming in C, 6 2ind my e.pos#re to &orth
!nd 2!ctoring 5ene2its my C code3 6t h!s 5een s!id th!t there !re three types o2
proced#re c!*
1) c! 5y 8!#e
2) c! 5y re2erence
3) c! 5y te.t editor
C! 5y te.t editor is not good pr!ctice in !ny !ng#!ge, yet 6 !m const!nty !m!:ed
5y the n#m5er o2 t4o !nd three ine code #nits in C progr!ms th!t !re repe!ted !g!in
!nd !g!in3 Bepe!ted code #nits sti need testing !nd m!inten!nce3
%n !ddition! 5ene2it o2 2!ctoring is th!t e!ch #nit is simper, #s#!y 4ith 2e4er
items on the st!c7, !nd hence e!sier !nd 2!ster to progr!m3 Progr!mmers ne4 to
&orth 4i 2ind 2!ctoring e!ses the e!rning c#r8e3 %s it h!s 5ig 5ene2its 2!ctoring is !
h!5it to 5e enco#r!ged3
22
How Forth is documented
! "ow Forth is documented
Comments
&orth h!s t4o prim!ry comment 4ords3 Go# c!n p#t te.t 5et4een ro#nd 5r!c7ets M
p!rentheses3 )here m#st 5e ! sp!ce !2ter the opening p!renthesis*
( <comment> )
!ny4here in yo#r so#rce code3 % comment to the end o2 the ine is st!rted 5y !
5!c7s!sh #sed !s ! 4ord*
<code> \ <comment>
62 yo# 4!nt to disp!y mess!ges 4hie ! 2ie is 5eing compied 5y
INCLUDE <filename>
Go# c!n #se the 4ord .( 4hich 5eh!8es i7e the ( comment 5#t disp!ys the te.t3
.( This is displayed during compilation )
-tack comments
=ords in this 5oo7 !re doc#mented in ! stye pop#!r 4ith m!ny &orth progr!mmers3 6t
sho4s 4h!t is on the st!c7 5e2ore the 4ord e.ec#tes (the inp#t), !nd 4h!t is on the st!c7
!2ter the 4ord h!s e.ec#ted (the o#tp#t)3 )he top o2 the st!c7 is right o2 the gro#p, !nd the
e.ec#tion point is m!r7ed 5y t4o d!shes3
)he m#tipy oper!tor * t!7es t4o p!r!meters on inp#t, !nd e!8es one on o#tp#t3 6t is th#s
sho4n*
( n1 n2 -- n3 )
or
\ n1 n2 -- n3
)he ro#nd 5r!c7ets !re &orthOs 4!y o2 m!r7ing ! comment, !nd n2 is the top o2 the st!c7
5e2ore e.ec#tion3 6n the m!n#! &orth 4ords !re 4ritten in c!pit! etters to disting#ish
them 2rom the o4er c!se etters o2 the rest o2 the te.t3 6t does not m!tter 4hich yo# #se in
yo#r progr!ms3 Person!y, 6 pre2er the oo7 o2 progr!ms 4ritten in o4er c!se3 %
chidren !re t!#ght to re!d #sing o4er c!se etters3 % 7ey5o!rds !re m!r7ed in #pper
c!se, e8en those 2or #se 5y chidrenT
;otation
>!t! items !re descri5ed #sing the 2oo4ing not!tion
OPERAND DESCRIPTION
n1,n2.. signed numbers (integers)
d1,d2.. double precision signed numbers
u1,u2.. unsigned numbers (integers)
23
How Forth is documented
ud1,ud2.. double precision unsigned numbers
addr1.. address
b1,b2.. bytes
c1,c2.. ASCII characters
char1,char22.. ASCII characters
t/f,t,f boolean flag, true, false
0=false, nz=true,
flag 0=false, -1 =true
Aote th!t the %A" st!nd!rd #ses f 2or ! 2!g, 4here!s m!ny progr!mmers sti #se t !nd
f to indic!te tr#e !nd 2!se3
24
First words in Forth
# First words in Forth
)he ony s#re 4!y to e!rn &orth is to #se it3 &orth progr!mmers spend more time !t
the termin!, 5ec!#se the inter!cti8e n!t#re o2 the !ng#!ge me!ns th!t 4ords c!n 5e
tested !s soon !s they !re entered3 % res#t o2 this 2e!t#re is th!t s#cceeding 4ords,
4hich #se pre8io#s ones, #se tested code3 %dherence to the proced#re o2 Qtop do4n
designO, 2oo4ed 5y Q5ottom #pO coding !nd inter!cti8e testing, e!ds to 8ery r!pid
de5#gging, !nd s#ccess2# progr!m gener!tion3 %#dits o2 !rge so2t4!re proJects re8e!
th!t o8er h!2 the time m!y 5e spent on de5#gging3 %s this is the !rgest singe !cti8ity,
it is the one to red#ce3 62 yo# !re !t ! interested in so2t4!re m!n!gement, do re!d &red
9roo7Os 5oo7, O)he Mythic! M!n0MonthO3
)o 4rite ne4 4ords yo# c!n either J#st type them in !t the 7ey5o!rd, or yo# c!n #se
the editor to p#t so#rce code in ! 2ie3
62 yo# decide J#st to enter the e.!mpes directy, yo# do not need to enter the
comments or #se the s!me !yo#t3 6n 2!ct &orth is competey 2ree02orm3 )his me!ns
th!t the position o2 the 4ords is #nimport!nt, ony their order3
MPEism: M7, Forths do not care %hether a %ord is in !77,R 0"(, or in lo%er
case or in Mi;e: case.
&orth 4ord n!mes c!n cont!in !ny ch!r!cters e.cept sp!ces or n#s (%"C66 ch!r!cter
0)3 6t is sensi5e to #se print!5e ch!r!cters, 5#t &orth does not !ct#!y chec7 the
ch!r!cters3
Ae4 &orth 4ords !re de2ined 5y the 4ord 4hose 2irst !ction is to pic7 #p the n!me
th!t 2oo4s !nd #se it to m!7e ! ne4 entry in the diction!ry3 )hen, e8erything th!t
2oo4s #p to the ne.t ; de2ines the !ction o2 the 4ord3
9y comp!rison 4ith e.tended 9%"6Cs is eF#i8!ent to DEFine PROCedure or
DEFine FuNction !nd ! is eF#i8!ent to END PROCedure or END DEFine3
&or e.!mpe*
: NEW-NAME \ --
CR ." This is a new word" CR ;
NEW-NAME
)he e.!mpe 4ord !5o8e is c!ed NEWNAME 0 4hen yo# type NEWNAME it 4i
print ! ne4 ine, !nd the print the te.t Q)his is ! ne4 4ordO, !nd then print !nother ne4
ine3 )he 4ord .! prints o#t ! the ch!r!cters e.cept the sp!ce !2ter .! #p to 5#t not
inc#ding the ne.t do#5e F#ot!tion m!r7 (!)3 )he 4ord "R is ! prede2ined 4ord th!t
gener!tes ! ne4 ine 0 "R st!nds 2or C!rri!ge0Bet#rn3
% ne4 &orth 4ord c!n cont!in !ny 4ords th!t e.ist in the diction!ry3 )he ne4 &orth
4ord c!n 5e e.ec#ted 5y typing its n!me, or inc#ded in the de2inition o2 !nother 4ord3
: TIMES \ n1 n2 --
* . ;
2 4 TIMES
)his e.!mpe 4i m#tipy t4o n#m5ers together !nd print the res#t3 )he 4ord * is
&orthOs m#tipy 4ord, !nd . is the 4ord to print ! n#m5er3 TIMES c!n 5e #sed !s p!rt
o2 ! 4ord th!t presents in2orm!tion more prettiy to the #ser3 &irst 4e print ! ne4 ine
#sing "R then 4e d#pic!te the t4o n#m5ers #sing #DUP !nd print them o#t together
4ith the res#t3 =hy is the 4ord SWAP #sedD )ry it 4itho#t SWAP3
25
First words in Forth
: MULTIPLY ( n1 n2 -- )
CR 2DUP SWAP . ." multiplied by " .
." equals " TIMES CR ;
4 3 MULTIPLY
=e h!8e sho4n the de2inition entered on t4o ines3 =hen yo# type it in there 4i 5e
no Oo7O prompt !2ter the 2irst ine3 )his is 5ec!#se yo# h!8e not 2inished the de2inition3
)he &orth system h!s con8erted the ist o2 4ord n!mes into ! diction!ry entry c!ed
MULTIPL$ !nd its !ssoci!ted code3 )his process is c!ed compi!tion, !nd d#ring
compi!tion so#rce te.t entered 2rom the 7ey5o!rd is disc!rded3
62 yo# 4!nt to 7eep so#rce code !8!i!5e 2or re0#se, #se yo#r st!nd!rd te.t editor, s!8e
the 2ie, con8ention!y 4ith ! 3&)H e.tension, !nd #se the 4ord IN"LUDE to o!d it,
e3g3
INCLUDE MULTIPLY.FTH
4hich 4i compie it J#st !s i2 yo# h!d entered the te.t !t the 7ey5o!rd3 IN"LUDEs
c!n 5e nested inside other 2ies3 M!ny &orth progr!mmers compie 5ig !ppic!tions 5y
compiing ! contro 2ie 4hich J#st inc#des other 2ies3 $n m!ny systems yo# c!n 2ind
the so#rce code o2 ! 4ord 5y typing*
L$C%)E Un!meV
Go# c!n !so o2ten see 4h!t 4!s compied #sing one o2 the 2oo4ing*
DIS <name>
SEE <name>
VIEW <name>
"#ppose 4e h!d ! section o2 ! progr!m th!t h!d to greet peope3 &irst, 4e co#d de2ine
! 4ord to s!y OheoO3 =e #se ! dot !t the 5eginning o2 the n!me 5ec!#se it is ! &orth
con8ention th!t 4ords 4hich print st!rt 4ith ! dot3 =e #se to st!rt ! de2inition
(2oo4ed 5y its n!me) !nd ; to end it3
: .HELLO \ -- ; has no effect on the stack
." Hello " ;
62 yo# no4 type .HELLO UEA)EBV, &orth 4i respond, 2oo4ed 5y Qo7O to sho4 th!t
there 4ere no errors in the !st entry3 =e no4 need some 4ords to print o#t the n!mes
o2 the peope 4e 4!nt to greet3
( -- )
: .FRED
." Fred " ;
: .MARY
." Mary " ;
: .NEIL
." Neil " ;
: .LINDA
." Linda " ;
=e 4i !so need ! 4ord to in7 these together3
: .AND \ --
." and " ;
=e c!n no4 de2ine ! 4ord to greet ! these peope3 &orth 4ords c!n occ#py !s m!ny
ines !s !re needed3 Go# c!n #se ine 5re!7s !nd !ddition! sp!ces to emph!si:e the
phr!sing o2 the 4ord3
26
First words in Forth
: .GREET \ --
.HELLO .MARY .AND .FRED
.AND .LINDA .AND .NEIL CR ;
=hen yo# type .%REET &ENTER', &orth 4i respond 0
Hello Mary and Fred and Linda and Neil ok
%t some st!ge yo# 4i 4!nt to see 4h!t 4ords !re in the diction!ry, to do this enter*
WORDS
Go# 4i see ! ong ist o2 4ords ro p!st3 Go# c!n stop the isting 5y pressing the
sp!ce 5!r3 Press it !g!in !nd the isting 4i contin#e3 Press !ny other 7ey, !nd the
isting 4i 2inish3 % the n!mes yo# see !re the n!mes o2 prede2ined 4ords in &orth,
p#s !ny th!t yo# h!8e cre!ted3 % these 4ords !re !8!i!5e 2or yo# to #se, !nd the
prede2ined ones !re doc#mented !ter in this m!n#!3 )he 4ords th!t yo# 4rite 4i #se
these 4ords !s their 5!sis3
)he secret o2 4riting progr!ms in &orth is to 7eep e8erything simpe3 Bemem5er the
(6"" method (7eep it simpe, st#pid)3 "impe things 4or7, !nd compic!ted things c!n
5e 5#it o#t o2 simpe things3 % progr!mmerOs Jo5 is to decide 4h!t those simpe things
sho#d 5e, !nd then to design !nd code them3 62 the n!mes o2 the 4ords re2ect 4h!t
they !re to do, then the code 4i 5e re!d!5e !nd e!sy to 2oo43 )he ne.t sections gi8e
!n introd#ction to the components o2 &orth, !nd ! description o2 the progr!m contro
str#ct#res !8!i!5e3
27
Components of Forth
$ Components of Forth
$ny the 4ords needed 2or this 5oo7 !re doc#mented here3 Most &orths h!8e m!ny
more3 %n H)ML 8ersion o2 the !st p#5icy !8!i!5e %A" &orth doc#ment, 4hich is
8ery cose to the 2in! st!nd!rd, is pro8ided on the C> s#ppied 4ith this 5oo73 "t!rt
4ith >P%A"3H)M3
*ata stack operations
Le!rning !ny ne4 !ng#!ge in8o8es some gr#nt 4or73 6n &orth, m#ch o2 this gr#nt
4or7 in8o8es e!rning ho4 to m!nip#!te items on the d!t! st!c73 )o F#ote Ei:!5eth
B!ther*
:evelopment of good stack management skills is a core component of Forth practice,
and a key to en1oying its #enefits. /f you regard the stack as a nuisance or an
impediment, you3re missing the %hole point..
9y con8ention the top item o2 the d!t! st!c7 is c!ed )$" !nd second item is c!ed
A$"3 Go# m!y !so see the terms 3$" !nd ,$" in some code3
DUP \ x -- x x
>'Pic!te the top st!c7 item3
(DUP \ x -- 0 | x x
DUPic!te the top st!c7 item ony i2 it is non0:ero3 Ae!ry !4!ys #sed 5e2ore !
condition! 5r!nch3
DROP \ x --
>isc!rd the top d!t! st!c7 item !nd promote A$" to )$"3
SWAP \ x1 x2 -- x2 x1
E.ch!nge the top t4o d!t! st!c7 items3
O)ER \ x1 x2 -- x1 x2 x1
M!7e ! copy o2 the second item on the st!c73
NIP \ x1 x2 -- x2
>ispose o2 the second item on the d!t! st!c73
TU"* \ x1 x2 -- x2 x1 x2
6nsert ! copy o2 the top d!t! st!c7 item #nderne!th the c#rrent second item3
EF#i8!ent to SWAP O)ER3
ROT \ n1 n2 n3 -- n2 n3 n1
B$)!te the positions o2 the top three st!c7 items s#ch th!t the c#rrent top o2 st!c7
5ecomes the second item3
2%
Components of Forth
ROT \ x1 x2 x3 -- x3 x1 x2
)he reciproc! o2 ROT3 Aon %A", 5#t 4idey !8!i!5e3
PI"* \ xu .. x0 u -- xu .. x0 xu
Eet ! copy o2 the #0th d!t! st!c7 item !nd p!ce on top o2 st!c73 + PI"* is
eF#i8!ent to DUP, , PI"* to O)ER !nd so on3
#DUP \ x1 x2 -- x1 x2 x1 x2
DUPic!te the top ce0p!ir on the d!t! st!c73 )
#DROP \ x1 x2 --
>isc!rd the top t4o d!t! st!c7 items3
#SWAP \ x1 x2 x3 x4 -- x3 x4 x1 x2
E.ch!nge the top t4o ce0p!irs on the d!t! st!c73
#O)ER \ x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2
Copy ce p!ir .1 .2 to the top o2 the st!c73
0eturn -tack operations
'R \ x -- ; R: -- x
P#sh the c#rrent top item o2 the d!t! st!c7 onto the top o2 the ret#rn st!c73
R- \ -- x ; R: x -- x
Copy the top item o2 the ret#rn st!c7 !nd p!ce on the d!t! st!c73
R' \ --x ; R: x --
Pop the top item o22 the ret#rn st!c7 !nd p!ce on the d!t! st!c73
#'R \ x1 x2 -- ; R: -- x1 x2
P#sh the c#rrent top ce p!ir 2rom the d!t! st!c7 onto the ret#rn st!c73
#R- \ -- x1 x2 ; R: x1 x2 -- x1 x2
Copy the top ce p!ir o2 the ret#rn st!c7 !nd p!ce on the d!t! st!c73
#R' \ -- x1 x2 ; R: x1 x2 --
Pop the top ce p!ir 2rom the ret#rn st!c7 !nd p!ce on the d!t! st!c73
:aths operations
. \ n1|u1 n2|u2 -- n3|u3
%dd t4o singe precision integer n#m5ers* n3Wn1+n23 )he st!c7 comment
indic!tes th!t the oper!tion 4or7s 2or 5oth signed !nd #nsigned n#m5ers3
\ n1|u1 n2|u2 -- n3|u3
"#5tr!ct t4o singe precision integer n#m5ers* n3Wn10n23
30
Components of Forth
* \ n1 n2 -- n3
"t!nd!rd signed m#tipy* n3 W n1 X n23
/ \ n1 n2 -- n3
"t!nd!rd signed di8ision oper!tor* n3 W n1In23
MOD \ n1 n2 -- n3
"t!nd!rd signed di8ision oper!tor ret#rning the rem!inder* n3 W n1 mod n23
UM* \ u1 u2 -- ud3
%n #nsigned m#tipy th!t prod#ces !n #nsigned do#5e res#t3
*/ \ n1 n2 n3 -- n4
M#tipy n1 5y n2 to gi8e ! do#5e precision res#t, !nd then di8ide it 5y n3
ret#rning the F#otient3 )he point o2 this oper!tion is to !8oid oss o2 precision3
)he %A" st!nd!rd permits systems to restrict n3 to positi8e n#m5ers3 )his 4ord
is ide! 2or sc!ing oper!tions, e3g3 !2ter re!ding !n !n!og#e to digit! con8erter
or con8erting r!di!ns to degrees3
: PI \ n -- n*pi
355 113 */
;
UM/MOD \ ud u -- urem uquot
Per2orm #nsigned di8ision o2 do#5e n#m5er #d 5y singe n#m5er # !nd ret#rn the
rem!inder !nd F#otient3 6n most CP' !rchitect#res th!t h!8e di8ide oper!tions,
the rem!inder is prod#ced !t the s!me time !s the F#otient3 Aote th!t the di8idend
is ! do#5e n#m5er3 $2ten #sed in conJ#nction 4ith UM* 2or sc!ing oper!tions
th!t t!7e !d8!nt!ge o2 !n intermedi!te do#5e res#t to preser8e precision3
NE%ATE \ n1 -- n2
Aeg!te ! singe precision integer n#m5er3
ABS \ n -- u
62 n is neg!ti8e, ret#rn its positi8e eF#i8!ent (!5so#te 8!#e)3
MIN \ n1 n2 -- n1|n2
Bet#rn the esser o2 n1 !nd n23
MAX \ n1 n2 -- n1|n2
Bet#rn the gre!ter o2 n1 !nd n23
Comparisons
6n &orth there is no 5!sic 5ooe!n type3 )he st!c7 8!#e 0 (! 5its ce!r) is t!7en to
represent &%L"E, 4hie !ny other 8!#e is t!7en to represent )B'E3 )he st!c7 not!tion
2!g indic!tes ! ;4e 2ormed 2!g< 4hich me!ns th!t ! )B'E 8!#e is represented 5y !
5its set, 4hich corresponds to the n#m5er 0, 2or most CP's3
31
Components of Forth
& \ n1 n2 -- flag
Bet#rns tr#e i2 n1Un2
' \ n1 n2 -- flag
Bet#rns tr#e i2 n1Vn2
U& \ u1 u2 -- flag
'nsigned, ret#rns tr#e i2 #1U#2
U' \ u1 u2 -- flag
'nsigned, ret#rns tr#e i2 #1V#2
1 \ n1 n2 -- flag
Bet#rns tr#e i2 n1Wn2
&' \ n1 n2 -- flag
Bet#rns tr#e i2 n1 is not eF#! to n2
+1 \ x1 -- flag
Bet#rns tr#e i2 .1W03
+&' \ x1 -- flag
Bet#rns tr#e i2 .1 is not eF#! to 03
WITHIN \ n1|u1 n2|u2 n3|u3 -- flag
Bet#rn )B'E i2 n2Y#2 UW n1Y#1 U n3Y#33 Aote the conditions3 )his 4ord #ses
#nsigned !rithmetic, so th!t signed comp!res !re tre!ted !s e.isting on ! n#m5er
circe3
7idely a+ailable
&1 \ n1 n2 -- flag
Bet#rns tr#e i2 n1UWn2
'1 \ n1 n2 -- flag
Bet#rns tr#e i2 n1VWn2
2itwise logic
AND \ n1 n2 -- n3
Bet#rns n3 W n1 %A> n2
OR \ n1 n2 -- n3
Bet#rns n3 W n1 $B n2
XOR \ n1 n2 -- n3
Bet#rns n3 W n1 C$B n2
32
Components of Forth
IN)ERT \ n1 -- n2
Bet#rns 5it4ise in8erse o2 n13
LSHIFT \ x1 u -- x2
Logic!y shi2t .1 5y # 5its e2t3
RSHIFT \ x1 u -- x2
Logic!y shi2t .1 5y # 5its right3
:emory operations
6n &orth terminoogy items in memory th!t !re the s!me si:e !s items on the d!t! st!c7
!re c!ed ces3 )he 4idth o2 the st!c7 is #s#!y determined 5y the #nderying CP'
!rchitect#re, 5eing 16 5its on 16 5it CP's, 32 5its on 32 5it CP's !nd so on3 &or 5yte0
!ddressed CP's (the m!Jority), ! ch!r!cter is ! 5yte !nd 5ytes in !n !rr!y !re stored !t
consec#ti8e !ddresses3
- \ addr -- n
&etch !nd ret#rn the ce !t memory !ddress !ddr3
2 \ n addr --
"tore the ce F#!ntity n !t memory !ddress !ddr3
.2 \ n addr --
%dd n to the ce !t memory !ddress !ddr3
3- \ addr -- char
&etch !nd :ero e.tend the ch!r!cter !t memory !ddress !ddr3
32 \ char addr --
"tore the ch!r!cter ch!r !t memory !ddress !ddr3
"ELLS \ n1 -- n2
Bet#rns n2, the memory si:e reF#ired to hod n1 ces3 "ELLS impro8es
port!5iity !nd re!d!5iity3
"HARS \ n1 -- n2
Bet#rns n2, the memory si:e reF#ired to hod n1 ch!r!cters3 "HARS impro8es
port!5iity !nd re!d!5iity3
7idely a+ailable
4- \ addr -- val
&etch !nd :ero e.tend the 16 5it item !t memory !ddress !ddr3 's#!y ony 2o#nd
on 32 !nd 6, 5it systems3
33
Components of Forth
42 \ val addr --
"tore the 16 5it item 8! !t memory !ddress !ddr3 's#!y ony 2o#nd on 32 !nd
6, 5it systems3
Constants and +ariables
M!ny times in ! progr!m 4e need to #se ! 8!#e to represent something, ! type o2 2o4er,
or ! 5#s ro#te n#m5er3 $n other occ!sions the 8!#e corresponds to !n !ct#! 8!#e r!ther
th!n !n !ssoci!tion, the price o2 roses tod!y, the %"C66 code 2or ! speci! 7ey3 "ome o2
this d!t! ne8er ch!ngesS it is const!nt3 $ther d!t! ch!nges 2rom d!y to d!y or min#te to
min#te3 )he t4o types o2 d!t! !re cre!ted 5y "ONSTANT, )ARIABLE !nd )ALUE3
A!ming d!t! m!7es progr!ms e!sier to 4rite !nd re!d, !s peope remem5er n!mes more
e!siy th!n n#m5ers3
C/;-TA;Ts
Const!nts !re #sed 4hen the d!t! 4i not ch!nge, or 4i ony 5e ch!nged 4hen the
progr!mmer edits the progr!m (2or inst!nce, to ch!nge ! contro 7ey)3 Const!nts ret#rn
their 8!#e to the st!c73
DECIMAL \ all numbers are in decimal
( -- n )
13 CONSTANT ENTER-KEY
1 CONSTANT DAFFODIL
2 CONSTANT TULIP
3 CONSTANT ROSE
4 CONSTANT SNOWDROP
4A0IA26's
6n &orth ! 8!ri!5e is n!med !nd set #p 5y the 4ord )ARIABLE3
( -- addr )
VARIABLE FLOWER
%t this st!ge ! 8!ri!5e c!ed FLOWER h!s 5een dec!red 4ith !n initi! 8!#e o2 0 on
most systems3 )he %A" st!nd!rd does not m!nd!te ! speci2ic initi! 8!#e3 =hen yo# #se
FLOWER the !ddress o2 the d!t! is gi8en3 &orth #ses - (O2etchO) to 2etch the d!t! 2rom the
!ddress, !nd " (OstoreO) to store d!t! into !n !ddress3 62 ! speci2ic initi! 8!#e is needed 4e
c!n ch!nge it3
DAFFODIL FLOWER !
L!ter on in ! progr!m 4e c!n #se the 8!#e o2 FLOWER to ch!nge the 4!y the progr!m
!cts3 P!rt o2 the progr!m might 5e !5o#t to dr!4 the 2o4er, !nd 4e need to set the coo#r
propery3
: DAFF \ --
FLOWER @ DAFFODIL =
IF YELLOW INK THEN ;
)o m!7e ! progr!m 4!it #nti the EA)EB 7ey is pressed, yo# c!n try the code 5eo43
: WAIT-ENTER \ -- ; wait for <CR>
BEGIN KEY ENTER-KEY = UNTIL ;
34
Components of Forth
6n most 4ords d!t! is p!ssed 2rom 4ord to 4ord #sing the st!c73 62 yo# 2ind the st!c7
#s!ge getting too compe., try spitting the 4ord into other 4ords 4hich ony #se one or
t4o items on the st!c73 $n other occ!sions yo# 4i 2ind th!t ! the 4ords need to re2er to
the s!me 8!#e 4hich contros 4h!t h!ppens on this r#n o2 the progr!m (s!y, the type o2
2o4er)3 6n these c!ses the #se o2 ! 8!ri!5e is !ppropri!te3 %s yo#r &orth s7is impro8e,
yo# 4i 2ind th!t yo# #se 2e4er 8!ri!5es3
4A65's
)he 4ord )ALUE cre!tes ! 8!ri!5e th!t ret#rns its contents (8!#e) 4hen re2erenced,
!nd is 4idey #sed 2or 8!ri!5es th!t !re mosty re!d !nd r!rey ch!nged3 % )ALUE is
de2ined 4ith !n initi! 8!#e3
55 VALUE FOO
6n em5edded systems, yo# c!n rey on ! )ALUE 5eing initi!ised !t po4er #p, 4here!s
the %A" speci2ic!tion does not reF#ire )ARIABLEs to 5e initi!ised3 Go# get the
contents o2 ! @%L'E 5y re2erring to it, 5#t yo# set it 5y pre2i.ing it 4ith the 4ord TO3
: test \ n --
cr . The value of FOO was foo .
to foo
. and is now foo .
;
Control structures
% contro str#ct#re is one th!t !o4s yo# to contro the 4!y ! progr!m 5eh!8es depending
on the 8!#e o2 some piece o2 d!t! yo# h!8e pre8io#sy c!c#!ted3 )his gi8es ! progr!m
the po4er o2 choosing to do this i2 one thing h!ppens, or th!t i2 !nother thing h!ppens3
Contro str#ct#res in &orth !o4 e.ec#tion !nd ooping determined 5y 8!#es on the st!c73
%tho#gh the #ser is not necess!riy !4!re o2 it, contro str#ct#res !re #s#!y
impemented 5y me!ns o2 4ords th!t e.ec#te !t compie time (immedi!te 4ords), !nd
compie other 4ords th!t !ct#!y e.ec#te !t r#n time3 )echniF#es i7e these !o4 error
chec7ing to 5e impemented !s 4e3 Contro str#ct#res m#st 5e #sed inside ! coon
de2initionS they c!nnot 5e directy e.ec#ted 2rom the 7ey5o!rd3 %ny one str#ct#re m#st 5e
4ritten entirey 4ithin one de2initionS yo# c!nnot p#t the IF in one 4ord !nd the THEN in
!nother3 Contro str#ct#res c!n 5e nested inside one !nother, 5#t they m#st not o8er!p3
%tho#gh it is possi5e to 4rite oops !nd contro str#ct#res th!t ret#rn ! 8!ri!5e n#m5er
o2 items on the st!c7, this pr!ctice e!ds to errors !nd is not recommended3
IF ... T"';
flag IF <true words> THEN
)he 2!g on the top o2 the st!c7 contros e.ec#tion3 62 the 2!g is non0:ero (tr#e), the 4ords
5et4een IF !nd THEN !re e.ec#ted, other4ise they !re not3
Li7e most &orth 4ords IF cons#mes the 2!g #sed !s inp#t to it3 62 the 8!#e o2 the 2!g
m#st 5e #sed !g!in it c!n 5e d#pic!ted 5y DUP3 6n the c!se o2 IF 3333 THEN, 4here the
8!#e m!y ony 5e needed 5et4een IF !nd THEN, the #se o2 (DUP, 4hich ony d#pic!tes
! n#m5er i2 it is non0:ero, m!y 5e more !ppropri!te3
35
Components of Forth
: TEST \ flag --
IF ." top of stack is non-zero " THEN ;
1 TEST top of stack is non-zero ok
0 TEST ok
IF...'6-'...T"';
flag IF <true words> ELSE <false words> THEN
)his str#ct#re 5eh!8es J#st i7e IF 333 THEN !5o8e e.cept th!t !n !tern!te set o2 4ords
4i e.ec#te 4hen the 2!g is 2!se (:ero)3
: TEST \ flag
IF ." top of stack is non-zero "
ELSE ." top of stack is zero "
THEN
;
1 TEST top of stack is non-zero ok
0 TEST top of stack is zero ok
'<IT
EXIT c!#ses ! ret#rn 2rom the c#rrent de2inition3 9e2ore #sing EXIT yo# m#st ens#re
th!t the d!t! st!c7 is correct !nd th!t !nything yo# p#t on the ret#rn st!c7 4ith 'R h!s
5een remo8ed3 EXIT is o2ten #sed 4hen !n error chec7 2!is3
: FOO \ a b c result
TEST1
IF DROP 2DROP <errcode1> EXIT THEN
TEST2
IF DROP 2DROP <errcode2> EXIT THEN
...
0 \ for success
;
*/ ... 6//P and */ ... n =6//P
limit index DO <loop words> LOOP
limit index DO <loop words> <increment> +LOOP
)his str#ct#re is 8ery ro#ghy the s!me !s 9%"6COs &$B CW1 )$ 103333AEC)3
)o #se this str#ct#re, p!ce the imit 8!#e !nd the st!rting 8!#e o2 the oop inde. on the
st!c73 DO 4i cons#me this d!t! !nd tr!ns2er it to the ret#rn st!c7 2or #se d#ring
e.ec#tion o2 the oop3 LOOP 4i !dd one to the inde. !nd comp!re it to the imit3 62 the
inde. is sti ess th!n the imit the oop 4i 5e e.ec#ted !g!in3 %s ! res#t o2 this the imit
8!#e is ne8er #sed3 .LOOP 5eh!8es in the s!me 4!y e.cept th!t the increment on the
st!c7 is !dded to the inde.3
Go# c!n get o#t o2 the oop e!ry 4ith the 4ords LEA)E or (LEA)E3
LEA)E ( 5 ce!ns #p the ret#rn st!c7, !nd e.ec#tion then res#mes !2ter the LOOP
or .LOOP3 Aote th!t 4ords 5et4een LEA)E !nd LOOP or .LOOP !re not e.ec#ted3
36
Components of Forth
(LEA)E 5eh!8es i7e LEA)E e.cept th!t the oop is e2t ony i2 the top o2 the st!c7 is
non0:ero3 )his is ! #se2# 4ord 4hen chec7ing 2or errors3 )his 4ord is non0%A" 5#t is
4idey !8!i!5e3 6t is eF#i8!ent to IF LEA)E THEN3
DO ... LOOP str#ct#res m!y 5e nested to !ny e8e #p to the c!p!city o2 the ret#rn
st!c73 )he inde. o2 the c#rrent oop is inspected #sing I ( 6 53 )he inde. o2 the
ne.t o#ter oop is inspected #sing 7 ( 6 53
62 yo# need to termin!te the oop e!ry !nd get o#t o2 the c#rrent 4ord 5y #sing EXIT (see
!5o8e) the code 4i not p!ss thro#gh LOOP or .LOOP3 6n this c!se yo# m#st remo8e the
oop contro in2orm!tion #sing UNLOOP ( 53 )he 2oo4ing 4ord pos the
7ey5o!rd e8ery 100 miiseconds 2or one second3 6t ret#rns ! 7ey code immedi!tey i2 !
7ey is pressed, or ret#rns ! :ero !2ter one second i2 no 7ey h!s 5een pressed3
: TESTKEY \ -- char|0
10 0 DO \ ten times
KEY? IF \ true if char
KEY \ get character
UNLOOP EXIT \ clean up and get out
THEN
100 MS \ wait
LOOP
0 \ no key
;
#$%&' ()% 0
62 yo# #se the ret#rn st!c7 2or tempor!ry stor!ge !2ter DO, yo# m#st remo8e it 5e2ore
LOOP or .LOOP3
62 there is d!t! on the ret#rn st!c7 I !nd 7 4i ret#rn incorrect 8!#es3
)he oop 4i !4!ys 5e e.ec#ted !t e!st once3 62 yo# do not 4!nt this to h!ppen yo# m#st
!dd e.tr! code !ro#nd the oop or #se (DO , 4hich ony e.ec#tes i2 the imit is not the
s!me !s the inde.3
E.!mpe*
: TEST \ -- ; display numbers 1..9
10 1 DO I . LOOP ;
TEST<cr> 1 2 3 4 5 6 7 8 9 ok
: TEST2
10 1 DO I . 3 +LOOP ;
TEST2<cr> 1 4 7 ok
#$%&' ()% 0
: TEST3 \ -- ; display 9..0 in descending order
0 9 DO I . -1 +LOOP ;
TEST3<cr>9 8 7 6 5 4 3 2 1
=hen the oop increment is neg!ti8e, DO8.LOOP 4i inc#de !n iter!tion 4ith the
imit3 )his occ#rs 5ec!#se the oop test is dependent on the CP' o8er2o4 2!g3
37
Components of Forth
>*/ ... 6//P and >*/ ... n =6//P
limit index ?DO <loop words> LOOP
limit index ?DO <loop words> increment +LOOP
)hese str#ct#res 5eh!8e in the s!me 4!y !s DO 333 LOOP !nd DO 333 6 .LOOP e.cept the
oop is not e.ec#ted !t ! i2 the inde. !nd the imit !re eF#! on entry3 &or e.!mpe i2 the
4ord SPA"ES 4hich prints n sp!ces is de2ined !s*
: SPACES \ n --
0 DO SPACE LOOP ;
the phr!se + SPA"ES c!#ses 65536 sp!ces to 5e disp!yed on ! 16 5it system (2Z32
sp!ces on ! 32 5it system), 4here!s the de2inition 5eo4 disp!ys no sp!ces3
: SPACES \ n --
0 ?DO SPACE LOOP ;
2'?I; ... A?AI;
BEGIN <words> AGAIN
)his str#ct#re 2orms ! oop th!t ony 2inishes i2 !n error condition occ#rs, or ! 4ord s#ch
!s THROW, ABORT or 9UIT (see !ter) is e.ec#ted3 )he 2irst e.!mpe 4i re!d !nd echo
ch!r!cters 2rom the 7ey5o!rd 2ore8er, the second 4i e.it 4hen the EA)EB 7ey is
pressed3
E.!mpe*
: TEST \ -- ; runs forever
BEGIN KEY EMIT AGAIN ;
DECIMAL
: TEST2 \ -- ; runs until CR pressed
BEGIN KEY DUP 13 =
IF ABORT THEN \ could use EXIT
EMIT
AGAIN ;
2'?I; ... 5;TI6
BEGIN <words> flag UNTIL
)his str#ct#re 2orms ! oop 4hich is !4!ys e.ec#ted !t e!st once, !nd e.its 4hen the
4ord UNTIL is e.ec#ted !nd the 2!g (on the d!t! st!c7) is tr#e (non0:ero)3 62 yo# need to
#se the termin!ting condition !2ter the oop h!s 2inished #se (DUP to d#pic!te the top
item o2 the st!c7 i2 it is non0:ero3
BE%IN ... UNTIL oops m!y 5e nested to !ny e8e3
E.!mpe*
: TEST
BEGIN KEY DUP EMIT 13 = UNTIL ;
38
Components of Forth
2'?I; ... 7"I6' ... 0'P'AT
BEGIN <test words> flag WHILE <more words> REPEAT
)his is the most po4er2# !nd perh!ps the most eeg!nt (tho#gh cert!iny not some
p#ristsL choice) o2 the &orth contro str#ct#res3 )he oop st!rts !t BE%IN !nd ! the
4ords !re e.ec#ted !s 2!r !s WHILE3 62 the 2!g on the d!t! st!c7 is non0:ero the 4ords
5et4een WHILE !nd REPEAT !re e.ec#ted, !nd the cyce repe!ts !g!in 4ith the 4ords
!2ter BE%IN3
)his str#ct#re !o4s 2or e.tremey 2e.i5e oops, !nd perh!ps 5ec!#se it is some4h!t
di22erent 2rom the str#ct#res o2 9%"6C or P!sc!, this str#ct#re is o2ten some4h!t
negected3 6t does ho4e8er, rep!y e.!min!tion3 Li7e ! the str#ct#res it c!n 5e nested to
!ny depth, imited ony 5y st!c7 depth consider!tions3 6n the e.!mpe 5eo4, the consoe
is poed #nti ! 7ey is pressed, !nd ! co#nter is incremented 4hie 4!iting3
VARIABLE COUNTER
: TEST \ --
0 COUNTER !
BEGIN KEY? 0=
WHILE 1 COUNTER +!
REPEAT ;
CA-' ... /F ... ';*/F ... ';*CA-'
CASE key
value1 OF <words> ENDOF
value2 OF <words> ENDOF
...
<default words> ( otherwise clause )
ENDCASE
)his is the most common "ASE st!tement in &orth3 6t is the res#t o2 ! competition 2or the
5est "ASE st!tement3 )he competition 4!s r#n 5y &orth >imensions, the Jo#rn! o2 the
&orth 6nterest Ero#p (&6E) in the '"%3 % !rge n#m5er o2 "ASE st!tements 4ere
proposed, 5#t this one h!s stood the test o2 time !s it is sec#re, e!sy to #se !nd #nderst!nd,
!nd e!sy to re!d3 6t 4!s in8ented 5y >r3 Ch!res E3 E!7er, !nd 2irst p#5ished in &orth
>imensions, @o3 66 n#m5er 3, p!ge 373
"ASE st!tements e.ist to rep!ce ! !rge ch!in o2 nested IFs, ELSEs, !nd THENs3 "#ch
ch!ins !re #n4iedy to 4rite, prone to error, !nd e!d to se8ere 5r!in0str!in3
)he 2#nction o2 ! "ASE st!tement is to per2orm one !ction dependent on the 8!#e o2 the
7ey p!ssed to it3 62 none o2 the conditions is met, ! de2!#t !ction (the other4ise c!#se)
sho#d 5e !8!i!5e3 Aote th!t ! 8!#e to seect !g!inst m#st 5e !8!i!5e 5e2ore e!ch $&
!g!inst 4hich the entered p!r!meter m!y 5e tested3 )he seect 8!#e is top o2 st!c7, the
p!r!meter is ne.t on st!c7 (5y reF#irement)S OF then comp!res the t4o 8!#es, !nd i2 they
!re eF#!, the 4ords 5et4een OF !nd ENDOF !re e.ec#ted, !nd the progr!m contin#es
immedi!tey !2ter END"ASE3 62 the test 2!is, the code 5et4een OF !nd ENDOF is
s7ipped, so th!t the seect 8!#e 5e2ore the ne.t OF m!y 5e tested3 62 ! the tests 2!i the
p!r!meter is sti on the d!t! st!c7 2or the de2!#t !ction, !nd is then cons#med 5y
END"ASE3 %ddition! contro str#ct#res c!n 5e #sed inside OF 333 ENDOF c!#ses3
E.!mpe*
3%
Components of Forth
: STYLE? ( n -- )
CASE
1 OF ." Mummy, I like you" ENDOF
2 OF ." Pleased to meet you" ENDOF
3 OF ." Hi!" ENDOF
4 OF ." Hello" ENDOF
5 OF ." Where's the coffee" ENDOF
6 OF ." Yes?" ENDOF
." And who are you?"
ENDCASE ;
)he phr!se*
n STYLE?
4i seect !n opening phr!se !ccording to the 8!#e o2 n3 62 n is in the r!nge 1336 !
prede2ined string is o#tp#t, 2or !ny other n#m5er the de2!#t phr!se O%nd 4ho !re yo#DO is
o#tp#t3 C!se st!tements !re o2ten #sed to seect !ctions 5!sed on %"C66 ch!r!cters3 6n !n
editor sections o2 code i7e the one 5eo4 !re o2ten 2o#nd3
CASE
KEY
[CHAR] I OF INDEX ENDOF
[CHAR] M OF MOVE-BLOCK ENDOF
[CHAR] D OF DIRECTORY ENDOF
...
ENDCASE
MPEisms: CA-' e(tensions
6n order to e.tend the #se2#ness o2 the 5!sic "ASE str#ct#re 4e h!8e !dded three
e.tensions to the st!nd!rd E!7er "ASE3
)he 2irst (OF !o4s the #se o2 ! ogic! test r!ther th!n eF#!ity3 62 yo# need to test
4hether or not ! ch!r!cter is in the right r!nge the 2oo4ing rep!ces ! !rge n#m5er o2
OF 333 ENDOF sets3 )he 4ord WITHIN( ret#rns ! tr#e 8!#e i2 the 8!#e is 5et4een (or
eF#! to) the o4er !nd #pper imits3 (OF cons#mes the 2!g gi8en to it3
DUP 32 127 WITHIN? ?OF ... ENDOF
)he second e.tension END"ASE 5eh!8es J#st i7e END"ASE, e.cept th!t it does not
DROP !nything 2rom the st!c7, so !o4ing ! de2!#t c!#se to cons#me the seect 8!#e
4itho#t h!8ing to *)Pic!te it3
)he third e.tension NEXT"ASE compies ! 5r!nch 5!c7 to the &$SE, so prod#cing !
oop th!t e.its 8i! one the OF ... ENDOF or (OF ... ENDOF phr!ses3 "#ch ! oop
per2orms ! di22erent e.it !ction 2or e!ch condition3 )he intention o2 this str#ct#re is to
!o4 ! 2orm! method o2 constr#cting oops 4ith more th!n one e.it !nd e.it !ction3 "#ch
oops !re o2ten necess!ry 4hen de!ing 4ith te.t entry3 NEXT"ASE cons#mes no d!t!3
E.!mpe*
CASE KEY
13 OF <cr action> ENDOF
10 OF <lf action> ENDOF
40
Components of Forth
DUP 32 127 WITHIN?
?OF <normal action> ENDOF
CR ." Character code " . ." is invalid" CR
NEXT-CASE
0estarts and errors
E.ception h!nding is co8ered in more det!i in ! sep!r!te ch!pter3 )he BE%IN ...
A%AIN e.!mpe !5o8e #ses ABORT, 4hich #s#!y per2orms ! 4!rm rest!rt o2 the
system, 5#t is impement!tion dependent3 Con8ention!y, ABORT resets the st!c7s !nd
r#ns the &orth interpreter oop in 9UIT3
Te(t and strings
)here !re not m!ny 4ords in ! 5!sic st!nd!rd &orth th!t de! 4ith strings, 5#t they do
!o4 the #ser to 5#id 4ords th!t 4i per2orm !ny reF#ired 2#nction3 )4o types o2
strings !re de2ined, 4hich 6 sh! c! counted !nd character3 &orth systems inter2!cing
to oper!ting systems !nd C i5r!ries !so pro8ide 4ords to #se +ero,terminated strings3
%ppic!tions th!t oper!te on !rge 5oc7s o2 te.t !ndIor !re intern!tion!ised #se wide or
)nicode strings !s 4e3
Historic!y, &orth systems m!iny #sed co#nted strings, 4hich consist o2 ! co#nt 5yte
2oo4ed 5y th!t m!ny ch!r!cters3 )hey !re re2erenced 5y the !ddress o2 the co#nt 5yte
( 3addr 53 )his is the s!me str#ct#re !s #sed 5y m!ny P!sc! impement!tions3
Co#nted strings !re 2!st to m!nip#!te 5ec!#se their ength is !4!ys !8!i!5e3 Ho4e8er
co#nted strings !re di22ic#t to #se 4hen p!rsing !nd processing !rger 5oc7s o2 te.t3
9ec!#se o2 this imit!tion it 5ec!me common pr!ctice to re2er to them 5y !ddressIength
p!irs on the st!c7 ( 3addr :e6 5, 4here c!ddr re2ers to ! ch!r!cter !ddress3
)he %A" committee decided to st!nd!rdise on these ch!r!cter strings3 9ec!#se o2
4idespre!d p!st pr!ctice, it 4!s impossi5e to eimin!te co#nted strings, nor is it
desir!5e to do so, !s co#nted strings !re ! 8ery con8enient stor!ge 2orm!t3
%tho#gh there 4!s some press#re to st!nd!rdise :ero termin!ted strings, their
ine22iciencies (especi!y 2or em5edded systems) !nd !c7 o2 comp!ti5iity 4ith memory
oper!tions e!d to the reJection o2 this press#re3
6t sho#d 5e noted th!t m!ny &orth progr!mmers, J#st i7e progr!mmers in other
!ng#!ges, h!8e 5ecome !cc#stomed to the !ss#mptions th!t ! ch!r!cter is ! #nit o2 -
5its (!n RoctetL), th!t ! 5yte is !n - 5it #nit, !nd th!t memory is !ddressed in - 5it #nits3
)his is especi!y tr#e o2 progr!mmers 4hose 2irst !ng#!ge is Engish, !nd s#ch
progr!mmers !re !so o2ten ony #sed to the %"C66 7 5it ch!r!cter set3 Ao4!d!ys, e8en
the 16 5it 'nicode set (')&016) is in!deF#!te 2or ! !ng#!ges3 )he C> !ccomp!nying
this 5oo7 inc#des the dr!2t %A" &orth propos!s 2or h!nding 4ide ch!r!cters !nd
intern!tion!is!tion3
Counted strings
% co#nted string is stored !s ! co#nt 5yte 2oo4ed 5y th!t m!ny ch!r!cters3 )o p#t !
string into ! 4ord #se C- 4hich compies ! string into the diction!ry, !nd ret#rns its
!ddress 4hen the 4ord e.ec#tes3
41
Components of Forth
: HELLO$ \ -- caddr
C" Hello there " ;
)he string 4i st!rt 4ith the OHO !nd end 4ith the sp!ce 5e2ore the F#ot!tion m!r73 )he
!ddress ret#rned 5y HELLO; points to the co#nt 5yte3 )o con8ert this !ddress to the
!ddress o2 the 2irst ch!r!cter !nd the n#m5er o2 ch!r!cters, the 4ord "OUNT is #sed3
=hen ! string is to 5e printed, it is #s#!y done 5y the 4ord T$PE, 4hich needs the
!ddress o2 the te.t to 5e printed !nd the n#m5er o2 ch!r!cters to 5e printed3 )o print the
string !5o8e 4e 4o#d #se*
HELLO$ COUNT TYPE
)o pic7 indi8id#! ch!r!cters o#t o2 ! string yo# simpy !dd the n#m5er o2 the reF#ired
ch!r!cter to the st!rt !ddress !nd 2etch it3 &or the 2irst OO*
HELLO$ 3 + C@ EMIT
)o print the seF#ence Oo tO*
HELLO$ 4 + 4 TYPE
Character -trings
% ch!r!cter string in memory is descri5ed 5y its st!rt !ddress !nd ength3
: HELLO$ \ -- caddr
C" Hello there " ;
Character 6iterals
"ometimes 4e need to #se the iter! 8!#e 2or ! ch!r!cter3 B!ther th!n #sing 65 2or
%"C66 % or /7 2or %"C66 !, it is m#ch ce!rer to #se ! 4!y o2 entering them, !nd it s!8es
h!8ing to oo7 them #p3 %A" &orth pro8ides t4o 4ords 2or gener!ting ch!r!cter iter!s,
<"HAR= !nd "HAR3 6nside ! * (coon) de2inition, #se ["HAR=3 =hie interpreting, #se
"HAR3
: t [char] A emit ;
char / emit
Te(t and -tring input
)he princip! 4ord to 2etch strings 2rom the 7ey5o!rd is A""EPT 4hich reF#ires the
!ddress o2 ! 5#22er in 4hich to p#t the string, the m!.im#m n#m5er o2 ch!r!cters to re!d,
!nd ret#rns the n#m5er o2 ch!r!cters re!d3 )o cre!te !n -0 5yte 5#22er, re!d ! string into it,
!nd inspect the contents o2 the 5#22er, 4e cre!te ! 5#22er c!ed BUFFER; !nd then
reser8e !nother 7- 5ytes (the 8!ri!5e reser8es t4o), re!d -0 5ytes into it, !nd then disp!y
the contents o2 BUFFER;3
CREATE BUFFER$ 80 ALLOT
CR BUFFER$ 80 ACCEPT
( now enter a string at the keyboard )
BUFFER$ SWAP DUMP
42
Components of Forth
Go# 4i see th!t BUFFER; cont!ins the te.t yo# entered 4itho#t ! co#nt 5yte3 6nside
&orth there is !n !re! c!ed the termin! inp#t 5#22er (its !ddress is ret#rned 5y the 4ord
TIB)3 )he 4ord 9UER$ re!ds ! ine o2 te.t into TIB3 )he 4ord WORD then e.tr!cts !
s#50string 5o#nded 5y ! speci2ied ch!r!cter, !nd copies the string to the end o2 the
diction!ry !s ! co#nted string (co#nt 5yte + ch!r!cters), ret#rning the !ddress !t 4hich it
e2t the string3 )ry entering the 4ord 5eo4*
: T \ just another test word
BL WORD 40 DUMP ;
T xxxx yyyy zzzz
%A" &orth speci2ies ! 5#22er c!ed PAD ( addr5 4hich is !8!i!5e 2or
!ppic!tion #se3 M!ny &orth systems (e8en some nomin!y %A" compi!nt) #se PAD
intern!y3 62 yo# #se PAD !nd see inconsistent res#ts rechec7 yo#r code 4ith ! 5#22er
other th!n PAD3
Print Formatting
&orth h!s ! 8ery po4er2# n#m5er string 2orm!tting system3 6t is F#ite di22erent 2rom th!t
s#ppied 4ith C or 9%"6C3 )o print ! n#m5er !s po#nds !nd pence (or do!rs !nd cents,
or 2r!ncs !nd centimes), try the 2oo4ing*
HEX
: .POUNDS \ u --
[CHAR] EMIT
S>D <# # # [CHAR] . HOLD #S #> TYPE
;
DECIMAL
5050 .POUNDS
)he phr!se <"HAR= > EMIT prints the po#nd sign3 A#m5er con8ersion is st!rted 5y &?
!nd 2inished 5y ?'3 )he 4ord &? needs ! do#5e n#m5er (S'D con8erts singe n#m5ers
to do#5e)3 A#meric con8ersion then proceeds LE%") "6EA6&6C%A) >6E6) 2irst3 &or
e!ch ? ! digit is con8erted3 )he 4ord HOLD t!7es ! ch!r!cter !nd inserts it into the
ch!r!cter string 5eing gener!ted3 "o the phr!se
# # [CHAR] . HOLD
prod#ces the t4o e!st signi2ic!nt digits !nd ! decim! point (the pence portion)3 )he 4ord
?S con8erts the rest o2 the n#m5er, prod#cing !t e!st one digit3 A#meric con8ersion is
2inished 5y ?' 4hich e!8es the !ddress o2 the gener!ted string, !nd the n#m5er o2 5ytes
in the string3 T$PE then prints the string3
Go# c!n e!siy prod#ce yo#r o4n n#m5er con8ersion 2orm!ts3 "#ppose 4e 4!nted to
print n#m5ers !s po#nds !nd pence, 4ith si. 2ig#res 5e2ore the decim! point, t4o !2ter it,
!nd e!ding :eros s#ppressed e.cept in the ch!r!cter 5e2ore the decim! point3 )he 2orm!t
4e 4!nt is O.....y3yyO 4here . is ! digit or ! 5!n7 !nd y is ! digit3
=e need to gener!te ! 4ord ?B 4hich prod#ces ! digit i2 possi5e or ! 5!n7, i2 n#m5er
con8ersion h!s 2inished3
6n 5et4een &? !nd ?' the n#m5er 5eing con8erted is in do#5e n#m5er 2orm3 =hen !
digit is con8erted 5y . it is di8ided 5y the c#rrent 5!se, the rem!inder is con8erted to !
43
Components of Forth
ch!r!cter to 5e o#tp#t, !nd the F#otient is ret#rned3 )h#s the 2#nction o2 ?B is to !o4
n#meric con8ersion i2 the n#m5er is non0:ero, other4ise to insert ! 5!n7 into the o#tp#t3
: D0= ( d -- t/f )
OR 0= ;
: #B ( d1 -- d2 )
2DUP D0=
IF BL HOLD
ELSE #
THEN ;
)he 4ord BL ret#rns the ch!r!cter code 2or ! sp!ce3 Ao4 4e c!n gener!te .P 4hich 4i
print ! do#5e n#m5er !s eight ch!r!cters 4ith ! decim! point3
: .P \ d1 --
<# # # [CHAR] . HOLD # #B #B #B #B #B #>
TYPE ;
500.00 .P
=hen yo# enter ! n#m5er th!t inc#des ! dot, it is tre!ted !s do#5e n#m5er3 )he position
o2 the comm! h!s no signi2ic!nce, e.cept th!t the n#m5er o2 digits !2ter it is hed in the
8!ri!5e DPL in m!ny systems3 )ry*
5,0000 .P DPL @ .
500.00 .P DPL @ .
9oth n#m5ers !re con8erted to the s!me 8!#e, 5#t the system 8!ri!5e DPL tes yo# ho4
m!ny digits 4ere entered !2ter the dot3 62 no dot h!d 5een entered, the n#m5er 4o#d h!8e
5een tre!ted !s ! singe n#m5er, !nd the 8!#e o2 DPL 4o#d h!8e 5een 013
62 yo# 4!nt to e.pore print 2orm!tting more 2#y, !nd g!in yo#rse2 2!me 2or the more
e.otic stye o2 progr!mming, try 2orm!tting time !nd d!te 2rom ! 32 5it n#m5er o2
seconds3 Ch!nging the n#m5er con8ersion 5!se in the midde o2 print 2orm!tting 4ords
c!n 5e 8ery #se2#3
MPEism: 8ecause the <.= and <,= characters are #oth used as num#er separators for
currency in ,urope, M7, Forths default to using <,= in a num#er to indicate a dou#le
num#er. -his also avoids confusion %ith floating point num#ers. -he default can #e
changed to the ")( standard.
4ocabularies
6n constr#cting !n !ppic!tion 4ritten in &orth ! !rge n#m5er o2 ne4 4ords !re gener!ted3
=ith the !re!dy !rge n#m5er pro8ided in the n#ce#s, pro5ems c!n !rise in simpy
remem5ering 4h!t the 4ords me!n3 $ther pro5ems c!n !rise 5ec!#se o2 n!me re#se3 6n
one p!rt o2 !n !ppic!tion, ATTA"H m!y re2er to !tt!ching !n interr#pt to ! piece o2 code3
6n !nother section, it m!y re2er to !n oper!tion on ! 2ie, !nd !g!in m!y re2er ese4here to
the !ppic!tion per2ormed 5y the ro5ot #nder contro3
% method is needed to contro the en8ironment in 4hich 4e !re 4or7ing3 6n the e.!mpes
!5o8e the 4ord ATTA"H h!s di22erent me!nings in di22erent conte.ts3 )he conte.t in
4hich ! 4ord e.ists is its 8oc!5#!ry3 )echnic!y, 8oc!5#!ries !re #s#!y de2ined in
44
Components of Forth
terms o2 wordlists, 5#t since the 8!st m!Jority o2 &orths s#pport 8oc!5#!ries 2or #ser
con8enience, 6 h!8e chosen to disc#ss 8oc!5#!ries 2irst3
@oc!5#!ries !re cre!ted 5y the phr!se*
VOCABULARY <vocabulary-name>
&or e.!mpe the 8oc!5#!ry o2 4ords de!ing 4ith the ro5ot might 4e 5e c!ed
ROBOTI"S, !nd 4o#d 5e de2ined 5y*
VOCABULARY ROBOTICS
)he &orth system is tod 4hich 8oc!5#!ry 4ords !re de2ined into 5y the 4ord
DEFINITIONS, 4hich sets the 8oc!5#!ry th!t 4ords !re c#rrenty to 5e de2ined in3
%2ter the phr!se*
ROBOTICS DEFINITIONS
! ne4 4ords 4i 5e p!rt o2 the ROBOTI"S 8oc!5#!ry, !nd yo# co#d ist ! the 4ords
in th!t 8oc!5#!ry 5y typing*
ROBOTICS WORDS
H!8ing de2ined 4hich 8oc!5#!ry ne4 4ords !re 5#it into, 4e m#st no4 de2ine 4hich
conte.ts !re ree8!nt 4hen se!rching 2or 4ord n!mes3 &or e.!mpe, mo8ing ! ro5ot !rm
might need !ccess to 2o!ting point 4ords in 8oc!5#!ry FPA"*, the gr!phics 4ords in
%RAPH 2or consoe disp!ys, !nd the m#ti0t!s7ing 4ords in TAS*IN%3 )o cope 4ith !
this 4e !so need ! 4!y to st!rt !t the 5eginning !g!in3
)he 4ord th!t me!ns Ose!rch the minim#mO is ONL$ 4hich sets &orth to se!rch the
minim#m, o2ten ony ! tiny 8oc!5#!ry c!ed ROOT3 Most o2 the common 4ords !re in
FORTH 4hich is the m!in 8oc!5#!ry3 )h#s the phr!se*
ONLY FORTH
resets the system to ony #se FORTH (!nd the itte ROOT)3 =e c!n !dd !nother
8oc!5#!ry to 5e se!rched 4ith the 4ord ALSO 4hich !dds the ne4 8oc!5#!ry so th!t its
se!rched 2irst3 %2ter e.ec#ting*
ALSO F-PACK
the FPA"* 8oc!5#!ry 4i 5e se!rched 2irst, then &orth, !nd 2in!y ROOT3 )o pro8ide
the compe. order descri5ed e!rier, the 2oo4ing phr!se c!n 5e #sed*
ONLY FORTH
ALSO F-PACK ALSO GRAPH ALSO TASKING
ALSO ROBOTICS DEFINITIONS
6t is #s#! 2or the 8oc!5#!ry into 4hich 4ords !re de2ined to 5e the 2irst in the se!rch
order, !nd so the !st one speci2ied3 =hen the ROBOTI"S 8oc!5#!ry is 5eing de2ined
into, it is most i7ey th!t other 4ords in the s!me ROBOTI"S conte.t 4i 5e reF#ired,
!nd i2 d#pic!te n!mes e.ist, it is the ones in the ROBOTI"S conte.t th!t !re most i7ey
to 5e needed3
6n m!ny &orths yo# c!n get ! ist o2 ! the 8oc!5#!ries th!t h!8e 5een de2ined 5y typing*
45
Components of Forth
VOCS
!nd yo# c!n see the se!rch order #sed 5y typing*
ORDER
)he 2oo4ing &orth 4ords !re in8o8ed in 8oc!5#!ry contro, !nd they 4i ! 5e
doc#mented in the goss!ry 2or yo#r &orth*
CONTEXT CURRENT \ pointers
FORTH ROOT \ vocabularies
VOCS ORDER WORDS \ display words
ONLY ALSO DEFINITIONS PREVIOUS
7ordlists
=hen ! 4ord is se!rched 2or 5y n!me, the n!me is p!rt o2 ! wordlist3 Concept#!y the
ist is singe in7ed ist o2 n!mes, 4ith the !st 4ord !dded 5eing oo7ed !t 2irst3 )his
me!ns th!t 4hen ! ne4 de2inition h!s the s!me n!me !s ! pre8io#s one, the ne4 one is
2o#nd r!ther th!n the od one3
Ho4 4ordists !re impemented is o2ten r!ther di22erent3 )ypic!y, the n!me is h!shed
to prod#ce !n inde. into se8er! s#50ists3 )he n#m5er o2 s#50ists (#s#!y c!ed
thre!ds) 8!ries F#ite 4idey3 $ther systems gener!te dyn!mic h!sh0t!5es or #se
d!t!5!ses3 =h!te8er intern! mech!nisms !re #sed, !n %A" &orth system 4i 2oo4 the
mode !5o8e !s the #ser sees it3
% ne4 4ordist is cre!ted 5y the 4ord WORDLIST ( 4@d 5 4hich ret#rns ! wid
or 4ordist0identi2ier3 Go# c!nnot !ss#me !nything !5o#t the me!ning o2 ! 4id nor #se
it e.cept 4here ! 4id is reF#ired, other4ise yo# !re m!7ing !ss#mptions !5o#t the
intern! str#ct#res in the &orth system3
WORDLIST is pro8ided to !o4 yo# to cre!te !nd m!nip#!te the se!rch order 2or
4ords* it is there 2or toom!7ers3 6t is o2ten #sed to pro8ide ! se!ed en8ironment 2or
#ser comm!nds, to hide gro#ps o2 4ords in !rge proJects, or to hide methods in o5Ject
oriented e.tensions3 =hen #sed i7e this, the most import!nt 4ord #sed is
SEAR"HWORDLIST c-addr u wid -- 0 | xt 1 | xt -1
&ind the de2inition identi2ied 5y the string c0!ddr # in the 4ord ist identi2ied 5y
4id3 62 the de2inition is not 2o#nd, ret#rn :ero3 62 the de2inition is 2o#nd, ret#rn its
e.ec#tion to7en .t !nd one (1) i2 the de2inition is immedi!te, min#s0one (01)
other4ise3
)he 4ord FIND is #sed 5y the te.t interpreter to oo7 2or ! 4ord in ! the 4ords in the
"ONTEXT se!rch order, 4hich is #s#!y ! ist o2 4ordists !nd 8oc!5#!ries3
FIND c-addr -- c-addr 0|xt 1|xt -1
Per2orm the "E%BCH0=$B>L6") oper!tion on ! 4ordists 4ithin the c#rrent
se!rch order3 )his de2inition t!7es ! co#nted string r!ther th!n ! c0!ddr # p!ir3 )he
co#nted string is ret#rned !s 4e !s the 0 on 2!i#re3
An application of SEAR"HWORDLIST is pro8ided in the ch!pter ;'sing the
&orth interpreter<3 &#rther #se o2 4ordists 4i reF#ire the #se o2 the 2oo4ing 4ords
46
Components of Forth
de2ined in the %A" st!nd!rd* SET"URRENT SET"ONTEXT %ET"URRENT %ET
"ONTEXT3
47
Example: Date validation
& '(ample) *ate +alidation
*ate 4alidation) the re@uirement
6t is reF#ired to 8!id!te ! d!te 4hich is entered in the 2orm*
dd mm yyyy
@!id!tion sho#d ens#re the 2oo4ing*
- Ge!r is 8!id in the r!nge 1752 to 2050 inc#si8e3
- Month is 8!id in the r!nge 1 to 12 inc#si8e3
- >!y is 8!id in the r!nge 1 to 2-,2/,30 or 31 depending #pon the entered
month !nd ye!r
% e!p ye!r is de2ined !s ! ye!r 4hich is e.!cty di8isi5e 5y , i2 it is not di8isi5e 5y 100, 5#t
e.!cty di8isi5e 5y ,00 i2 it is3 )he e.pression de2ining ! e!p ye!r is there2ore*
((year mod 4)=0 and (year mod 100)<>0)
or (year mod 400)=0
% &orth 4ord )ALID( is reF#ired to meet this need3 )he 4ord )ALID( sho#d e.pect d!y,
month !nd ye!r !nd ret#rn tr#e (01) i2 the d!te is 8!id !nd 2!se ($) i2 it is not3 6t m!y 5e
!ss#med th!t the inp#ts to the 4ord 4i 5e three integers in the r!nge 03276- to 32767
inc#si8e3
)he st!c7 description 2or )ALID( is th#s*
VALID? \ day month year -- t|f
*esigning the solution
6n order to so8e this pro5em, it is necess!ry to 5re!7 it do4n into se8er!
s#50pro5ems3 )his is the most n!t#r! 4!y o2 pro5em so8ing !nd techniF#e c!rries
2or4!rd into comp#ter progr!mming #nder the n!me Q)op0>o4n >esignO3 &orth is
p!rtic#!ry s#it!5e 2or this since pro5ems c!n 5e 5ro7en do4n into 8ery sm! re#s!5e
p!rts* =ords3
6n this c!se 4e note th!t the pro5em comprises three m!in p!rts3 )hese !re*
1) @!id!tion o2 the ye!r* ! 4ord c!ed $EAR(
2) @!id!tion o2 the month* ! 4ord c!ed MONTH(
3) @!id!tion o2 the d!y* ! 4ord c!ed DA$(
=e 4i consider e!ch o2 these in t#rn*
9oth the 8!id!tion o2 the ye!r !nd the 8!id!tion o2 the month c!n 5e considered in
iso!tion !nd 4e c!n code these e!siy3 )he 8!id!tion o2 the d!y, ho4e8er, is more
4%
Example: Date validation
compe. !nd this 4i need to 5e considered more c!re2#y gi8en the d!y n#m5er !nd
the ye!r3
Coding the solution
&or the ye!r, 4e !re reF#ired to chec7 4hether the n#m5er s#ppied is in the r!nge
1752020503 $#r 2irst !ttempt might 5e*
: year? \ year -- t|f
dup 1752 >= swap 2050 <= and
;
Ho4e8er, 4e c!n #se the 4ord WITHIN( to per2orm the r!nge test3 WITHIN( h!s the
2oo4ing st!c7 e22ect*
WITHIN? \ n1 n2 n3 -- t|f
6t ret#rns tr#e i2 the 2oo4ing condition hods*
n2 <= n1 <= n3
62 yo#r &orth system does not h!8e WITHIN( Go# c!n de2ine it !s 2oo4s #sing the
%A" 4ord WITHIN3
: WITHIN? \ x n1 n2 -- flag
1+ WITHIN
;
$#r de2initions o2 $EAR( !nd MONTH( !re there2ore*
: year? \ year -- t/f
1752 2050 within? ;
: month? \ month -- t/f
1 12 within? ;
E!ch 4ord is s#22i.ed 4ith ! F#estion m!r73 )his impies th!t the 4ord 4i ret#rn !
8!#e o2 tr#e !nd 2!se3 6t is ! n!ming con8ention3
$#r de2inition o2 DA$( is not so simpe, since ! 8!id d!y is 5oth dependent #pon the
month !nd ye!r in 4hich it occ#rs (Qthirty d!ys h!8e "eptem5erO etc3) )he m!.im#m
n#m5er o2 8!id d!ys di22ers depending on the month !nd, in the c!se o2 &e5r#!ry, on
the ye!r3 $#r de2inition o2 DA$( is there2ore*
: day? \ day year month -- t|f
>days 1 swap within? ;
)his c!s ! 4ord 4e h!8e not yet de2ined3 6n the top0do4n design p!th, this 4ord m#st
ogic!y come ne.t, 5#t 5ec!#se 4e !re 4riting &orth, 4e m#st de2ine this ne4 4ord
2irst3 )he 4ord 'DA$S (prono#nced Pto d!ysP) 4i con8ert the gi8en month !nd ye!r
into the m!.im#m n#m5er o2 8!id d!ys 2or th!t com5in!tion3 )his 8!#e is then #sed !s
the #pper 5o#nd 2or the WITHIN( test3
)he de2inition o2 'DA$S 4i 5e in t4o p!rts* th!t 4hich de!s 4ith &e5r#!ry !nd e!p
ye!rs !nd th!t 4hich de!s 4ith ! other months3 )his is sho4n 5eo4*
50
Example: Date validation
: >days \ year month -- maxdays
dup 2 =
if drop >leapdays
else nip >otherdays
then
;
6n the c!se o2 &e5r#!ry 4e ret#rn ! 8!#e depending on the ye!r s#ppied, other4ise 4e
c!n disc!rd the ye!r !nd J#st ret#rn ! 8!#e 5!sed #pon the month3 )he de2inition o2
'OTHERDA$S is*
: >otherdays \ month -- maxdays
dup 4 =
over 6 = or
over 9 = or
swap 11 = or
if 30 else 31 then
;
)his 4ord in8o8es ! ot o2 st!c7 m!nip#!tion to 7eep the one item (the month) on the
top o2 the st!c7 2or testing3 More eeg!nt so#tions e.ist, 5#t 4e 4i come to them !ter3
)he 4ord 'LEAPDA$S m#st t!7e the ye!r, determine i2 it is ! e!p ye!r !nd ret#rn
either 2- or 2/ !ccordingy3 $#r de2inition is there2ore*
: >leapdays \ year -- maxdays
leap?
if 29 else 28 then
;
Ei8en the de2inition o2 ! e!p ye!r (see e!rier), o#r de2inition o2 LEAP( 4o#d 5e*
: leap? \ year -- t/f
dup 4 mod 0=
over 100 mod 0<>
and
swap 400 mod 0=
or ;
=e no4 h!8e ! the s#504ords needed to 8!id!te ! gi8en d!te3 )hey m!y no4 5e p#t
together to m!7e the reF#ired 4ord3
Putting it all together
$#r top e8e de2inition )ALID( 2or 8!id!ting ! d!te 4i #se the 4ords 4e h!8e J#st
de2ined* $EAR(, MONTH( !nd DA$(3 6t h!s the 2orm*
: valid? \ day month year -- t|f
dup year?
if over month?
if swap day?
else 2drop drop 0 \ clean up and leave false
then
else 2drop drop 0 \ clean up and leave false
then
;
51
Example: Date validation
Aote th!t i2 ! test 2!is 4e m#st ce!n #p the st!c7 !nd e!8e J#st the 8!#e o2 2!se3
6essons from this e(ample
)his e.!mpe o2 the #se o2 the st!c7 in &orth to m!nip#!te n#m5ers !nd test res#ts, etc3
sho4s #s se8er! things !5o#t design o2 &orth !ppic!tions*
)he pro5em sho#d 5e spit #p into se8er! sm!er pro5ems3
E!ch o2 these sho#d 5e t!c7ed in the simpest 4!y possi5e3
)he code sho#d 5e tested !s it is 4ritten3
"m!er de2initions !re 5etter3
Progr!mmers #sed to C o2ten comp!in th!t #sing m!ny sm! 2#nctions m#st res#t in
so4 code3 )he &orth 8irt#! m!chine is optimised 2or h!nding !nonymo#s inp#ts !nd
o#tp#ts !nd the code does not h!8e to 5#id !nd destroy st!c7 2r!mes3 ConseF#enty the
ony o8erhe!ds o2 sm! 2#nctions !re the C%LL !nd BE)'BA m!chine instr#ctions
themse8es3 "ome &orths, s#ch !s MPELs @&C &orth, c!n !#tom!tic!y e.p!nd sm!
de2initions to !8oid e8en this o8erhe!d3
52
Simple character I!
, -imple character I./
M!ny 4ords re!ting to ch!r!cter 6I$ h!8e !re!dy 5een #sed in preceding ch!pters3 )he
de2initions o2 the %A"6 6I$ 4ords !re coected here33
/utput
EMIT char --
)his 4ord 4i print the speci2ied ch!r!cter !t the c#rrent o#tp#t position, !nd
#pd!te the c#rsor position3 EMIT m!y !so correcty 4or7 4ith contro codes3
Concept#!y, EMIT is the 2#nd!ment! 4ord #sed 5y more compe. screen
o#tp#t 4ords3
% 2e4 e.!mpes*
Decimal
65 emit \ will print the letter "A"
48 emit \ will print the digit "O"
7 emit \ will usually cause a beep to sound
T$PE addr length --
)he 4ord T$PE 4i print ength n#m5er o2 ch!r!cters st!rting 2rom the gi8en
!ddress3 )o con8ert the !ddress o2 ! co#nted string to the p!r!meters needed 5y
T$PE, the 4ord "OUNT is necess!ry3
"R --
Per2orm ! c!rri!ge ret#rn, ine 2eed oper!tion3 6n other 4ords, go to the st!rt o2 the
ne.t ine3
PA%E --
)his 4ord 4i ce!r the screen !nd mo8e the c#rsor to the top e2t0h!nd corner o2
the screen3 $2ten c!ed "LS3
Input
*E$ -- char
*E$ 4!its #nti ! 7ey is pressed !t the 7ey5o!rdS 4hen one is pressed it ret#rns
the %"C66 8!#e o2 th!t 7ey on the st!c73 &rom the 7ey5o!rd, try typing /E03
Go# 4i see the c#rsor !d8!nce one sp!ce !nd 4!it 2or yo# to enter ! 7ey3 62 yo#
no4 enter ! 7ey, !nd then type PdotP . yo# 4i see the %"C66 code o2 the
ch!r!cter3 )ry this sm! progr!m*
: enter-key \ --
cr ." Enter character : " key
cr ." You entered : " emit
;
53
Simple character I!
*E$( -- t/f
*E$( ret#rns ! tr#e 2!g i2 ! ch!r!cter is !8!i!5e !t the 7ey5o!rdS this ch!r!cter
c!n then 5e re!d 5y *E$3
A""EPT addr +n -- len
)ypic! p!ces to store te.t string inp#t !re TIB, !nd PAD3 A""EPT is #sed to
!ccept more th!n one ch!r!cter !t ! time 2rom the 7ey5o!rd3 A""EPT t!7es !n
!ddress, !nd ! positi8e integer !s itOs !rg#ments 2rom the st!c73 )he 7ey5o!rd
inp#t is !ccepted #nti either ! UCBV is entered, or Q+nO ch!r!cters !re re!d3
=hen this occ#rs the string is stored !t the !ddress gi8en3 )he ength o2 the string
th!t 4!s !ct#!y inp#t is ret#rned3 )ry this sm! 4ord*
: greetings \ --
cr ." Enter your name : " pad 40 accept
cr ." Hi there " pad swap type
;
-tring /utput
"trings !re h!nded in &orth in t4o 4!ys3
)he 2irst 2orm #ses strings de2ined !s t4o ces on the st!c7 ( 3addr :e6 5
which can be passed directly to T$PE. The address of
characters is often shown as 3addr.
: myTown \ -- caddr len
S Southampton ;
E.ec#ting ABTC46 4i ret#rn the !ddress o2 the 2irst ch!r!cter o2 the string !nd its
ength3
| S | o | u | t | h | a | m | p | t | o | n |
^
)he string c!n 5e disp!yed #sing*
MyTown type
)he second 2orm is c!ed ! co#nted string i3e3 strings !re stored !s ! co#nt 5yte (the
ength o2 the string) 2oo4ed 5y the !ct#! ch!r!cters th!t m!7e #p the string3
: town$ \ -- $addr
C" Southampton" ;
=hen e.ec#ted this 4ord 4i ret#rn the !ddress o2 the co#nted string
| 11 | S | o | u | t | h | a | m | p | t | o | n |
^
)he !ddress ret#rned is th!t o2 the co#nt 5yte3 )he !ddress ret#rned 4i no4 h!8e to 5e
con8erted to p!r!meters th!t !re #s!5e 5y the 4ord T$PE !5o8e3
"OUNT \ addr -- addr+1 length
)o print the string "o#th!mpton de2ine*
54
Simple character I!
: print-town$ \ --
town$ count type ;
"ince T$PE 4or7s 4ith !ny !ddress !nd ength gi8en to it, it is possi5e to !ter the
st!rting point 2rom 4hich to 5egin printing !nd !so the n#m5er o2 ch!r!cters printed3
e3g3
town$ \ get counted string address
1+ \ skip the count byte
4 + \ skip 4 chars. "h"
3 \ going to print 3 characters
type \ go ahead and print
-tring input and the input stream
WORD char <text> -- addr
9y con8ention, the 2orm <text> on the e2t0h!nd side o2 ! st!c7 comment
does not indic!te ! st!c7 item3 6nste!d, it indic!tes th!t te.t is re!d 2rom the inp#t
5#22er, 4hich is #s#!y 2ied 4ith the te.t coected 5y A""EPT3
WORD 4i !o4 yo# to sho4 th!t &orth is c!p!5e o2 in2i. not!tion3 WORD
!ccepts inp#t 2rom the inp#t 5#22er 4itho#t modi2ying it3 6t does this 5y
e.!mining e!ch ch!r!cter in the inp#t stre!m, i2 the ch!r!cter is eF#! to the
deimiting ch!r!cter Qch!rO s#ppied, WORD ret#rns !n !ddress cont!ining !
co#nted string 4hich represents the inp#t #p to the deimited ch!r!cter3 1ote
Le!ding deimiter ch!r!cters !re ignored3
62 the inp#t does not cont!in the deimiting ch!r!cter, the ret#rned string 4i
cont!in the rest o2 the inp#t 5#22er3
WORD oper!tes on the c#rrent ine3 )he !ddress !nd ength o2 the ine c!n 5e 2o#nd #sing
SOUR"E3
SOUR"E -- c-addr u
Bet#rns the !ddress !nd ength o2 the c#rrent ine in the termin! inp#t 5#22er3
)he 8!ri!5e 'IN cont!ins the o22set in the c#rrent ine o2 pointer Pinto the inp#t
stre!mP3 )his tes the interpreter ho4 2!r it h!s got into the inp#t stre!m3 6t is #s#!y !
USER 8!ri!5e3
: i'm \ <text> --
bl word
cr ." Hi there " count type ;
'se this 4ord in the 2orm*
i'm Fred
Aotice th!t P&redP h!d !re!dy 5een typed 4hen IDM 4!s e.ec#tedS it h!d !re!dy 5een
A""EPTed into the inp#t 5#22er3
Progr!mming Aote* BL is ! const!nt ret#rning the %"C66 code 2or ! sp!ce ch!r!cter3
55
Simple character I!
;umber output
)his 4ord 5eo4 4i print the n#m5ers 1 to 100 4hen e.ec#ted*
: 1to100 \ --
101 1
do i . space loop ;
)he 2orm!t o2 the o#tp#t 4i 5e simi!r to*
1 2 3 4 5 6 7 8 9 10 11 12
13 14 15 16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31 32 33 34
35 36 37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55 56
57 58 59 60 61 62 63 64 56 66 67
68 69 70 71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 90
91 92 93 94 95 96 97 99 100
)his sort o2 o#tp#t is messy !nd #ns#it!5e 2or the o#tp#t o2 t!5es etc3 Ho4e8er there is
! 4ord .2 4hich 4i o#tp#t n#m5ers in 2ieds o2 speci2ied ength3
.R \ n field-width --
% sight re0de2inition o2 the pre8io#s 4ord ,EC,++ #sing the 4ord .2 4o#d consist
o2 *
: 1to100 \ --
101 1
do i 4 .r loop ;
)his 4ord 4i gi8e !n o#tp#t simi!r to*
01 02 03 04 05 06 07 08
09 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52 53 54 55 56
57 58 59 60 61 62 63 64
65 66 67 68 69 70 71 72
73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88
89 90 91 92 93 94 95 96
97 98 99 100
"ee i2 yo# c!n modi2y this to gi8e 2i8e items per ine3
;umber input
A#meric! inp#t is h!nded 5y the pre8io#sy e.p!ined ch!r!cter !nd string inp#t
4ords3 $nce yo# h!8e the %"C66 string o2 the ch!r!cters, yo# m!y need to per2orm
m!them!tic! 2#nctions #pon them, so &orth pro8ides t4o 5!sic 4ords to en!5e the
progr!mmer to con8ert the pict#red inp#t into 5in!ry d!t!3
56
Simple character I!
DI%IT c base -- n t/f
"impe to #se 4ord th!t is #se2# 4hen p!rsing simpe n#meric! inp#t3 *I3I%
con8erts the %"C66 ch!r!cter gi8en to ! n#m5er, i2 possi5e, in the 5!se s#ppied,
5#t ret#rns ony the 2!se 2!g i2 it 2!ied to con8ert the ch!r!cters3 )ry this sm!
4ord*
: get-# \ --
cr ." Enter a number : " key 10 digit
if cr ." The number was : " .
else cr ." That was not a number !!!"
then
;
NUMBER( addr -- nl..nn n2
"impe to #se 4ord th!t is #se2# 4hen p!rsing n#meric! string inp#t3 NUMBER(
con8erts the co#nted string into ! n#m5er i2 possi5e3 62 con8ersion 4!s
s#ccess2#, then the n#m5er o2 4ords gener!ted, !s 4e !s ! n#m5er o2 th!t si:e is
e2t on the st!c73 62 con8ersion 4!s #ns#ccess2# then ! :ero, 2!se, 2!g is e2t on
the st!c7*
No conversion -- 0
Single number -- n 1
Double number -- d 2
62 ! do#5e n#m5er is enco#ntered the #ser 8!ri!5e DPL 4i cont!in the n#m5er o2
digits !2ter the decim! point3
MPEism: -he ")( standard specifies that a dou#le num#er is indicated #y a <.=
character in the num#er. 8ecause this confuses people used to entering floating point
num#ers %ith a dot, and #ecause there is considera#le variation %ithin ,urope on the
use of commas and dots in num#ers, M7, Forths default to using a comma to indicate
dou#le num#ers. M7, Forths use the varia#le DP-CHAR to hold the character %hich
signifies a dou#le num#er.
0edirecting *E$ and EMIT
M!ny systems permit *E$, EMIT !nd 2riends to 5e redirected to de8ice other th!n the
consoe3 >es7top systems #se this 2or 4indo4s, seri! ines, memory 5#22ers, 2ies !nd
so on3 Em5edded systems c!n #se redirection to s4itch o#tp#t 2rom the de8eopment
port to !n LC> disp!y or ! tic7et printer3 Bedirection is #s#!y set independenty 2or
e!ch t!s73
9ec!#se 6I$ redirection is not de2ined 5y the %A" st!nd!rd, the impement!tion o2
redirection 8!ries 4idey 5et4een &orth systems3
57
Defining with C"EA#E $$$ D!ES%
*efining with "REATE ... DOES'
)his section is de8oted to ! 2!ciity 4hich disting#ishes &orth 2rom !most ! other
!ng#!ges3 )o #se this 2!ciity yo# 4i ony need to e!rn one ne4 &orth 4ord3 )he
concepts in8o8ed 4ith this 4ord ho4e8er !re pro2o#nd3 62 yo# c!n m!ster it yo# 4i
h!8e 5ecome ! tr#e &orth progr!mmerT
Most !ng#!ges disting#ish ! QQcompie timeOO ph!se 2rom ! QQr#n timeOO ph!se3 &or
e.!mpe 4hen dec!ring !n !rr!y in P!sc!, !t compie time sp!ce m#st 5e reser8ed !nd
!t r#n time the !rr!y eements 4i 5e !ccessed3
&orth does not inc#de ! st!nd!rd method 2or de2ining !rr!ys3 6nste!d it gi8es yo# the
toos to de2ine compie time !nd r#n time 5eh!8io#r, so yo# c!n cre!te yo#r o4n
QQde2ining 4ordsOO to set #p !rr!ys !nd m!ny other QQc!ssesOO o2 4ord3 "t!nd!rd &orth h!s
some 5!sic QQde2ining 4ordsOO !re!dy s#ppied3 &or e.!mpe* "ONSTANT, "REATE !nd
)ARIABLE3 =e 4i no4 h!8e ! coser oo7 !t "ONSTANT to see ho4 s#ch de2ining
4ords c!n themse8es 5e de2ined3
% 4ords de2ined 5y "ONSTANT h!8e ! simi!r 5eh!8io#r3 "#ppose 4e de2ine*
3 CONSTANT FRED
7 CONSTANT JIM
=hen &orth re!ds the de2inition o2 FRED, ! diction!ry entry 2or FRED is cre!ted !nd the
8!#e 3 is !ssoci!ted 4ith it3 =e c! this the compie time !ction 2or FRED3 =hen the
FRED is s#5seF#enty in8o7ed, !s in*
FRED .
the r#n time !ction 2or FRED is e.ec#ted, !nd this p#shes the 8!#e 3 onto the st!c73
FRED is c!ed ! child o2 "ONSTANT3 % possi5e de2inition o2 "ONSTANT is*
: CONSTANT \ n -- ; -- n
CREATE \ compile time, create new data word
, \ lay down the value n
DOES> \ what the child does, get data address
@ \ fetch contents
;
"REATE &6aAe' m!7es ! ne4 entry in the diction!ry3 )he r#n time !ction o2
&6aAe' is to ret#rn the !ddress !t 4hich !ny d!t! (!id do4n 5y F) m!y 5e 2o#nd3
)he phr!se "REATE F is the compie time !ction 4hich t!7es p!ce 4hen ! const!nt is
de2ined3 %t this point "REATE 5#ids the diction!ry entry 2or the ne4 const!nt !nd its
8!#e is compied into the ne.t 2ree diction!ry oc!tion3
)he 4ords F !nd "F !re #sed to compie ! ce0 or ch!r!cter0si:ed #nit in the diction!ry3
F \ x --
P!ce the 8!#e x into the diction!ry !t HERE !nd #pd!te the pointer the pointer
5y the si:e o2 ! ce3
5%
Defining with C"EA#E $$$ D!ES%
"F \ char --
P!ce the ch!r!cter0si:ed d!t! (#s#!y ! 5yte) into the diction!ry !t HERE !nd
#pd!te the pointer the pointer 5y the si:e o2 ! ch!r!cter3
HERE \ -- addr
Bet#rn the !ddress o2 the ne.t 2ree sp!ce in the diction!ry d!t! !re!3 Go# 4i
come !cross this 4ord !ter3
ALLOT \ n --
Beser8e sp!ce in the diction!ry d!t! !re! 4itho#t initi!ising it3 Go# 4i come
!cross this 4ord !ter3
DOES' sep!r!tes the compie time !ction 2rom the r#n time !ction, ret#rning the !ddress
o2 the d!t! !t r#n time3 )he r#n time !ction 2or ! const!nt is simpy to per2orm ! QQ2etchOO
4ith the comm!nd 5#t ! 2etch 2rom 4hich !ddressD Bec! th!t 4ords de2ined 5y
"REATE ret#rn the !ddress o2 the ne.t 2ree diction!ry oc!tion !t the time they 4ere
cre!ted3 )his ide! sti hods, 5#t no4 4e c!n !dd 4ords 2oo4ing DOES' 4hich !ct on
this !ddress3
)r!dition!y the !ddress e2t 2or the r#n time code is c!ed the ;p!r!meter 2ied
!ddress< o2 the 4ord3 % const!nts per2orm the s!me r#n time !ction, 5#t on di22erent
p!r!meter 2ieds3
MPEism2 " defining %ord has t%o stack comments. -he first is for the stack action
%hen the defining %ord runs and the second is for %hen the child is run.
Arrays
: Array \ size -- ; [child] n -- addr ; cell array
Create \ create data word
cell * \ calculate size
Here over erase \ clear memory
allot \ allocate space
Does> \ run time gives address of data
Swap cell * + \ index in
;
: 2Array \ n1 n2 -- ; [child] n1 n2 -- addr ; 2-D array
Create \ create data word
Over , \ save width for run-time
cell * * \ calculate size
Here over erase \ clear memory
allot \ reserve n cells
Does> \ run time gives address of data
Dup @ Rot * Rot + 1+
cell *
+
;
: Message-array \ len mesgs -- ; [child] n - addr
\ generate an array for mesgs messages of size len
Create \ create data word
Over , \ save the size of the array
60
Defining with C"EA#E $$$ D!ES%
* \ calculate space needed
Here over erase \ clear memory
allot \ reserve space for it
Does> \ run time gives address of data
Dup @ \ get length
Rot * \ calculate offset
+ \ add to base
cell + \ skip length
;
-tructures
% str#ct#re is ! temp!te 2or the !yo#t o2 d!t!3 %n inst!nce o2 ! str#ct#re m!y 5e go5!
d!t! or ! record in memory or ! peripher! in ! microcontroer3 % 2ied in ! str#ct#re is !
d!t! #nit o2 ! cert!in si:e3 )he core !ction o2 ! 2ied is to !dd !n o22set (position) in the
temp!te to the 5!se !ddress (4here the physic! str#ct#re is oc!ted)3 =hen ! str#ct#re
is re2erred to 5y n!me in the code, 4e need the si:e o2 the str#ct#re3
=hen impementing ! str#ct#re not!tion in &orth 4e !re #sing de2ining 4ords to e.tend
the compier3 )he 8ersion here pro8ides the reF#ired 2#nction!ity 4ith ! itte 5it o2
synt!ctic s#g!r to m!7e the code e!sier to re!d3
0 constant [struct \ -- 0 ; start
\ Start a structure definition, returning zero as
\ the initial offset.
: field \ offset n -- offset+n ; addr -- addr+offset
\ When defining a structure, a field of size n starts
\ at the given offset, returning the next offset. At
\ run time, the offset is added to the base address.
create
over , + \ lay offset and update
does>
@ + \ addr offset to address
;
: struct] \ offset -- ; -- size ; end
\ End a structure definition by naming it.
constant
;
)he 2irst !nd third 4ords !re J#st synt!ctic s#g!r to m!7e the code e!sier to re!d3 &or
e.!mpe, 4e c!n de2ine ! simpe !rr!y o2 integers !s 2oo4s*
: int \ addr addr+offset
cell field
;
[struct \ -- 0
int link \ link to previous structure
int ident \ identifier
int data \ data value
61
Defining with C"EA#E $$$ D!ES%
16 field name \ name string
struct] record \ -- size
=hen 4e need ! go5! inst!nce o2 this str#ct#re 4e c!n #se*
Create FirstRec \ -- addr
Record allot
$r, more prettiy*
Record buffer: FirstRec \ -- addr
)o 4rite ! 8!#e into the d!t! 2ied, 4e c!n #se*
55 FirstRec data !
%tho#gh this is ! 8ery simpe e.!mpe, it pro8ides 4h!t 4e need3 Ho4e8er, to some
eyes it 4o#d 5e e!sier to re!d i2 the str#ct#re is n!med 2irst !nd de2ined !2ter4!rds3
M!ny &orth compiers, e8en optimising ones, do not e.p!nd chidren o2 de2ining 4ords
!nd the code m!y 5e some4h!t ine22icient3 "o#tions to these pro5ems !re pro8ided in
the !ter ch!pter ;E.tending the compier<3
62
Diar& and 'hone (ook Examples
% *iary and Phone 2ook '(amples
)his ch!pter gi8es t4o 4or7ed e.!mpes3 &or !rr!y de2initions see the de2ining 4ord
ch!pter3 )hese e.!mpes !re not 4ritten in the most ;&orth0i7e< stye, they pro8ide
so#tions th!t 4i 5e 2!mii!r in other !ng#!ges3 )he phone 5oo7 e.!mpe is re8isited
in ! !ter ch!pter to sho4 ho4 to t!7e more !d8!nt!ge o2 &orth3
*iary
-pecification
\"tores . entries in the 2orm!t*
d!y, month, ye!r, ho#r, min, #ser mess!ge3
\@!id!tes ! 2ieds 5e2ore stor!ge, inc#ding e!p ye!rs333
\Pro8ide 4ords th!t *0
"tore0Entry \ dd mm yy hh mm <message> --
)o0>o \ dd mm yy -- ; display messages for day
\"h! pro8ide !rr!y05#iding 4ords3
Implementation
13 constant cr-chr \ code for carriage return
10 Constant Max-entries \ maximum number of entries allowed
20 Constant Max-message-len \ maximum message length
Variable #entries \ number of entries in diary
Max-message-len Max-entries \ array of max-entries and
Message-array Messages \ max-message-len long
Max-entries 2 2Array Times \ array for holding times
0 Constant Hour \ index for hours
1 Constant Minute \ index for minutes
Max-entries 3 2Array Dates \ array for holding dates
0 Constant Day \ index for hours
1 Constant Month \ index for minutes
2 Constant Year \ index for years
: $move \ src$ dest$ -- ; copy counted string
over c@ 1+ move
;
: Save-message \ message$ entry# -- ; save message$ at entry#
Messages $Move \ copy message to array
;
: Save-time \ hh mm entry# -- ; save time (hh:mm) in array
Tuck Minute Times ! \ save minutes
63
Diar& and 'hone (ook Examples
Hour Times ! \ save hours
;
: Save-date \ dd mm yy entry# -- ; save date
Tuck Year Dates ! \ save year
Tuck Month Dates ! \ save month
Day Dates ! \ save day
;
: Valid-message? \ message$ -- t/f ; is message valid?
Dup c@ 0<> \ must be non zero
Swap c@ Max-message-len <= and \ and must fit in array
;
: on \ -- ; just added for readability
;
: at \ dd mm yy -- t/f ; save date if valid
3Dup Valid-date? \ is date valid?
If \ Yes,
#entries @ Save-date \ save date
True \ return true
Else \ No,
2Drop Drop \ clear stack
False
then
;
: ?Valid-message \ message$ -- t/f ; validate and save
Dup Valid-message? \ is message valid?
If \ Yes,
#entries @ Save-message \ save message
True
Else \ No,
Drop \ clear stack
False
then
;
: ?Valid-time \ hh mm -- t/f ; validate and save time
2Dup Valid-time? \ is message valid?
If \ Yes,
#entries @ Save-time \ save message
True
Else \ No,
2Drop \ clear stack
False
Then
;
: Write \ hh mm <name> -- t/f t/f ; validate and save
[char] . Word ?Valid-message \ validate and save message
-Rot ?Valid-time \ validate and save time
;
64
Diar& and 'hone (ook Examples
: Diary-full? \ -- t/f ; is Diary full?
#entries @ Max-entries = \ at maximum?
;
: To-diary \ t/f t/f t/f -- ; accept entry?
And And \ all ok?
Diary-full? Not And \ and is diary is not full?
If \ Yes,
#entries incr \ accept entry
cr ." Set entry in diary" \ tell user
Else \ No,
cr ." Cant set diary entry" \ tell user
Then
;
: This-date? \ dd mm yy entry# -- t/f ; entry has date?
Tuck Year Dates @ = \ year match?
-Rot Tuck Month Dates @ = Rot and \ and month match?
-Rot Day Dates @ = and \ and day match?
;
: .Time \ entry# -- ; display time
Dup Hour Times @ 2digits \ display hour
[char] : Emit \ display colon
Minute Times @ 2digits \ display minutes
;
: .Message \ entry# -- ; display message for entry
Messages count type
;
: .entry \ entry# -- ; display entry
cr
Dup .Time \ display time
5 Spaces \ leave a gap
.Message \ display message
;
: Diary \ dd mm yy -- ; display messages for this date
#entries @ 0
?Do
3Dup i This-date? \ a matching date?
If \ Yes,
i .entry \ display message
Then
Loop
2Drop Drop
;
\ Example diary entries
on 3 12 1992 at 10 30 write message 1. to-diary
65
Diar& and 'hone (ook Examples
on 3 11 1992 at 10 30 write message 2. to-diary
on 3 12 1992 at 12 30 write message 3. to-diary
on 2 12 1992 at 10 30 write message 4. to-diary
on 2 12 1992 at 10 30 write message 4. to-diary
on 3 12 1991 at 10 30 write message 5. to-diary
on 3 12 1992 at 11 15 write message 6. to-diary
on 29 2 1988 at 10 30 write message 7. to-diary
on 24 12 1992 at 10 30 write message 8. to-diary
on 3 12 1992 at 01 00 write message 9. to-diary
0 [if]
\ Example invalid diary entries
on 32 1 1991 at 10 30 write message 5. to-diary
on 29 2 1991 at 10 30 write message 5. to-diary
on 2 13 1991 at 10 30 write message 5. to-diary
on 2 12 2100 at 10 30 write message 4. to-diary
on 2 12 1992 at 24 30 write message 4. to-diary
on 2 12 1992 at 10 70 write message 4. to-diary
on 2 12 1992 at 10 70 write message this message is far, far far
too long. to-diary
[then]
66
Diar& and 'hone (ook Examples
An Internal Phone 2ook
-pecification
Go# !re reF#ired to cre!te !n !ppic!tion to !o4 the storing !nd F#erying o2 !n
eectronic phone 5oo7 2or intern! c!s3
)he d!t! to 5e recorded is the s#rn!me o2 the empoyee*
1 <= length(surname) <= 15
!nd his or her teephone n#m5er*
0 <= number <= 9999
)here m!y 5e #p to t4enty entries in the phone 5oo7 !t !ny one time3 %p!rt 2rom 0
itse2, teephone n#m5ers m!y not 5egin 4ith ! 03 )he #ser inter2!ce reF#irement is !s
2oo4s3
$dding
)o !dd ! n#m5er to the 5oo7 the #ser sho#d type in the 2oo4ing 2orm!t*
nnnn calls name<Cr>
=here QnnnnO is ! phone n#m5er in the correct r!nge (0 UW n#m5er UW ////) !nd Qn!meO
is the s#rn!me o2 the empoyee (not more th!n 15 ch!r!cters ong)3 UCrV represents the
pressing o2 the PBet#rnP or PEnterP 7ey3
E.!mpes*
3270 calls prefect
4298 calls slartibarfast
0 calls switchboard
42 calls dent
4uerying
)he phone 5oo7 m!y 5e F#eried in three 4!ys3
=ho is !t this n#m5erD
nnnn calls?<Cr>
EnF#ires 4hich person ! n#m5er c!s3 )he comp#ter sho#d repy 4ith the s#rn!me o2
the indi8id#! or gi8e !n !ppropri!te error mess!ge3
42 calls? Dent
25 calls? Nobody \ error case
=h!t is COs n#m5erD
phone name<Cr>
6nF#ires the teephone n#m5er o2 the person n!med3 )he comp#ter sho#d respond 4ith
the n#m5er o2 the person n!med or gi8e !n !ppropri!te error mess!ge3
67
Diar& and 'hone (ook Examples
phone Prefect<Cr>
3270
phone Marvin
Marvin Has No Phone!
5ist the boo6
entries?<Cr>
List the contents o2 the phone 5oo73
entries?<Cr>
Prefect -- 3270
Slartibartfast -- 4298
Switchboard -- 0
Dent -- 42
-ome design notes
)he 2irst thing 4e 4i need 2or !n !ns4er to the pro5em is ! d!t! str#ct#re to cont!in
the n!mes, !nd !nother to cont!in the phone n#m5ers3 )hin7ing 5!c7 to the notes on
!rr!ys, 4e c!n see th!t the 5est 4!y to hod the phone n#m5ers 4i 5e !n !rr!y o2
t4enty entries3 )his is 2!iry str!ight2or4!rd3 Ho4e8er, ! itte tho#ght 4i 5e reF#ired
to hod the n!mes in ! d!t! str#ct#re3
=e 4i need to de2ine ! d!t! str#ct#re th!t consists o2 QsotsO o2 16 5ytes e!ch (one 2or
the 1015 ch!r!cters o2 the n!me, !nd one 2or the co#nt 5yte o2 the co#nted string)3 6t is
s#ggested th!t the d!t! str#ct#re th!t hods these n!mes h!s the 2oo4ing st!c7 e22ect*
\ entry# -- $addr
4hich 4i t!7e the n#m5er o2 !n entry, !nd ret#rn the !ddress in memory o2 the te.t3
=e 4i !so need to 7no4 4hich is the ne.t 2ree entry in the 5oo7 so th!t 4hen 4e !dd
!nother, 4e 4i !dd it into the ne.t 2ree sot3 )his 4e c!n do 4ith ! 8!ri!5e3
=hen 4e !dd !n entry, 4e de2ine the n!me !nd the phone n#m5er3 )he 4ord "ALLS
4i there2ore t!7e ! n#m5er o22 the st!c7 !nd store it in the ne.t 2ree sot in the !rr!y o2
phone n#m5ers3 )he 2ree sot 4i 5e determined 2rom the 8!ri!5e 4hich cont!ins this,
!nd 4i st!rt !t :ero3 9e2ore storing the phone n#m5er, the condition th!t it does not
st!rt 4ith ! :ero, #ness it is :ero 4i h!8e to 5e tested3 )his test 4i r#n !ong the ines
th!t i2 the n#m5er is :ero, it is !ccept!5e3 Ho4e8er, i2 the n#m5er is non0:ero, the
n!t#re o2 the &orth interpreter is s#ch th!t e!ding :eros !re remo8ed 2rom ! n#m5er3
)his me!ns th!t !ny n#m5er typed 4i not h!8e ! e!ding :ero on it 5y the time it is on
the st!c73 )his meets the condition reF#ired3 H!8ing stored the teephone n#m5er, the
"ALLS 4ord m#st !so e.tr!ct the n!me o2 the c!ed 2rom the comm!nd ine3 )his m!y
5e done #sing the phr!se QBL WORDO3 )his 4i ret#rn the !ddress o2 the co#nted string
so g!thered3 )his string m!y 5e trimmed to 15 ch!r!cters i2 it is too ong, 5y 2i.ing the
co#nt 5yte3 )he te.t !nd co#nt 5yte m#st then 5e mo8ed into the !rr!y cont!ining the
n!mes3 H!8ing done so, the 8!ri!5e indic!ting the ne.t 2ree sot m#st 5e #pd!ted3
)he "ALLS( 4ord is #sed to 2ind o#t 4ho ! teephone n#m5er c!s3 )his 4i t!7e the
phone n#m5er o22 the st!c7 !s ! p!r!meter, !nd test e!ch entry in the !rr!y o2 phone
n#m5ers (#p to the 2irst 2ree sot)3 62 the n#m5er is 2o#nd, then the !ppropri!te n!me 4i
68
Diar& and 'hone (ook Examples
5e e.tr!cted 2rom the n!me !rr!y, !nd printed3 62 the phone n#m5er is not 2o#nd, the
error mess!ge 4i 5e printed3
)he 4ord PHONE ret#rns the phone n#m5er 2or the person n!med on the comm!nd ine3
)his 4ord 4i t!7e the n!me 2rom the comm!nd ine, m#ch i7e "ALLS, !nd 4i then
oo7 #p ! entries in the !rr!y o2 n!mes #nti one m!tches3 62 no m!tch is 2o#nd, the
error mess!ge 4i 5e printed3 62 ! m!tch is 2o#nd, then the eF#i8!ent phone n#m5er
4i 5e e.tr!cted 2rom the !rr!y o2 phone n#m5ers, !nd 4i 5e printed3
Listing the phone 5oo7 (ENTRIES() 4i inde. thro#gh the !rr!y o2 n!mes, !nd print
e!ch n!me o#t !s it 2inds it3 %s it 2inds ! n!me, it 4i oo7 in the !rr!y o2 phone
n#m5ers 2or the eF#i8!ent entry, !nd 4i print o#t the phone n#m5er3 6t 4i the print !
UCrV !nd go on to the ne.t one3
Implementation
)his 8ersion is ! simpe c!ssic! impement!tion #sing !n !rr!y o2 records3 % !ter
ch!pter disc#sses !n impement!tion th!t t!7es !d8!nt!ge o2 &orthLs intern! str#ct#res3
Structures
0 constant struct{ \ -- 0
\ Start a structure.
: fld \ len size "<name>" -- len' ; addr -- addr+len
\ Define a field in a structure, given the current length
\ of the structure and the size of the field. The name follows
\ in the input stream.
create
over , +
does>
@ +
;
: }struct \ len "<name>" -- ; -- len
\ End a structure definition and give it a name.
\ At run time <name> returns the length of the structure.
constant
;
Strings
[undefined] UPC [if]
: UPC \ char -- char'
\ Convert supplied character to upper case if it was
\ alphabetic otherwise return the unmodified character.
dup [char] a >= if
dup [char] z <= if
$DF and
then
then
;
[then]
6%
Diar& and 'hone (ook Examples
[undefined] UPPER [if]
: UPPER \ addr len --
\ Convert the ASCII string described to upper-case. This
\ operation happens in place.
bounds ?do
i dup c@ upc swap c!
loop
;
[then]
7iscellaneous
[undefined] place [if]
: place \ caddr len dest --
\ Store the string given by caddr/len as a counted string
\ at dest.
2dup 2>r \ write count last
1 chars + swap move
2r> c! \ to avoid in-place problems
;
[then]
[undefined] >pos [if]
: >pos \ +n --
\ Place cursor on current line to column n if possible.
out @ - spaces
;
[then]
[undefined] bounds [if]
: bounds \ addr len -- addr+len addr
\ Convert an address and length to a form suitable for use
\ with DO...LOOP structures.
over + swap
;
[then]
Phone 8oo6 data
struct{
cell fld PB.Phone# \ phone number
#16 fld PB.Name \ name
}struct PBentry \ -- len
\ The structure that defines a record in the phone book.
20 constant MaxEntries \ -- n
\ Maximum number of entries in the phone book.
MaxEntries PBentry * constant /PhoneBook \ -- len
\ Size of the phone book data.
create PhoneBook \ -- addr
70
Diar& and 'hone (ook Examples
\ The phone book data.
/PhoneBook allot
Processing the phone boo6
: PB[] \ n -- addr
\ Return address of nth entry in phone book.
PBentry * PhoneBook +
;
: CheckNumber \ n --
\ Error if n is outside the range 0..9999.
0 9999 within?
0= abort" Telephone number outside range 0..99999"
;
: CheckName \ caddr len --
\ Apply checks to a name.
dup 15 > abort" Name too long"
2drop
;
: FindNumber \ num -- n true | false=0
\ Given a number, find the slot it occupies in the phone book
\ and return the slot number and true. If the number cannot be
\ found, just return false.
MaxEntries 0 do \ -- num
dup i PB[] PB.Phone# @ = if
drop i true unloop exit \ -- n true
then
loop
drop 0 \ -- 0
;
#32 buffer: N1
#32 buffer: N2
: SameNames? \ caddr1 len1 caddr2 len2 -- flag
\ Return true if the names given by caddr1/len1 and
\ caddr2/len2 are the same. Why is this word provided?
\ How can you compare names in different CaSes?
N2 place N1 place
N1 count upper N2 count upper
N1 count N2 count compare 0=
;
: FindName \ caddr len -- n true | false=0
\ Given a name, find the slot it occupies in the phone book
\ and return the slot number and true. If the number cannot be
\ found, just return false.
MaxEntries 0 do \ -- caddr len
2dup i PB[] PB.Name \ -- caddr len caddr len an
count SameNames? if
71
Diar& and 'hone (ook Examples
2drop i true \ -- n true
unloop exit
then
loop
2drop 0 \ -- 0
;
: FindFree \ -- n true | false=0
\ Find a free slot in the phone book and return the
\ slot number and true. If there is no room, just return
\ false.
MaxEntries 0 do \ --
i PB[] PB.Phone# @ -1 = if
i true unloop exit \ -- n true
then
loop
0 \ -- 0
;
: EraseEntry \ n --
\ Wipe nth entry in phone book.
PB[] dup PBentry erase
-1 swap PB.Phone# !
;
: EraseBook \ --
\ Wipe the phone book
MaxEntries 0
do i EraseEntry loop
;
EraseBook
: MakeEntry \ num caddr len n --
\ Add the entry whose phone number is num and name is
\ given by caddr/len to slot n in the phone book.
PB[] >r
2dup CheckName r@ PB.name place
dup CheckNumber r> PB.Phone# !
;
: .PBname \ slot --
\ Display name in entry.
PB.name count type
;
: .PB# \ slot --
\ Display name in entry.
PB.Phone# @ .
;
: ShowEntry \ n --
\ Display the contents of slot n in the phone book
PB[] dup PB.name c@ if \ if slot has name
cr dup .PBname \ display name
72
Diar& and 'hone (ook Examples
#16 >pos ." -- " \ step to col 16
.PB# \ display number
else
drop
then
;
$pplication words
: Calls \ num "<name>" --
\ Make a new entry in the phone book in the form:
\ <nnn> Calls <name>
dup FindNumber abort" Number in use"
bl word count 2dup FindName abort" Name in use"
FindFree 0= abort" Phone book full"
MakeEntry
;
: Calls? \ num --
\ Report who is called by number num. Use in the form:
\ <nnn> Calls?
FindNumber if
PB[] .PBname
else
." Nobody"
then
;
: Phone \ "<name>" --
\ Give the phone number for name. Use in the form:
\ Phone <name>
bl word count 2dup FindName if
cr PB[] .PB# 2drop
else
cr type ." has no phone."
then
;
: Entries? \ --
\ Display the contents of the phone book.
MaxEntries 0 \ --
do i ShowEntry loop
;
73
Execution #okens and )ectors
13 '(ecution Tokens and 4ectors
=hen the &orth te.t interpreter or the &orth compier oo7s #p ! 4ord in the diction!ry
they 2ind the QQe.ec#tion to7enOO !ssoci!ted 4ith the 4ord3 %n e.ec#tion to7en, o2ten
re2erred to !s !n xt, is ! #niF#e identi2ier 2or ! &orth 4ord3 6t is #s#!y, 5#t not !4!ys,
the !ddress o2 the code to c!3
6n this section 4e see ho4 the !5iity to h!nde !n e.ec#tion to7en c!n 5e #se2# in !n
!ppic!tion3
6np#t the 2oo4ing comm!nd ine*
1 2 ' + {ok}
)here !re no4 three items on the st!c7, 4hich !re the 8!#es 1 !nd 2, !nd the e.ec#tion
to7en 2or .3 )he singe !postrophe (re2erred to !s QQtic7OO) oo7s #p the 2oo4ing 4ord
!nd e!8es its e.ec#tion 8ector3 62 yo# need to re2er to the .t o2 ! 4ord inside ! coon
de2inition #se the phr!se <G= &4Crd'3
=e c!n e.ec#te the to7en*
EXECUTE . {3 ok}
9y de2inition, the phr!se G &4Crd' EXE"UTE h!s the s!me !ction !s &4Crd', so
this 4i h!8e the s!me o8er! e22ect !s per2orming*
1 2 + . {3 ok}
)he 4ord EXE"UTE ( @*H HE I*H 5 J#st per2orms the .t p!ssed to it3 6t is, i2
yo# i7e, !n indirect c! to HE3 )he not!tion i*x !nd 9*x indic!tes th!t the st!c7 !ction is
de2ined 5y th!t o2 HE !nd not 5y EXE"UTE3
Exercise* Predict 4h!t &orth 4i print in response to*
100 20 ' * EXECUTE .
'(ecution +ectors
=e c!n tre!t !n e.ec#tion to7en i7e !ny other d!t! item, p!ss it !s ! st!c7 p!r!meter,
s!8e it in ! 8!ri!5e or in ! t!5e !nd so on3 6n the 2oo4ing e.!mpe 4e de2ine !
8!ri!5e OPERATION 4hich 4i 5e #sed to hod !n e.ec#tion to7en3 DOIT is de2ined
to e.ec#te the oper!tion, !nd SETOP 2inds ! ne4 to7en !nd stores it in OPERATION3
VARIABLE OPERATION \ -- addr
: DO-IT ( i*x - j*x ) OPERATION @ EXECUTE ;
: SET-OP ( -- ) ' OPERATION ! ;
=e c!n #se this !s 2oo4s3
SET-OP / \ store xt of / in OPERATION
75
Execution #okens and )ectors
9 3 DO-IT . {3 ok}
Aote th!t 4hen ;tic7< is em5edded in !nother de2inition, !s it is in SETOP, this
de2inition t!7es on the property o2 oo7ing #p the ne.t 4ord in the diction!ry3 6t is !so
possi5e to oo7 #p ! 4ord th!t occ#rs 4ithin the compied te.t3 )his is done 5y the
4ord <D=3
&or e.!mpe the 2oo4ing de2inition 4i set the e.ec#tion to7en o2 . in the 8!ri!5e
OPERATION3
: SET+ ['] + OPERATION ! ;
Ao4 4e c!n enter*
SET+ 9 3 DO-IT . {12 ok}
Exercise* >e2ine ! 4ord *E$S 4hich inp#ts ch!r!cter codes 2rom the 7ey5o!rd !nd
emits them to the screen, termin!ting 4hen ! c!rri!ge ret#rn 7ey is recei8ed3 *E$S is to
4or7 in se8er! di22erent modes3
NORMAL *E$S 4i echo ! ch!r!cters 4itho#t ch!nging them3
UPPER *E$S 4i echo ony #pper c!se etters, 4ith ! dot printed 2or ! other
ch!r!cters3
"AP *E$S 4i con8ert o4er c!se etters to #pper c!se, then o#tp#t3
EN"ODE *E$S 4i !dd one to the %"C66 code o2 e!ch 7ey 5e2ore o#tp#t3
Compete the 2oo4ing o#tine code to impement the !ppic!tion3 Aote th!t the design
!o4s !ddition! modes to 5e !dded 4itho#t ch!nging the e.isting codeT Aote !so th!t
yo# c!n de2ine ! ch!r!cter inside ! coon de2inition #sing*
<"HAR= A ( JK5
VARIABLE KEY-OPERATION
: TRANSFORM-KEY
KEY-OPERATION @ EXECUTE
;
: KEYS \ --
BEGIN
KEY DUP 13 <>
WHILE
TRANSFORM-KEY EMIT
REPEAT
DROP \ drop CR key code
;
: NORMAL \ --
['] NO-OP KEY-OPERATION !
;
: ENCODE \ --
['] 1+ KEY-OPERATION ! \ 1+ is short for 1 +
;
76
Execution #okens and )ectors
: <UPPER> \ char1 - char2
your code goes here \ if not A..Z, replace by `.'
;
: <CAP> \ char1 - char2
your code goes here \ if a..z, replace by A..Z
;
: UPPER \ --
your code \ store xt of <UPPER> in KEY-OPERATION
;
: CAP \ --
your code goes here
;
Most &orth systems pro8ide ! de2ining 4ord c!ed DEFER 4hich cre!tes ! 8!ri!5e
(hoding !n .t) 4hich e.ec#tes the .t 4hen the 4ord is re2erenced3
DEFER <name>
% common not!tion 2or setting the !ction is*
` <action> IS <name>
!tho#gh se8er! others !re !so #sed3
MPEism: -he ")( standard does not define DEFER or a means of setting an action. "s
%ell as supporting IS M7, code uses the form2
ASSIGN <ACTION> TO-DO <NAME>
'(ecution arrays
)here !re c!ses 4hen the !ction o2 ! system is dependent o2 the 8!#e o2 the inp#t d!t!3
%n e.!mpe o2 this is h!nding the 7eystro7es 2or !n editor3 M!ny editors !re
progr!mm!5e 2or the !ctions o2 7ey stro7es3
% n!i8e 5#t e8ent#!y compe. method 4o#d 5e to hod the 7eys 2or speci2ic !ctions in
! set o2 8!ri!5es !nd to chec7 e!ch 7ey 8!#e !g!inst e!ch o2 these3 )his e8ent#!y
5ecomes tedio#s !nd ong 4inded in the so#rce code, !nd so4 to e.ec#te3 )his m!y not
5e import!nt in h#m!n terms, 5#t c!n signi2ic!nty imp!ct the per2orm!nce 4hen
rep!ying ! m!cro3 6n other !ppic!tions th!t process ! seri! d!t! stre!m, per2orm!nce
m!y 5e import!nt3
6n o#r editor e.!mpe, 4e 4i !ss#me 2or the moment th!t 4e !re h!nding - 5it
ch!r!cters3 )his me!ns th!t 4e h!8e 256 ch!r!cters to choose 2rom3 =e c!n store the .t
o2 the 4ord th!t h!ndes ch!r!cter n in the nth sot in !n !rr!y3 "ince m!ny o2 the
ch!r!cters !re h!nded in the s!me 4!y (disp!yed) 4e c!n simpi2y i2e 5y p!ssing the
ch!r!cter code to the 4ord th!t h!ndes it, !nd gi8e ! the ch!r!cter0h!nding 4ords the
st!c7 !ction*
char --
)o de2ine the !rr!y*
create KeyTable \ -- addr
256 cells allot \ reserve space for 256 xts
77
Execution #okens and )ectors
Ao4 4e need to initi!ise the t!5e 4ith the de2!#t !ction, 4hich is to disp!y the
ch!r!cter3 =e !ss#me th!t this 4ord is c!ed D@sL:aB"Mar3
: InitTable \ --
KeyTable 256 cells bounds
do [`] DisplayChar i ! cell +loop
;
Ao4 4e need ! 4ord to set ! ch!r!cterLs !ction*
: SetKey \ char name --
` \ find xt of the next word
swap cells KeyTable + ! \ index into the table
;
Ao4 4e c!n de2ine the !ction o2 e!ch 7eystro7e 5y #sing ! simpe script3 62 4e 7eep this
script in ! 2ie, 4e c!n m!7e the editor competey con2ig#r!5e, 4e c!n preser8e the
settings, !nd 4e c!n #se the &orth interpreter itse2 to o!d o#r editorLs settings3 "ince 4e
h!8e !n inter!cti8e !ng#!ge, there is no re!son not to #se the interpreter !ndIor
compier !t r#n0timeT
13 SetKey doCR
10 SetKey doLF
...
6n ! 2i.ed !ppic!tion, e3g3 seri! ine processing, 4e m!y ony need to h!nde the contro
7eys (03331) in this 4!y, !nd 4ith 2i.ed !ctions ( 53 =e c!n prod#ce ! prede2ined
t!5e !s 2oo4s*
Create KeyTable \ -- addr
` action0 , ` action1 ,
` action2 , ` action3 ,
...
: ProcessKey \ char --
dup #32 u< if
cells KeyTable + @ execute
else
DisplayChar
then
;
78
Extending the compiler
11 '(tending the compiler
&orth is !n e.tensi5e !ng#!ge3 6n &orth yo# c!n !dd to the compier itse2 to prod#ce
compier m!cros !nd ne4 contro str#ct#res3
Immediate words
&orth h!s ! compier th!t pro8ides seF#enti! composition o2 oper!tions3 "ome !spects
o2 the compi!tion process reF#ire more th!n this ho4e8er, !nd these sit#!tions !re de!t
4ith 5y QQimmedi!te 4ordsOO3
6mmedi!te 4ords occ#r in &orth de2initions in the norm! 4!y 5#t they !re e.ec#ted
d#ring compi!tion inste!d o2 5eing compied3 "#ppose 4e enter the de2inition*
: BEEP 7 EMIT ; IMMEDIATE
BEEP emits !n %"C66 code 7, 4hich c!#ses ! 5eep to 5e so#nded 5y the consoe3 )he
4ord IMMEDIATE 2!gs the most recenty de2ined 4ord !s QQimmedi!teOO3 Ao4 i2 4e
in8o7e BEEP d#ring compi!tion o2 !nother 4ord it 4i 5e e.ec#ted immedi!tey r!ther
th!n 5eing composed !s p!rt o2 the ne4 de2inition3 &or e.!mpe enter*
: TEST 100 . BEEP 200 . ;
)he 5eep so#nds !s the de2inition o2 TEST is 5eing compied3 6t is not compied !s p!rt
o2 TEST3
6mmedi!te 4ords !re #sed to pro8ide ! the e.tensions to the 5!sic &orth compier3 )he
2oo4ing 4ords !re ! immedi!te3
. ; IF ELSE THEN BEGIN WHILE REPEAT UNTIL AGAIN
&or ! more serio#s e.!mpe 4e st!rt 5y st#dying the de2inition o2 &orthOs IF ...
THEN contro str#ct#re3 Aote th!t the techniF#es 4e descri5e en!5e yo# to !dd ne4
contro str#ct#res to &orth in !n increment! 2!shion3
&irst 4e need to oo7 ! itte more cosey !t the compied 2orm o2 ! &orth de2inition3
)he 2oo4ing session !ss#mes yo# !re se!ted !t yo#r &orth termin!3 )he res#ts !re
t!7en 2rom @&C &orth 2or =indo4s, 4hich gener!tes optimised n!ti8e code3 $ther
compiers 4i gener!te di22erent res#ts3 Enter the de2inition*
: ABS DUP 0< IF NEGATE THEN ;
Ao4 e.!mine the code gener!ted 5y the compier*
see abs
ABS
( 00495EC4 0BDB ) OR EBX, EBX
( 00495EC6 0F8D02000000 ) JNL/GE 00495ECE
( 00495ECC F7DB ) NEG EBX
( 00495ECE C3 ) NEXT,
( 11 bytes, 4 instructions )
ok
7%
Extending the compiler
' abs 10 dump
0049:5EC4 0B DB 0F 8D 02 00 00 00 F7 DB C3 04 44 55 4D 50
ok
Here, the phr!se D ABS oo7s #p ABS in the diction!ry !nd ret#rns its e.ec#tion
!ddress (!s disc#ssed in the pre8io#s section on e.ec#tion 8ectors)3 )he 5ody o2 the
de2inition (#s#!y) 2oo4s this !ddress, so the d#mped 8!#es m#st represent the
oper!tions DUP +& etc3
)he g#ts o2 the de2initions o2 IF !nd THEN in @&C &orth !re !s 2oo4s*
: IF \ C: -- orig ; Run: x --
\ *G Mark the start of an IF..[ELSE]..THEN conditional
block.
s_?br>,
; IMMEDIATE
: THEN \ C: orig -- ; Run: --
\ *G Mark the end of an IF..THEN or ..ELSE..THEN
conditional.
s_res_br>,
; IMMEDIATE
: AHEAD \ C: -- orig ; Run: --
\ *G An unconditional forward branch resolved later.
s_br>,
; IMMEDIATE
)hey simpy pro8ide !ccess to compi!tion primiti8es 4hich st!rt !nd reso8e 2or4!rd
5r!nches, prod#cing or cons#ming 5r!nch t!rget !ddresses3 )he intern!s o2 e!ch &orth
compier 4i 5e di22erent !nd hence !re not port!5e 5et4een &orth impement!tions3
=h!t is reF#ired is ! 4!y to #se 4ords s#ch !s IF !nd THEN inside other compiing
4ords3 )his 2!ciity is pro8ided 5y the 4ord POSTPONE, 4hich is !4!ys #sed inside !
coon de2inition in the 2orm POSTPONE &6aAe' to de!y e.ec#tion or compi!tion o2
&6aAe'3 62 &6aAe' is immedi!te, it is not e.ec#ted, 5#t compied into the coon
de2inition3 62 &6aAe' is not immedi!te, it 4o#d norm!y 5e compied 5#t no4 the
coon de2inition 4i compie &6aAe' 4hen the coon de2inition is e.ec#ted3
Ao4 4e h!8e the mech!nics o2 #sing the e.isting compi!tion str#ct#res3 %s !n
e.!mpe, et #s de2ine ! 4!y o2 compiing ! ;short circ#ited< condition!3 =hen 4e
4!nt to per2orm !n !ction !s res#t o2 conditions !, 5 !nd c 5eing tr#e 4e c!n de2ine it
t4o 4!ys3 )he 2irst 4!y is*
A B AND C AND IF
...
THEN
62 A ret#rns 2!se, e.ec#tion o2 B !nd " is red#nd!nt3 )o !8oid this, 4e might code it !
second 4!y 4ith se8er! condition!s*
A IF
B IF
C IF
...
THEN
80
Extending the compiler
THEN
THEN
9#t this is tedio#s !nd t!7es ! ot o2 so#rce code sp!ce3 % ne!ter not!tion 4hich
gener!tes the s!me code !s the second so#tion might 5e ! third so#tion, origin!t!ted 5y
=i 9!den*
A ANDIF B IF C IF
...
THENS
ANDIF st!rts the str#ct#re !nd THENS reso8es the 2o4!rd 5r!nches3 Ao4 4e go 5!c7
!nd see th!t 4hen IF e.ec#tes (d#ring compi!tion) it prod#ces !n orig on the
compi!tion st!c7 (#s#!y the d!t! st!c7)3 %n orig is ! re2erence to 4here the 2or4!rd
5r!nch h!s 5een compied3 )his is cons#med 5y THEN 4hich p!tches #p the 2or4!rd
re2erence3 %ss#ming th!t ANDIF !so prod#ces !n orig, 4hen THENS is re!ched it 4i
2ind three origs on the compi!tion st!c73 =e 4i #se ! m!r7er o2 0 to indic!te th!t
there !re no more origs to 5e reso8ed3
: ANDIF \ C: -- 0 orig ; Run: x --
0 POSTPONE IF
; IMMEDIATE
: THENS \ C: 0 orig1..orign -- ; Run: --
BEGIN
DUP
WHILE \ if not the marker
POSTPONE THEN \ resolve the latest orig
REPEAT
DROP \ discard the marker
; IMMEDIATE
%s yo# c!n see, i2 t!7es m#ch onger to descri5e this techniF#e th!n to #se it3 $nce these
4ords h!8e 5een de2ined, they c!n 5e #sed !s descri5ed !5o8e3 )his is !n e.!mpe o2 !
7ey techniF#e in &orth, 4hich is to ch!nge the not!tion to s#it the pro5em !t h!nd3
6mmedi!te 4ords hep #s to ch!nge the compi!tion not!tion3
Cautionary notes
)he %A" &orth st!nd!rd de2ines ! compie0time contro02o4 st!c7, !s indic!ted 5y the
C: in the st!c7 comments 2or the 4ords !5o8e3 )he m!Jority o2 &orth systems #se the
d!t! st!c7 2or the contro02o4 st!c73 )he e.!mpes !5o8e 4i not 4or7 on systems th!t
do not #se the d!t! st!c7 2or the contro02o4 st!c73 Aote !so th!t the st!nd!rd does not
de2ine the si:e o2 orig or dest3 =e h!8e seen systems 4ith these r!nging 2rom one to
three ces, 8!rying !ccording to circ#mst!nce3
Accessing the compiler
&orth is composed o2 4ords !nd n#m5ers3 Go# c!n c!#se ! 4ord to 5e compied in !
de2inition #sing the 4ord "OMPILEF ( HE 5 J#st !s yo# c!n 2orce it to 5e
e.ec#ted #sing EXE"UTE ( HE 5, 4here .t is !n e.ec#tion to7en !s ret#rned 5y
G or <G=3
81
Extending the compiler
"imi!ry (5#t ony inside ! coon de2inition) yo# c!n 2orce ! 8!#e (n#m5er) to 5e
compied into the current de2inition #sing LITERAL ( H 53 )o #se LITERAL
!s the compiing primiti8e yo# m#st POSTPONE it M LITERAL is !most !4!ys
IMMEDIATE3
&or e.!mpe to !y do4n code th!t !dds ! n#m5er to ! 5!se 8!#e, 4e c!n de2ine ! 4ord
.LITF ( 6 5 4hich compies code to !dd ! iter! to the c#rrent top o2 the d!t!
st!c73 9y con8ention, 4ords 4hose n!mes end in ! comm! #s#!y compie code or d!t!
into the diction!ry3
: +lit, \ n --
\ Lay down code to add a literal to the top stack item.
postpone literal [] + compile,
;
62 yo#r system h!s !n immedi!te 8ersion o2 ., yo# 4i h!8e to postpone it3 6n most
c!ses POSTPONE 4i do 4h!t yo# 4!nt, 5#t "OMPILEF reF#ires yo# to 5e c!re2#3
: +lit, \ n --
\ Lay down code to add a literal to the top stack item.
postpone literal postpone +
;
6n m!ny systems, POSTPONE !nd "OMPILEF 4i gi8e !n error i2 the compier h!s not
5een t#rned on3 )he compier is t#rned on 5y = ( 5 !nd t#rned o22 5y < ( 5
which is immediate.
Go# c!n #se < !nd = inside ! coon de2inition to c!c#!te !n e.pression !nd compie the
res#t !s ! iter!3 )his 4!s common pr!ctice 5e2ore optimising &orth compiers 4ere
!8!i!5e !nd pr!ctice is sti #sed 2or port!5e code in some shops3
: foo \ --
...
[ const 55 * ] literal \ equivalent to const 55 *
...
;
Aote th!t 5ec!#se LITERAL is immedi!te, the res#t o2 interpreting the e.pression is
compied inside NCC3
6n some c!ses, yo# 4i need to 7no4 4hether the system is compiing or interpreting3
)he contents o2 the 8!ri!5e STATE indic!te 4hether &orth is compiing (non0:ero) or
interpreting (:ero)3 =ords 4hich h!8e di22erent 5eh!8io#rs in the t4o c!ses !re re2erred
to !s ;st!te0sm!rt<3 )he #se o2 st!te0sm!rt 4ords is deprec!ted 5y some &orth e.perts
(see 5eo4), 5#t it is ! con8enience to !8oid h!8ing to 7no4 the c!rn! det!is o2 yo#r
system3 6ncorrect #se o2 st!te0sm!rt 4ords c!n e!d to 5#gs 4hich !re 8ery h!rd to tr!ce3
K#st 5e sensi5e !nd c!#tio#s 4hen #sing them3 )he gener! r#e to !8oid pro5ems is
ne8er to tic7, POSTPONE or <"OMPILE= st!te0sm!rt 4ords3 %tho#gh <"OMPILE= is
st!nd!rdised, yo# c!n norm!y #se POSTPONE inste!d3
9e c!re2# 4ith o8er0enth#si!stic #se o2 compi!tion techniF#es to impro8e
per2orm!nce3 6t c!n e!d to code th!t is h!rd to m!int!in, !nd in most c!ses optimising
the !gorithm c!n e!d to m#ch higher per2orm!nce th!n t#ning the compier3 )he re!
8irt#e o2 these techniF#es is in ch!nging the not!tion o2 yo#r code to s#it the !ppic!tion3
82
Extending the compiler
-tructures re+isited
)he str#ct#res e.!mpe in the e!rier ch!pter ;>e2ining 4ords< does not pro8ide
e22icient code in m!ny &orth systems3 )his 8ersion so8es the pro5em o2 n!ming the
str#ct#re 2irst !nd pro8ides 5etter compi!tion o2 2ieds3 =e #se de2ining 4ords,
IMMEDIATE 4ords !nd the compier to g!in e22iciency !t the e.pense o2 compe.ity3
Aote th!t the intern! mech!nisms o2 &orth compiers 8!ry gre!ty !nd th!t 2or 5est
res#ts 7no4edge o2 the speci2ic compier is reF#ired3 )he e22iciency is g!ined 5y #sing
the 8!ri!5e STATE to determine 4hether interpret!tion o2 compi!tion is reF#ired3
: struct \ -- addr 0 ; -- size
\ Begin definition of a new structure. Use in the form
\ STRUCT <name>
\ At run time <name> returns the size of the structure.
create
here 0 , 0 \ mark stack, lay initial offset
does>
@ \ get size of structure
;
)o !8oid the o8erhe!d o2 2ied c!c#!tions, the ne4 8ersion o2 FIELD !ccesses the
compier to !y do4n the code 2or :@E .3
: field \ offset n <"name"> -- offet ; Exec: addr -- 'addr
\ Create a new field within a structure definition of
\ size n bytes.
create immediate \ the child is IMMEDIATE
over , +
does>
@ state @ if \ compile
postpone literal postpone +
else
+
then
;
: end-struct \ addr n --
\ Terminate definition of a structure.
swap ! \ set size of structure
;

: int \ <"name"> -- ; Exec: addr -- 'addr
\ Create a new field within a structure definition
\ of size one cell.
cell field
;
struct record \ -- addr 0 ; -- size
int link \ link to previous structure
int ident \ identifier
int data \ data value
16 field name \ name string
end-struct
83
Extending the compiler
%s in the e!rier ch!pter, 4hen 4e need ! go5! inst!nce o2 this str#ct#re 4e c!n #se*
Create FirstRec \ -- addr
Record allot
$r, more prettiy*
Record buffer: FirstRec \ -- addr
)o 4rite ! 8!#e into the d!t! 2ied, 4e c!n #se*
55 FirstRec data !
9ec!#se 2ied !ccesses !re p!ssed to the compier r!ther th!n !s c!s to the 2ied 4ords,
optimising compiers h!8e more optimis!tion opport#nities, res#ting in sm!er !nd
2!ster code3 6n 4riting the de2inition o2 STRU"T 4e h!d to #se ! de2ining 4ord 4ith its
!5eit sm! r#n time o8erhe!d 4hen re2erring to the si:e o2 ! str#ct#re3 9y !ppying the
techniF#e 4e #sed in FIELD 4e c!n o8ercome e8en this3
: struct \ -- addr 0 ; -- size
\ Begin definition of a new structure. Use in the form
\ STRUCT <name>
\ At run time <name> returns the size of the structure.
Create immediate
here 0 , 0 \ mark stack, lay initial offset
does>
@ state @ \ compile literal?
if postpone literal then
;
Cautionary notes
:State,smart words are evil;
% 2# proposition o2 this st!tement m!y 5e 2o#nd !t
http*II4443comp!ng3t#4ien3!c3!tIp!persI !s ert/-3ps3g:3
%nton Ert commented !s 2oo4s on the e.!mpes !5o8e* 6 h!8e re8ised ony the
2orm!tting o2 his rep!cement code3
FIELD* =h!tOs 4orse th!n ! st!te0sm!rt 4ordD % de2ining 4ord th!t de2ines STATE0
sm!rt 4ords3 62 yo# 4!nt 2ieds to 5e e22icient, de2ine FIELD i7e this*
: field \ offset1 n "name" -- offset2 ; addr1 -- addr2
over >r
: r> postpone literal postpone + postpone ;
+
;
!nd e!8e it to the ininer to optimi:e thisS this is !so m#ch shorter3 %nother 4!y th!t
2ied c!n 5e optimi:ed is 2or o22set 0*
: field \ offset1 n "name" -- offset2 ; addr1 -- addr2
over >r
:
r> dup if
postpone literal postpone +
84
Extending the compiler
then
postpone ;
+
;
STRU"T h!s the s!me pro5em 4ith ")%)E0sm!rtnessS this co#d 5e 2i.ed 5y etting
ENDSTRU"T de2ine ! const!nt 4ith the n!me gi8en 5y STRU"T3 )his !so c!n e!d to
#ne.pected 5eh!8io#r, 5#t itOs 5etter th!n ")%)E0sm!rtness3 )hese pro5ems !re 4h!t
yo# get 2or 4or7ing !g!inst the gr!in o2 &orth3
So why use state,smart words<
)here !re indeed pro5ems 4ith st!te0sm!rt 4ords !nd the pro5ems they c!n introd#ce
!re o2ten h!rd to 2ind3 )heir p!rtic#!r !d8!nt!ge is in red#cing the n#m5er o2 4ords to
5e de2ined, !nd so impro8ing e!se o2 #se3 62 yo# !re introd#cing ! 2!ciity th!t is #sed
#nder 4e de2ined circ#mst!nces, st!te0sm!rt 4ords h!8e their p!ce in yo#r coection
o2 techniF#es3 62 yo# !re J#st #sing them to pro8ide ! per2orm!nce micro0optimis!tion,
they sho#d 5e !8oided3
&or most c#rrent &orth compiers, the st!te0sm!rt 8ersions o2 the e.!mpes !5o8e 4i
gener!te 2!ster code3
Bemem5er, ne8er tic7, POSTPONE or <"OMPILE= st!te0sm!rt 4ords3
85
Errors and exception handling
12 'rrors and e(ception handling
ABORT9 9UIT and ABORTO
ABORT ( @*H 5 resets the d!t! st!c7 !nd r#ns the &orth te.t interpreter, #s#!y
5y c!ing 9UIT3 ABORT is essenti!y ! 4!rm rest!rt o2 the system !nd in some
systems the !ction o2 ABORT c!n 5e modi2ied 5y !ppic!tions3
<fatal error check> \ return non-zero on error
IF ABORT THEN
9UIT resets the ret#rn st!c7, 2orces inp#t to come 2rom the system consoe, !nd r#ns the
&orth te.t interpreter oop3
ABORTO ( H P&EeHE'O 5 tests x, !nd i2 it is non0:ero resets the d!t! st!c7,
#s#!y disp!ys the te.t !s ! mess!ge, !nd then r#ns 9UIT3 62 x is :ero, the mess!ge
te.t is ignored !nd e.ec#tion contin#es3
<fatal error check> \ return non-zero on error
ABORT"Fatal error"
6n most modern &orth systems ABORT !nd ABORTO !re impemented #sing THROW
5eo43
CATC" and T"0/7
9e2ore the %A" speci2ic!tion, &orth !c7ed ! port!5e nested e.ception h!nder3 )he
design o2 "AT"H !nd THROW is e.ceent, !nd 6 recommend th!t they 5e #sed to rep!ce
the #se o2 ABORT !nd ABORTO, 4hich c!n 5e de2ined in terms o2 "AT"H !nd THROW3
*escription
)he 2oo4ing description o2 the 4ords "AT"H !nd THROW 4!s 4ritten 5y Mitch
9r!dey3
"AT"H is 8ery simi!r to EXE"UTE e.cept th!t it s!8es the st!c7 pointers 5e2ore
EXE"UTEing the g#!rded 4ord, remo8es the s!8ed pointers !2ter4!rds, !nd ret#rns !
2!g indic!ting 4hether or not the g#!rded 4ord competed norm!y3 6n the s!me 4!y
th!t ! &orth 4ord c!nnot eg!y p!y 4ith !nything th!t its c!er m!y h!8e p#t on the
ret#rn st!c7, !nd !so is #n!22ected 5y ho4 its c!er #ses the ret#rn st!c7, ! 4ord
g#!rded 5y "AT"H is o5i8io#s to the 2!ct th!t "AT"H h!s p#t items on the ret#rn
st!c73
HereOs the impement!tion o2 "AT"H !nd THROW in ! mi.t#re o2 &orth !nd pse#do0
code*
VARIABLE HANDLER \ Most recent error frame
: CATCH \ cfa -- 0|error-code
<push parameter stack pointer on to return stack>
<push contents of HANDLER on to return stack>
<set HANDLER to current return stack pointer>
EXECUTE
87
Errors and exception handling
<pop return stack into HANDLER>
<pop & drop saved parameter stack ptr from return stack>
0
;
: THROW \ error-code --
?DUP
IF
<set return stack pointer to contents of HANDLER>
<pop return stack into HANDLER>
<pop saved parameter stack pointer from return stack>
<back into the parameter stack pointer>
<return error-code>
THEN
;
)he description !s 4ritten impies the e.istence o2 ! p!r!meter st!c7 pointer !nd ! ret#rn
st!c7 pointer3 )h!t is !ct#!y !n impement!tion det!i3 )he p!r!meter st!c7 pointer
need not !ct#!y e.istS ! th!t is necess!ry is the !5iity to restore the p!r!meter st!c7 to
! 7no4n depth3 )h!t c!n 5e done in ! competey st!nd!rd 4!y, #sing DEPTH, DROP,
!nd DUP3 Li7e4ise, the ret#rn st!c7 pointer need not e.picity e.istS ! th!t is
necess!ry is the !5iity to remo8e things 2rom the top o2 the ret#rn st!c7 #nti its depth is
the s!me !s ! pre8io#sy0remem5ered depth3 )his c!nOt 5e port!5y impemented in high
e8e, 5#t 6 neither 7no4 o2 nor c!n 6 concei8e o2 ! system 4itho#t some str!ight2or4!rd
4!y o2 doing so3
-ample implementation
6n most &orth systems, the 2oo4ing code 4i 4or7*
VARIABLE HANDLER \ Most recent exception handler
: CATCH \ execution-token -- error# | 0
( token ) \ Return address already
\ on data stack
SP@ >R ( token ) \ Save data stack pointer
HANDLER @ >R ( token ) \ Previous handler
RP@ HANDLER ! ( token ) \ Set current handler to this one
EXECUTE ( ) \ Execute the word passed
R> HANDLER ! ( ) \ Restore previous handler
R> DROP ( ) \ Discard saved stack pointer
0 ( 0 ) \ Signify normal completion
;
: THROW \ ?? error#|0 -- ?? error# ;
\ Returns in saved context
?DUP
IF
HANDLER @ RP! ( err# ) \ Back to saved R.
\ stack context
R> HANDLER ! ( err# ) \ Restore previous handler
( err# ) \ Remember error# on
\ return stack before
( err# ) \ changing data stack ptr.
R> SWAP >R ( saved-sp ) \ err# is on return stack
SP! ( token) \ switch stacks back
DROP ( )
88
Errors and exception handling
R> ( err# ) \ Change stack pointer
THEN
\ This return will return to the caller of catch, because
\ the return stack has been restored to the state that
\ existed when CATCH began execution.
;
Features
6n p!rtic#!r the 2oo4ing 2e!t#res o2 "AT"H !nd THROW sho#d 5e noted3
"AT"H !nd THROW do not restrict the #se o2 the ret#rn st!c7
)hey !re neither IMMEDIATE nor Pst!te0sm!rtPS they c!n 5e #sed inter!cti8ey,
compied into coon de2initions, or POSTPONEd 4itho#t str!ngeness3
)hey do not introd#ce !ny ne4 synt!ctic contro str#ct#res (i3e3 4ords th!t m#st 5e
e.ic!y Pp!iredP i7e IF !nd THEN)
)o h!nde the c!se 4here there is no "AT"H to h!nde ! THROW, it is 4ise to "AT"H the
m!in oop o2 the !ppic!tion3 % di22erent so#tion, i2 yo# donOt 4!nt to modi2y the oop,
is to !dd this ine to THROW*
HANDLER @ 0= ABORT" Uncaught THROW"
-tack rules for CATC" and T"0/7
LetOs s#ppose th!t 4e h!8e the 4ord FOO th!t 4e 4ish to Pg#!rdP 4ith "AT"H3 FOOOs
st!c7 di!gr!m oo7s i7e*
FOO \ a b c -- d
HereOs ho4 to "AT"H it*
<prepare arguments for FOO> ( -- a b c )
['] FOO CATCH
IF ( -- x1 x2 x3 )
<some code to execute if FOO caused a THROW>
ELSE ( -- d )
<some code to execute if FOO completed normally>
THEN
Aote th!t, in the c!se 4here "AT"H ret#rns non0:ero (i3e3 ! THROW occ#rred), the st!c7
depth (denoted 5y the presence o2 .1, .2 !nd .3) is the s!me !s 5e2ore FOO e.ec#ted,
5#t the !ct#! contents o2 those three st!c7 items is #nde2ined3 A393 items on the st!c7
#nderne!th those three items sho#d not 5e !22ected, #ness the st!c7 di!gr!m 2or FOO,
sho4ing three inp#ts, does not tr#y represent the n#m5er o2 st!c7 items potenti!y
modi2ied 5y FOO3
6n pr!ctice, !5o#t the ony thing th!t yo# c!n do 4ith those Pd#mmyP st!c7 items .1, .2
!nd .3 is to DROP them3 6t is import!nt, ho4e8er, th!t their n#m5er 5e !cc#r!tey
7no4n, so th!t yo# c!n 7no4 ho4 m!ny items to DROP3 "AT"H !nd THROW !re
competey predict!5e in this reg!rdS THROW restores the st!c7 depth to the s!me depth
8%
Errors and exception handling
th!t e.isted J#st prior to the e.ec#tion o2 FOO, !nd the n#m5er o2 st!c7 items th!t !re
potenti!y g!r5!ge is the n#m5er o2 inp#ts to FOO3
-ome more features
THROW c!n ret#rn !ny non0:ero n#m5er to the "AT"H point3 )his !o4s 2or seecti8e
error h!nding3 % good 4!y to cre!te #niF#e n!med error codes is 4ith )ARIABLEs !s
they ret#rn #niF#e !ddresses 4itho#t h!8ing to 4orry !5o#t 4hich n#m5er to #se, e3g3
VARIABLE ERROR1
VARIABLE ERROR2
cre!tes t4o 4ords, e!ch o2 4hich ret#rns ! di22erent #niF#e n#m5er3 &or seecti8e error
h!nding, it is con8enient to 2oo4 "AT"H 4ith ! "ASE st!tement inste!d o2 !n IF3
HereOs ! more compic!ted e.!mpe*
BEGIN
['] FOO CATCH
CASE
0 OF ." Success; continuing" TRUE ENDOF
ERROR1 OF ." Error #1; continuing" TRUE ENDOF
ERROR2 OF ." Error #2; retrying" FALSE ENDOF
( default ) ." Propagating error upwards" THROW
ENDCASE ( retry? )
UNTIL
Aote the #se o2 THROW in the de2!#t 5r!nch3 %2ter "AT"H h!s ret#rned, 4ith either
s#ccess or 2!i#re, the error h!nder conte.t th!t it cre!ted on the ret#rn st!c7 h!s 5een
remo8ed, so !ny s#ccessi8e THROWs 4i tr!ns2er contro to ! "AT"H h!nder !t !
higher e8e3 6t is good pr!ctice to de2ine ! top e8e h!nder 2or ! t!s7s3 &or !n
inter!cti8e &orth, the termin! t!s7 inc#des this inside its m!in oop3
)he "AT"H !nd THROW scheme !ppe!ed to peope 5ec!#se it is simper th!n most
other schemes, !s po4er2# !s !ny (!nd more po4er2# th!n most), is e!sy to impement,
introd#ces no ne4 synt!., h!s no sep!r!te compiing 5eh!8io#r, !nd #ses the minim#m
possi5e n#m5er o2 4ords (t4o)3
'rror codes and return results
&orth 4ords th!t per2orm he!p reF#ests !nd 6I$ to 2ies !nd other de8ices, e3g3 OPEN
FILE, ret#rn !n ;6I$ res#t<, !55re8i!ted to ior in the %A" &orth doc#ment!tion3 %n ior
is :ero 2or s#ccess3 THROW ( 6 5 does nothing i2 nW03 Go#r !ppic!tion sho#d
decide ho4 to h!nde this ior i2 it is non0:ero3 =hether to h!nde the error oc!y, e3g3
retry, or 4hether to tre!t 2!i#re !s ! 2!t! error is yo#r decision3
62 ! memory reF#est 8i! ALLO"ATE ( s@Qe addr @Cr 5 2!is, it m!y 5e th!t
!nother t!s7 is tempor!riy #sing memory3 6n this c!se it m!y 5e 4orth trying e8ery 20
ms 2or 100 ms to get the memory 5e2ore triggering ! 2!t! error3 62 ! 2!t! error occ#rs,
yo# c!n THROW #p ! e8e3 )his e!ds in t#rn to the F#estion o2 4h!t error code to #se
2or the 2!t! THROW3 6n o#r e.perience, the 5est t!ctic is to #se the s!me codes 2or iors
!nd 2or thro4 codes3
%0
Errors and exception handling
Let #s de2ine t4o 8ersions o2 ! protected 8ersion o2 ALLO"ATE3 )he 2irst tre!ts !
2!i#res !s 2!t!, 4here!s the second tries to reco8er 5e2ore c!#sing ! THROW3
: ProtAlloc \ size -- addr
allocate throw \ all errors fatal
;
: ProtAlloc \ size -- addr
0 0 \ dummy addr and ior
5 0 do \ -- addr ior
2drop \ discard previous results
dup allocate \ -- size addr ior
dup 0= \ exit loop on success
if leave endif
20 ms \ wait
loop \ -- size addr ior ; try again
rot drop \ -- addr ior
throw \ -- addr
;
)hese e.!mpes i#str!te th!t, pro8iding there !re no side e22ects, yo# c!n r!dic!y
ch!nge the !rchitect#re o2 ! 4ord 4ith no imp!ct on the so2t4!re o#tside it3 9y
THROWing #sing !n ior !s ! thro4 code, yo#r #pper e8e error h!nder per2orms the
s!me !ction in 5oth c!ses3
)he gener! r#e is th!t yo# try to h!nde reco8er!5e errors oc!y, !nd 2!t! errors
c!#se ! THROW3 )he h!nder 2or the ne.t e8e #p 4i THROW !g!in i2 it c!nnot h!nde
the error3 )he top e8e error h!nder, s#ch !s the one in 9UIT, processes ! errors3
)he %A" st!nd!rd reser8es neg!ti8e thro4 codes 2or the &orth system3 6n p!rtic#!r, 01
!nd M2 !re reser8ed 2or ABORT !nd %9$B)< so th!t they c!n 5e impemented in terms
o2 THROW3 Most modern &orths t!7e this !ppro!ch3 % side e22ect o2 this is th!t ABORT is
no onger ! system04ide 4!rm rest!rt3
Always clean up
M!ny oper!tion per2orm ! seF#ence th!t c!n 5e descri5ed !s*
OPEN PROCESS CLOSE
or
SETUP OPERATE CLEANUP
62 PRO"ESS or OPERATE enco#nter ! 2!t! error, they m!y THROW3 62 yo# do not
per2orm the termin!tion oper!tions, yo#r !ppic!tion m!y 5ecome #nst!5e3 )his is
p!rtic#!ry tr#e o2 ong0r#nning em5edded systems !nd ser8er !ppic!tions s#ch !s
2ire4!s3 =e #sed to re5oot o#r em!i ser8er PC e8ery month or so to reco8er 2rom
memory e!7s (#nree!sed memory !oc!tions)3 )he 2oo4ing code ens#res th!t the
"LOSE oper!tion !5o8e is !4!ys per2ormed*
: DOIT
...
OPEN [] PROCESS CATCH CLOSE THROW
...
;
%1
Errors and exception handling
)he ior ret#rned 5y "AT"H is cons#med 5y the THROW !2ter "LOSE h!s 5een e.ec#ted,
!nd i2 the ior is non0:ero !nother THROW 4i occ#r3 6n this 4!y, the "LOSE oper!tion is
!4!ys per2ormed, !nd pro5ems s#ch !s memory e!7s !nd open 2ies 4i 5e remo8ed3
%2
Files
1! Files
A;- File Access 7ordset
)he 5!sis 2or ! 2ie oper!tions comes 2rom the %A" speci2ic!tion 4ordset 2or &ies3
)he 2oo4ing gro#p o2 de2initions !re impement!tions o2 the %A" st!nd!rd set3
)he 2oo4ing d!t! types !re #sed*
2!m P&ie %ccess MethodP, descri5es re!dI4rite permission etc3
ior P6$ Bes#tP, % ret#rn res#t 2rom most 6$ c!s, this 8!#e is 0 2or
s#ccess or non0:ero !s !n error0code3
2ieid P&ie 6denti2ierP, ! h!nde 2or ! 2ie3
Table 1) File access data types
B@6 \ fam -- fam'
Modi2y ! 2ie0!ccess method to inc#de 96A%BG3
r/C \ -- fam
Eet Be!d$ny 2!m3
4/C \ -- fam
Eet =riteony 2!m3
r/4 \ -- fam
Eet Be!d=rite 2!m
"REATEFILE \ c-addr u fam -- fileid ior
Cre!te ! 2ie on dis7, ret#rning ! 0 ior 2or s#ccess !nd ! 2ie id3
OPENFILE \ c-addr u fam -- fileid ior
$pen !n e.isting 2ie on dis73
"LOSEFILE \ fileid -- ior
Cose !n open 2ie3
WRITEFILE \ caddr u fileid -- ior
=rite ! 5oc7 o2 memory to ! 2ie3
WRITELINE \ c-addr u fileid -- ior
=rite d!t! 2oo4ed 5y E$L3 6$BW0 2or s#ccess3
%3
Files
READFILE \ caddr u fileid -- u2 ior
Be!d d!t! 2rom ! 2ie3 )he n#m5er o2 ch!r!cter !ct#!y re!d is ret#rned !s #2, !nd
ior is ret#rned 0 2or ! s#ccess2# re!d3
READLINE \ c-addr u1 fileid -- u2 flag ior
Be!d !n %"C66 ine o2 te.t 2rom ! 2ie into ! 5#22er, 4itho#t E$L3 Be!d the ne.t
ine 2rom the 2ie speci2ied 5y 2ieid into memory !t the !ddress c0!ddr3 %t most
#1 ch!r!cters !re re!d3 'p to t4o ine0termin!ting ch!r!cters m!y 5e re!d into
memory !t the end o2 the ine, 5#t !re not inc#ded in the co#nt #23 )he ine 5#22er
pro8ided 5y c0!ddr sho#d 5e !t e!st #1+2 ch!r!cters ong3
62 the oper!tion s#cceeds, 2!g is tr#e !nd ior is :ero3 62 ! ine termin!tor 4!s
recei8ed 5e2ore #1 ch!r!cters 4ere re!d, then #2 is the n#m5er o2 ch!r!cters, not
inc#ding the ine termin!tor, !ct#!y re!d (0 UW #2 UW #1)3 =hen #1 W #2, the
ine termin!tor h!s yet to 5e re!ched3
62 the oper!tion is initi!ted 4hen the 8!#e ret#rned 5y FILEPOSITION is
eF#! to the 8!#e ret#rned 5y FILESIRE 2or the 2ie identi2ied 5y 2ieid, 2!g is
2!se, ior is :ero, !nd #2 is :ero3 62 ior is non0:ero, !n e.ception occ#rred d#ring
the oper!tion !nd ior is the 6I$ res#t code3
%n !m5ig#o#s condition e.ists i2 the oper!tion is initi!ted 4hen the 8!#e
ret#rned 5y FILEPOSITION is gre!ter th!n the 8!#e ret#rned by FILE
SIRE 2or the 2ie identi2ied 5y 2ieid, or i2 the reF#ested oper!tion !ttempts to
re!d portions o2 the 2ie not 4ritten3
%t the conc#sion o2 the oper!tion, FILEPOSITION ret#rns the ne.t 2ie
position !2ter the !st ch!r!cter re!d3
FILESIRE \ fileid -- ud ior
Eet si:e in 5ytes o2 !n open 2ie !s ! do#5e n#m5er, !nd ret#rn iorW0 on s#ccess3
FILEPOSITION \ fileid -- ud ior
Bet#rn 2ie position, !nd ret#rn iorW0 on s#ccess3
REPOSITIONFILE \ ud fileid -- ior
"et 2ie position, !nd ret#rn iorW0 on s#ccess3
RESIREFILE \ ud fileid -- ior
"et the si:e o2 the 2ie to #d, !n #nsigned do#5e n#m5er3 %2ter #sing RESIRE
FILE, the res#t ret#rned 5y FILEPOSITION m!y 5e in8!id3
FLUSHFILE \ fileid -- ior
%ttempt to 2orce !ny 5#22ered in2orm!tion 4ritten to the 2ie re2erred to 5y 2ieid
to 5e 4ritten to m!ss stor!ge3 62 the oper!tion is s#ccess2#, ior is :ero3
DELETEFILE \ c-addr u -- ior
>eete ! n!med 2ie 2rom dis7, !nd ret#rn iorW0 on s#ccess3
%4
Files
IN"LUDEFILE \ file-id --
6nc#de so#rce code 2rom !n open 2ie 4hose 2ie0id (h!nde) is gi8en3 %2ter
IN"LUDEFILE h!s e.ec#ted the 2ie 4i h!8e 5een cosed3
IN"LUDED \ c-addr u --
6nc#de so#rce code 2rom ! 2ie 4hose n!me is gi8en 5y c0!ddrI#3
IN"LUDE \ "<name>" --
% more con8enient 2orm o2 IN"LUDED3 'se in the 2orm PIN"LUDE &6aAe'P3
)his 4ord is not p!rt o2 the %A" st!nd!rd, 5#t is 4idey !8!i!5e3 %so c!ed
FLOAD in some systems3 'nder oper!ting systems th!t s#pport sp!ces in 2ie
n!mes, yo# m!y 5e !5e to #se the 2orms*
INCLUDE my file.f
INCLUDE my file.f
-imple file tools
)his e.!mpe is deri8ed 2rom code 5y =i 9!den in his )oo9o. series3 6t co8ers 4h!t
is reF#ired 4hen o!ding ! compete 2ie into memory !nd 4riting ! memory 5oc7 to !
2ie3
\ *************
\ *S File tools
\ *************
: FILE-CHECK \ n --
ABORT" File Access Error "
;
: MEMORY-CHECK \ n --
ABORT" Memory Allocation Error "
;
: rewind-file \ file-id -- ior
0 0 rot reposition-file
;
0 value pData \ -- addr ; poi to data block
0 value /Data \ -- n ; size of data block
0 value hData \ -- handle ; handle of data file
: InitReadFile \ handle -- size
\ *G Reset the file to the start and return its size.
dup rewind-file file-check
file-size file-check drop
;
: OpenMouth \ caddr len --
\ *G Open the file for read only.
r/o open-file file-check dup to hData
InitReadFile to /Data
;
%5
Files
: guzzle \ file-id -- addr length
\ *G Reads file from disc to HERE without ALLOTing space.
\ ** The file is left open.
dup InitReadFile \ -- handle len
here swap rot read-file file-check \ -- #read
here swap \ -- addr #read
;
: slurp \ file-id -- addr length
\ *G Reads the contents of a file into ALLOCATEd memory
\ ** and returns the address and length. Release the
\ ** memory using BURP.
dup InitReadFile \ -- handle len
dup allocate memory-check \ -- handle len addr
dup to pData dup >r swap rot \ -- addr len h ; R: -- addr
read-file file-check \ -- #read
r> swap \ -- addr #read
;
: Hiccup \ --
\ *G Close the file opened by OpenMouth.
hData close-file file-check
;
: BURP \ --
\ *G Release memory ALLOCATEd by SLURP.
pData free memory-check
;
: Spit \ caddr len name namelen --
\ *G Write the memory defined by caddr/len to the file
\ ** whose name is given by name/namelen. A THROW occurs
\ ** on any error.
r/w create-file throw >r \ create
r@ write-file throw \ write
r> close-file throw \ close
;
%6
Common extensions
1# Common e(tensions
:ultitasking
M#tit!s7ing h!s 5een p!rt o2 &orth 2or ! 8ery ong time, !nd s#pport 2or it is 5#it into
the 7erne !t the o4est e8es3 M!ny systems e8en reser8e ! CP' register !s ! t!s7
pointer3
'n2ort#n!tey, the %A" 1//, &orth st!nd!rds te!m 4!s #n!5e (4orn o#t, not eno#gh
time) to re!ch ! consens#s on m#tit!s7ing !nd there2ore this ch!pter c!n ony s7etch o#t
the principes !nd #se 8endor0speci2ic e.!mpes3 >espite this, the !ppro!ch t!7en 5y
most 8endors !nd impementers is 5ro!dy simi!r3
Cooperati+e and Preempti+e taskers
6n gener!, hosted systems 2or oper!ting systems s#ch !s =indo4s, Lin#. !nd other
'nices t!7e !d8!nt!ge o2 oper!ting system ser8ices3 Commerci! 8endors 4ho !so
s#pport em5edded systems o2ten pro8ide ! 4r!pper !yer to pro8ide some so#rce code
comp!ti5iity 4ith em5edded system pr!ctice3 )he m#tit!s7ers 2or oper!ting systems
!re ne!ry !4!ys pre0empti8e 0 triggered 5y !n interr#pt3
&orth em5edded systems mosty #se cooper!ti8e (sometimes c!ed ro#nd0ro5in)
m#tit!s7ers3 6n these, progr!mmers h!8e to c! ! 4ord, #s#!y c!ed PAUSE, 4hich
sched#es the ne.t t!s73 "ome &orth progr!mmers do #se pre0empti8e m#tit!s7ers, !nd
these !re #s#!y 5!sed on cooper!ti8e sched#ers e.tended to imit the time sot #sed 5y
! singe t!s73 % 2e4 2#y preempti8e systems h!8e 5een 4ritten3
)he choice 5et4een the t4o types comes do4n to the !ppic!tion dom!in3 Em5edded
systems c!n h!8e 8ery he!8y CP' o!dings !nd the o8erhe!ds o2 ! preempti8e sched#er
m!y not 5e s#it!5e3 6n ! he!8iy o!ded system, the simpicity (!nd hence per2orm!nce)
o2 ! cooper!ti8e sched#er c!n e!d to higher ser8ice e8es th!n !re !8!i!5e 2rom !
preempti8e sched#er3 Ho4e8er, this e!ds to !c7 o2 2e!t#res 4hich !n oper!ting system
progr!mmer 2ees n!7ed 4itho#t3 Pro8ided th!t yo# t!7e the tro#5e to e!rn the &orth
cooper!ti8e m#tit!s7er !nd !ppy ! 2e4 simpe r#es, the &orth cooper!ti8e m#tit!s7er
is ! 4onder2#y e22ecti8e ight4eight sched#er3
% 2o#r0!.is 5om50dispos! m!chine r!n t4e8e t!s7s #sing the st!nd!rd MPE sched#er,
!nd 4e h!8e he!rd o2 systems 4ith #p to ,00 t!s7s3
USER +ariables
)he eF#i8!ent o2 4h!t =indo4s progr!mmers c! ;thre!d0oc! stor!ge< is pro8ided
5y USER 8!ri!5es, #s#!y de2ined in the 2orm*
offset USER <name> \ -- addr
% USER 8!ri!5e ret#rns its !ddress3 E!ch t!s7 h!s its o4n USER 8!ri!5e !re!3
ConseF#enty, commony #sed system 8!ri!5es s#ch !s BASE c!n 5e set independenty
2or e!ch t!s73 "imi!ry, e!ch t!s7 c!n h!8e its o4n comm#nic!tions ch!nne, e3g3 in !n
inteigent seri! c!rd h!nding di22erent protocos3 )o e!se de2inition o2 t!s70speci2ic
%7
Common extensions
5#22ers, !nd to red#ce progr!mmer thin7ing time, m!ny systems m!int!in ! co#nt o2 the
#sed si:e o2 the USER !re! !nd pro8ide ! 2!ciity to !dd ! 5#22er3
size +USER <name> \ -- addr
USER 8!ri!5es !re o2ten !so pro8ided 2or high0e8e interr#pt h!nders in em5edded
systems !nd 2or oper!ting system c!5!c7s (#ser0s#ppied ro#tines c!ed 5y the
oper!ting system)3 M!ny &orth impementers consider USER 8!ri!5es to 5e so
import!nt th!t they dedic!te ! m!chine register to hod the 5!se !ddress o2 the USER
!re!3
-imple Forth tasks
9e2ore !ny t!s7s c!n 5e !cti8!ted, the m#tit!s7er m#st 5e initi!ised3 )his is done 4ith
the 2oo4ing code*
INIT-MULTI
)he 4ord INITMULTI initi!ises ! the m#tit!s7erOs d!t! str#ct#res !nd st!rts
m#tit!s7ing3 )his 4ord need ony 5e e.ec#ted once in ! m#tit!s7ing system !nd is
#s#!y done !#tom!tic!y !t po4er #p3
#1000 VALUE DELAY \ -- n ; time delay between #'s
: ACTION1 \ -- ; task to display #'s
[CHAR] $ EMIT \ Display a dollar ($)
BEGIN \ Start continuous loop
[CHAR] # EMIT \ Display a hash (#)
DELAY 0 \ Reschedule Delay times
?DO PAUSE LOOP
AGAIN \ Back to the start ...
;
62 4e 4!nted to 4!it ! speci2ic time there is ! 4ord MS ( u 5 4hich 4!its the
gi8en n#m5er o2 miiseconds3 6n this c!se 4e rep!ce the code
DELAY 0 \ Reschedule Delay times
?DO PAUSE LOOP
4ith
DELAY MS \ wait x milliseconds
)o !cti8!te (r#n) the e.!mpe t!s7, type*
TASK TASK1
` ACTION1 TASK1 INITIATE
)his 4i !cti8!te A"TION, !s the !ction o2 t!s7 TAS*,3 6mmedi!tey yo# 4i see !
do!r !nd ! h!sh (]^) disp!yed3 62 yo# press Uret#rnV ! 2e4 times, yo# notice th!t the
&orth interpreter is sti r#nning3 %2ter ! 4hie !nother h!sh 4i !ppe!r3 )his is the
e.!mpe t!s7 4or7ing in the 5!c7gro#nd3 Go# c!n 7i the t!s7 #sing
TASK1 TERMINATE
%8
Common extensions
Most &orth systems pro8ide 2!ciities to stop ! t!s7 tempor!riy, to rest!rt it !nd to send
mess!ges to t!s7s3
I./ and PAUSE
%ny 6I$ oper!tion th!t h!s to 4!it sho#d c! PAUSE inside its poing oop so th!t
other t!s7s !re not st!ed3 )he inp#t 4ord *E$ ( 3Mar 5 ne!ry !4!ys cont!ins
PAUSE3 =hether *E$( ( N:aS 5 c!s PAUSE is system dependent3 My
pre2erence is ony to c! PAUSE 4hen no inp#t is !8!i!5e3 )his optimises system
thro#ghp#t #nder he!8y o!d 5y red#cing the o8er! n#m5er o2 PAUSEs, 5#t m!y
reF#ire !ddition! code i2 !n 6I$ !cti8ity c!n c!#se o8ero!d3 )he s!mpe
impement!tion o2 *E$ #ses *E$PRIM ( 3Mar 5, ! primiti8e 4ord th!t 5oc7s3
: key \ -- char
begin
key? 0=
while
pause
repeat
keyprim
;
'rror checking
)he most common 2!#t is ! st!c7 2!#t3 "ince ! t!s7 is !n endess oop it is simpe to p#t
st!c7 depth chec7s in the m!in oop3 % simpe t!s7 4ith chec7ing is sho4n 5eo43
: TASK-ACTION \ --
sp@ s0 ! \ store stack base
<initialisation>
BEGIN
<body of task>
depth IF \ non-zero if anything there
s0 @ sp!
<warn programmer!>
ENDIF
PAUSE
AGAIN
;
Go# sho#d !so consider chec7ing 2or THROWs3
: StackCheck \ ?? --
depth if \ non-zero if anything there
s0 @ sp! <warn programmer!>
then
;
: TASK-ACTION \ --
sp@ s0 ! \ store stack base
<initialisation>
BEGIN
[`] BodyOfTask catch if
<warn programmer!>
then
StackCheck
%%
Common extensions
PAUSE
AGAIN
;
Floating point
%A" &orth st!nd!rdises 2o!ting point h!nding 4ithin ! 2r!me4or7 4hich e!8es some
2e.i5iity 2or the impementer3 "ee the %A" &orth st!nd!rd 2or more det!is3
)he intern! stor!ge 2orm!t o2 2o!ting point n#m5ers is not de2ined 5y the st!nd!rd !s
5eing 6EEE 2orm!t 5ec!#se o2 the n#m5er o2 non06EEE 2orm!ts in #se, especi!y 5y
>"P (>igit! "ign! Processing) chips3
M!ny impement!tions do not 7eep 2o!ting point n#m5ers on the &orth d!t! st!c73
6nste!d they #se ! sep!r!te 2o!ting point st!c7 in memory to !8oid st!c7 gyr!tions or
they #se the intern! st!c7 o2 ! h!rd4!re 2o!ting point engine s#ch !s the A>P o2 6nte
des7top PCs3 )his is re2erred to !s ! separate 2o!t st!c73 'sing the &orth d!t! st!c7 is
re2erred to !s ! combined st!c73
)r!dition!y &orth progr!mmers h!8e #sed 2o!ting point ess th!n C progr!mmers3
&orthLs 2!ciities 2or mi.ed !nd do#5e integer m!de it e!sy to constr#ct m#tipe
precision oper!tors3 )his sit#!tion h!s ch!nged !2ter the 2o!ting point per2orm!nce o2
des7top PCs impro8ed to the point th!t some 2o!ting point oper!tions !re no4 2!ster
th!n some integer oper!tions3 Ho4e8er, this does not me!n th!t 2o!ting point is s#it!5e
2or ! !ppic!tions reF#iring ! 8ery 4ide dyn!mic r!nge3 &o!ting point c!c#!tions c!n
s#22er 2rom imprecise c!c#!tion !nd ro#nding errors3 >#ring the constr#ction o2 the
Hong (ong !irport, it 4!s reported th!t the cost di22erence in the estim!tion 2or one p!rt
o2 the concrete 4!s o8er ten miion do!rs 5et4een ! c!c#!tion #sing 12- 5it integers
!nd ! c!c#!tion #sing 6, 5it 2o!ts3 )he integer c!c#!tion 4!s the !cc#r!te one3
%nton Ert h!d this to s!y !5o#t the concrete c!c#!tion3 His comments emph!si:e the
point th!t #se o2 2o!ting point c!n reF#ire c!#tion 4ith !ny progr!mming !ng#!ge3
"#out the concrete calculations2 -he total volume of the pro1ect %as pro#a#ly on the
order of 1,000910,000 million dollars, so an error of 10 million is 0.1>91>. -hat3s not
the result of plain floating9point rounding errors *%hich are on the order of 1e91? for
?@9#it F7 operations+, or even accumulated errors *it %ould need 1e16 F7 operations
%ith %orst9case rounding error accumulation to get there, or 1e2? F7 operations %ith
epected error accumulation+. /t3s the result of a numerically unsta#le algorithm.
F7 is pro#a#ly more surprising to programmers in that respect than fied point,
though5 e.g., if you calculate using integer num#ers, you kno% that you %ill never get
any fractional result, %hereas it surprises programmers %hen this happens %ith F7
num#ers..
)he &orth "cienti2ic Li5r!ry (&"L) proJect origin!y coordin!ted 5y "7ip C!rter
pro8ides ! h#ge r!nge o2 scienti2ic c!c#!tion ro#tines, mosty #sing 2o!ting point3 )he
&"L is s#ppied !s p!rt o2 se8er! systems3
100
Common extensions
6ocal +ariables
% set o2 4ords 2or oc! 8!ri!5e h!nding is pro8ided 5y %A" &orth3 "!dy, the st!nd!rd
does not pro8ide 4h!t is reF#ired 2or inter2!cing 4ith oper!ting systems s#ch !s
=indo4s, especi!y in h!nding oc! !rr!ys3 6t !so #ses ! 8ery c#msy not!tion th!t is
h!rd to re!d3 Ho4e8er, it did 2oo4 pr!ctice o2 the time3 )he most pop#!r !tern!ti8e
not!tion is descri5ed 5eo43 Aot ! systems pro8ide it !nd se8er! 8!ri!nts e.ist3
MPEism2 -he description #elo% is of the M7, implementation, %hich is #roadly
similar to many others.
)he seF#ence
: <name> { ni1 ni2 ... | lv1 lv2 ... -- o1 o2 }

;
de2ines n!med inp#ts, oc! 8!ri!5es, !nd o#tp#ts3 )he n!med inp#ts !re !#tom!tic!y
copied 2rom the d!t! st!c7 on entry3 A!med inp#ts !nd oc! 8!ri!5es c!n 5e re2erenced
5y n!me 4ithin the 4ord d#ring compi!tion3 )he o#tp#t n!mes !re d#mmies to !o4 !
compete st!c7 comment to 5e gener!ted3
)he items 5et4een T !nd U !re n!med inp#ts3
)he items 5et4een U !nd !re oc! 8!ri!5es3
)he items 5et4een !nd V !re o#tp#ts3
A!med inp#ts !nd oc!s ret#rn their 8!#es 4hen re2erenced, !nd m#st 5e preceded 5y
TO to per2orm ! store, or 5y ADDR to ret#rn the !ddress3
%rr!ys m!y 5e de2ined in the 2orm*
arr[ n ]
%ny n!me ending in the O[O ch!r!cter 4i 5e tre!ted !s !n !rr!y, the e.pression #p to the
termin!ting O_O 4i 5e interpreted !s the si:e3 %rr!ys !4!ys ret#rn their 5!se !ddresses,
! oper!tors !re ignored3
6n the e.!mpe 5eo4, ! !nd 5 !re n!med inp#ts, a.W !nd a*W !re oc! 8!ri!5es, !nd
arr< is ! 10 5yte !rr!y3
: foo { a b | a+b a*b arr[ 10 ] -- }
arr[ 10 erase
a b + to a+b
a b * to a*b
cr a+b . a*b .
;
Cautionary notes
6n the 2oo4ing disc#ssion the term ;&orth oc!s< re2ers to 5oth n!med inp#ts !nd oc!
8!ri!5es3
#riting & in =orth %tho#gh #se o2 &orth oc!s c!n 5e 8!#!5e 2or oc! !rr!ys !nd
re!d!5iity, there is ! gre!t d!nger 2or C progr!mmers e!rning &orth to o8er#se them3
101
Common extensions
)here !re some in the &orth comm#nity 4ho 5eie8e th!t oc! 8!ri!5es h!8e no p!ce
in ! co#rse or te.t #nti the second or third e8e3 6 h!8e seen eno#gh &orth th!t oo7s
i7e C to 7no4 th!t there is ! re! pro5em3 9ec!#se o2 the 5ene2its 4hen inter2!cing to
modern oper!ting systems !nd in cert!in c!sses o2 pro5ems, 6 re#ct!nty decided to
inc#de them3
E.cessi8e #se o2 &orth oc!s inhi5its e!rning ho4 to #se the d!t! st!c7 e22icienty !nd
red#ces the incenti8e to 2!ctor into sm! de2initions3 6n t#rn, th!t e!ds to Pc#t !nd
p!steP errors !nd to 5igger code, 4hich 2#rther e!ds to di22ic#ties in m!inten!nce !nd
de5#gging3 6 !so note th!t progr!mmers 4ho #se &orth oc!s he!8iy tend not to #se
de2ining 4ords !nd other more !d8!nced &orth techniF#es3
Performance )he &orth 8irt#! m!chine is optimised 2or t4o st!c7s, !nd the code
gener!tion o2 modern &orth compiers re2ects this3 Especi!y on CP's 4ith more th!n
eight registers, good st!c7 code is 2!ster !nd sm!er th!n code 4ith he!8y #se o2 oc!
8!ri!5es3
6 recenty o8erh!#ed p!rts o2 ! )CPI6P st!c7 !nd remo8ed &orth oc!s 4here possi5e3
%2ter testing on !n %BM (16 registers) em5edded system, the si:e o2 re4ritten 4ords
red#ced 5y 20` !nd per2orm!nce impro8ed 5y 50`3 6n p!rtic#!r c!ses code si:e
red#ced 5y 50` or more3 Code si:e impro8es 5ec!#se the compier m!7es 5etter #se o2
CP' registers !nd per2orm!nce impro8es 5ec!#se o2 sm!er code !nd red#ced memory
tr!22ic3 %tho#gh ess dr!m!tic 4e h!8e simi!r res#ts 2or most CP's3 &or CP's 4ith
32 or more registers, e3g3 "P%BC !nd Po4erPC, &orth compier 4riters c!n e!siy #se
registers 2or oc! 8!ri!5es3
=riters o2 &orth compier !re #ni7ey to p#t in ! h#ge e22ort to optimise 5!d code3 %2ter
!n e!rier ree!se o2 this 5oo7, the 2oo4ing comments 4ere m!de on the
comp3!ng32orth ne4sgro#p comp!ring C !nd &orth compiers3
%nton Ert* Aou might #e surprised5 as long as the #ad code occurs in sufficiently
important #enchmarks, they are very likely to put in a huge effort. Bo%ever, in the case
of Forth, optimiCing stack code %ill #enefit all the code out there *including code using
locals+, %hereas optimiCing locals %ill only #enefit a minority of code5 it should come
as no surprise that Forth compiler implementors %ill concentrate on optimiCing stack
accesses first..
%ndre4 H!ey* $ell, it3s not 1ust that2 %e can3t tell %hether the <#ad= code has #een
%ritten #y a programmer or is the output of a previous compilation pass. (o, %e
optimiCe everything %e can, even if it3s something no sane programmer %ould ever
%rite..
$voiding locals )he m!in re!son th!t peope 2ee they need oc!s is h!8ing too m!ny
items in #se on the d!t! st!c73 )here !re three 4!ys to !8oid this*
1) Be02!ctor into sm! de2initions th!t #se 2e4er items on the st!c7,
2) 'se the ret#rn st!c7 to hod the e!st commony #sed items,
3) =here items !re p!irs or !rger, 2or e.!mpe .Iy coordin!te p!irs 2or points or
.IyI4Ih sets 2or ! rect!nge description, consider 7eeping them in str#ct#res !nd
p!ssing pointers to the str#ct#res3 %tho#gh pointers incre!se memory tr!22ic, they
consider!5y red#ce st!c7 tr!22ic !t 4ord entry !nd e.it3
102
Common extensions
=e re4rote !n em5edded E'6 p!c7!ge !2ter ! cient reF#ested ch!nges3 )he origin!
code h!d 5een 4ritten 4ith e.tensi8e #se o2 &orth oc!s3 %2ter reorg!nis!tion !nd
o8erh!#, ony one 4ord #sed oc! 8!ri!5es3 )he code is shorter 5oth in terms o2 ines
o2 so#rce code !nd in terms o2 compied code si:e3 )he code is e!sier to m!int!in3
#hen to use locals
1) )o !8oid st!c7 repetition o2 compe. c!c#!tions3 "ome c!c#!tions h!8e common
s#50e.pressions 4ith re#sed intermedi!te res#ts3 "toring these on either st!c7 c!n
e!d to ;st!c7ro5!tics<3 6n per2orm!nce !nd code si:e, oc! 8!ri!5es !re che!p
comp!red to n!med inp#ts3 >e2ining oc! 8!ri!5es 2or these c!n 5e 8ery e22ecti8e3
2) &or tempor!ry sm! 5#22ers3 )he !tern!ti8es to oc! 5#22ers !re ! he!p, go5! or
t!s705!sed (thre!d oc!) str#ct#res3 %tho#gh he!p 2#nctions !re 4idey !8!i!5e
!nd st!nd!rdised, they reF#ire code, h!8e per2orm!nce !nd rei!5iity pen!ties
(he!p e!7s !re not #n7no4n in !ny !ng#!ge) !nd reF#ire gre!t c!re in e.ception
h!nding3 Loc! 5#22ers !re !#tom!tic!y disc!rded on e.it 2rom ! 4ord, !nd, in
e8ery &orth impement!tion 6 h!8e inspected, they !re competey comp!ti5e 4ith
"AT"H !nd THROW3
/bAect oriented programming
% pethor! o2 o5Ject oriented e.tensions e.ist 2or &orth r!nging 2rom 16 to se8er!
tho#s!nd ines o2 so#rce code3 )he Aeon (!ter %ctor) $$ progr!mming !ng#!ge 4!s
itse2 4ritten in &orth3 )his mode h!s pro5!5y 5een the most 4idey #sed !nd is
!8!i!5e 2or se8er! des7top &orth systems3 Em5edded system modes !so 8!ry 4idey3
)here is not yet eno#gh common pr!ctice to m!7e 2#rther e.!mpes !nd disc#ssion
4orth4hie3
Integrated assembly
)he m!Jority o2 &orth systems 4ritten 2or ! speci2ic CP' (not 4ritten in !nother high
e8e !ng#!ge) inc#de !n !ssem5er 2or the CP' !nd 2!ciities to cre!te 4ords 4ritten
entirey in !ssem5er3 "#ch 4ords !re c!ed "ODE 4ords3 %s 4ith C compiers there is
! 4ide 8!riety o2 not!tions !nd oper!nd orders3
"ODE de2initions 4ere 4idey #sed 5y indirect (6)C) !nd direct0thre!ded (>)C)
systems to impro8e the per2orm!nce o2 per2orm!nce0critic! inner oops3 =ith
optimising n!ti8e code compiers this is 2!r ess necess!ry3 $#r =indo4s &orth #ses
ony !5o#t 30 ro#tines coded in !ssem5er, mosty to do 4ith st!rt #p !nd inter2!cing
4ith the oper!ting system3 6n em5edded systems, "ODE ro#tines !re reser8ed 2or
!ccessing speci! CP' registers s#ch !s the st!t#s register (e3g3 2or interr#pt en!5ing
!nd dis!5ing), 2or the occ!sion! interr#pt h!nder, !nd 2or the sched#er in the
m#tit!s7er3
)he em5edded systems ch!pter cont!ins se8er! e.!mpes o2 "ODE de2initions3
-ource location
%s !ppic!tions get !rger, the !5iity to 5ro4se so#rce code r!pidy 5ecomes more
import!nt3 M!ny &orth systems pro8ide ! 4!y to 2ind the so#rce code o2 ! 4ord,
typic!y #sing ! phr!se s#ch !s
103
Common extensions
LOCATE <name>
SEE <name>
VIEW <name>
4here &6aAe' is the n!me o2 the 4ord 4hose so#rce code is reF#ired3 )he so#rce code
is #s#!y disp!yed 5y !n intern! or e.tern! editor3 62 the so#rce code is not !8!i!5e,
the code m!y 5e dis!ssem5ed or decompied3
:i(ed language programming
6t is ! sin to rein8ent the 4hee #ness it is J#st 2or the pe!s#re o2 e.por!tion3 Per2ecty
good code e.its in ! 4ide r!nge o2 !ng#!ges3 Be#sing code is #s#!y che!per th!n
re4riting it3 &or &orth systems r#nning #nder !n oper!ting system the most common
so#tion is to pro8ide !n inter2!ce to sh!red i5r!ries or =indo4s >LLs, commony the
s!me mech!nism reF#ired to !ccess the oper!ting system itse23 &or em5edded systems,
the iss#es re8o8e !ro#nd o5Ject 2ie 2orm!ts3
Parameter passing
)he 2irst iss#e is to 4or7 o#t ho4 to tr!ns!te &orth st!c7 items into the 2orm reF#ired 5y
the other !ng#!ge3 =e 4i #se the 5!sic =indo4s Send7essage %P6 c! !s !n
e.!mpe3
int PASCAL SendMessage(
HWND hwnd, WORD msg, WPARAM wParam, LPARAM lParam
);
)o c! this 2rom &orth, 4e c!n de2ine it in t4o 4!ys3
SendMessage \ hwnd msg wparam lparam -- int
or
SendMessage \ lparam wparam msg hwnd -- int
=hich choice yo# m!7e !22ects ho4 the &orth p!r!meters h!8e to 5e org!nised 4hen
they !re p!ssed to the C system3 >epending on the oper!ting system !nd compier,
p!r!meters !re p!ssed in registers or on ! st!c73 62 p!r!meters !re p!ssed in registers,
e3g3 %BM or "P%BC CP's, there 4i 5e ! imit on the n#m5er th!t !re p!ssed in
registers, !nd !ddition! p!r!meters 4i 5e p!ssed on ! st!c73 )he order in 4hich
p!r!meters !re p!ssed 4i depend on the !ng#!ge3
)he ne.t st!ge is to 4rite !n inter2!ce ro#tine 4hich t!7es the p!r!meters 2rom the &orth
d!t! st!c7 !nd !n !ddress to c!, per2orms the c!, !nd 2in!y ret#rns the res#t i2 there
is one3 =e #s#!y c! this ro#tine X"ALL3 )hese inter2!ce ro#tines reF#ire the #se o2
speci2ic CP' registers !nd so !re 5est 4ritten in !ssem5er3 6t is 4e 4orth 4hie
4riting ! &orth de2ining 4ord or c#stom p!rser to h!nde de2ining the &orth side o2 the
c!3 Ho4 yo# do this 4i in2#ence ho4 yo# 4rite the inter2!ce ro#tine or ro#tines !nd
yo# sho#d design !nd code them together3
&or re!d!5iity, it is common to 7eep the &orth st!c7 order !nd C p!r!meter order
8is#!y the s!me in order to red#ce progr!mmer typing errors3
104
Common extensions
*66s and shared libraries
$nce yo# h!8e decided on the p!r!meter p!ssing !nd not!tion, yo# then h!8e to
determine ho4 to o!d the i5r!ry, 2ind the !ddress o2 ! ro#tine in ! sh!red i5r!ry, !nd
ree!se the i5r!ry3 )his is oper!ting system dependent !nd o2ten reF#ires ! speci!
section in the e.ec#t!5e 2ie3 $per!ting system doc#ment!tion !t this e8e is o2ten
5!dy org!nised, tedio#s !nd o5sc#re3 &or =indo4s, the %P6 ro#tines yo# need !re
c!ed 5oad5ibrary, 3etProc$dress !nd =ree5ibrary3
$nce yo# h!8e these three 2#nctions, yo# c!n no4 m!7e ! ro#tine th!t se!rches 2or
2#nctions 5y n!me (pro5!5y c!se sensiti8e) !nd s!8es the 2#nction !ddresses in the right
p!ces3 Go#r de2ining 4ord or p!rser c!n prod#ce the right d!t! 2or the CC%LL ro#tine
!5o8e3 % typic! &orth de2inition 2or Send7essage !5o8e co#d 5e*
4 1 libfunction: SendMessage
4hich de2ines th!t there !re 2o#r inp#t p!r!meters !nd one o#tp#t3 "ince most C
2#nctions !4!ys ret#rn ! 8!#e it is not #ncommon to omit the o#tp#t p!r!meter3 62 yo#
!re #sing ! c#stom p!rser to h!nde inter2!cing, yo# c!n go !s 2!r !s*
EXTERN: int PASCAL SendMessage(
HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam
);
4hich is the MPE @&C &orth description o2 the Send7essage %P6 c!3
-tatic linking
6n !n em5edded system 4ith no oper!ting system, yo# 4i h!8e to do the 4or7 o2
in7ing !nd reoc!tion yo#rse23 )his reF#ires processing compier o5Ject 2ies !nd in7
m!ps3 6t c!n 5e done, 5#t is compier speci2ic !nd !4!ys tedio#s3 6t is ony
recommended i2 yo# c!n ony get ! i5r!ry !s !n #nin7ed o5Ject 2ie3 )he gener!
process is*
1) >e2ine the p!r!meter p!ssing !nd inter2!ce ro#tine !s !5o8e,
2) =or7 o#t ho4 to per2orm reoc!tion,
3) =or7 o#t ho4 to get to the proced#re n!mes !nd 2ind the 2#nction !ddresses,
,) >e2ine the &orth inter2!ce to e!ch 2#nction,
5) "ort o#t the st!rt #p reF#irements o2 the i5r!ry M this c!n 5e ! m!Jor p!in3
6) Com5ine the &orth !nd C 5in!ries3
)he 5iggest m!inten!nce iss#e here is th!t i2 yo# recei8e ! ne4 8ersion o2 the o5Ject
i5r!ry, yo# 4i h!8e to go thro#gh st!ges 3) to 5) ! o8er !g!in3 &!r !nd !4!y the
simpest !ppro!ch is #se the J#mp t!5e !ppro!ch 5eo43
Bump tables
)he 5!sis o2 this !ppro!ch is to pro8ide ! t!5e o2 2#nction !ddresses in the C mod#e
!nd in7 it !t ! 2i.ed !ddress3 )he &orth inter2!ce reF#ires the s!me X"ALL ro#tines !s
in the pre8io#s !ppro!ches3 &orth c!s the ree8!nt 2i.ed !ddress in the t!5e3 Ao
reoc!tion is reF#ired !s the C in7er h!s done this 2or yo#3 6n m!ny c!ses, c!ing !
105
Common extensions
d#mmy main 2#nction 2rom &orth !t po4er #p 4i !8oid most o2 the initi!is!tion
pro5ems3 Go# c!n !4!ys !dd e.picit initi!is!tion into main3
=h!t yo# ose 2rom this !ppro!ch is memory 5ec!#se yo# h!8e sep!r!ted !nd 2i.ed the
&orth !nd C 5in!ries3 Go# ose memory 2or the t!5e itse2 !nd yo# m!y ose ! 2e4 coc7
cyces more in per2orming the c!3 )o !8oid compier iss#es, yo# !re i7ey to h!8e to
4rite the 2#nction t!5e in !ssem5er3 Ho4e8er, simpicity !nd rei!5iity m!7e J#mp
t!5es the !ppro!ch o2 2irst choice 2or em5edded systems3
106
Em*edded S&stems
1$ 'mbedded -ystems
)he m!Jor di22erence 5et4een em5edded system progr!mming !nd progr!mming 2or !n
oper!ting system is th!t yo# h!8e to do e8erything yo#rse23 Go# h!8e to 5e !5e to
speci2y e.!ct memory oc!tions 2or B$M, &!sh, B%M !nd peripher!s3 Go# !re !so
i7ey to 5e tighty constr!ined 5y imited B%M !nd !n #nderpo4ered CP'3 Go# 4i
5ecome 8ery good !t re0re!ding !rge d!t!sheets !nd tre!ting their contents 4ith some
scepticism3
Code 2or em5edded systems is #s#!y cross0compied on ! PC !nd the 2in! code is
do4no!ded to the t!rget system3 &orth cross compiers 8!ry 4idey in c!p!5iities !nd
code gener!tion F#!ity3 Ho4e8er, the commerci! 8endors s#ppy cross compiers 2or !
8ery 4ide r!nge o2 CP's !nd h!rd4!re impement!tions3 &orth cross compiers !re !so
#sed 4hen porting hosted &orths 5et4een oper!ting systems, e3g3 2rom =indo4s to
Lin#.3 Cross compiers c!n #s#!y gener!te ! compete &orth interpreter !nd compier
on yo#r t!rget system, or c!n compie ! c#t0do4n system 4hich is inter!cti8ey
de5#gged o8er ! seri! ine or other ch!nne3 )hese 'm5iic! (or tethered) systems !re
disc#ssed !ter in this ch!pter3
Em5edded systems progr!mming is !n !re! in 4hich &orth scores 8ery 4e3 )he #se o2
inter!cti8e de5#gging directy on the t!rget permits 8ery r!pid de8eopment !nd
consider!5y red#ces the need 2or !ddition! (!nd e.pensi8e) toos s#ch !s 6n0Circ#it
Em#!tion (6CE)3 =e 5ro#ght #p ! !rge "trong%BM "%01110 system #sing ! K)%E
&!sh progr!mmer, !n oscioscope !nd ! sodering iron3 =ith more modern CP's th!t
incorpor!te ! 5oot o!der, the K)%E progr!mmer c!n 5e dispensed 4ith3
%p!rt 2rom controing ! m!ss spectrometer, this "trong%BM system h!s !n Ethernet
connection !nd r#ns ! 2# )CPI6P st!c7 !nd m#ti0thre!ded 4e5 ser8er 4ith CE6 !nd
%"P3 Em5edded &orth is not J#st 2or itte systems3
%tho#gh &orth cross compiers 8!ry 4idey, there is ! dr!2t %A" &orth cross compier
st!nd!rds propos! 5y Ei:!5eth B!ther 4hich h!s 5een !dopted 5y MicroProcessor
Engineering !nd &orth 6nc3 !nd some others3 )he propos! 4!s the res#t o2 5oth
comp!nies 4or7ing on p!rts o2 the s!me proJect3 )his ch!pter !ss#mes the #se o2 the
proposed st!nd!rd3 )his te.t is some4h!t in2orm!, so 2or de2initi8e de2initions cons#t
the P>& 2ies on the C>3
*efining and using memory
Em5edded systems reF#ire !t e!st three types o2 memoryS code in B$M or &!sh,
norm!y re!d0onyS B%M th!t is initi!ised !t po4er #p or resetS !nd B%M th!t is
#niniti!ised !t po4er #p or reset3 )hese three types !re 7no4n !s "DATA, IDATA, !nd
UDATA respecti8ey in %A" terminoogy3
HDATA \ --
"eect this type o2 memory !s the one to oper!te on ne.t3 )his 4i !22ect the
oper!tion o2 the 4ords isted 5eo43
F (comm!) ALI%N ALI%NED ALLOT "F HERE UNUSED
107
Em*edded S&stems
)he de2ining 4ord SE"TION ( sEarE e6d 5 cre!tes ! 4ord 7no4n ony to
the cross0compier (not to the t!rget code) th!t n!mes ! piece o2 memory3
HEX
8000 FFFF CDATA SECTION PROGRAM \ Program in Flash
0800 08FF IDATA SECTION IRAM \ Initialized RAM
0900 0BFF UDATA SECTION URAM \ Uninitialized RAM
0400 07FF UDATA SECTION EEPROM \ Uninitialised EEPROM
0000 01FF UDATA SECTION PERIPHS \ peripherals
DECIMAL
Most cross compiers !tt!ch the #sed portion o2 the IDATA im!ges to the end o2 !
"DATA section !nd the st!rt #p code 4i copy it into B%M3 UDATA sections 4i not 5e
modi2ied !t st!rt #p #ness yo# p!ce st!c7s !nd other d!t! there3
$ther 8endor0speci2ic 2#nctions !re !8!i!5e to s#pport p!gesI5!n7s o2 memory 2or
CP's s#ch !s the /"12 !nd B!55it -I16 5it CP's3
Be2erencing ! section n!me d#ring interpret!tion m!7es th!t section the c#rrent section
o2 th!t type !nd seects the type !s the c#rrent type3
DECIMAL
IRAM
42 value answer \ -- n ; from previous question
URAM
#100 buffer: databuff \ -- addr ; uninitialised
EEPROM
variable BaudRate \ -- addr ; holds baud rate
variable UPort \ -- addr ; holds UART port address
CDATA
Create Powers2 \ -- addr ; powers of two
$01 c, $02 c, $04 c, $08 c,
$10 c, $20 c, $40 c, $80 c,
)he e.!mpe !5o8e dec!res di22erent 8!ri!5es in speci2ic B%M sections, !nd ! d!t!
t!5e in the c#rrent "DATA section3 62 yo#r cross compier 2orces )ARIABLEs to 5e in
IDATA, try either o2 the 2oo4ing*
create BaudRate cell allot \ -- addr ; holds baud rate
cell buffer: BaudRate \ -- addr ; holds baud rate
"ar+ard targets
"ome CP's, not!5y -051, a- !nd m!ny >"Ps #se ! H!r8!rd !rchitect#re in 4hich code
!nd d!t! !re in sep!r!te !ddress sp!ces3 &or some o2 these !rchitect#res, e3g3 -051, code
sp!ce is not 4rit!5e 5y CP' instr#ctions3 &or these systems "DATA corresponds to the
code !ddress sp!ce, !nd IDATA !nd UDATA to the d!t! !ddress sp!ce3
Memory !ccess 4ords th!t !ccess code sp!ce !re #s#!y c!ed
3-3 4-3 -3 323 423 23 3ACXe3
108
Em*edded S&stems
Compiler and Interpreter e(tensions
&orth cross0compiers !o4 yo# to e.tend the compierIinterpreter itse2 5y controing
4here ne4 4ords !re p!ced3 %2ter cross0compi!tion is st!rted, ! ne4 4ords !re
p!ced 5y de2!#t into the t!rget im!ge3 )he 2oo4ing directi8es contro 4here ne4
4ords !re p!ced3
*irecti+e and
corresponding
+ocabulary
Action
TAR%ET
*TAR%ET
Ae4 4ords !re p!ced in the t!rget im!ge
Concept#! se!rch order* *TAR%ET
"OMPILER
*"OMPILER
Ae4 4ords !re !dded to the cross0compierLs compie time
5eh!8io#r3 )hese 4ords !ct i7e IMMEDIATE 4ords in
con8ention! &orth, 5#t !re not !8!i!5e d#ring
interpret!tion3 % memory !ccess 4ords re2er to the t!rget3
Concept#! se!rch order* *"OMPILER *HOST
INTERPRETER
*INTERPRETER
Ae4 4ords !re !dded to the cross0compierLs interpret time
5eh!8io#r3 )hese 4ords !re not !8!i!5e d#ring
compi!tion3 % memory !ccess 4ords re2er to the t!rget3
"ee the ne.t section on de2ining 4ords 2or det!is o2 the
!ctions 2or de2ining 4ords #sing "REATE 8 DOES' or
"REATE 8 ;"ODE.
Concept#! se!rch order* *INTERPRETER *HOST
ASSEMBLER
*ASSEMBLER
Ae4 4ords !re !dded to the cross0compierLs !ssem5er3
)his directi8e is #s#!y #sed to !dd m!cros to the
!ssem5er3 %so se!rches the INTERPRETER 4ords3
Concept#! se!rch order* *ASSEMBLER *INTERPRETER
*HOST
HOST
*HOST
E.poses the #nderying host portion o2 the cross0compier
so th!t #tiity 4ords c!n 5e !dded th!t 4i 5e #sed !ter 5y
4ords de2ined #sing "OMPILER INTERPRETER or
ASSEMBLER3 'se o2 this mode is !t yo#r o4n ris73 &inish
this mode 4ith TAR%ET3
Concept#! se!rch order* *HOST
Table 2) Cross Compiler search orders
10%
Em*edded S&stems
6t is ! con8enient concept#! mode to reg!rd these directi8es !s corresponding to
8oc!5#!ries c!ed *TAR%ET *"OMPILER *INTERPRETER *ASSEMBLER !nd
*HOST3 )he t!5e sho4s the concept#! se!rch order gener!ted 5y the directi8es3
*efining words
>e2ining 4ords c!n 5e h!nded in t4o 4!ys, in some c!ses !#tom!tic!y 5y the cross0
compier, or e.picity #sing the e.tension mech!nism disc#ssed !5o8e3 )he o5Jecti8es
5ehind the t4o mech!nisms !re di22erent3
)he !#tom!tic mech!nism !ims to 5e tr!nsp!rent, so th!t code 2or the cross0compier
c!n 5e the s!me !s th!t 2or ! hosted &orth3 )his enco#r!ges port!5iity !nd m!7es the
cross0compier e!sier to #se 2or the m!Jority o2 de2ining 4ords3 )he !#tom!tic
mech!nism copes 4ith the m!Jority o2 de2ining 4ords3
)he e.picit mech!nism pro8ides 8ery 2ine contro o2 the host !nd t!rget en8ironments,
5#t c!n 5e more con2#sing to #se3
$utomatic handling
MPEism2 )ote that not all cross compilers support automatic handling of defining
%ords. -he eamples here are %ritten for the M7, Forth ? cross compiler.
)he cross0compier 4i !#tom!tic!y 5#id !n !n!og#e o2 the de2ining 4ord in the
hostLs concept#! *INTERPRETER 8oc!5#!ry #p to the termin!ting ; DOES' or
;"ODE3 )his is triggered 5y the 4ord "REATE3 ConseF#enty, !ny code 5et4een the :
!nd the "REATE 4i not h!8e ! host !n!og#e3 )he 4ords 5et4een "REATE !nd the
termin!ting DOES' or ;"ODE m#st either 5e in the *INTERPRETER 8oc!5#!ry or
m#st 5e t!rget const!nts or 8!ri!5es, 4hich !o4s constr#ction o2 in7ed ists th!t re2er
to t!rget 8!ri!5es3
% t!rget 8ersion o2 the de2ining portion #p to DOES' or ;"ODE is 5#it i2 the t!rget
4ords h!s he!ds3
)he r#n0time portion o2 the code is !4!ys p!ced in the t!rget3
Constr#ction o2 the host !n!og#e is inhi5ited 5et4een the directi8es s#ch !s TAR%ET
ONL$ !nd HOSTYTAR%ET3
9oth the de2ining 4ords 5eo4 c!n 5e h!nded !#tom!tic!y 5y MPE cross0compiers
: CON \ n -- ; -- n ; a constant
CREATE
,
DOES>
@
;
VARIABLE LINKIT \ exists in target
: IN-CHAIN \ n -- ; -- n ; constants linked in a chain
CREATE
, \ lay down value
HERE LINKIT @ , LINKIT ! \ link to previous
DOES>
110
Em*edded S&stems
@
;
Explicit handling
E.picit h!nding #ses the compier directi8es disc#ssed in the pre8io#s section to
contro ho4 de2ining 4ords !re cre!ted3 )his is p!rtic#!ry #se2# 2or more compe.
4ords, !nd 4here no t!rget 8ersion o2 the de2ining 4ord is reF#ired, !s is o2ten the c!se
4hen !n 'm5iic! &orth t!rget is 5eing #sed3
)he e.!mpes 2rom the !#tom!tic h!nding section !re repe!ted here #sing the e.picit
mech!nism3 )he 4ords -(H5 !nd 2(H5 !re #sed 5ec!#se LIN*IT# is in the host3
INTERPRETER
: CON \ n -- ; -- n ; a constant
CREATE
,
DOES>
@
;
VARIABLE LINKIT \ exists in target
: IN-CHAIN \ n -- ; -- n ; constants linked in a chain
CREATE \ only in host
, \ lay down value
HERE LINKIT @ , LINKIT ! \ link to previous
DOES> \ run time in target
@
;
HOST
VARIABLE LINKIT2 \ exists in host
INTERPRETER
: IN-CHAIN2 \ n -- ; -- n ; link variable in host
CREATE \ in host
,
HERE LINKIT2 @(H) , LINKIT2 !(H)
DOES>
@
;
TARGET
%s c!n 5e see 2rom the e.!mpes !5o8e, the !#tom!tic h!nding mech!nism is simper,
5#t the e.picit h!nding mech!nism permits 2iner contro o8er 4here code is gener!ted,
4hich m!y 5e #se2# 4hen de2ining 4ords !re reF#ired !nd the !5so#te min#m#m o2
t!rget memory is to 5e #sed3
Compiler macros
)here !re o2ten occ!sions in 4hich short pieces o2 code !re repe!ted, 5#t sho#d re!y
5e compied inine to !o4 the code gener!tor to optimise them 2#rther or to !8oid !
111
Em*edded S&stems
c!Iret#rn per2orm!nce pen!ty3 )he 2oo4ing e.!mpe is #se2# 2or stepping thro#gh
!n !rr!y o2 integers3
: @++ \ addr -- addr+cell x
\ Fetch the contents of addr and increment addr.
dup @ swap cell + swap
;
: !++ \ addr x -- addr+cell
\ Store x at addr and increment addr.
over ! cell +
;
Go# c!n e.tend the compier to tre!t these !s m!cros !s 2oo4s*
compiler
: @++ \ addr -- addr+cell x
dup @ swap cell + swap
;
: !++ \ addr x -- addr+cell
over ! cell +
;
target
=hen the 2oo4ing code is compied, the m!cros 4i 5e e.p!nded, reg!rdess o2
4hether or not t!rget de2initions o2 -.. !nd 2.. !re!dy e.ist3
: CopyInts \ src dest #ints --
0 ?do \ -- src dest
swap @++ rot !++
loop
2drop
;
I./ ports
Memory m!pped 6I$ is h!nded #sing the norm! &orth memory oper!tors3 6n some
c!ses, peripher!s !re reset 5y re!ding ! register !nd disc!rding the res#t*
<address> @ drop
E.tremey !ggressi8e compiers, e3g3 the MPE 6-... !nd 3-6 @&C compiers, c!n
optimise s#ch phr!ses !4!y3 6n these c!ses, synonyms s#ch !s P- in p!ce o2 - (RPL 2or
Port) 4i 5e !8!i!5e th!t c!nnot 5e optimised !4!y3
=here code s#ch !s de8ice dri8ers is intended to 5e port!5e !cross di22erent h!rd4!re,
#se o2 port !ccess 4ords m!7es port!5iity m#ch e!sier 4hen code is mo8ed to ! CP'
4ith ! sep!r!te 6I$ sp!ce, e3g3 B!55it or 3-63 )he st!nd!rd port !ccess 4ords !re*
PC@ PW@ PL@ P@ PC! PW! PL! P!
112
Em*edded S&stems
)he CI=IL denote -I16I32 5it !ccess !nd P- !nd P2 denote ! n!ti8e ce3 &or memory
m!pped systems yo# c!n !4!ys !i!s these 4ords to !n e.isting 4ord #sing compier
m!cros3
% &orth cross compiers 4e h!8e come !cross (!t e!st 2or em5edded 4or7) pro8ide !
2!ciity to n!me ! n#m5er3 )his permits the n!mes o2 n#m5ers to 5e hed in the compier
4itho#t #sing !ny sp!ce in the t!rget e.cept 4hen #sed, in 4hich c!se they 4i tre!ted
J#st i7e the n#m5er they represent3 )hey !re eF#i8!ent to con8ention! !ssem5y
!ng#!ge eF#!tes !nd !re de2ined i7e "ONSTANTs3
<value> EQU <name>
Interrupt handlers
9ec!#se o2 the 4ide 8!riety o2 CP' !rchitect#re !nd peripher!s, it is in pr!ctice !most
impossi5e to pro8ide ! #ni8ers! 4ord set 2or interr#pt h!nders3 &or e.!mpe, 8ectored
interr#pt controers 2or %BMs come in !t e!st 2o#r 2orms3 Ho4e8er, the principes !re
essenti!y the s!me 2or ! CP's3
&or !ny interr#pt yo# m#st 2irst o2 ! decide 4hether to #se !n !ssem5er coded
interr#pt ser8ice ro#tine or ! high e8e &orth ro#tine3 High0e8e interr#pt ser8ice
ro#tines t!7e more instr#ctions (!nd CP' time) to set #p, 5#t !re 8ery con8enient to #se3
)he phr!ses o2 the 2orm*
[ TASKING? ]
in ! de2inition tempor!riy t#rn o22 the compier to interpret TAS*IN%( in the midde o2
the 4ord3 )he 2!g ret#rned is #sed the immedi!te 4ords <IF= <ELSE= !nd <THEN=
for conditional compilation.
Assembler interrupt
)he 2oo4ing e.!mpe is 2or !n M"P,30 r#nning !t 327H:3
variable rx0-char \ -- addr ; low byte holds KEY character
rx0-char 1+
equ rx0-avail \ high bye holds KEY? flag
proc Rx0-isr \ --
mov .b & u0rxbuf & rx0-char \ stash character
mov .b # -1 & rx0-avail \ flag character available
bic # _cpuoff 0 (sp) \ return with cpu active
reti
end-code
rx0-isr USART0rx_vec ! \ set vector
code init-ser \ --
or .b # $c0 & me1 \ enable USART0 tx and rx
or .b # $30 & u0tctl \ baud rate source is smclk
mov .b # $a1 & u0br0 \ 9600 baud
mov .b # $01 & u0br1
mov .b # $03 & u0mctl
mov .b # $30 & u0ctl \ 8N2, clear reset
or .b # $30 & p3sel \ P3.4,5 = USART0 TXD/RXD
113
Em*edded S&stems
or .b # $10 & p3dir \ P3.4 output dirction
mov # 0 & rx0-char \ no characters received yet
bis .b # $40 & ie1 \ enable UART 0 RX interrupt
bic .b # $80 & BCSCTL1 \ XT2 = HF XTAL
bis .b # $88 & BCSCTL2
eint \ global enable interrupts
ret
end-code
: key?0 \ -- flag ; true if USART0 received a character
rx0-avail c@ 0<>
;
: key0 \ -- char ; wait for character from USART0
begin
di rx0-avail c@ 0=
while
[ tasking? ] [if]
ei pause \ schedule
[else]
\ cpu to sleep, GIE set
[asm bis # _cpuoff _gie + sr asm]
[then]
repeat
rx0-char c@ 0 rx0-avail c!
ei
;
: emit0 \ char -- ; send character through USART0
begin u0tctl c@ 1 and until \ wait for empty buffer
u0txbuf c! \ write buffer
;
: type0 \ c-addr len --
bounds
?do i c@ emit0 loop
;
: cr0 \ --
$0D emit0 $0A emit0
;
"igh le+el interrupts
)he 2oo4ing code is t!7en 2rom the seri! dri8er 2or !n %n!og#e >e8ices %d#C7020
seri! dri8er3
: >RxQ \ char queue --
\ *G Put character from UART into queue.
dup (cqFull?) \ if queue full
if 2drop exit endif \ discard character
(>cqueue) \ queue character
;
: FIFO>RxQ \ base queue --
114
Em*edded S&stems
\ *G Given a UART base address and a character queue,
\ ** empty the UART FIFO into the queue.
begin
over ComSta0 + @ $01 and
while
over ComRx + @ $FF and over >RxQ
repeat
2drop
;
: ser-isr \ --
\ *G UART0 high level ISR.
_INTCON IrQSta + @ SerialBit and if
case _UART dup ComIId0 + @ 7 and
0 of ComSta1 + @ drop endof \ MSR for UART
2 of endof \ Tx interrupt
4 of SerInpQ FIFO>RxQ endof \ read characters
6 of ComSta0 + @ drop endof \ Line Status interrupt
nip
endcase
endif
;
' ser-isr add-irq
: seremit \ char --
\ *G Transmit a character on UART.
_UART
begin
dup ComSta0 + @ %00100000 and
until
ComTx + !
;
: serkey? \ -- t/f
\ *G Return true if the UART has a character available.
SerInpQ cqnotempty?
;
: serkey \ -- char
\ Wait for a character on the UART and return it.
SerInpQ cqueue>
;
: serTYPE \ c-addr len --
\ *G Type a string to the UART.
bounds
?do i c@ seremit loop
;
: serCR \ --
\ *G Issue a CR/LF pair to the UART.
$0D seremit $0A seremit
;
115
Em*edded S&stems
Interlocks
)he M"P,30 e.!mpe i#str!tes ho4 to !8oid ! common so#rce o2 error 4hen
progr!mming code th!t r#ns in the m!in code !nd e.tr!cts in2orm!tion 2rom d!t! stored
5y !n interr#pt h!nder3 62 yo# do not carefully contro the interr#pts, the interr#pt
h!nder m!y modi2y d!t! 4hie the m!in code !ss#mes th!t it is st!5e3 )he M"P,30
e.!mpe is repe!ted 5eo43
: key0 \ -- char ; wait for character from USART0
begin
di rx0-avail c@ 0=
while
[ tasking? ] [if]
ei pause \ schedule
[else]
\ cpu to sleep, GIE set, in assembler
[asm bis # _cpuoff gie + sr asm]
[then]
repeat
rx0-char c@ 0 rx0-avail c!
ei
;
)he 2oo4ing code is 2or the 2o#r 4ords #sed to contro interr#pts3 )he 4ords DI !nd
EI !re simpe go5! interr#pt en!5es !nd dis!5es3 )he 4ords <I !nd I= de2ine !
section in 4hich interr#pt st!t#s is preser8ed to !nd restored 2rom the ret#rn st!c73
6nside the section interr#pts !re dis!5ed3 )hese 2o#r 4ords !re present in ! MPE
systems3 EF#i8!ents 4i e.ist in systems 2rom other 8endors3 9ec!#se these 4ords !re
CP' !nd impement!tion dependent, they m#st 5e 4ritten in !ssem5er3 6n some
systems, optimised 8ersions m!y 5e !8!i!5e in the code gener!tor3
code ei \ -- ; enable interrupts
\ *G Global enable interrupts.
eint ret
end-code
code di \ -- ; disable interrupts
\ *G Global disable interrupts.
dint ret
end-code
code [I \ R: -- x
\ *G Preserve status on return stack, disable interrupts.
\ ** The state is restored by I].
pop r14
push sr
dint
br r14
end-code
code I] \ R: x -- ; restore I status from r. stack
\ *G Restore status saved by [I from the return stack.
pop r14
pop sr
br r14
end-code
116
Em*edded S&stems
5mbilical -ystems
% con8ention! &orth system inc#des its o4n te.t compier !nd interpreter3 6n sm!er
em5edded systems, there is not eno#gh &!sh or B%M 2or this, or che!per chips c!n 5e
#sed i2 ess &!sh !nd B%M is reF#ired3 6n !ddition, ! PC c!n compie m#ch 2!ster th!n
!n -0513 )o !8oid osing the inter!cti8ity th!t m!7es &orth so !ttr!cti8e, the st!nd!one
compierIinterpreter on the t!rget is rep!ced 5y ! mess!ge p!sser 4hich e.ec#tes
comm!nds (4ords) !s instr#cted 5y the host PC3
Ao4 ! the inter!ction is pro8ided 5y the cross0compier r#nning on the PC3 )he cross
compier c!n t!7e !d8!nt!ge o2 its o4n code gener!tor !nd integr!ted !ssem5er !nd
dis!ssem5er3 )his !rr!ngement is c!ed !n umbilical or tethered system3 6n pr!ctice,
the ony dis!d8!nt!ge o2 these is th!t de5#gging !nd m!inten!nce oper!tions reF#ire
e.!cty the s!me so#rce code !s gener!ted the code in the t!rget3 )his is !s it is d#ring
de8eopment, 5#t m!y c!#se pro5ems 2or m!inten!nce3 %nother dis!d8!nt!ge is th!t the
&orth interpreterIcompier c!nnot 5e #sed 2or prod#ction test !nd con2ig#r!tion3
'sing !n 'm5iic! &orth, it is F#ite possi5e to r#n t4o or more t!s7s on !n -051 singe
chip de8ice #sing ony the 256 5ytes o2 intern! B%M3
117
Em*edded S&stems
Pro5!5y the sm!est CP' 4e h!8e #sed this techniF#e on 4!s ! ,05it CP' 2rom the
Hit!chi HMC",00 r!nge3
)he in7 5et4een the host !nd t!rget is o2ten c!ed the C)L 2or cross t!rget in73 6t is
norm!y ! seri! ine3 "ome cross compiers c!n 5e e.tended 5y the #ser 4ith ne4
dri8ers3 =e h!8e #sed other in7s s#ch !s 62C, "P6, 9>M !nd ! K)%E inter2!ce3
*ebugging 'mbedded -ystems
)he essenti! de5#gging toos 2or em5edded systems !re t4o LE>s (pre2er!5y di22erent
coo#rs) dri8en 5y sp!re 6I$ ines3 )hese pins sho#d !so 5e !ccessi5e 5y oscioscope
pro5es3 Go# c!n pro5!5y de5#g !nything #sing t4o LE>s !nd !n oscioscope, 5#t it is
cert!iny not the e!siest 4!y to do things3
62 yo# c!nOt t!7 to it, yo# c!nOt de5#g it3 )he commonest !nd e!siest 4!y to t!7 to !n
em5edded system is o8er !n B"232 in73 >espite their dis!ppe!r!nce 2rom des7top PCs,
re! B"232 in7s !re sti the domin!nt 4!y to t!7 to em5edded systems3 62 yo#r
h!rd4!re does not h!8e one, consider em#!ting ! seri! ine #sing 62C or "P63 E8en !
118
Figure #) 5mbilical Forth
model
)ar!et *ource coe
Cro** com,iler . Sym/ol ta/le
)ar!et emulator
Me**a!e ,a**in! *y*tem 0#o*t1
Me**a!e ,a**in! *y*tem 0tar!et1
)ar!et e2ecuta/le coe
Em*edded S&stems
p!ir o2 6I$ ines c!n 5e progr!mmed to 5eh!8e i7e ! seri! port M itOs !n interesting
progr!mming e.ercise in itse23
Ao4 th!t 4e c!n t!7 to o#r h!rd4!re, 4e need to choose ho4 to t!7 to it3 6de!y, 4e
h!8e ! &orth on the t!rget h!rd4!re !nd 4e t!7 to th!t3 =e h!8e to design o#r
!ppic!tion so th!t it can 5e de5#gged3 62 there is eno#gh B%M, r#n the &orth interpreter
!s ! t!s7 so th!t it is !4!ys !ccessi5e3 62 yo# !re #sing !n 'm5iic! &orth, set it #p so
th!t the in7 r#ns in its o4n t!s73 )his 4!y 4e c!n #se the in7 !s ! norm! &orth
interpreter3
=hen 4e c!n #se ! &orth interpreter, 4e !re 2reed 2rom h!8ing to insert de5#g code,
recompie, reprogr!m the &!sh !nd 4!tch3 =e c!n #se the &orth interpreter to e.pore
o5ser8!tions o2 the 2!#t !nd the hypotheses 4e m!de 2rom the o5ser8!tions3 6n
com5in!tion 4ith o#r t4o LE>s !nd the oscioscope 4e c!n stim#!te h!rd4!re !nd
m!7e me!s#rements3
M!7e s#re th!t yo# #nderst!nd the ;Ho4 to >e5#g< section in Ch!pter 13
2asic rules
=ix bugs first3 )he more 5#gs yo# h!8e in ! system, the more di22ic#t it is to 2ind !ny
o2 them3 % 5#g is o2ten e2t in 5ec!#se the origin! !#thor co#d not 2ind it3 Ge!rs !ter it
4i m!7e yo#r i2e intoer!5e 5y m!s7ing the o5ser8!tion o2 yo#r 5#g3 9#gs h!8e !
h!5it o2 coecting in !ssoci!ted gro#ps, o2ten m!s7ed 5y the 7#ges yo# p#t in to get
!ro#nd them3
&rash early and crash often3 6t is ! 5ig tempt!tion to #se ! ot o2 de2ensi8e
progr!mming to cope 4ith e!rier progr!mming mist!7es3 6nside !n oper!ting system,
coping 4ith 5!d progr!mmers is pro5!5y ! m#st3 6n !n em5edded system, it J#st m!7es
5#gs h!rder to 2ind3 62 yo#r system 2!#ts 5ec!#se it 4rites to !ddress 0, yo# 4i h!8e to
2ind the 5#g r!ther th!n e!8e it !one3
-he primary duty of an eception handler is to get the error out of the lap of the
programmer and into the surprised face of the user. 7rovided you keep this cardinal
rule in mind, you can=t go far %rong. Derity (to#
=hen the ;s#rprised 2!ce o2 the #ser< is p!rt o2 ! 5om5 dispos! m!chine or !n
!n!esthetic 8enti!tor yo# h!8e ! di22erent c!ss o2 responsi5iity3 6n t#rn, yo# c!n do !
gre!t de! to m!7e i2e e!sier 2or yo#rse23
:ake faults +isible
Go# h!8e c!re2#y 4ritten !n e.ception h!nder so th!t it d#mps ! the CP' registers
!nd the st!c7s3 Go# h!8e e8en tested this !t the consoe3 >id yo# chec7 th!t the o#tp#t
sti comes o#t on the consoe 4hen ! cr!sh occ#rs in t!s7 #sing !nother seri! ineD >id
yo# m!7e s#re th!t interr#pt dri8en seri! dri8ers get re0en!5ed inside !n e.ception
h!nderD =o#d it 5e s!2er to s4itch the consoe dri8er to poed inside !n e.ception
h!nderD >o yo# need to ch!nge the 4!tchdog periodD
Bemem5er those LE>sD Ao4 is pro5!5y ! good time to t#rn on the red one3 M!y5e
e8en 2!sh it ! 2e4 times !nd 4!it ! 5it 5e2ore reco8ering the system3
11%
Em*edded S&stems
Check tasks
"ome o2 o#r coe!g#es do not test their code !s 4e !s 4e 4o#d i7e3 $ne res#t is th!t
4e sometimes see st!c7 2!#ts in t!s7s3 %2ter the 2!#t h!s occ#rred ! system0dependent
n#m5er o2 times, the st!c7 o8er2o4s !nd the system cr!shes3 )he cr!sh occ#rs some
indetermin!te time !2ter the 5#g 2irst occ#rred3 =e sho#d m!7e it 8isi5e !s soon !s
possi5e3
62 4e #se ! simpe ho#se r#e, 4e c!n system!tic!y protect ! o#r t!s7s3 )he ho#se r#e
is th!t there is nothing on the st!c7 !t the he!d o2 ! t!s7Os m!in oop3 )he e.!mpe 5eo4
is t!7en 2rom '"9 m!ss stor!ge code3 =e co#d !so consider #sing one o2 o#r LE>s to
chec7 !cti8ity3
: doSectorRW \ --
consoleIO decimal
ResetUSBdisk
begin
?StackEmpty \ *** check stack
WaitSecCmd 0 -> DriveComplete
case DriveBusy?
SecReadCmd of Disk>USB endof
SecWriteCmd of USB>Disk endof
SenseInvalidOp -> SenseCode
DrvBadCmd -> DriveStatus
endcase
WaitDrvComplete
again
;
)he 4ord (SEa3ZEALEB simpy chec7s the st!c7 depth !nd iss#es di!gnostic
mess!ges to the consoe3 )he MPE 8ersion is 5eo4 !nd is 8ery speci2ic to MPE 7ernes3
Ho4e8er, there 4i 5e ! 4!y to do the s!me 2or other em5edded &orth systems3
: ?StackEmpty \ --
\ *G If the stack depth is non-zero, issue a console
\ ** warning message and clear the stack. This is often
\ ** used at the end of a task loop.
depth 0= if exit endif
opvec @ >r ipvec @ >r ConsoleIO
cr ." *** Stack fault: depth = " depth .decimal ." (d) "
." in task " self .task
s0 @ sp!
cr ." Stack cleared."
r> ipvec ! r> opvec !
;
120
Em*edded S&stems
0eco+er well
%2ter yo# h!8e t!7en s#it!5e !ction 2!st eno#gh not to compromise s!2ety, yo# m#st
reco8er 2rom the dis!ster3 Beco8ery in m!ny systems c!n 5e !s simpe !s re5ooting, 5#t
m!y in8o8e m#ch more or m#ch ess, especi!y i2 there !re s!2ety impic!tions3
Be5ooting most microcontroers is !chie8ed 5y setting #p the 4!tchdog to per2orm !
h!rd reset3 $h 4hoops, the h!rd4!re reset ine is inp#t ony !nd is not connected to the
Ethernet PHG3
Eood reco8ery is o2ten not !s simpe !s it oo7s3
Talk to the hardware people
Go# c!nnot h!8e the coo#red LE>s #ness the h!rd4!re peope 7no4 yo# need them3
)his is 2ine 4hen yo# !re the h!rd4!re peope too, 5#t not so 2ine 4hen yo# re!y need
th!t B"232 ine !nd yo# donOt h!8e ! sodering iron on site3 =h!t, yo# do not t!7e !
sodering iron !nd !n oscioscope 4ith yo# e8ery4hereD
)o t!7 to dedic!ted h!rd4!re peope, yo# m#st 7no4 eno#gh h!rd4!re design to re!d
circ#it di!gr!ms3 )his pro5!5y m!7es yo# d!ngero#s in their eyes3
=h!t yo# !re trying to !chie8e is h!rd4!re th!t c!n itse2 5e de5#gged, !nd cont!ins
2!ciities so th!t yo# c!n de5#g yo#r o4n code3
2lock I./
&orth h!ndes 2ies on !ny gi8en comp#ter in m#ch the s!me 4!y !s !ny other !ng#!ge
r#nning on th!t comp#ter3 )he 4ords #sed to open !nd cose 2ies !re disc#ssed
ese4here3 Ho4e8er, &orth !so h!s ! system c!ed Q5oc7sO3
%tho#gh 5oc7s !re no onger o2ten #sed 5y &orths hosted on modern oper!ting
systems, 5oc7s c!n 5e 8ery #se2# on em5edded systems 2or d!t! ogging, especi!y in
! 16 5it &orth3 9oc7s c!n 5e impemented in p!ged or ine!r memory, seri! EEPB$M
or d!t! &!sh, o8er ! seri! ine or net4or7 to ! host, or ! physic! disc3
121
Em*edded S&stems
9oc7s !re #nits o2 memory o!ded 2rom !nd s!8ed to 4h!t is notion!y m!ss stor!ge3
)he d!t! si:e o2 ! 5oc7 is norm!y 102, 5ytes (1()3 )he system c!n 4or7 4ith ony
one 5oc7 5#22er, 5#t t4o or more !re 5etter3 9oc7s !re !ccessed 5y ! n#m5er 033#3
)he !ddresses %0 to %n c!n 5e o5t!ined 5y entering*
0 block .
1 block .
etc.
)hese e!ch ret#rn the !ddress o2 the 2irst 5yte in their respecti8e 5#22ers3 9oc7 5#22ers
!ct !s ! memory c!che 5et4een the m!ss stor!ge !nd the &orth system3 >i22erent &orth
systems #se 8!rio#s str!tegies 2or !oc!ting !nd re#sing 5#22ers3 )he most common !re
ro#nd ro5in !nd e!st recenty #sed (LB')3
62 yo#r d!t! c!n 5e ne!ty p!rtitioned into 175 #nits, 5oc7s c!n pro8ide e.tremey good
per2orm!nce3 9oc7s c!n 5e impemented in ! 2iing system or c!n simpy 5e tre!ted !s
r!4 sectors on ! disc3 E8en !5o8e ! 2iing system, 5oc7s c!n gi8e ! s#rprising
per2orm!nce impro8ement !t the e.pense o2 ! itte m!n!gement code3
BLO"* \ u -- a-addr
Lo!d the #th 5oc7 o2 1( 2rom m!ss stor!ge into ! 5#22er, !nd ret#rn the !ddress
o2 the 5#22er3
122
Figure $) 2lock buffers
Em*edded S&stems
BUFFER \ u -- a-addr
Beser8e ! d!t! 5#22er, !nd ret#rn the !ddress o2 the 5#22er3 )he contents o2 the
5#22er !re #nde2ined3 62 yo# 4rite this 5#22er 5!c7 to m!ss stor!ge, the pre8io#s
contents in stor!ge 4i 5e ost3
)he 5oc7 d!t! c!n no4 5e #sed !nd modi2ied3 =hen the d!t! h!s 5een modi2ied, yo#
m#st m!r7 the 5oc7 !s modi2ied #sing UPDATE3
UPDATE \ --
M!r7 the c#rrent 5#22er !s modi2ied3 62 the c#rrent 5#22er h!s to 5e re#sed 2or
!nother 5oc7, the contents 4i 5e 4ritten o#t 5e2ore re#se3
)he system 7no4s th!t !n #pd!te h!s occ#rred 5ec!#se !n #pd!te 2!g is set3 UPDATE
does not !ct#!y s!8e the 5oc7 to disc, 5#t tes the system th!t it o#ght to 5e 4ritten
ne.t time the 5#22er is re!oc!ted, i3e3 ne.t time ! 5oc7 is 4ritten to th!t 5#22er3
6n most systems, ony one 5#22er 4i 5e 4ritten to disc e!ch time !nd so ! disc or 2ie
4i ne8er 5e cosed ne!ty3 Ho4e8er, there !re three 4ords to do the Jo5 nicey3
FLUSH --
)his 4i s!8e !ny UPDATEd 5#22ers to disc !nd #n!ssign ! the 5#22ers3 )his
me!ns th!t the ne.t time ! 5oc7 is o!ded into ! 5#22er, the comp#ter t!7es the
5#22er !s 5eing empty3 &#sh is m!de #p o2 the 4ords SA)EBUFFERS !nd
EMPT$BUFFERS3
SA)EBUFFERS --
)his 4i 4rite to !ny disc !ny 5#22ers m!r7ed !s UPDATEd, 5#t 4i not #n!ssign
them3 62 the 5oc7 is !ccessed !g!in it 4i not 5e o!ded into memory, 5ec!#se
the comp#ter 4i sti thin7 the 5oc7 is there !nd in 2!ct it 4i 5e3
EMPT$BUFFERS
)his 4ord !ct#!y #n!ssigned the 5#22ers, !nd !2ter this 4ord h!s 5een e.ec#ted,
!ny re2erence to ! 5oc7 4i c!#se the 5oc7 to 5e o!ded into memory 2irst3
-ource in blocks
9e2ore E'6 oper!ting systems !nd che!p PCs, m!ny &orth systems 7ept so#rce code in
5oc7s3 )he so#rce code 4!s disp!yed on0screen !s 16 ro4s o2 6, co#mn ines,
m!tching the 102, 5yte stor!ge3
123
Em*edded S&stems
)he #se o2 5oc7s 2or so#rce code is r!re in modern systems e.cept 2or em5edded
systems 4hich reF#ire oc! con2ig#r!tion !nd editing 4itho#t the presence o2 ! PC3 9y
ch!nging the de2!#t 5oc7 si:e, some ingen#ity 4ith 7eys, !nd 2!mii!rity 4ith mo5ie
phone te.t mess!ging, it is per2ecty possi5e to edit so#rce code #sing ! he.!decim!
7eyp!d !nd ! , 5y 16 ch!r!cter LC> disp!y3 >esper!te pro5ems e!d to desper!te
so#tions3
124
Figure &) -ource in blocks
Forth Internals
1& Forth Internals
Anatomy of a Forth system
% &orth system consists o2 the 2oo4ing*
>iction!ry in 4hich to store the de2initions o2 4ords
P!r!meter st!c7 to p!ss in2orm!tion to !nd 2rom 4ords
Bet#rn st!c7 to hod ret#rn !ddresses
6np#t !nd o#tp#t 5#22ers
'ser 8!ri!5es
% minim#m system 4i occ#py !ro#nd -( 5ytes (,( ces)3 )he m!.im#m !ddress!5e
memory si:e on ! 16 5it &orth system is 6,75 !nd on ! 32 5it &orth is ,E53 % typic!
memory m!p on ! con8ention! CP' is sho4n 5eo4*
125
Figure ,) Typical Forth memory
model
Forth Internals
)he pict#re 5eo4 indic!tes ! con8ention! !yo#t o2 ! &orth 4ord3
)he 4ord descri5ed is*
: 2^2 \ n -- n*n
dup *
;
)here is gre!t 8!riety in diction!ry impement!tion schemes3 6n gener!, the in7 !nd
n!me 2ieds (the diction!ry he!der) !re together, !nd the code n!me !nd p!r!meter 2ieds
(the code 5ody) 2oo43 Ho4e8er, some systems 7eep the he!ders in ! sep!r!te d!t!5!se,
!nd in systems s#ch !s 'm5iic! &orths (see the em5edded systems ch!pter) the he!der
!nd the code 5ody m!y e8en 5e on sep!r!te CP's3
5in6 field* C !nd G in the 2ig#re !5o8e3 &orth 4ord n!mes !re ch!ined in ! in7ed ist
str#ct#re, !nchored in ! 4ordist3 )he in7ing schemes r!nge 2rom singe in7ed ists on
em5edded systems to 2#y h!shed schemes #nder oper!ting systems3
1ame field* 6nc#des the te.t o2 the 4ordLs n!me (o2ten preceeded 5y the co#nt), !nd
some other in2orm!tion controing 8isi5iity o2 the 4ord3
126
Figure ) *ictionary entry
Forth Internals
&ode name field* %, 9 !nd C in the 2ig#re !5o8e3 )he 2ied cont!ins compier0speci2ic
in2orm!tion gener!ted 5y the compier3 6n thre!ded code systems, this 4i cont!in !
pointer or code3 6n modern systems, the 2ied m!y not present !t ! 2or coon de2initions,
5#t 4i 5e present 2or chidren o2 "REATE3
Parameter field* =ords 5#it 5y "REATE cont!in d!t!3 )he p!r!meter 2ied !ddress,
sometimes 7no4n !s the P&%, is the st!rt !ddress o2 this d!t! !re!3 Coon de2initions do
not h!8e p!r!meter 2ieds !nd this region #s#!y J#st cont!ins compied code3
;a+igating the dictionary structure
9ec!#se o2 the 8!riety o2 impement!tion techniF#es, !nd 5ec!#se the %A" &orth
st!nd!rd c!re2#y !8oids impying !ny #nderying impement!tion techniF#es,
diction!ry n!8ig!tion is not st!nd!rdised3 Ho4e8er, m!ny systems pro8ide ! r!nge o2
4ords 2or stepping 2rom one 2ied to !nother 2or #se 4ithin their o4n toos3 Go# 4i
h!8e to re!d the m!n#! 2or the &orth yo# #se to 2ind o#t 4h!t is !8!i!5e3 Commony
!8!i!5e 4ords !re sho4n here3 )hey mosty !ss#me th!t the .t o2 the 4ord is the
st!rting point since this is the !ddress ret#rned 5y FIND !nd SEAR"HWORDLIST3
'BOD$ xt -- pfa
"tep 2rom the .t to the P&%3 6n %A" systems this oper!tion is ony speci2ied 2or
chidren o2 "REATE3
BOD$' pfa -- xt
"tep 2rom the P&% to the .t3
'NAME xt -- name
"tep 2rom the .t to the n!me 2ied3
NAME' name -- xt
"tep 2rom the n!me 2ied to the .t3
-tructure of compiled code
)his section de!s 4ith compiing code on con8ention! CP's3 >edic!ted t4o0st!c7
m!chines !re co8ered in the ne.t section3 )he code e.!mpes !re 2or coon de2initions
on the 6nte 6%32 instr#ction set #sed 2rom the -03-6 #p4!rds3 )his 4!s chosen 2or its
4ide 2!mii!rity, not 2or !ny endorsement o2 the !rchitect#re3 )he choice o2 compied
code str#ct#re depends on the reF#ired tr!de o22 5et4een code si:e, per2orm!nce !nd
compe.ity3 )he impement!tions !re descri5ed in the order o2 2!stest 2irst3
&orth reg3 &#nction
6P 6nstr#ctionI6nterpret!tion Pointer
B"P Bet#rn "t!c7 Pointer
P"P >!t!(P!r!meter) "t!c7 Pointer
Table !) ?eneric Forth registers
127
Forth Internals
;ati+e Code Compilation C;CCD
)his is the term #s#!y gi8en to systems th!t gener!te optimised m!chine code3 )he
code F#!ity o2 the 5est o2 these is !s good !s th!t prod#ced 5y compiers 2or other
!ng#!ges s#ch !s CIC++3 ACC systems h!8e m#ch in common 4ith the ")C systems
5eo43 )ests sho4 th!t code si:e need 5e no gre!ter th!n 2or >)C systems 5eo4,
!tho#gh the compe.ity o2 the code gener!tor is 8ery m#ch higher3 ACC is c#rrenty
(2005) the impement!tion o2 choice 2or most 16 !nd 32 5it CP's3
&orth reg3 CP' reg3
6P E6P (PC)
B"P E"P
P"P E9P
Table #) ;ati+e code register usage
&alling a word
CALL address
Entry>exit code
RET
-ubroutine Threaded Code C-TCD
)hese systems #se the CP' c! !nd ret#rn system3 )hey !re typic!y o8er t4ice !s 2!st
!s the >)C systems 5eo43 "ome 8ersions gener!te short code seF#ences 2or simpe
4ords to !8oid c!Iret#rn o8erhe!d, 5#t do not do eno#gh to 5e c!ssi2ied !s ACC
systems3
&orth reg3 CP' reg3
6P PC
B"P E"P
P"P E9P
Table $) -ubroutine Threaded Code register usage
&alling a word
CALL address
Entry>exit code
RET
128
Forth Internals
Aote th!t on B6"C CP's s#ch !s %BM !nd M6P", the ret#rn !ddress m!y 5e p!ced 5y
the 9L instr#ction in ! register !nd then ! 2#rther s!8e o2 the ret#rn !ddress m!y 5e
reF#ired in the entry code3
*irect Threaded Code C*TCD
% short m!chine code seF#ence is 2oo4ed 5y d!t! or ! ist o2 4ord !ddresses 2or coon
de2initions3 )he 4ord !ddresses point to the m!chine code seF#ence 2or the 4ord3 Coded
4ords end 5y J#mping to or inining the next seF#ence 5eo43
&orth reg3 CP' reg3
6P E"6
B"P E9P
P"P E"P
Table &) *irect Threaded Code register usage
&alling a word
address
Entry>exit code
JMP docolon | exit
docolon:
SUB EBP, 4
MOV 0 [EBP], ESI
next:
MOV EAX, 0 [ESI]
ADD ESI, 4
JMP EAX
exit:
MOV ESI, 0 [EBP]
ADD EBP, 4
JMP next
Indirect Threaded Code CITCD
)he st!rt o2 ! coon de2inition cont!ins the !ddress o2 the docoon code ro#tine3 6t is
2oo4ed 5y ! ist o2 !ddresses 2inishing 4ith the !ddress o2 the e.it ro#tine, 4hich is
coded3
12%
Forth Internals
&orth reg3 CP' reg3
6P E"6
= E9C M =or7 register #sed 5y some system code
B"P E9P
P"P E"P
Table ,) Indirect Threaded Code register usage
&alling a word
address
Entry>exit code
docolon | exit
docolon:
DD cocoloncode
docoloncode
SUB EBP, 4
MOV 0 [EBP], ESI
next:
MOV EBX, 0 [ESI]
ADD ESI, 4
MOV EAX, 0 [EBX]
JMP EAX
exit:
MOV ESI, 0 [EBP]
ADD EBP, 4
JMP next
Token Threaded Code CTTCD
)o7en thre!ded code is #sed 4hen code density is the o8erriding reF#irement3 ))C
systems #se to7en n#m5ers to represent &orth 4ords 5y sm! integers3 $2ten the most
common 4ords !re coded !s - 5it to7ens, !nd 16 5it to7ens !re #sed 2or other 4ords3
)o7en )hre!ded Code h!s 5een #sed on p!yment termin!s to pro8ide 5in!ry code
port!5iity o2 5!n7ing !ppic!tions !cross termin!s 2rom m!ny di22erent s#ppiers3 6t h!s
!so 5een #sed to red#ce the code si:e o2 g!mes in ! mo5ie phone3
9ec!#se o2 the 4ide 8!riety o2 impement!tion techniF#es on the s!me CP' (some ))C
systems !re 4ritten in C), no s!mpe impement!tion is gi8en3 ))C is 2!r !nd !4!y the
so4est techniF#e sho4n, 5#t 2or !ppic!tions 4hich spend the m!Jority o2 their time in
core 4ords or oper!ting system c!s, !ppic!tion per2orm!nce m!y 5e consider!5y
5etter th!n e.pected3
130
Forth Internals
/ther forms
$ther 2orms th!t h!8e 5een seen inc#de segment thre!ded code 2or -0.-6 re!0mode
!ppic!tions3 )he ingen#ity o2 impementers in e.poring the speedIsi:e tr!de0o22 is
impressi8e3
)he $pen &irm4!re system #sed 5y "#n Microsystems, 69M !nd %ppe to initi!ise
h!rd4!re !nd 5oot the oper!ting system #ses to7enised &orth source code 4hich is
compied !t po4er0#p3
Forth engines and stack machines
Commerci!y, microprocessors designed 2or ! speci2ic progr!mming !ng#!ge h!8e not
5een s#ccess2#3 CP's designed 2or e22icient e.ec#tion o2 P!sc!, L6"P, C, &orth !nd
$cc!m h!8e ! 5een prod#ced !s singe chip microprocessors3 'tim!tey, none h!8e
5een ! s#ccess in the ong term3 )he e.ception in this ist m!y 5e the )r!nsp#ter, 4hich
4!s origin!y designed to s#pport 5oth $cc!m !nd p!r!e processing3 $nce !n
e22icient C compier 2or the )r!nsp#ter 4!s !8!i!5e, it 5ec!me ! mid commerci!
s#ccess3
"t!c7 m!chines h!8e ret#rned to c#rrent compier !nd siicon design thro#gh e.ec#tion
o2 the K!8! @irt#! M!chine (K@M)3 %dd to this the re!is!tion th!t the 2!shions in
c#rrent !ng#!ge seection !re shorter th!n the commerci! i2etimes o2 CP'
!rchitect#res3 )he c#rrent 2oc#s in st!c7 m!chine design inc#des c!re2# design to
s#pport e22icient e.ec#tion o2 !ng#!ges other th!n &orth3
%tho#gh h!rd4!re s#pport 2or preser8ing ret#rn !ddresses on ! st!c7 h!s 5een common
since the 1/60s, s#pport 2or t4o or more st!c7s h!s 5een ess common3 =hen #sing !
d!t! st!c7 tr!nsient d!t! is ordered on the st!c7 r!ther th!n in ! register 2ie, so one
2e!t#re th!t disting#ishes CP's designed to s#pport t4o st!c7s is ! 8ery imited n#m5er
o2 registers th!t h!8e to 5e s!8ed 4hen per2orming ! conte.t s4itch3 )h#s interr#pt
response is 8ery good3 "#ch CP's !re #s#!y designed to 5e deterministic, i3e3 the time
t!7en 2or e.ec#tion o2 !n instr#ction seF#ence is competey predict!5e !nd st!5e3 )he
B)C2000 r#nning !t 10 MH: instr#ction r!te h!s ! ,00ns interr#pt response time 5e2ore
#se2# 4or7 c!n 5e per2ormed3 $ne o2 o#r cients #sed it 2or 8ideo d!t! !cF#isition #sing
! 1 MH: interr#pt r!te3 %nother #sed it !s ! timing gener!tor 2or medic! im!ging
systems3
6t is interesting to note th!t despite the enormo#s impro8ement in str!ight0ine
per2orm!nce o2 CP's o8er the !st 10015 ye!rs, there h!s 5een 8ery itte i2 !ny
impro8ement in interr#pt response times3 )his is disc#ssed in more det!i in ! 2oo4ing
section3
>eterministic e.ec#tion r#es o#t c!ching !nd pipeining 5eyond the 2etchIe.ec#te e8e3
9ec!#se o2 the o4 n#m5er o2 intern! registers !nd the #se o2 :ero oper!nd instr#ctions
red#cing instr#ction decode compe.ity, st!c7 m!chines tend to 5e 8ery simpe (o4
g!te co#nt, siicon !re!) 5y comp!rison 4ith c#rrent B6"C !nd C6"C !rchitect#res3 6n
t#rn this m!7es them 2!st 2or the gi8en process technoogy3 )heir !ppic!tion dom!in h!s
5een mosty in the !re! o2 h!rd re!0time (;!te !ns4ers !re 4rong !ns4ers<)3
&irst p#5ished in 1/-/, ;"t!c7 Comp#ters* the ne4 4!8e< 5y Phiip K3 (oopm!n, Kr3 is
sti the de2initi8e 4or7 2or !n introd#ction to st!c7 m!chines3 )he 5oo7 m!y 5e
do4no!ded 2rom http*II4443ece3cm#3ed#Ib7oopm!nIst!c7ccomp#tersIinde.3htm
131
Forth Internals
Commercial de+ices
Commerci!y !8!i!5e chips 5!sed on ! &orth e.ec#tion mode inc#ded the Ao8i.
AC,000, the H!rrisI6ntersi B)C2000I01I10 series, the 6C1 2rom >et!0t !nd the "iicon
Composers "C323
http*II4443inscenes3comIsiiconcomposers3shtmDsiiconcomposers
"e8er! others h!8e 5een prototyped 4itho#t !chie8ing commodity siicon st!t#s3 $2 the
n!med CP's !5o8e, the B)C2000 2!miy 5ec!me ! 4or7horse 2or sp!ce !nd s!teite
!ppic!tions !s it 4!s !8!i!5e in ! r!di!tion0h!rdened process3 6t s#r8i8es !s the
B)Ccore @H>L impement!tion 2rom MicroProcessor Engineering3 9oth &orth !nd C
compiers !re !8!i!5e3 )he 6C1 sod in consider!5e 8o#me into ! niche m!r7et !s !
2ied5#s processor, c!p!5e o2 s#pporting most seri! protocos !t #p to 1 M5ps3
% gro#p o2 de8ices inc#ding the P!triot "emicond#ctor P)"C1000 !nd the Light2oot
2!miy h!8e 5een prod#ced3 )hese !re essenti!y t4o0st!c7 m!chines enh!nced 2or C
!nd direct s#pport o2 K!8! 5ytecode e.ec#tion3 %t present their e8e o2 commerci!
s#ccess is #n7no4n3
=ith the e.posion in the c!p!5iity o2 &PE%s (&ied Progr!mm!5e E!te %rr!ys), the
c#rrent crop o2 !8!i!5e st!c7 m!chines !re mosty 2oc#ssed on impement!tion in
&PE%s 2rom @H>L or @eriog so#rces3 %p!rt 2rom the B)Ccore 2rom MPE, !n
interesting m!chine is the MicroCore (see http*II4443microcore3org) 4hich h!s !
p!rtic#!ry interesting e.ception h!nding mech!nism in h!rd4!re3 =ith the eno#rmo#s
costs o2 one t#rn o2 ! "ystem0on0Chip design to siicon, the &PE% !ppro!ch to CP'
design is the most i7ey to prod#ce commerci! s#ccess3
% Eooge se!rch 2or st!c7 m!chines 4i re8e! the c#rrent st!te o2 the !rt3
Prototype and research machines
Ch#c7 Moore !nd his !ssoci!tes h!8e prod#ced ! r!nge o2 de8ices 4hich h!8e !chie8ed
imited prod#ction3 His !ppro!ch h!s 5een to prod#ce !n integr!ted too ch!in 2rom
siicon modeing to tiing3 )he res#ts sho4 th!t this !ppro!ch c!n ! gi8e ! per2orm!nce
g!in o2 o8er ten times comp!red to !yo#t thro#gh !n ind#stry st!nd!rd too ch!in3 )he
do4nside o2 this !ppro!ch h!s 5een th!t e!ch siicon process ch!nge reF#ires
consider!5e 4or7 on the too ch!in, so red#cing the r!te !t 4hich ne4 processes c!n 5e
!dopted3 =hie (Eordon) MooreLs !4 hods, it is #ni7ey th!t this !ppro!ch 4i e!d to
commodity siicon, 5#t it c!n prod#ce st#nning per2orm!nce !t 8ery o4 cost 2or high0
8o#me niche prod#cts3
"e8er! E#ro&orth p!pers, especi!y 2rom 9ernd P!ys!n, descri5e the #se o2 sm! st!c7
m!chines inside em5edded prod#cts3 6n these designs the st!c7 m!chine is t#ned in
terms o2 instr#ction set, per2orm!nce !nd siicon !re! 2or e!ch !ppic!tion3
Chris 9!iey (no4 !t Gor7 'ni8ersity, '() h!s e.pored the possi5iities o2 s#persc!!r
e.ec#tion in st!c7 m!chines 4ith some s#ccess3 His rese!rch s#ggests th!t st!c7
m!chines !re s#it!5e 2or s#persc!!r e.ec#tion !nd sho4s ho4 it c!n 5e done3 6n the
ong term this opens the door to the #se o2 st!c7 m!chines in high per2orm!nce
en8ironments o#tside the tr!dition! h!rd re!0time dom!ins3
132
Forth Internals
;otes on embedded realEtime
)hese notes !re t!7en 2rom ! p!per 5y Chris 9!iey !nd "tephen Pec !t the E#ro&orth
200, con2erence3
)here !re 2o#r m!in !re!s in 4hich em5edded systems di22er 2rom des7top comp#ting3
1) 6mport!nce o2 interr#pt response time
2) 6mport!nce o2 deterministic response time
3) Economics o2 code si:e
,) 6mport!nce o2 5r!nch 5eh!8io#r
6n the c!se o2 st!c7 m!chines, ! comp!risons !re !g!inst !n B)C2000 CP' !t 10MH:
(circ! 1/--)3 )he st!te o2 the !rt 2or !n em5edded system is t!7en 2rom ! 60MH: Phiips
LPC2106 %BM05!sed microcontroer 4itho#t c!ches 5#t 4ith ! memory !cceer!tor
(2003I,)3
Interrupt response time
=e de2ine this !s the time t!7en 2or the CP' h!rd4!re !nd so2t4!re to s!8e conte.t
5e2ore st!rting #se2# 4or73 )o this m#st 5e !dded the conte.t restore time !2ter
per2orming #se2# 4or73 )he code 5eo4 sho4s the 2ig#res 2or ! 10MH: B)C !g!inst !
60MH: %BM7)>M6"3
Entry
RTX2000 400ns 0 bytes 0 instructions
ARM 432ns 20 bytes 5 ins, 27 cycles @
16ns
Exit
RTX20000 200ns 2 bytes 1 instruction
ARM 400ns 16 bytes 4 ins, 25 cycles
Aote th!t these 2ig#res e.c#de !ny o8erhe!ds 2or compier0gener!ted code3
)he 2ig#res sho4 th!t despite ! 6*1 to ,0*1 coc7 r!te incre!se in 15 ye!rs, 4here typic!
top0end em5edded CP's r#n !t 2000-00MH:, interr#pt response times h!8e not
impro8ed3 )he %BM is !mong the 5etter per2ormers in em5edded B6"C CP's3 %s
sho4n 5y (oopm!n !nd others, interr#pt response (entry) times in c#rrent C6"C CP's
c!n e.ceed ,00 coc7 cyces3 =hen c!ches !nd MM's !re in8o8ed, the sit#!tion
5ecomes e8en 4orse3
PROC IRQ_entry \ -- \ 4 cycles
\ --- save state ---
stmfd rsp ! { r0-r12, link } \ 3 + 14 mems
mrs r3, SPSR \ 1
stmfd rsp ! { r3 } \ 2 + 1 mem
\ --- call high level handler ---
l: IRQ_call
bl <action> \ 3
133
Forth Internals
\ --- restore state ---
ldmfd rsp ! { r3 } \ 3 + 1 mem
msr SPSR, _c _f r3 \ 1
ldmfd rsp ! { r0-r12, link } \ 3 + 14 mems
sub .s pc, link, # 4 \ 3
end-code
*eterminism
M!ny em5edded !ppic!tions s!mpe reg#!r sign!s (he!rt5e!t, 50I60H: m!ins, !#dio
etc3)3 6t is imper!ti8e th!t s!mping periods !re !t 2i.ed inter8!s to red#ce ph!se Jitter in
the s!mping3 Modern CP's !chie8e high coc7 speed #sing c!ches !nd ong pipeines3
9oth o2 these h!8e !d8erse imp!ct on determinism3 "ee (oopm!n et ! 2or the n#m5ers3
6t sho#d 5e noted th!t ! he!8y interr#pt o!d !22ects 5oth entry !nd e.it per2orm!nce3 6n
the 4orst c!se, the 4hoe o2 the interr#pt ro#tine m#st 5e o!ded 2rom m!in (so4est)
memory !nd disp!ces the 5!c7gro#nd t!s7 4hich in t#rn m#st 5e reo!ded 2rom m!in
(so4est) memory3
Economics of code si+e
"iicon costs go #p !s the 2o#rth po4er o2 dimension (yied, chipsI4!2er etc) !nd po4er
cons#mption goes #p 4ith the n#m5er o2 !cti8e tr!nsistors per coc7 4ithin the s!me
geometry3 6n the singe chip microcontroer !re!, code si:e !22ects memory in terms o2
onIo22 chip &!sh, !nd !so in terms o2 B%M #s!ge3 M!ny die photos demonstr!te th!t
the siicon !re! o2 on0chip memory e.ceeds th!t o2 the CP' !nd peripher!s3
Importance of branch behaviour
)ypic! microcontroer code sho4s th!t 5r!nches !nd 2o4 o2 contro occ#r ro#ghy
e8ery 5 instr#ctions (!ppro.im!tey 20` o2 the code)3 % Penti#m , 4ith ! 20 st!ge
pipeine, !nd misses in ! c!ches !nd 5r!nch prediction 5#22ers c!n s#22er ! 30 cyce
pen!ty 2or ! missed 5r!nch (20 cyces in the pipeine, 10 in the memory)3 )he %BM
!5o8e h!s ! , cyce 4orst c!se (1 2or decode, 3 2or memory), 4here!s the B)C h!s !
2i.ed 2 cyce o8erhe!d in ! c!ses3
)he Penti#m , 2ig#res gi8en !5o8e !re pro5!5y 5est c!se3 )he !ct#! timings depend
he!8iy on the chip0set !nd memory system3 $ne correspondent reports th!t he h!s
me!s#red ! de!y o2 3-5 cyces on ! Penti#m ,3
134
+sing the Forth interpreter
1, 5sing the Forth interpreter
&orth is !n inter!cti8e e.tensi5e !ng#!ge3 Go# c!n #se the interpreter !t compi!tion
time !nd d#ring progr!m e.ec#tion !s 4e !s 2or progr!m testing3 Go# c!n !so #se the
compier !t r#n time3 C!re2# #se o2 the interpreter, compier !nd &orth system c!n gi8e
5ig di8idends in terms o2 code si:e !nd timesc!es3
)he 2irst e.!mpe sho4s ho4 con2ig#r!tion code c!n 5e #sed to set de2!#ts !t compie
time, !nd to pro8ide con2ig#r!tion toos 2or the !ppic!tion3
)he second e.!mpe #ses the compier to pro8ide stor!ge o2 n!med items, !nd e.pores
! n#m5er o2 iss#es r!ised 5y this3
Configuration e(ample
Application and design
)he !ppic!tion is 2rom ! seri! de8ice dri8er #sed in !n em5edded PC r#nning >$" !nd
@&C &orth 2or >$"3 Aot ! the code is pro8ided here, so yo#L h!8e to #se this code !s
!n i#str!tion 2rom ! re!04ord e.!mpe M it is not compete in itse23 )he point is to
i#str!te ho4 the &orth interpreter c!n 5e #sed 5oth !t compie time !nd !t r#n time3
)o con2ig#re ! seri! port, not ony do yo# need to speci2y the 5!#d r!te, p!rity !nd so
on !t r#n time, 5#t yo# !so need to 5e !5e to speci2y the 6I$ port !ddress, interr#pt
n#m5er !nd so on3 )he h!rd4!re con2ig#r!tion 2or the 2irst three seri! ports is (mosty)
st!nd!rd !nd c!n 5e done !t compie time3 6nd#stri! !ppic!tions c!n reF#ire ! 8ery
!rge n#m5er o2 seri! ports !nd since their con2ig#r!tions m!y ch!nge (it is di22ic#t to
5#y the s!me PC mother5o!rd 2or more th!n t4o or three ye!rs in s#ccession), the
con2ig#r!tion m!y h!8e to 5e done d#ring inst!!tion !nd commissioning o2 the
eF#ipment3 )his con2ig#r!tion in2orm!tion c!n 5e hed in ! 2ie 4hich is IN"LUDEd !t
progr!m st!rt3 6t #ses the &orth interpreter to set #p the system3
)he &orth system !ccesses 6I$ de8ices thro#gh ! ;Eeneric 6I$ str#ct#re<3 )his is ! d!t!
str#ct#re 4hose 2irst p!rt is common to ! de8ices, !nd the 2oo4ing p!rts cont!in d!t!
pri8!te to e!ch de8ice3 &or e!ch seri! de8ice, ! con2ig#r!tion string is #sed to the d!t!
into the d!t! str#ct#re3 )he strings !re simi!r to those #sed 5y the >$" M$>E
comm!nd, e3g3
COM2: 38400 baud N,8,1 8 kb 4 kb buffers
speci2ies th!t the de8ice #ses the h!rd4!re 2or C$M2, r#ns !t 3-,00 5!#d, no p!rity,
eight d!t! 5its, one stop 5it !nd h!s inp#t !nd o#tp#t 5#22ers o2 - !nd , 7io5ytes
respecti8ey3
6nterpret!tion o2 the string st!rts 4ith the !ddress o2 ! str#ct#re on the d!t! st!c73 E!ch
4ord th!t processes p!rt o2 the con2ig#r!tion, s#ch !s BAUD !nd NF[F,, cons#mes
ree8!nt d!t! !nd e!8es the str#ct#re !ddress on the st!c7 re!dy 2or the ne.t 4ord3
135
+sing the Forth interpreter
Implementation
)he code is t!7en directy 2rom one o2 the @&C &orth 2or >$" so#rce 2ies3 )he
comment ines th!t st!rt Rd X.L !re processed 5y doc#ment!tion toos to prod#ce H)ML
!nd P>& doc#ment!tion directy 2rom the so#rce code3
struct /ComData \ -- n ; size of uart/queue structure
\ *G The /ComData structure holds the data needed to process
\ ** a channel, including the UART address, queue addresses,
\ ** and transmit flags. This is a Generic I/O structure.
\ GENIO data
int C.handle \ device handle or -1
int C.vectors \ pointer to Gen I/O vectors
\ UART configuation
int C.mode \ mode flags, b0=16450, b1=16550,
int C.baud \ baud rate
byte C.int# \ DOS interrupt#
byte C.#data \ #data bits, 5, 7, 8
byte C.parity \ parity
byte C.#stop \ stop bits
\ buffer configuation
int C.port \ UART port base address
int C./inpQ \ size of input queue
int C.inpQ \ input queue (allocated from heap)
int C./outQ \ size of output queue
int C.outQ \ output queue
int C.flag \ true if TX in progress
\ PIC configuation
int C.pic0 \ first PIC port (must be set)
int C.pic1 \ second PIC port (0=unused)
byte C.irqPic0 \ PIC0 IRQ#
byte C.enPic0 \ PIC0 channel enable mask
byte C.disPic0 \ PIC0 channel disable mask
byte C.irqPic1 \ PIC1 IRQ#
byte C.enPic1 \ PIC1 channel enable mask
byte C.disPic1 \ PIC1 channel disable mask
aligned
\ Interrupt counters and state
int C.#ints \ number of times interrupts checked
int C.#MSRints \ number of MSR interrupts
int C.#RXints \ number of receive interrupts
int C.#TXints \ number of transmit interrupts
int C.#LSRints \ number of LSR interrupts
byte C.lastMSR \ last value from MSR
byte C.lastLSR \ last value from LSR
aligned
\ Saved UART configuation
/UARTstate field C.US \ UART state save area (all bytes)
aligned
end-struct
136
+sing the Forth interpreter
\ ************************
\ *S Configuring serial ports
\ ************************
\ *P Serial ports are initalised and opened using command
\ ** strings similar to those used in DOS commands. The
\ ** commands are Forth words in a private vocabulary.
vocabulary COMsettings \ --
\ *G Used for serial port set up commands. All words in this
\ ** vocabulary must return the /Comdata structure passed
\ ** to them, e.g.
\ *C 115200 baud ( struct n -- struct )
\ ********************************
\ *N Words used in command strings
\ ********************************
\ *P The /ComData structures are initialised using command
\ ** strings held in a private vocabulary. The same strings
\ ** are used when opening the device.
\ *C COM2: 38400 baud N,8,1 8 kb 4 kb buffers
also COMsettings definitions
: baud \ struct baudrate -- struct
\ *G Set the structure's baudrate.
\ ** The default is 9600.
over C.baud ! ;
: port \ struct port -- struct
\ *G Set the structure's I/O port base address.
\ ** No default unless SET by COM1..COM4 below.
over C.port ! ;
: int# \ struct int# -- struct
\ *G Set the structure's DOS interrupt number.
\ ** No default unless SET by COM1..COM4 below.
over C.int# c! ;
\ LCR - Line control register
: #data \ struct #bits -- struct
\ *G Set the structure's number of data bits. Defaults to 5.
5 - %00000011 and \ LCR bits 1:0
over C.#data c! ;
: #stop \ struct #stop -- struct
\ *G Set the structure's number of stop bits. Must be 1 or 2.
\ ** The default is 1.
1- 0<> $04 and over C.#stop c! ; \ LCR bit 2
$00 constant no \ LCR bits 5:3
$08 constant odd
$18 constant even
137
+sing the Forth interpreter
$28 constant par1
$38 constant par0
: parity \ struct #bits -- struct
\ *G Set the structure's parity usage. #bits must be one of
\ ** NO, ODD, EVEN, PAR1 or PAR0. The default is NO.
over C.parity c!
;
: buffers \ struct #in #out -- struct
\ *G Set the input and output queue buffer sizes, which
\ ** must be a power of 2. If unused, defaults to 1024
\ ** and 256.
rot tuck C./outQ ! tuck C./inpQ !
;
: PIC0 \ struct bit# port -- struct
\ *G Set the bit# and base address of the PIC that will be
\ ** used first to clear/enable/disable an interrupt.
\ ** Defaults to the COM1 standard settings or as set
\ ** by COM1..4.
...
;
: PIC1 \ struct bit# port -- struct
\ *G Set the bit# and base address of the PIC that will be
\ ** used second to clear/enable/disable an interrupt.
\ ** Use 0 0 PIC1 if the second PIC is unused.
\ ** Defaults to the COM1 standard settings or as set
\ ** by COM1..4.
...
;
: COM1: \ struct -- struct
\ *G Set the default conditions for COM1:
$03F8 port $0C int# 4 $20 PIC0 0 0 PIC1
;
: COM2: \ struct -- struct
\ *G Set the default conditions for COM2:
$02F8 port $0B int# 3 $20 PIC0 0 0 PIC1
;
: COM3: \ struct -- struct
\ *G Set the default conditions for COM3:
$03E8 port $0C int# 4 $20 PIC0 0 0 PIC1
;
: COM4: \ struct -- struct
\ *G Set the default conditions for COM4:
$02E8 port $0B int# 3 $20 PIC0 0 0 PIC1
;
138
+sing the Forth interpreter
: N,8,1 \ struct -- struct
\ *G Set the structure to no parity, 8 data bits, 1 stop bit.
no parity 8 #data 1 #stop
;
previous definitions
\ ***************************
\ *N Handling command strings
\ ***************************
also COMsettings
: ([COM) \ struct -- struct
-1 over C.handle ! \ mark as closed
COM1: #9600 baud N,8,1 \ default initialisation
/ComRxQ /ComTxQ buffers
;
previous
: [COM \ struct -- struct
\ *G Starts a definition of a /ComData structure.
\ ** [COM may be followed by any of the words above up to
\ ** the closing COM]. Unless overriden, sets
\ ** COM1:9600,N,8,1. Use as indicated
\ ** in the example below:
\ *C struct [COM COM2: 38400 baud N,8,1 COM]
state @
if postpone ([COM) else ([COM) endif
also COMsettings
; immediate
: COM] \ struct --
\ *G Closes the definition started by *\fo{[COM} above.
state @
if postpone drop else drop endif
previous
; immediate
SysErrDef err-COMstring "Error in COM command/open string"
: (SetComData) \ caddr len struct --
depth >r
[COM -rot evaluate COM]
depth r> swap - 3 <> err-COMstring ?throw
;
: SetComData \ caddr len struct --
\ *G The string caddr/len is processed by EVALUATE as
\ ** between [COM string COM]. Any error causes a THROW.
\ ** Zero length strings are ignored so that previously
\ ** set data is used.
over if
['] (SetComData) catch err-COMstring ?throw
13%
+sing the Forth interpreter
else
drop 2drop
endif
;
% seri! port de8ice is cre!ted 5y the 4ord SerDeX: 4hich c!n then 5e set #p #sing the
s!me comm!nd strings3
SerDev: COM1dev \ -- sid
\ *G Standard PC COM1 port device set by default to:
\ *C COM1: #115200 baud
COM1dev [COM COM1: #115200 baud COM]
SerDev: COM2dev \ -- sid
\ *G Standard PC COM2 port device set by default to:
\ *C COM2: #38400 baud
COM2dev [COM COM2: #38400 baud COM]
Phone book re+isited
)he phone 5oo7 e.!mpe comes 2rom !n MPE co#rse th!t h!s 5een r#n 2or m!ny ye!rs3
=hie gi8ing the co#rse !t ! c#stomer site, 6 re!ised th!t the impement!tion sho4n in !
pre8io#s ch!pter t!7es no !d8!nt!ge o2 &orth itse23 6 then re4rote the e.ercise to t!7e
2# !d8!nt!ge o2 &orth itse23
)he origin! impement!tion in the co#rse 2ie reF#ires !5o#t 270 ines o2 so#rce code3
)he impement!tion presented here t!7es !5o#t -0 ines 5#t t!7es some i5erties 4ith the
intent o2 the speci2ic!tion3 6t #ses &orthLs diction!ry str#ct#re !nd e.tensi5iity !s p!rt o2
the !ppic!tion3
*esign
%n entry in the phone 5oo7 is ! com5in!tion o2 ! string !nd !n e.tension n#m5er3 &rom
the speci2ic!tion, the string is ! singe n!me3 )he !ssoci!tion o2 the t4o is per2ormed 5y
de2ining ! const!nt, e3g3
10 constant benedict
)o !8oid con2icts 4ith 4ords o2 the s!me n!me in the #nderying &orth system, 4e
7eep the n!mes in ! sep!r!te 4ordist (n!meess 8oc!5#!ry) !s "ONSTANTs3 9y
cre!ting !nd se!rching 2or n!mes in this 4ordist 4e c!n #se the &orth interpreter itse2
to cre!te the entries !nd the st!nd!rd diction!ry se!rch toos to 2ind the n!mes3 $nce 4e
h!8e 2o#nd the n!me 4e c!n EXE"UTE the const!nt to ret#rn its 8!#e3
9ec!#se %A" &orth does not speci2y either the impement!tion str#ct#re o2 the
diction!ry or the toos reF#ired to 4!7 ! 4ordist, 6 h!8e chosen to m!7e !n !ss#mption
(see the 4ords "ALLS !nd "ALLS( 5eo4) !5o#t the diction!ry !nd d!t! !yo#t o2 the
#nderying &orth system3 )his techniF#e 4i not 4or7 on 'm5iic! systems3 62 yo# 2ind
other &orth systems 2or 4hich the !ss#mption 2!is, pe!se et me 7no43 )he !ss#mption
is reF#ired to 2ind ! n!me 2rom ! n#m5er3 6 !ss#me th!t the d!t! 8!#e de2ined 2or !
"ONSTANT is !t the 8ery end o2 the 4ordLs d!t! str#ct#re !nd th!t i2 6 ;comm!< more
140
+sing the Forth interpreter
d!t! into the diction!ry the ne4 d!t! 2oo4s on immedi!tey3 6 !so !ss#me the
e.istence o2 the 4ord BOD$' ( LNa HE 5 4hich e.ists on most hosted systems3
Implementation
only forth definitions decimal
wordlist constant widPhone \ -- wid
\ *G Make the wordlist for the PhoneBook.
0 value LastEntry \ -- addr
\ *G Holds linked list of entries.
: FindName \ "<name>" -- xt nz | 0
\ *G Return the xt and non-zero of the name that follows.
\ ** If the name cannot be found just return zero.
bl word count widPhone search-wordlist
;
: CheckNumber \ n --
\ *G Error if n is outside the range 0..9999
0 9999 within? 0=
abort" Telephone number outside range 0..9999"
;
: CheckName \ caddr len --
\ *G Apply checks to a name
dup 15 > abort" Name too long"
2drop
;
: Calls \ n "<name>" --
\ *G Make a new entry in the phone book in the form:
\ *C <nnn> Calls <name>
dup CheckNumber
>in @ bl word count CheckName >in ! \ abort if exists
get-current >r widPhone set-current \ private wordlist
constant \ make entry
here LastEntry , to LastEntry \ link in chain
r> set-current \ restore
;
: Calls? \ n --
\ *G Report who is called by number n.
LastEntry
begin \ -- n addr
dup
while \ -- n addr
2dup cell - @ = if \ check value of constant
body> >name .name
drop exit
endif
@
141
+sing the Forth interpreter
repeat
2drop ." Nobody"
;
: Phone \ "<name>" --
\ *G Display the number of the name that follows.
FindName if \ -- xt |
execute cr . \ execute to return value
else
cr ." has no phone"
then
;
: Entries? \ --
\ *G Display the phonebook names and numbers.
LastEntry
begin
dup \ address of link
while
cr dup body> >name .name
17 >pos ." -- " dup cell - @ .
@
repeat
drop
;
*e+iations9 issues and lessons
)his impement!tion de8i!tes 2rom the origin! speci2ic!tion in ! n#m5er o2 4!ys*
the n#m5er o2 entries is not de2ined,
the disp!y 2orm!t is sighty di22erent,
ch!nged e.tension n#m5ers !re not remo8ed3
6n e22ect, the impement!tion is ! F#ic7 !nd dirty h!c7 to get something r#nning3
Ho4e8er, it r!ises se8er! iss#es !5o#t the speci2ic!tion*
=hy !re n!mes restricted in si:eD
Ho4 sho#d the phone 5oo7 5e s!8edD
C!n t4o peope h!8e the s!me n!meD
>o peope sh!re e.tensionsD
6n my c!reer it h!s 5een 8ery r!re to recei8e ! compete or good speci2ic!tion3 6n
pr!ctice speci2ic!tions e8o8e 5y re2inement M the ;spir! i2ecyce< r!ther th!n the
;4!ter2!< mode3 Ho4e8er, !n impement!tion !rchitect#re th!t m!7es ! 2!se
!ss#mption !5o#t the ong0term e8o#tion o2 the system 4i e8ent#!y 2!i !nd h!8e to
5e disc!rded3 &i.ing !rchitect#r! 2!#ts is o2ten more e.pensi8e th!n st!rting !g!in3
142
+sing the Forth interpreter
=hen yo# !re 2!ced 4ith ! ne4 speci2ic!tion, yo# h!8e to F#estion it3 )here !re o2ten
!ss#mptions m!de 5y the !#thors !5o#t so2t4!re th!t !re in8!id3 "imi!ry, !s !
so2t4!re engineer, yo# !re i7ey to m!7e !ss#mptions !5o#t the !ppic!tion th!t !re !so
in8!id3 )he 2ine (!nd o2ten critic!) det!is !5o#t the process 5eing !#tom!ted !re ! too
o2ten #nst!ted in the speci2ic!tion3
%nother cr#ci! p!rt o2 the initi! st!ges is to simpi2y !s m#ch !s possi5e3 "ep!r!te the
m!in o5Jecti8es 2rom the ;4o#dnLt it 5e nice i2s< (=69A6s)3 6n the !ter st!ges o2 !
proJect =69A6s o2ten introd#ce compe.ity, cons#me more time th!n the origin!
o5Jecti8es, !nd de!y prod#ct !#nch3 %tho#gh the m!r7eting dep!rtment !nd s!esmen
!re 7ey 2riends e!ry on, their enth#si!sm c!n gener!te #ne.pected pro5ems !ter on3 6n
most proJects, !nd especi!y em5edded ones, the so2t4!re peope !re the !st in the
ch!in, !nd th#s !re most 8isi5e 2or !te dei8ery, e8en i2 !te dei8ery o2 o#t0o20
speci2ic!tion mech!nic! systems is the c!#se o2 yo#r grie23 $n one proJect 6 4or7ed on,
the mech!nics 4ere t!7en !4!y 2or o8ernight p!inting !nd 4ere dei8ered 5!c7 2o#r
d!ys !ter, e!8ing ess th!n eight ho#rs 2or so2t4!re testing 5e2ore the system 4!s
dei8ered 2or tri!s3
%n!ysis o2 !rge so2t4!re proJects sho4s th!t 2reF#ent dei8eries o2 so2t4!re mod#es
th!t c!n 5e tested contri5#tes eno#rmo#sy to proJect s#ccess r!te3 62 the !rchitect#re is
right, !ddition! 2e!t#res c!n 5e !dded !ter3 Ei8ing the end0#ser something to try
contri5#tes to the sense o2 progress !nd re8e!s !ny design pro5ems e!ry3 &i.ing
something costs !s !t e!st three times !s m#ch !s getting it right 2irst time3
$ne o2 the 7ey 5ene2its o2 &orth is th!t the inter!cti8ity !o4s 2or 8ery r!pid
in8estig!tion o2 2!#ts3 Go# c!n #se the inter!cti8ity not ony 2or de5#gging 5#t !so to
demonstr!te possi5iities to peope in other discipines3 6n order to do this s#ccess2#y
yo# h!8e to h!8e !n initi! ch!ssis to 4or7 2rom3 "o dei8er something e!ry !nd #se it to
test not ony so2t4!re, 5#t !so the speci2ic!tions !nd !ss#mptions yo# !re 4or7ing 2rom
M not ony other peopesL !ss#mptions, 5#t !so yo#r o4n3
143
Code ,a&out
1 Code 6ayout
Code !yo#t is ! 8e.ed topic in !ny progr!mming !ng#!ge3 M!ny progr!mmers,
especi!y ;g#r#< c!ss progr!mmers, h!8e ! stye o2 their o4n !nd !re re#ct!nt to
ch!nge it3 Ho4e8er, 2rom my o4n o5ser8!tion o2 !rge proJects, the #se o2 ! ;ho#se
stye< 2or so#rce code prod#ces signi2ic!nt 5ene2its o8er the i2etime o2 ! prod#ct3 )he
!rger the te!m, the more import!nt this 5ecomes3
)his does not me!n to s!y th!t ! ho#se coding stye sho#d not e8o8e3 My o4n
progr!mming stye h!s ch!nged !s 6 h!8e e!rnt, !nd in some c!ses it ch!nges it
!ccording to the !ppic!tion dom!in !nd 4ho is going to re!d the code3
)he 7ey 2e!t#res 2or ! so#rce coding st!nd!rd !re
Consistency 2rom one progr!mmer
Consistency 5et4een m!ny progr!mmers
)he st!nd!rd is e!sy to 2oo4 !nd #nderst!nd
)he res#ting code is e!sy to 2oo4 !nd #nderst!nd
Code 4hich is di22ic#t to get 4rong 5ec!#se o2 !yo#t
% !yo#t 4hich is !so 8is#!y pe!s!nt
% second!ry (!nd incre!singy import!nt) 5ene2it is th!t ! consistent stye m!7es it m#ch
e!sier to #se !#tom!ted so#rce m!inten!nce !nd doc#ment!tion toos3 )his m!y not
!ppe!r 4orth m#ch 2or ! F#ic7 !nd dirty proJect, 5#t it is in8!#!5e 2or !rge proJects3
)here !re c#rrent &orth proJects !ppro!ching 1,000,000 ines o2 &orth so#rce code3
% description o2 the reF#irement o2 the st!nd!rd 4i 5e 2oo4ed 5y !n e.!mpe3 6n the
e.!mpe, the ree8!nt code 2r!gments 4i 5e printed in 'PPEB C%"E3 )he comments
in the e.!mpe 4i 5e in o4er c!se3 Ho4e8er, the c!se o2 the ch!r!cters #sed in re!
code is not speci2ied3 "ome compiers m!y 5e c!se0sensiti8e, others not3 %so di22erent
progr!mmers m!y h!8e c!se pre2erences3 )he code e.!mpes in this doc#ment 4i
!ss#me th!t the e2t0h!nd end o2 the ine comes directy 5eo4 the e2t0h!nd end o2 this
type o2 te.t3 6ndented code 4i 5e re!ti8e to this co#mn position*
\ the beginning of the line
\ indented by one space
7hy a standard>
)here !re se8er! re!sons 2or prod#cing !nd 2oo4ing ! st!nd!rd 2or !nything3 )his
st!nd!rd is prod#ced 2or the 2oo4ing re!sons3
6n !ny org!nis!tion, i2 m!ny progr!mmers !re ! #sing the s!me !ng#!ge, they 4i
ine8it!5y 5e sh!ring so#rce code, or 4or7ing in te!ms on ! gi8en proJect3 62 e8ery
progr!mmer 4rites code to his o4n or no st!nd!rd, then comm#nic!tion 4i 5e
di22ic#t, !nd progr!mmers 4i tend to pre2er to re0in8ent the 4hee r!ther th!n try to
145
Code ,a&out
#nderst!nd !nd #se !nother personLs code3 )his is 5oth costy !nd time0cons#ming3 9y
2oo4ing ! st!nd!rd 0 !ny st!nd!rd 0 e!ch progr!mmerLs code 4i 5e me!ning2# to the
others3
=hen ! progr!mmer st!rts to e!rn ! !ng#!ge, he or she 4i not 7no4 ho4 5est to
either 4rite or !y o#t the code 5eing 4ritten3 )#tori!s !5o#nd to te!ch the synt!.,
str#ct#re !nd 4ord0set o2 &orth, 5#t there is itte !d8ice gi8en on !yo#t !nd pr!ctice3
)his doc#ment see7s to o22er the coected e.perience o2 st!22 !t MPE so th!t other
progr!mmers e!rn !n !ccepted !nd ce!r st!nd!rd3
Ho4e8er, the st!nd!rd !s presented here sho#d not 5e t!7en !s ! di7t!t3 62 !n
org!nis!tion h!s its o4n speci2ic !yo#t or doc#ment!tion reF#irements, these sho#d not
5e ignored3 % st!nd!rd is there to hep, not hinder in the prod#ction o2 so#rce code3
$ther &orth coding st!nd!rds e.ist3 % good p!ce to st!rt oo7ing 2or them is !t
http*II44432orth3org3
Implications of editors
Progr!mmers 8!ry 4idey in their !ttit#des to editors3 "ome c!n (!nd 4i) #se !most
!ny editor to h!nd3 $thers !re ost 4itho#t !n (ine8it!5y o5sc#re !nd o5soete) editor
!nd ! set o2 idiosyncr!tic m!cros3 $8er the ye!rs 6 h!8e come to the conc#sion th!t
trying to impose ! p!rtic#!r editor 4i ony sp!r7 ! ong !nd e.pensi8e reigio#s 4!r3
Editors !re che!p comp!red to progr!mmer s!!ries !nd PC costs3
)he #se o2 !n editor h!s m!ny impic!tions3 $ne o2 these is the !mo#nt o2 code 8isi5e
on the monitor !t !ny one time3 %nother is the #se o2 t!5s !nd sp!ces in 4hite sp!ce3
%nother is synt!. coo#ring, 4hich h!s ! re! imp!ctS 6 !m !4!ys s#rprised 4hen 6 re!d
my code in #ncoo#red 2orm3 Get !nother is the decision o2 ho4 the code is 2r!gmented 0
ho4 m!ny 4ords in ! section or in ! 2ie 0 !nd ho4 m!ny 2ies in the !ppic!tion or
proJect3
)he n#m5er o2 ines 8isi5e on the screen, co#ped 4ith the speed o2 c#rsor mo8ement
!most dict!tes the si:e o2 !ny 4ord or proced#re prod#ced3 )his is o2 direct ree8!nce to
the stye o2 code e8ent#!y 4ritten* 4hether the code is 8ery 8ertic! 4ith ots o2 4hite
sp!ce, or is 8ery hori:ont! 4ith m#ch code on e8ery ine3 )his is disc#ssed !ter3
)he decision o2 ho4 m!ny 4ords 4i 5e p!ced on one p!ge or in one 2ie depends on
the n!t#re o2 the compier !nd editor in #se3 62 the editor c!n h!8e m!ny 4indo4s onto
m!ny 2ies, then m!ny 2ies m!y 5e #sed e!siy 0 4ith the code 2!ctored o#t on ! per02ie
5!sis3 Ho4e8er, i2 the editor does not s#pport m#tipe 2ies, then there 4i 5e !
tendency to p!ce ! code in one 2ie3
Tabs
)he #se o2 t!5s to sp!ce o#t code !nd comments h!s ! direct ree8!nce to the !mo#nt o2
4hite sp!ce 5et4een eements o2 the so#rce 2ie3 62 sp!ces m#st 5e #sed, there 4i 5e
itte 4hite sp!ce (!s its prod#ction is tedio#s), 5#t i2 t!5s !re #sed, there m!y 5e F#ite !
ot o2 sp!ce in the 2ie, !nd it 4i 5e #ni2orm, 5#t 4i 5e !t the 4him o2 !ny too #sed
4ith the 2ie3 % good e.!mpe o2 this is the 2!ct th!t >$" (!nd m!ny =indo4s
comm!nd0ine toos) t!5s !re preset to - co#mns (1,/,17, etc3) 2or progr!ms s#ch !s
PB6A) !nd )GPE, 5#t editors gener!y h!8e progr!mm!5e t!50stops3
146
Code ,a&out
6t is there2ore import!nt to consider the t!5 sp!cing #sed in conJ#nction 4ith the toos
i7ey to 5e #sed 4ith the so#rce 2ies3 62 !n editor is c!p!5e o2 sm!rt indenting, the
!mo#nt o2 indent h!s to 5e considered3 62 the indent is set too deep, 8ery 2e4 str#ct#res
4i 5e e!siy nest!5e (sometimes !n !d8!nt!ge), 5#t i2 the indent is too sm!, then the
indent 4i not st!nd o#t !s s#ch3
$#r ho#se r#e is th!t i2 yo# edit 4ith t!5s set to !nything other th!n e8ery eight
ch!r!cters, the editor m#st 5e set to insert sp!ces r!ther th!n h!rd coded t!5s3 )his ets
#s #se some od 5#t po4er2# comm!nd ine toos 4hie ret!ining 2e.i5iity in the
editor3
=hen yo# recei8e third p!rty code, yo# 4i o2ten 2ind th!t it h!s h!rd t!5s set to some
8!#e other th!n the one yo# #se3 % F#ic7 Eooge se!rch 4i 2ind )%93ECE or ! simi!r
too th!t 4i s#5stit#te sp!ces 2or t!5s3 "ome 4i e8en rep!ce sp!ces 5y the
!ppropri!te t!5 settings3
"oriFontal and 4ertical layouts
)here !re t4o m!in styes o2 so#rce0code !yo#t in #se3 $ne is 8ertic!, !s #sed in
!ssem5er so#rce, !nd the other is hori:ont!, !s #sed 5y most C progr!mmers (!nd
others)3
@ertic! code*
mov ax, bx
add bx, 3inc di
Hori:ont! code*
for (i=0; i++, i<=20) printf (%d, i);
)he hori:ont! !yo#t e!ds to ! high code density !nd minim! eye mo8ement to re!d3
)he 8ertic! !yo#t enco#r!ges in0ine comments !nd impro8ed 8isi5iity d#e to 4hite
sp!ce3 9oth h!8e their 5ene2its !nd dis!d8!nt!ges3
&orth progr!mmers #s#!y pre2er in0ine comments !ong the de2inition o2 ! 4ord3 )his
#ndo#5tedy e!ds to more comprehensi5e code !s it is 5oth re!d !nd 4ritten, 5#t reies
on ! r!ther 8ertic! code !yo#t3 Ho4e8er, the no8ice progr!mmer is i7ey to e.tend the
8ertic! !yo#t to the e.treme o2 ! typic! !ssem5er !yo#t, !nd th#s ose the high0e8e
str#ct#re !nd 2o4 o2 &orth so#rce3
)his gener!y deri8es 2rom the phr!sing o2 code 0 4riting me!ning2# phr!ses or
2r!gments o2 code on one ine s#ch th!t the comment descri5es the o8er! e22ect o2 the
ine, not the !ctions o2 indi8id#! 4ords s#ch !s - !nd .3 Phr!sing !so heps point o#t
code 2r!gments 4hich co#d 5e 4ritten more e22icienty !s sep!r!te 4ords 0 5eing
2!ctored o#t3
M!7ing &orth code egi5e is ! compromise 5et4een 8ertic! !nd hori:ont! !yo#ts 0
4ith code 4e phr!sed or 2!ctored, 5#t 4ith str#ct#res spre!d o#t 2or e!sy chec7ing or
modi2ying3 %s disc#ssed in the section Contro "tr#ct#re L!yo#t, ho4e8er, e8en these
!re open to de5!te, !s short 5odies 4ithin str#ct#res !re o2ten 5est on the s!me ine !s
the entire str#ct#re3
147
Code ,a&out
Comments
)here h!8e 5een t4o st!nd!rds o2 &orth so#rce code comments3 $ne is the in0ine
comment, the other is !n !ddition! 5oc7 o2 comment 5e2ore or !2ter in the 2ie, or in
!nother 2ie3
)he 2ormer h!s the !d8!nt!ge o2 5eing p!r!e to the code to 4hich it re!tes 4hist the
!tter re!ds !s consistent Engish, or other h#m!n !ng#!ge, !nd is more descripti8e3 6n !
te.t 2ie, 5oth 2orms o2 comment m!y 5e s#pported3 9ec!#se the p!ge is !t e!st -0
ch!r!cters 4ide, e!ch ine m!y inc#de ! good in0ine comment3 9ec!#se the monitor
screen is !t e!st 25 ines deep, ! de2inition m!y !so h!8e ! he!der 5oc7 o2 comment
!5o8e or 5eo4 it3 )his comment co#d potenti!y 5e in !nother 2ie, perh!ps !
doc#ment!tion 2ie, 5#t is 2!r more ree8!nt !nd #se!5e i2 it is in the s!me 2ie, !nd in
the s!me section !s the code it e.p!ins3
=isdom sho#d 5e #sed in the 4ording in comments3 )he comment sho#d not 5e so
tri8i! th!t it is pointess (2etch the contents o2 the 8!ri!5e), 5#t sho#d not 5e so
remo8ed 2rom the code th!t it con8eys no in2orm!tion (re!ds d!t! str#ct#re)3 6t sho#d
indic!te ce!ry, !ssisting the &orth itse2 (get the pointer 8!#e)*
: EXAMPLE \ -- ; comments example
\ pointless ...
DATA 4 + @ \ get the contents of the variable
\ no information ...
\ read data structure
\ useful ...
\ get the second pointer value
@ EXECUTE ;
A!t#r!y the #se o2 the phr!se \ . in this code is deprec!ted3 )he #se o2 str#ct#res or
n!med o22sets is m#ch to 5e pre2erred3
File layout
$#r 2ies tend to consist o2 se8er! sections3 )he 2irst section is ! he!der section, 4hich
is 2oo4ed 5y one or more sections o2 re!ted code, 2oo4ed 2in!y 5y 2ie test code3
"ome progr!m editors permit yo# to enter p!ge 5re!7s !s section 5re!7s !nd disp!y
them !s hori:ont! ines3 "ome ye!rs !go this 4!s pop#!r 5#t the pr!ctice h!s no4
!most died o#t3 $#r e.perience 4!s th!t printed copies (sti #se2#) o2 so#rce code did
not oo7 good #ness progr!mmers rigidy m!int!ined ! m!.im#m o2 (s!y) 66 ines per
p!ge3 % 2e4 d!ys o2 !te night commissioning on site r#ined it !3 =e rep!ced the
p!ges 4ith sections deimited 5y p!rtic#!r commenting con8entions, e3g3
\ *******
\ Section
\ *******
\ ==========
\ SubSection
\ ==========
\ -------------
\ SubSubSection
\ -------------
148
Code ,a&out
"eader -ection
)he 2irst section o2 ! 2ie sho#d inc#de !ny copyright, !#thor, or other speci2ic
in2orm!tion3 )his m!y !so inc#de proJect det!is or other in2orm!tion ree8!nt to the
#se o2 the code3 62 there !re speci2ic h!rd4!re dependencies, these sho#d 5e o#tined on
the 2irst p!ge 0 this p!ge is the one #s#!y 2irst seen 4hen the 2ie is 5ro4sed or edited3
\ Code for Front panel control
\ Customer: xxxxxxxx
\ Project: yyyyyyyy
\ (c) MicroProcessor Engineering Ltd and xxxxxxxxx
\ 133 Hill Lane
\ Southampton SO15 5AF
\ UK
\ Phone +44 (0)23 8063 1441
\ Note: this code requires the zzzzzzzz
\ interface card, and MPE 8031 Cross-compiler
\ and interrupt handling code.
>o not 2orget to #se 2# intern!tion! !ddresses !nd teephone n#m5ers3 Go#L 5e
!m!:ed 4here yo#r code gets to !2ter ! 2e4 ye!rs3
M!ny &orth compiers h!8e e.tended comment oper!tors 4hich ignore p!rentheses3
)his !o4s he!der comments to 5e 4ritten 4itho#t the #se o2 ! 5!c7s!sh comment on
e8ery ine3 MPE !nd others #se the 2orm*
(( can extend over many lines and include () chars ))
62 yo# do not h!8e these, yo# c!n #se the %A" condition! compi!tion 2orm 2or
ong comments*
0 [IF] ... [THEN]
)he st!nd!rd MPE he!der oo7s i7e this*
\ Filename - description
((
Copyright (c) 2005
MicroProcessor Engineering
133 Hill Lane
Southampton SO15 5AF
England
tel: +44 (0)23 8063 1441
fax: +44 (0)23 8033 9691
net: mpe@mpeforth.com
tech-support@mpeforth.com
web: www.mpeforth.com
Short description of the function of the code in this file.
To do
=====
14%
Code ,a&out
Change history
==============
20050131 SFP002 Converted for Program Forth
20041205 RBM001 Removed potential insult
))
((
Put the design description here. Design information
is really important!
))
=e pro8ide ! ch!nge history in the 2orm o2 ! d!te code th!t c!n 5e !#tom!tic!y sorted,
then ! ch!nge code o2 three initi!s 2or the !#thor !nd ! three digit ch!nge n#m5er,
2oo4ed 5y ! 5rie2 description o2 the ch!nge3 E!ch ch!nged ine is m!r7ed 4ith the
ch!nge code3 Ch!nges c!n 5e F#ic7y monitored 5y se!rching 2or the ree8!nt ch!nge
code3
=here the design in2orm!tion is non0o58io#s, p#t !n o8er! design in sep!r!te comment
5oc7 M itLs e!sier to 2ind th!t 4!y3 9e 7ind to yo#r 2eo4 progr!mmers, they m!y not
5e !s 5right !s yo# !re !nd yo# do not 4!nt to 5e pestered 5y them ong !2ter4!rds3
More import!nty, p#tting do4n design in2orm!tion here c!ri2ies the mind !nd red#ces
the 5#g e8e in yo#r code3
Code sections
)he rest o2 the 2ie, either the code !2ter the proJect in2orm!tion, or the s#5seF#ent
sections, 4i cont!in the code 2or the proJect, or the portion o2 the proJect3
6t is norm! to spit the code 2or !n entire system into se8er! 2ies3 )hese !re norm!y
gro#ped into re!ted !re!s* ! the d!t! str#ct#res in one 2ie, ! the seri! iIo in !nother,
!nd so on3 62 the proJect is sm! eno#gh not to 4!rr!nt m!ny so#rce 2ies, then the code
!re!s 4i 5e gro#ped on di22erent sections3 62 the proJect is 5ig, then some p!rts o2 the
code 4i ine8it!5y st!rt sm!, !nd then e8o8e into ! monster3 "pit these into e!siy
identi2i!5e sections3
\ *******
\ Section
\ *******
\ Design info
: foo \ a b - c
...
;
"ince 4e st!rted #sing !#tom!ted toos to e.tr!ct doc#ment!tion 2rom the so#rce code,
4e h!8e noticed th!t 4e tend to stic7 to o#r ho#se coding stye m#ch more cosey3 $#r
cients !nd contr!ctors h!8e noticed this !nd s!y th!t the !5iity to prod#ce H)ML !nd
P>& doc#ments F#ic7y h!s imp!cted their coding stye too3 9ec!#se design in2orm!tion
c!n 5e e.tr!cted F#ic7y !nd #s #p to d!te, it is re!d more3 ConseF#enty there is more
positi8e 2eed5!c7 th!t enco#r!ges progr!mmers to prod#ce this doc#ment!tion3 E!ry
doc#ment!tion red#ces 5#gs3
150
Code ,a&out
Test -ection
%tho#gh m#ch ignored, test code c!n 5e in8!#!5e 4hen the 2ie h!s 5een 5ro7en3
=hen yo# h!8e 2inished 4ith initi! test code, comment it o#t !ndIor mo8e it to the end
o2 the ree8!nt section or the end o2 the 2ie3 >o try to doc#ment it to some e8e,
other4ise yo#r s#ccessors 4i thro4 yo#r 4or7 !4!y3
2ase and numbers
62 the n#m5er 5!se 2or the code on ! section is import!nt, the 5!se sho#d 5e speci2ied !t
the top o2 the section3 $#r h!5it is !4!ys to re8ert to DE"IMAL !2ter4!rds3
M!ny recent &orth systems permit yo# to #se ! pre2i. ch!r!cter to indic!te the n#m5er
5!se3 )he most common !re*
;KKAA he.!decim!
?,+++ decim!
],+,+ 5in!ry
62 the compier to 5e #sed s#pports this 2e!t#re, then it is good pr!ctice to #se it, !s there
c!n then 5e no mist!7e 4hich n#m5er is me!nt !t !ny time3 62 the compier does not
s#pport the tempor!ry 5!se de2inition, then it is 5est to !4!ys pre2i. ! he. n#m5er 4ith
! :ero*
HEX
0100 \ hex 100 = decimal 256
0ADD \ hex ADD = decimal 2781
ADD \ the word ADD
DECIMAL
4ocabularies and wordlists
62 ! 8oc!5#!ry or conte.t s4itch is to 5e m!de in the so#rce code, the 8oc!5#!ry
sho#d 5e the s!me !t the end o2 ! section !s !t the 5eginning3 )his me!ns th!t i2 ! ne4
section is inserted !2ter4!rds, the se!rch order !nd de2ining 8oc!5#!ry 4i 5e 7no4n*
\ ************
\ I/O handling
\ ************
ALSO IO
.........
PREVIOUS
6ayout of a definition
6t is !c7no4edged th!t ! &orth de2inition sho#d 5e !s short !s possi5e3 )his m!y 5e 2
or 3 ines, or it m!y 5e 15 or 20 ines3 )he !ct#! si:e 4i depend on circ#mst!nces, 5#t
sho#d !4!ys 5e !s short !s possi5e3 &orth minim!ists s!y th!t good &orth de2initions
cont!in no more th!n se8en so#rce to7ens, 4hich is 8ery di22ic#t to !chie8e in pr!ctice,
especi!y 4hen coding 2or oper!ting systems s#ch !s =indo4s3 )his recommend!tion
comes 2or se8er! re!sons3
"hort code 2r!gments !re e!sy to test !nd hence !re rei!5e
151
Code ,a&out
"hort code 2r!gments promote code re#se
"hort code is #nderst!nd!5e
62 yo# re#se code 4here8er possi5e, it c!n then 5e possi5e to m!7e m!Jor !rchitect#r!
ch!nges to ! so2t4!re s#5system 4itho#t introd#cing 5#gs ! o8er the rest o2 the
system3
"eader comments
$ne method 2or 4riting ! engthy descripti8e comment 2or ! &orth 4ord is to #se !
he!der 5oc73 )his is ! 5oc7 o2 comments J#st !5o8e the st!rt o2 the 4ord, 4hich
descri5es the 2#nction o2 the 4ord in det!i3 )his is norm!y det!i or description 4hich
4o#d not 2it 4e in the in0ine comments do4n the right h!nd side o2 the p!ge*
\ this word ...
\ ...
\ ...
: word1 \ a b -- c ; does ...
... \ ...
;
9ec!#se o2 the 4!y o#r doc#ment!tion toos 4or7, MPE p#ts these comments !2ter the
de2inition ine3 =h!t m!tters is to 5e consistent3
=e tend to #se he!der 5oc7s 5e2ore ! gro#p o2 4ords 2or design in2orm!tion th!t co8ers
the gro#p3
;ame and stack comment
)he 2irst ine o2 ! de2inition 4i consist o2 the st!rt o2 the de2inition 0 either ! coon : or
! "ODE, or !5e, etc3 !nd the n!me o2 the proced#re3 )his 4i then 5e 2oo4ed 5y the
st!c7 e22ect 2or the 4ord3 6n o#r st!nd!rd, st!c7 comments st!rt !t co#mn 17 (second t!5
stop)3
: WORD1 \ n1 -- n2 n3 ; description
... \ ...
;
: WORD2 ( n1 -- n2 ; description )
... \ comment
;
CODE WORD3 \ n1 -- n2 n3 ; description
...
END-CODE
)he :, etc3 4i st!rt !t the 8ery e2t0h!nd end o2 the ine3 )here 4i 5e one sp!ce
5et4een this !nd the n!me o2 the 4ord3
)he st!c7 comment !nd description 4i st!rt some 4!y !cross the ine 0 5#t 2#rther
to4!rds the e2t !nd the 4ord n!me th!n the in0ine comments3 %'E2E #I55
$5#$0S 8E $ S%$&/ &(77E1%3 6t is ! m!Jor sin i2 the st!c7 comment is
152
Code ,a&out
incorrect3 =ithin the st!c7 e22ect, e.ec#tion 4i 5e identi2ied 5y one o2 the recognised
m!r7s*
-- --- -->
)he 2irst o2 these is o#r st!nd!rd3 )he description is recommended, !s 2orm! so#rce0
sc!nning toos 4i oo7 2or this r!ther th!n the others3 62 it 5ecomes necess!ry to !so
doc#ment the ret#rn st!c7 e22ect, #se
R: a -- bc
"ome peope #se .. in p!ce o2 2or ret#rn st!c7 comments3 Ho4e8er, m!ny peope
#se F: to indic!te the 2o!ting point st!c7, so B* is consistent 4ith this3 62 yo# need
speci! !ddition! st!c7s yo# c!n e.tend the not!tion, e3g3 4ith S:, to indic!te these3 62
yo# need m#tipe st!c7 e22ects sep!r!te them 4ith ; ; ;, e3g3
: >R \ x -- ; R: -- x ; copy one item to r.stack
...
;
6t is good pr!ctice to 2oo4 the st!c7 e22ect 4ith ! short description o2 the !ction o2 the
4ord 0 !5o#t three or 2o#r 4ords*
: D* \ d1 d2 -- d3 ; double multiply
62 there is ! short description o2 the 4ord, it sho#d 5e sep!r!ted 2rom the st!c7 e22ect 5y
! semicoon (S) or other o58io#s ch!r!cter3 )his 4i disting#ish the description 2rom !
st!c7 e22ect consisting o2 descripti8e n!mes 2or the st!c7 items3 'sing ! st!nd!rd
semicoon, other 2orm! toos s#ch !s so#rce !n!ysers c!n correcty h!nde the so#rce
code !nd the comments3
Indenting and phrasing
)he 5ody o2 the 4ord 0 the 4ords it c!s, or the !ssem5er mnemonics it #ses 4i 5e
indented 2rom the e2t0h!nd end o2 the ine3 )his indent 4i 5e #ni2orm thro#gho#t the
2ie, !nd 4i norm!y 5e t4o sp!ces in MPE code, 5#t &orth 6nc3 !nd others o2ten #se
three3
E!ch ine o2 code in ! de2inition sho#d constit#te ! re!d!5e !nd me!ning2# phr!se3 62
yo# h!8e more th!n one phr!se on ! ine sep!r!te them 5y t4o sp!ces3 &orth sho#d not
5e !id o#t so 8ertic!y th!t e!ch ine is indi8id#!y me!ningess3 % singe phr!se 4i
consist o2 eno#gh code to per2orm some !ppropri!te p!rt o2 the !ppic!tion*
VAR @ 10 +
OVER 4 <
SWAP 3 + BILL +!
'nd of definition
%t the end o2 the de2inition, the 2in! 4ord, the semicoon or END"ODE 4i not 5e
indented3 )his ens#res th!t the end o2 the de2inition c!n 5e 2o#nd e!siy3 6t !so heps
4hen code is !dded to the end o2 ! 4ord, 5y !8oiding the possi5iity o2 h!8ing se8er!
semicoons !t or ne!r the end o2 the 4ord3
153
Code ,a&out
: WORD1 \ n1 n2 -- n3 ; function to ...
...
...
;
CODE WORD2 \ n1 n2 -- n3 ; function to ...
...
...
END-CODE
62 ! 4ord is to 5e m!de IMMEDIATE, the 4ord to m!7e it so sho#d !ppe!r J#st !2ter the
semicoon or END"ODE*
: WORD1 \ n1 n2 n3 ; function to ...
...
...
; IMMEDIATE
62 the 4ord 4ere to 5e p!ced on the ine 2oo4ing the end o2 the de2inition, tho#gh
eg!, there 4o#d 5e ! possi5iity o2 !nother 4ord 5eing inserted 5et4een the t4o, !nd
the 2irst 4ord then osing its immedi!te st!t#s3 "imi!ry, !n !ssignment o2 the !ction o2
! DEFERred 4ord to reso8e ! 2or4!rd re2erence sho#d !ppe!r on this ine
Comments
>e2initions sho#d 5e commented !s 4e !s possi5e3 6n ! te.t 2ie there is no e.c#se 2or
not h!8ing eno#gh room to 4rite comments, !nd so comments sho#d 5e #sed i5er!y3
6n ! de2inition, there sho#d 5e comments do4n the right0h!nd side o2 the p!ge, in
p!r!e 4ith the code3 )hese comments sho#d st!rt in ! #ni2orm co#mn, 4hich sho#d
!s 2!r !s possi5e 5e consistent thro#gho#t the 2ie3 )his co#mn sho#d 5e 2#rther to the
right th!n the st!rting co#mn 2or the st!c7 comment !nd short description, #s#!y !5o#t
h!2 4!y !cross the p!ge3 =e de2!#t to co#mn ,13
: WORD1 \ n1 n2 -- n3 ; function to ...
... \ get the pointer
... \ modify the address
;
Line comments !re 5est st!rted 4ith the ^ 4ord 0 comment to end o2 ine3 )his is in
pre2erence to the ( 4ord, 4hich m#st 5e termin!ted 4ith ! 53 )his !st is e!siy
2orgotten3 )hese comments sho#d not 5e on the st!c70det!i e8e, tho#gh this m!y 5e
!ppropri!te in cert!in c!ses3 )hey sho#d, ho4e8er, gi8e descripti8e in2orm!tion on the
st!te o2 the system !t th!t point 0 descri5ing the o8er! !ction o2 the ine o2 code, o2 the
phr!se3 Aeedess to s!y, comments sho#d !so 5e correct3
$n ! point o2 stye, it is 5etter i2 the editor inserts t!5s 5et4een the code !nd the
comment th!n ! series o2 sp!ces3 )his e!8es ess tidying0#p to do !2ter sm! ch!nges to
! ine o2 code3 6t !so m!7es the so#rce 2ie more comp!ct on disc !nd 2!ster to o!d,
!tho#gh gi8en the speed o2 modern des7top comp#ters !nd the si:e o2 their discs, this is
no4 o2 second!ry import!nce3
154
Code ,a&out
*efining words
>e2ining 4ords present ! speci! c!se o2 de2inition3 )his is 5ec!#se, !s the 4ord 5re!7s
do4n into t4o p!rts, more c!re sho#d 5e gi8en 5oth to indent!tion !nd to commenting*
: WORDN \ n1 -- ; -- n3 ; function to ...
CREATE \ defining portion
... \ lay down data
DOES> \ execution portion
... \ process data ...
;
)he "REATE !nd DOES' 4ords sho#d 5e indented to 5eo4 the n!me o2 the 4ord3 )he
code in the "REATE !nd DOES' portions sho#d then 5e indented 5y 2#rther sp!ces3
)he !yo#t o2 DOES' !nd ; !so !ppies to ;"ODE !nd END"ODE3 6t is !so o2ten
2o#nd #se2# to doc#ment the st!c7 !ction o2 the ree8!nt portion o2 the 4ord on the ine
4ith the "REATE !nd DOES' 4ords*
: WORDN \ n1 n2 -- ; -- n3 ; function to ...
CREATE \ n1 n2 -- ; defining portion
... \ lay down data
DOES> \ -- n3 ; execution portion
... \ process data ...
;
Control -tructure layout
Contro str#ct#res sho#d 5e !id o#t 2or e!se o2 #nderst!nding, !nd to e!siy spot
o8er!pping or incompete str#ct#res3 )o this end, indenting !nd the #se o2 m!ny ines
m!7es the !yo#t e!sy, especi!y 2or ine.perienced &orth progr!mmers3
Flags and limits
%s &orth #ses ! post2i. not!tion, the 2!g #sed to contro progr!m 2o4 is speci2ied
5e2ore the str#ct#re or test 4hich #ses it3 )he 2!g sho#d 5e identi2ied on the ine
immedi!tey preceding the test 4hich 4i #se it, !s sho#d oop imits*
VAR @ \ get flag
IF \ if set ...
...
THEN
VAR @ 0 \ make loop limits
DO \ for each ...
...
LOOP
VAR1 @ VAR2 @ AND \ this and this
VAR3 @ OR \ or this
IF
...
THEN
155
Code ,a&out
Indenting
&or e!se o2 re!ding, the st!rt !nd end 4ords o2 ! contro str#ct#re sho#d 5e p!ced on
ines 5y themse8es3 )his m!7es them e!sy to spot 0 2or presence or !5sence3 )he code
4ithin the str#ct#re sho#d then 5e indented 5y ! #ni2orm !mo#nt*
...
DO
...
LOOP
...
...
IF
...
ELSE
...
THEN
...
...
BEGIN
...
WHILE
...
REPEAT
...
...
CASE
... OF ... ... ENDOF \ case 1
... OF ... ENDOF \ case 2
... OF ... \ big case 3
...
ENDOF
... \ default
ENDCASE
...
%t the end o2 ! contro str#ct#re, the str#ct#re termin!tion 4ord 4i 5e 4itho#t
indent!tion !nd 5!c7 5eo4 the st!rt o2 the str#ct#re, ens#ring th!t st!rts !nd ends o2
str#ct#res !re 8ertic!y !igned, it is e!sy to see !n #n5!!nced str#ct#re or piece o2
code3 "ee !5o8e 2or e.!mpes3
-hort -tructures
62 the code 4ithin ! contro str#ct#re is 8ery short, then it is good pr!ctice to e!8e the
st!rt !nd end o2 the str#ct#re on one ine, 4ith the 5ody o2 the str#ct#re3 Ho4e8er, 4h!t
constit#tes ! short str#ct#re is 8ery s#5Jecti8e3
...
DO I . LOOP
Aote th!t there is more th!n one sp!ce 5et4een the DO !nd the I ., !nd !g!in to the
LOOP3 )his heps the code to ret!in phr!sing3
156
Code ,a&out
IG+e changed my mind
)he !5o8e !yo#t 2or contro str#ct#res 4!s de2ined in the !te 1/-0s 4hen 4e tr!ined !
!rge n#m5er o2 peope 4ith 8ery itte progr!mming e.perience3 =e 4ere te!ching
them &orth !s ! 2irst progr!mming !ng#!ge3 Ao4!d!ys, the m!Jority o2 the peope 4e
tr!in h!8e h!d some e.pos#re to progr!mming3 )e!ching ! K!8! progr!mmer the
me!ning o2 !n !ddress !nd 6I$ progr!mming c!n 5e ! 2rightening e.perience J#st !2ter
doing ! 5om50dispos! m!chineT
$8er the ye!rs, my coding stye h!s ch!nged, 2or the 5etter 6 hope3 6 h!8e !so 5een !5e
to 2oo4 the code prod#ced 5y se8er! good &orth progr!mmers o8er ! period o2 se8er!
ye!rs, !s they mo8e 2rom no8ice &orth progr!mmers to 8ery good &orth progr!mmers3
$nce ! progr!mmer 5ecomes 2#ent in &orth, he (!nd there !re 8ery 2e4 shes in
progr!mming, 5#t th!tLs ! sep!r!te topic) tends to 4rite onger de2initions3 )his is !
mist!7e, 5ec!#se code re#se goes do4n !nd ;c! 5y te.t editor< goes #p (! 5!ne o2 C
progr!mmers), e!ding to ess m!int!in!5e !nd ess modi2i!5e code3
P!rtic#!ry 2or IF ... ELSE ... THEN !nd DO ... LOOP str#ct#res, 6 no4
recommend th!t IF !nd DO !re !t the end o2 the ine th!t gener!tes the 2!g or imits3
... DO \ -- a b
...
LOOP
...
... IF \ -- c d
...
ELSE
...
THEN
)here !re t4o re!sons 2or this3 )he 2irst re!son is th!t 6 !m no4 4riting shorter 4ords,
!nd so 6 4!nt to see more 4ords on the screen !t the s!me time, !nd so 6 4!nt 2e4er
ines per 4ord 4itho#t s!cri2icing !yo#t3 )he second re!son is th!t 6 6now th!t IF
cons#mes ! 2!g !nd th!t DO cons#mes !n inde. !nd ! imit3 =h!t m!tters, 5oth 2or me
!nd 2or ess e.perienced progr!mmers, is to remem5er the st!c7 condition !t the
repetition o2 the oop str#ct#re or the entry to the condition! c!#se3 My th!n7s to Bic7
8!n Aorm!n 2or my introd#ction to (!nd his persistent promotion o2) this 2orm!t3
6ayout of code definitions
)he !yo#t o2 code de2initions 4i 5e sighty di22erent 2rom the !yo#t o2 high0e8e
de2initions3 &or ! st!rt, the !yo#t 4i 5e more 8ertic! th!n the corresponding high0
e8e code3 62 ! 4ord is 5eing de2ined, the top ine o2 the de2inition 4i re2ect th!t o2
!ny other 4ord 0 ie it 4i h!8e ! st!c7 comment !nd ! 5rie2 description3 62 ! !5e is
5eing de2ined, then there m!y not 5e ! st!c7 e22ect, 5#t there 4i sti 5e ! 5rie2
description o2 the 2#nction o2 the proced#re or s#50ro#tine3 )he code th!t then 2oo4s
m!y 5e 8ery 8ertic!, or m!y 5e phr!sed more*
CODE WORD1 \ n1 -- n2 ; word to ...
MOV AX, BX
ADD BX, # 03
XCHG BP, SP INC BP INC BP XCHG BP, SP
...
END-CODE
157
Code ,a&out
$2 co#rse, there 4i sti 5e penty o2 in0ine comments3
Constants9 4alues and 4ariables
Const!nts reF#ire !n inp#t 8!#e !s p!rt o2 their de2inition3 )his 8!#e sho#d !ppe!r !t
the e2t0h!nd end o2 the ine3 62 se8er! const!nts !re 5eing de2ined !t one time, the 4ord
"ONSTANT sho#d ine #p 8ertic!y, especi!y i2 the 8!#es correspond to items o2 the
s!me si:e, s#ch !s -I16I32 5it m!s7s3
6t is good pr!ctice to de2ine ! const!nts, 8!#es !nd 8!ri!5es in one p!ce in the 2ie, or
in one 2ie in the set3 62 ! 8!ri!5e or const!nt is ony #sed in one section o2 ! 2ie, o2
co#rse it m!y 5e de2ined in th!t section3 Ho4e8er, the !ppe!r!nce o2 s#ch 8!ri!5es m!y
indic!te !n #n4iingness to #se the &orth d!t! st!c7 5ec!#se it is getting too deep3 )his
is o2ten ! sign o2 5!dy 2!ctored code3
)hey ! reF#ire st!c7 commentsT )his is not J#st 5ec!#se the st!c7 comment is ! p!ce
to indic!te 4h!t d!t! type is 5eing ret#rned, 5#t !so 5ec!#se they need doc#ment!tion
too3
62 8!ri!5es !re to 5e pre0initi!ised to !nything other th!n :ero, the initi!is!tion
8!#e sho#d 2oo4 the de2inition o2 the 8!ri!5e*
VARIABLE BILL \ -- addr ; holds what he has
25 BILL !
VARIABLE BEN \ -- addr ; holds what he has
FLOWERPOT BEN !
2uffers
% 5#22er m!y 5e de2ined !nd reF#ire more th!n ! ce o2 diction!ry sp!ce3 )his sp!ce
m!y 5e pre0initi!ised, or it m!y 5e ! scr!tch !re!, or other4ise 2ied 5y the !ppic!tion3
)he 5#22er sho#d 5e de2ined !nd !ny pre0initi!is!tion sho#d immedi!tey 2oo4 its
de2inition*
CREATE BILL \ -- addr ; the ...
10 ALLOT \ for a hosted Forth in RAM
S this" BILL PLACE \ preset to this
62 yo# !re 4riting 2or 5oth hosted !nd em5edded systems, B%M05!sed 5#22ers c!n 5e
de2ined #sing BUFFER: ( :e6 ; addr 5, e3g3
#12 BUFFER: BILL \ -- addr
BUFFER: is de2ined in the dr!2t %A" cross compier propos!3 62 yo#r hosted system
does not pro8ide BUFFER: yo# c!n de2ine it 8ery e!siy !s*
: BUFFER: \ len -- ; -- addr ; create len-byte buffer
CREATE ALLOT
;
158
Code ,a&out
*ata Tables
% t!5e m!y 5e prede2ined 0 s#ch !s ! oo70#p t!5e3 )his 4i #s#!y 5e cre!ted in the
diction!ry, !nd 4i inc#de its d!t!3 )he import!nt point is consistency !nd e!se o2
re!ding*
CREATE TABLE \ -- addr ; bit-pattern table
1 C, 2 C, 4 C, 8 C, \ b0..b3
16 C, 32 C, 64 C, 128 C, \ b4..b7
Aote th!t the n#m5ers !nd the comm!s ine0#p3 )his m!7es re!ding e!sy3 Aote
ho4e8er th!t these !re 5it p!tterns3 )he more ped!ntic m!y pre2er the 2oo4ing*
CREATE TABLE \ -- addr ; bit-pattern table
$01 C, $02 C, $04 C, $08 C, \ b0..b3
$10 C, $20 C, $40 C, $80 C, \ b4..b7
Case @uestions
)he c!se o2 the 4ords #sed in ! &orth !ppic!tion is ! 8ery deic!te iss#e !s di22erent
progr!mmers h!8e di22erent pre2erences3 % MPE &orth systems !re c!se0insensiti8e,
!nd so the c!se #sed is ony ! recommend!tion, not ! reF#irement3
6t is recommended th!t o4er c!se 5e #sed thro#gho#t3 &irsty, this is e!sier to type, !nd
secondy it is e!sier to re!d3 'sing #pper c!se thro#gho#t is not recommended3
Ho4e8er, it m!y 5e 2o#nd th!t cert!in c!sses o2 4ords !re 5etter c!pit!ised3 )hese
might 5e contro str#ct#res or const!nts, or the n!me o2 the 4ord !s it is de2ined3 E!ch
org!nis!tion 4i 2ind !ny pre2erence !nd #se it3 %n import!nt point to remem5er 4ith
!ny decision m!de is to 5e consistent thro#gho#t ! so#rce code3 )he 2oo4ing
e.!mpes !re dei5er!tey in mi.ed c!se, !nd do not 2oo4 pre8io#s con8ention3
: WORD1 \ n1 n2 -- ; word does ...
... \ lower case code
...
;
: word2 \ n1 -- n2 ; word to ...
... IF \ lc code, UC structure
...
...
THEN
;
23 CONSTANT BILL \ n - avoids magic number
: word3 \ n1 -- ; function to ...
... \ lower case code
BILL + \ upper case constant
... \ lower case code
;
15%
Exercises
1% '(ercises
-tack operations
6n gener! these itte e.ercises !re 5est done 5y de!ing 4ith the 5ottom o2 the st!c7
2irst !nd reordering the top !2ter4!rds3
Exercise ?.?* >e2ine the 4ord @*)P in terms o2 st!c7 oper!tions on singe n#m5ers3
: 2DUP \ x1 x2 -- x1 x2 x1 x2
<your code>
;
Exercise ?.@* >e2ine NIP ( H, H# H# 5
Exercise ?.A* >e2ine TU"* ( H, H# H# H, H# 5
Exercise ?.B >e2ine the 4ord A*)P in terms o2 st!c7 oper!tions on singe !nd do#5e
items3
: 3DUP \ x1 x2 x3 -- x1 x2 x3 x1 x2 x3
<your code>
;
Exercise ?.C >e2ine the 4ord \DUP in terms o2 st!c7 oper!tions on singe !nd do#5e
items3
: 4DUP \ x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2 x3 x4
<your code>
;
Arithmetic
Exercise @.?* Ei8e &orth comm!nds th!t 4o#d print in decim! the !rgest 08e n#m5er
!nd the !rgest +8e n#m5er th!t c!n 5e hed !s signed 16 5it n#m5ers3
'int* )he he.!decim! represent!tion o2 these n#m5ers is 0-000 !nd 7&&& 2or ! 16 5it
&orth3
Exercise @.@* =o#d yo# e.pect the comm!nd seF#ence ,K+++ \ * . to gi8e the
correct !ns4er on ! 32 5it &orth !nd on ! 16 5it &orthD 62 not 4hy notD
Exercise @.A* Consider the e8!#!tion o2 the 2oo4ing e.pressions*
100 0 /
-10 4 /
-32768 -1 /
)he %A" &orth speci2ic!tion gi8es t4o preconditions 2or the di8ision oper!tion 2or
( 6, 6# 6_ 53 &irsty, the denomin!tor n2 m#st not 5e :ero, !nd secondy n1In2
m#st ie 4ithin the r!nge o2 signed singe0ce n#m5ers3 62 either o2 these conditions is
8io!ted, !n error condition e.ists, 5#t the speci2ic!tion does not te 4h!t 4i h!ppen in
s#ch c!ses3
161
Exercises
%re the pre0conditions 2or / ( 6, 6# 6_ 5 s!tis2ied in these e.pressionsD 62 so,
4h!t !re the 8!#es o2 n3D =o#d there 5e ! di22erence 5et4een the res#ts on 16 !nd 32
5it systemsD Ho4 4i the res#ts 8!ry 2or 2oored !nd symmetric di8isionD
Exercise @.B* >e2ine the 4ord FUN"# 4hich h!s the 2oo4ing speci2ic!tion*
FUNC2 a b c -- d
d = a + 7*(b+c)
Exercise @.C* Here !re the speci2ic!tions o2 some 2#nctions th!t c!n 5e coded in &orth
#sing st!nd!rd !rithmetic oper!tors !ong 4ith DUP !nd SWAP3 Edit their &orth
de2initions onto ! 2ie, compie it !nd test the de2initions3
FUNC5 x y -- z
z = x^2 + 5y
FUNC6 x y -- z
z = 3*x^2 + 2y + y^2
FUNC7 x y -- z
z = 2 + x + x^2 + y + y^2
FUNC8 a b c -- d
d = a^2 + b^2 + c^2
FUNC9 x y -- z
z = x^2 + 2*x*y + y^2
'int* this one m!y need ! 5it o2 !ter! thin7ing3 )he de2inition consists o2 J#st 3 &orth
4ordsT
Exercise @.D* >e2ine &orth 4ords 4ith the 2oo4ing speci2ic!tions3
FUNC10 x y -- z
z = x+xy
FUNC11 a b c -- a^2 b^2 c^2
E.pects 3 st!c7 items, remo8es them 2rom the st!c7, !nd rep!ces them 4ith their
sF#!res3
Exercise @.E* >e2ine 4ords O"TAL !nd BINAR$ 4hich 4i set the system to 5!se -
!nd 5!se 2 respecti8ey3 )ry them o#t doing some oct! !nd 5in!ry !rithmetic3 =h!t do
yo# e.pect the systemLs response 4i 5e to these comm!ndsD
HEX BASE @ .
OCTAL BASE @ .
BINARY BASE @ .
(62 yo# thin7 it 4i 5e to print 16, - !nd 2, thin7 !g!inT)
>e2ine ! 4ord .BASE th!t 4i print the c#rrent n#m5er 5!se in decim!3 .BASE sho#d
e!8e the n#m5er 5!se !s it 2inds it3
>e2ine ! 4ord .BIN th!t prints the top item on the st!c7 !s !n #nsigned 5in!ry n#m5er3
.BIN sho#d e!8e the n#m5er 5!se !s it 2inds it3
162
Exercises
Exercise @.F* )he 4ord .2 is present in ! &orth ! systems, 5#t c!n yo# de2ine yo#r
o4n 8ersion #sing the &orth 4ords descri5ed so 2!rD C! yo#r 8ersion M$.2 !nd test it
!s sho4n !5o8e3
'int* % so#tion c!n 5e o5t!ined #sing the 4ords
@ ! + OVER SWAP
%n !tern!ti8e so#tion c!n 5e o5t!ined #sing
@ ! + DUP ROT SWAP
Exercise @.G* >e2ine 8!ri!5es TEMP !nd PRESSURE !nd ! 4ord "HE"* 4ith the
2oo4ing speci2ic!tion3
-- flag
&!g is tr#e i2 the 8!#e stored in TEMP is ess th!n 700 !nd the 8!#e stored in
PRESSURE is 5et4een 1200 !nd 2200 inc#si8e3 M!7e s#re th!t yo#r de2inition o2
"HE"* prod#ces the 2oo4ing res#ts3
600 TEMP ! 1200 PRESSURE ! CHECK . ( -1 ok )
2200 PRESSURE ! CHECK . ( -1 ok }
2201 PRESSURE ! CHECK . ( 0 ok )
2200 PRESSURE ! 700 TEMP ! CHECK . ( 0 ok )
1199 PRESSURE ! -1 TEMP +! CHECK . ( 0 ok )
Exercise @.?H* >e2ine the 4ord TEST 4ith the 2oo4ing speci2ic!tion3
n -- flag
Le!8es ! tr#e 2!g i2 n U 50 or n V100, !nd e!8es ! 2!se 2!g other4ise3
Exercise @.??* >e2ine the 4ords '1 !nd &1 4ith the 2oo4ing specs3
>= \ n1 n2 -- flag
&!g is tr#e i2 n1 is gre!ter th!n or eF#! to n2
<= \ n1 n2 -- flag
&!g is tr#e i2 n1 is ess th!n or eF#! to n2 !nd 2!se other4ise3
Exercise @.?@* )r!ce the e.ec#tion o2 #+ ,+ MAX3
Code !nd test ! de2inition 2or MIN3 )his h!s the speci2ic!tion*
MIN n1 n2 -- n3
=here n3 is the signed minim#m o2 n1 !nd n23
163
Exercises
Exercise @.?A >e2ine 8ersions o2 MAX !nd MIN 4ith !n IF ... THEN constr#ct, i3e3,
4itho#t #sing !n ELSE3
%n IF constr#ct need not h!8e !n ELSE3 &or e.!mpe, consider ! possi5e de2inition 2or
the st!nd!rd 4ord ABS3 )his t!7es ! signed n#m5er 2rom the st!c7 !nd rep!ces it 4ith !
positi8e n#m5er o2 the s!me m!gnit#de, !s in*
100 ABS . <cr> 100 ok
-200 ABS . <cr> 200 ok
)he de2inition o2 ABS reF#ires ! 4ord 4e h!8e not introd#ced yet, 4hich is NE%ATE3 6t
J#st ch!nges the sign o2 the top st!c7 item3
: ABS ( n -- abs[n] )
DUP 0<
IF NEGATE THEN
;
Exercise @.?B* >e2ine 4ords to meet the 2oo4ing speci2ic!tions3
TEST1 n1 -- n2
If $n_1 > 100$
then $n_2 = 2 times n1
else n2 = n1 - 20
TEST2 n1 n2 -- n3
If n1 > n2
then n3 = 1000
else n3 = n1
Exercise @.?C* "#ppose the 8!ri!5es TEMP !nd HEATERSWIT"H h!8e 5een dec!red
!s p!rt o2 !n ind#stri! sim#!tion3 TEMP hods ! sim#!ted temper!t#re !nd HEATER
SWIT"H hods ! 8!#e th!t indic!tes 4hether ! sim#!ted he!ter is on or o223 Code !
4ord ST" (QQsim#!te temper!t#re ch!ngeOO) 4hich h!s the 2oo4ing spec3
62 the 8!#e hed in HEATERSWIT"H is non :ero, !dd 2 to the 8!#e hed in TEMP
other4ise s#5tr!ct 1 2rom the 8!#e hed in TEMP3
Exercise @.?D* >e2ine ! 4ord .B (QQprint 5ooe!nOO) 4hich remo8es the top st!c7 item
!nd prints QQtr#eOO i2 its 8!#e is non :ero !nd QQ2!seOO i2 its 8!#e is :ero3 )he 4ord c!n 5e
#sed i7e this*
5 6 < .B <cr> true ok
Aote th!t !tho#gh the de2inition o2 .B cont!ins !n IF constr#ct it does not need to
cont!in ! testT
164
Exercises
Exercise @.?E* "t#dies h!8e s#ggested th!t &orth !ppic!tions #se QQi2OO str#ct#res m#ch
ess 2reF#enty th!n C or P!sc!3 62 this is the c!se it is pro5!5y 5ec!#se &orth
enco#r!ges ! stye 4hich QQhidesOO decisions 4ithin other 4ords3 &or e.!mpe the
de2inition o2 ABS c!n 5e 4ritten 4itho#t !n IF, c!n yo# see ho4D
'int* )he de2inition is three 4ords ong, !nd the 4ord yo# need to m!7e the hidden
decision is MAX3
Exercise @.?F* % 8ery e!ry description o2 !n !gorithm 2or comp#ting ! m!them!tic!
res#t is E#cidOs method 2or comp#ting the gre!test common di8isor o2 t4o n#m5ers3
)his !gorithm is presented !t the st!rt o2 E#cid 5oo7 7, !ong 4ith ! proo2 th!t it 4i
!4!ys gener!te the correct res#t3
Bec! th!t the EC> o2 t4o 4hoe n#m5ers is the gre!test 4hoe n#m5er th!t c!n 5e
di8ided into 5oth o2 them 4ith no rem!inder3 "o the EC> o2 16 !nd 2, is - 2or e.!mpe3
6n E#cidOs time (!ro#nd 30093C3) n#m5ers 4ere re!soned !5o#t in terms o2 ines o2 !
cert!in ength3 6nste!d o2 #sing . to represent ! F#!ntity they 4o#d t!7 !5o#t ! str!ight
ine %93 )he ength o2 %9 4o#d represent the F#!ntity #nder disc#ssion3 Ei8e t4o
ines %9 !nd C>, e!ch !n e.!ct n#m5er o2 #nits in ength, the pro5em is to 2ind the
ongest ine th!t c!n 5e #sed to me!s#re 5oth %9 !nd C> e.!cty3 &or e.!mpe, gi8en
ines %9 !nd C> o2 engths 26 !nd 16 #nits, ! ine o2 - #nits 4i 2it into %9 three times
!nd into C> t4o times3 )h#s - 5ecomes the gre!test common ;me!s#re< o2 2, !nd 163
%n import!nt ide! !ssoci!ted 4ith common me!s#re c!me 2rom E#do.#s, ! p#pi o2
P!to !nd ! reno4ned m!them!tici!n !cti8e !ro#nd ,00 93C3 He noted th!t the gre!test
common me!s#re o2 ines %9 !nd C> is the s!me !s th!t o2 ines %9 !nd %9 + C>3 )o
see this, 4e 2irst re!son th!t the gre!test common me!s#re o2 %9 !nd C> m#st 5e !
common me!s#re o2 %9 !nd %9 + C>, 2or since it c!n me!s#re 5oth %9 !nd C> it c!n
me!s#re %9 + C>3 "econdy, 4e re!son th!t it m#st 5e the gre!test common me!s#re,
2or i2 there 4ere ! gre!ter common me!s#re 2or %9 !nd %9 + C>, this 4o#d me!s#re
%9, hence it 4o#d me!s#re the %9 p!rt o2 %9 + C>, !nd hence it 4o#d h!8e to 5e
!5e to me!s#re C> since it is ! me!s#re 2or %9 + C>, !nd th#s it 4o#d 5e ! common
me!s#re 2or %9 !nd C>, 4hich contr!dicts o#r !ssertion th!t it is gre!ter th!n the
gre!test common me!s#re o2 %9 !nd C>3
E#cid in8erted this3 Let E& 5e the s!me ength !s %9 + C>, !nd consider the ines
(n#m5ers) %9 !nd E&3 "#5tr!ct the sm!er 2rom the !rger (i3e3, %9 2rom E&) !nd 4e
o5t!in ! ine o2 ength C>3 Ao4 ines %9 !nd C> h!8e the s!me common me!s#re !s
ines %9 !nd E&3 )he import!nce o2 in8erting E#do.#sO proced#re is th!t it gi8es !
process th!t 4hen repe!ted, m#st 2inish, since 4e !re gener!ting p!irs o2 ines th!t !re
getting shorter 5y some #nits o2 ength !t e!ch st!ge3
)his s#ggests the 2oo4ing !gorithm, 4hich is ! sight simpi2ic!tion o2 th!t 2o#nd !t
the st!rt o2 E#cid 5oo7 73 )o 2ind the EC> o2 !ny t4o n#m5ers*
1) 'sing !ny #nit me!s#re dr!4 t4o ines 4hose me!s#res !re eF#! to the t4o n#m5ers
(e3g3, 2or n#m5ers 2, !nd 16 dr!4 ines 2, #nits !nd 16 #nits in ength)3
2) L!5e the !rger ine %9 !nd the sm!er C>3
,) "#5tr!ct C> 2rom the ength o2 %9 to gi8e ines C> !nd %9 0 C>3
165
Exercises
5) 62 these t4o ines !re eF#! in ength, this ength is the gre!test common me!s#re o2
the origin! t4o ines3 62 not t!7e C> !nd %9 M C> !s ! ne4 p!ir o2 ines 2or the ne.t
st!ge o2 the method3
6) Contin#e !t step 23
Code E#cidLs !gorithm in &orth, 4ith the 2oo4ing speci2ic!tion*
GCD x y -- z
: is the gre!test common di8isor o2 . !nd y3
'int* >e2ine ! 4ord ORDER 4hich remo8es t4o n#m5ers 2rom the st!c7 !nd rep!ces
them in the order, sm!er !rger3 'se ORDER 4ithin ! BE%IN ... WHILE ...
REPEAT oop3
Exercise @.?G* Code ! 8ersion o2 EC> #sing E#cidOs !gorithm !nd ! BE%IN ...
UNTIL oop3 Per2orm !t e!st the 2oo4ing tests on yo#r de2inition*
16 24 GCD .<cr> 8 ok
24 16 GCD . <cr> 8 ok
8 8 GCD .<cr> 8 ok
Exercise @.@H* )he com5ined eectric! resist!nce B o22ered 5y t4o resistors 4ith 8!#es
B1 !nd B2 connected in p!r!e is gi8en 5y*
R = {{R1 * R2} / {R1 + R2}}
>e2ine ! 4ord //RES 4ith the 2oo4ing spec*
//RES R1 R2 -- R
Le!8es B, the resist!nce o5t!ined 5y connecting B1 !nd B2 in p!r!e3
'int* )he 5est so#tion is three 4ords ong3
>e2ine ! 4ord ///RES 4hich c!c#!tes the 8!#e o2 three resistors connected in
p!r!e3
'int* )he 5est so#tion is t4o &orth 4ords ong !nd #ses //RES3
Exercise @.@?* MOD c!n 5e #sed to de2ine the gre!test common di8isor 2#nction3 Ei8en
!ny n#m5ers . !nd y 4e c!n o5t!in ne4 8!#es .L !nd yL 2rom*
x' = y
y' = x mod y
62 4e c!rry on gener!ting ne4 p!irs o2 n#m5ers i7e this #nti the y 8!#e is :ero, the
corresponding . 8!#e 4i 5e the gre!test common di8isor o2 the origin! . !nd y3 &or
166
Exercises
e.!mpe i2 the origin! 8!#es o2 . !nd y !re 2, !nd 16, 4e 4o#d get the 2oo4ing .
!nd y 8!#es d#ring the c!c#!tion*
. y Aotes
16 2, 16 mod 2, W 16, this 4i 5e the ne.t y 8!#e3
2, 16 2, mod 16 W -, this 4i 5e the ne.t y 8!#e3
16 - 16 mod - W 0, this 4i 5e the ne.t y 8!#e3
- 0 "ince y W 0 4e !re 2inished, res#t is -3
'sing the method i#str!ted here de2ine ! %"D 2#nction #sing ! BE%IN ...
WHILE ... REPEAT oop !nd the MOD 2#nction3 %"D sho#d remo8e t4o n#m5ers
2rom the st!c7 !nd e!8e their gre!test common di8isor3
Input9 output and loops
Exercise A.?* >e2ine ! 4ord X th!t 4!its 2or ! ch!r!cter to 5e inp#t !t the 7ey5o!rd, !nd
then o#tp#ts the ch!r!cter !nd its %"C66 code3 'sing <"HAR=, de2ine ! 4ord STAR th!t
o#tp#ts !n !steris73 STAR co#d 5e #sed !s 2oo4s*
STAR <cr> *ok
Exercise A.@* >e2ine ! 4ord %ES%? th!t re!ds ch!r!cters 2rom the 7ey5o!rd !nd 2or
e!ch 7ey entered disp!ys 5oth the ch!r!cter !nd its %"C66 code3 )ermin!te on recei8ing
! c!rri!ge ret#rn code3
>e2ine ! 4ord TEST# th!t re!ds ch!r!cters 2rom the 7ey5o!rd, ignores ! ch!r!cters
th!t !re not #pper c!se etters, !nd 2or #pper c!se etters con8erts % to 9, 9 to C, 333, a to
% !nd then o#tp#ts the res#ting codes to the screen3
'int* #se WITHIN to test 4hether ! ch!r!cter is !n #pper c!se etter3
>e2ine ! 4ord TEST_ th!t re!ds ch!r!cters 2rom the 7ey5o!rd, con8erts #pper c!se
ch!r!cters to o4er c!se, !nd o#tp#ts to the screen3
Exercise A.A* >e2ine ! 4ord E)ENS 4ith the 2oo4ing spec*
EVENS n --
Prints ! e8en n#m5ers 5et4een 0 !nd ]2n]3
'int* )he oop imit n is on the st!c7 4hen yo# enter E)ENS3
167
Exercises
Exercise A.B* >e2ine ! 8ersion o2 SPA"ES ( 6 5 c!ed M$SPA"ES th!t de!s
4ith the 0 c!se correcty3 i3e3, + M$SPA"ES sho#d print 0 sp!ces3 =h!t
4o#dIsho#d s#ch ! 4ord do i2 n is ess th!n 0D
Exercise A.C* 'sing the 4ord STAR, 4hich yo# c!n de2ine !s*
: STAR ( -- ) [CHAR] * EMIT ;
>e2ine ! 4ord STARS th!t t!7es ! n#m5er 2rom the st!c7 !nd prints th!t m!ny !steris7s3
&or e.!mpe*
5 STARS <cr> *****ok
7 STARS <cr> *******ok
Exercise A.D* 6n the 2oo4ing e.ercises m!7e #se o2 the 4ords STAR !nd STARS
de2ined in the pre8io#s e.ercise3
>e2ine ! 4ord RE"T th!t prints !n - 5y 5 rect!nge o2 !steris7s !s 2oo4s*
RECT <cr>
********
* *
* *
* *
********ok
'ints* )o 7eep the code oo7ing !s simpe !s possi5e #se the 4ords STAR !nd STARS
de2ined in the pre8io#s e.ercise, !nd de2ine !nd #se the 2oo4ing 4ords*
MAR%IN o#tp#t c!rri!ge ret#rnIine 2eed !nd 5 sp!ces3
HORIRONTAL o#tp#t ! m!rgin !nd - st!rs3
)ERTI"ALS print the 8ertic! sides o2 the rect!nge
Exercise A.E* >e2ine ! 4ord "HARA"TERS 4ith the 2oo4ing speci2ic!tion3
CHARACTERS n --
6np#t n ch!r!cters 2rom the 7ey5o!rd (4here nV0) !nd o#tp#t e!ch one to the
screen 5e2ore the ne.t is inp#t3
E.!mpe #s!ge co#d 5e*
6 CHARACTERS <cr> QWERTYok
168
Exercises
Exercise A.F* >e2ine ! 4ord SMALL 4ith the 2oo4ing spec3
SMALL n --
6np#t ch!r!cters 2rom the 7ey5o!rd, con8ert #pper c!se !ph!5etic ch!r!cters to
o4er c!se, !nd disp!y the ch!r!cters on the screen #nti !n %"C66 sp!ce is
recei8ed or n ch!r!cters h!8e 5een inp#t3
:emory
Exercise B.?* Ho4 do yo# s#ppose ALLOT is de2inedD
Ho4 do yo# s#ppose )ARIABLE is de2inedD
Exercise B.@* "#ppose 4e de2ine ! 16 5yte 5#22er 4ith*
CREATE BUFF1 16 ALLOT
>escri5e the e22ect o2 e.ec#ting
HEX 1234 BUFF1 C!
M!7e s#re yo# chec7 yo#r !ns4er 5y !ct#!y per2orming the oper!tion (in he.) !nd
o5ser8ing its e22ect on oc!tions 9'&&1 !nd 9'&&1 + 13 )he 4ord DUMP ( addr
:e6 5 is #s#!y !8!i!5e3
Exercise B.A* >e2ine yo# o4n 8ersion o2 DUMP3 C! it M$DUMP3 >onOt 4orry too
m#ch !5o#t the 2iner det!is i7e 2orm!tting the o#tp#t in co#mns !nd disp!ying the
%"C66 ch!r!cters3
>e2ine WDUMP 4hich t!7es the s!me !rg#ments !s DUMP 5#t disp!ys the 16 5it
contents o2 co#nt 4ords st!rting !t !ddr3
'int* 'se the contro str#ct#re
DO ... 2 +LOOP
!t .LOOP the top st!c7 item is remo8ed !nd !dded to the inde., so in this c!se the inde.
4i go #p in steps o2 23 )his 7ind o2 oop termin!tes 4hen the inde. re!ches or p!sses
the imit3
62 yo# !re #sing ! 32 5it &orth system de2ine LDUMP 4hich t!7es the s!me !rg#ments !s
DUMP 5#t disp!ys the 32 5it contents o2 co#nt 4ords st!rting !t !ddr3
Exercise B.B* 9ytes o2 d!t! !re compied 4ith "F3 =rite ! speci2ic!tion 2or this 4ord,
!nd sho4 ho4 yo# 4o#d #se it 4hen setting #p ! , 5yte t!5e c!ed NAME cont!ining
the %"C66 codes 2or QQKOO QQ$OO QQHOO !nd QQAOO3
"#ggest ho4 the 4ord QQcomm!OO is de2ined3
16%
Exercises
'int, the 4ords HERE !nd ALLOT 4i 5e #se2#3
Exercise B.C* "ho4 ho4 FILL ( addr :e6 3Mar 5 co#d 5e de2ined #sing
"MO)E, not !s ! 5oc7 mo8e, 5#t in the QQ4rong directionOO3 )hen #se FILL to de2ine the
4ords ERASE !nd BLAN*3 )he 4ords FILL, ERASE !nd BLAN* h!8e ! 5een
descri5ed e!rier3
Exercise B.D* Consider ! temper!t#re sensor connected 8i! !n % to > con8erter !nd
gi8ing re!dings th!t 8!ry 5et4een 0 !t 5 C !nd 255 !t 160 C3 %ss#ming th!t the
8!ri!tion in the re!ding is ine!r 4ith temper!t#re de2ine ! 4ord c!ed DE%REES th!t
4i con8ert ! temper!t#re 8!#e in degrees C to the eF#i8!ent % to > con8erter
re!ding3
Exercise B.E* >e2ine ! 4ord OFTEMPTABLE 4ith the 2oo4ing spec3
OF-TEMP-TABLE n -- t
t is the temp o2 eement n in the t!5e (0 UW n U 5)3
E.!mpe #s!ge*
2 OF-TEMP-TABLE . <cr> 3349 ok
Exercise B.F Aon ine!r temper!t#re con8ersion 8i! t!5e oo7#p !nd interpo!tion3
"#ppose ! temper!t#re sensor connected to !n % to > con8erter h!s 5een c!i5r!ted 4ith
the res#ts !s sho4n in the 2oo4ing t!5e3
600 12.36
1100 23.42
1600 33.49
2100 42.02
2600 50.10
=e consider ho4 to de2ine ! 4ord READIN%'DE% 4hich con8erts ! re!ding t!7en
2rom the con8erter to the eF#i8!ent temper!t#re3 &irst 4e see ho4 to do the con8ersion
5y h!nd, 4itho#t !ny p!rtic#!r re2erence to &orth3 "#ppose !n % to > re!ding o2 1507 is
recei8ed3 )his is 5et4een the 8!#es 1100 !nd 1600 in the t!5e, so the reF#ired
temper!t#re 4i 5e 5et4een 233,2 !nd 333,/3
)o estim!te the temper!t#re 4e #se ! techniF#e c!ed QQine!r interpo!tionOO3 )he
re!ding 8!#e 1507 is -13,` (,07I500) o2 the 4!y 5et4een t!5e 8!#es 1100 !nd 1600,
!nd 4ith ine!r interpo!tion 4e estim!te the corresponding temper!t#re to 5e -13,` o2
the 4!y 5et4een 233,2 !nd 333,/3
temp = 23.42 + {407 / 500} * ( 33.49 - 23.42 )
"ince 4e !re imiting o#rse8es to integer !rithmetic !nd temper!t#res !re gi8en to t4o
decim! p!ces o2 !cc#r!cy, 4e 4i sc!e the temper!t#res 5y ! 2!ctor o2 100 !nd hod
them in ! t!5e de2ined !s 2oo4s*
170
Exercises
CREATE TEMP-TABLE \ -- addr
1236 , 2342 , 3349 , 4202 , 5010 ,
Aote th!t 4e h!8e not 5othered to record the % to > re!dings in ! t!5e3 )his is 5ec!#se
they occ#r !t reg#!r inter8!s !nd the d!t! they pro8ide c!n e!siy 5e encoded in the
ogic o2 o#r progr!m3
=e 4i de2ine ! 4ord to re!d 8!#es 2rom the temper!t#re t!5e3 Go# 4ere !s7ed to
pro8ide this de2inition in the pre8io#s e.ercise3
Ao4 here is the st!rt o2 one possi5e 4!y to de2ine READIN%'DE%3
: READING->DEG ( n t )
\ convert a-d reading to scaled temperature
600 -
500 /MOD ( r q )
...
;
)o see 4h!t is h!ppening here, consider the e.ec#tion o2 the e.!mpe 4e too7 5e2ore*
1507 READING->DEG
)he 8!#es sho4n !s r !nd F in the comment th!t 2oo4s IM$> 4i then 5e rW,07 !nd
FW13 )he 8!#e o2 F tes #s th!t the reF#ired temp is 5et4een , OFTEMPTABLE !nd
# OFTEMPTABLE3 )he 8!#e o2 r tes #s th!t the reF#ired temp 4i 5e r 500ths o2
the 4!y 5et4een these t4o 8!#es3
Compete the de2inition o2 READIN%'DE% #sing the comments in the 2oo4ing
o#tine code3 Aote th!t in the comments t[F_ is #sed to represent the temp !t position F
o2 the temper!t#re t!5e (FW0 to ,)3
: READING->DEG ( n -- t )
\ convert a-d reading to scaled temperature
600 -
500 /MOD ( -- r q )
( -- r q q+1 )
( -- r t[q] t[q+1] )
( -- r t[q] t[q+1]-t[q] )
( -- t[q] {t[q+1]-t[q]}*r/500 )
( -- t[q]+{t[q+1]-t[q]}*r/500 )
;
Aote the #se o2 the TV 5r!c7ets in p!ce o2 the ( 5 4ithin the comment3 )his is 5ec!#se
the 5 is #sed to indic!te the end o2 the comment3 )he #se o2 the 5!c7s!sh comments
4o#d h!8e !8oided this pro5em3
171
Exercises
*efining words
Exercise C.?* >e2ine ! 4ord ."ONSTANT 4hich de2ines 4ords 4hich record ! 16 5it
8!#e !t compie time !nd !dd this 4ord to the 8!#e !t the top o2 the st!c7 !t r#n time3
E.!mpe #s!ge*
5 +CONSTANT PLUS5
10 +CONSTANT PLUS10
100 PLUS5 PLUS10 . <cr> 115 ok
Exercise C.@* Compete the 2oo4ing de2inition o2 9G)E"3
&or o#r ne.t e.!mpe, 4e cre!te ! de2ining 4ord B$TES 4hich c!n 5e #sed to set #p
t!5es o2 - 5it 8!#es3 E.!mpe #s!ge o2 B$TES is*
10 BYTES BTABLE1
20 BYTES BTABLE2
77 0 BTABLE1 C! ( store 77 in byte 0 of BTABLE1 )
40 1 BTABLE1 C! ( store 40 in byte 1 of BTABLE1 )
"o + BTABLE, ret#rns the !ddress o2 5yte 0 in BTABLE,, , BTABLE, ret#rns the
!ddress o2 5yte 1 in BTABLE,, etc3
'ints* Go# need to !dd J#st one 4ord o2 compie time !ction !nd J#st one 4ord o2 r#n
time !ction3
)he comment th!t 2oo4s DOES' sho4s 4h!t is on the st!c7 4hen the code 2oo4ing
DOES' commences e.ec#tion3
: BYTES
CREATE ...
DOES> ( -- index addr ) ... ;
Exercise C.A* Pro8ide de2initions 2or WITEMS !nd LITEMS 4hich c!n 5e #sed i7e
B$TES 5#t de2ines t!5es 4hose eements !re 16 !nd 32 5its 4ide3 &or e.!mpe ,+
WITEMS TABLE, 4o#d de2ine !n !rr!y o2 10 1605it items c!ed TABLE,3
Exercise C.B* %nother #se o2 "REATE ... DOES' is to de2ine the opcode c!sses 2or
!n !ssem5er3 )he simpest c!ss o2 opcodes 2or !n !ssem5er to h!nde !re those 4hich
h!8e ! 2i.ed opcode3 Here !re some s#ch opcodes 2or the -0-6 instr#ction set
Opcode Mnemonic
C3 RET
FA CLI
FB STI
9B WAIT
F0 LOCK
6n ! &orth !ssem5er e!ch o2 the mnemonics s#ch !s RET !nd "LI 4o#d 5e de2ined !s
! &orth 4ord3 =hen e.ec#ted these 4ords compie their !ssoci!ted 1 5yte opcode into
the ne.t 2ree 5yte o2 diction!ry memory3
172
Exercises
"#ppose the 4ord "LASS, is #sed to de2ine the gi8en instr#ctions3 's!ge 4i 5e*
HEX
C3 CLASS1 RET
FA CLASS1 CLI
...
)he compie time !ction 2or "LASS, is to compie the 1 5yte opcode into the ne.t 2ree
diction!ry oc!tion3 )he r#n time !ction is to retrie8e the opcode 2rom the p!r!meter
2ied !nd compie it into the ne.t 2ree 5yte o2 the diction!ry3 &or e.!mpe the !ction o2
RET is to compie the 5yte C3, 4hich is the opcode 2or the -0-6 BE) instr#ction3
Ao4 see i2 yo# c!n de2ine "LASS,3
:iscellaneous
Exercise D.?* "#ppose the 2oo4ing de2initions !re o!ded3
: TEST1 ." old version " ;
: TEST2 TEST1 ;
: TEST1 ." new version " ;
=h!t 4i 5e the o#tp#t gener!ted 5y*
TEST1 TEST2
173
Solutions to Exercises
23 -olutions to '(ercises
-tack operations
Solution ?.?* >e2ine the 4ord @*)P in terms o2 st!c7 oper!tions on singe n#m5ers3
: 2DUP \ x1 x2 -- x1 x2 x1 x2
OVER OVER
;
Exercise ?.@* >e2ine NIP ( H, H# H# 5
: nip \ x1 x2 - x2
swap drop
;
Solution ?.A* >e2ine TU"* ( H, H# H# H, H# 5
: tuck \ x1 x2 -- x2 x1 x2
swap over
;
Solution ?.B >e2ine the 4ord A*)P in terms o2 st!c7 oper!tions on singe !nd do#5e
items3
: 3DUP \ x1 x2 x3 -- x1 x2 x3 x1 x2 x3
dup 2over rot
;
Solution ?.C >e2ine the 4ord \DUP in terms o2 st!c7 oper!tions on singe !nd do#5e
items3
: 4DUP \ x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2 x3 x4
2over 2over
;
Arithmetic
Solution @.?* Ei8e &orth comm!nds th!t 4o#d print in decim! the !rgest 08e n#m5er
!nd the !rgest +8e n#m5er th!t c!n 5e hed !s signed 16 5it n#m5ers3
HEX -8000 DECIMAL .
HEX 7FFF DECIMAL .
Solution @.@* =o#d yo# e.pect the comm!nd seF#ence ,K+++ \ * . to gi8e the
correct !ns4er on ! 32 5it &orth !nd on ! 16 5it &orthD 62 not 4hy notD
Ao, 5ec!#se the QQcorrectOO res#t is 060000 4hich c!nnot 5e e.pressed !s ! 16 5it 2Os
compement n#m5er !nd so 2!is on ! 16 5it system3
Solution @.A* Consider the e8!#!tion o2 the 2oo4ing e.pressions*
100 0 /
n2=0 => fail
-10 4 /
Symmetric: n2<>0 => ok, result 2 in range
Floored : n2<>0 => ok, result 3 in range
175
Solutions to Exercises
-32768 -1 /
n2<>0 => ok, result = 32768, fail on 16 bit system.
Solution @.B* >e2ine the 4ord FUN"# 4hich h!s the 2oo4ing speci2ic!tion*
FUNC2 a b c -- d
d = a + 7*(b+c)
: FUNC2 \ a b c -- d
+ 7 * +
;
Solution @.C* Here !re the speci2ic!tions o2 some 2#nctions th!t c!n 5e coded in &orth
#sing st!nd!rd !rithmetic oper!tors !ong 4ith DUP !nd SWAP3 Edit their &orth
de2initions onto ! 2ie, compie it !nd test the de2initions3
FUNC5 x y -- z
z = x^2 + 5y
: FUNC5 \ x y - z
5 * SWAP DUP * +
;
FUNC6 x y -- z
z = 3*x^2 + 2y + y^2
: FUNC6 \ x y -- z
DUP DUP \ -- x y y y
* SWAP \ -- x y^2 y
2 * + \ -- x y^2+2y
SWAP DUP * \ -- y^2+2y x^2
3 * + \ -- z
;
FUNC7 x y -- z
z = 2 + x + x^2 + y + y^2
: FUNC7 \ x y - z
DUP DUP * + \ -- x y+y^2
SWAP \ -- y+y^2 x
DUP DUP * + \ -- y+y^2 x+x^2
+ 2+
;
FUNC8 a b c -- d
d = a^2 + b^2 + c^2
: FUNC8 \ x y -- z
DUP * \ -- a b c^2
SWAP DUP * \ -- a c^2 b^2
+ \ -- a b^2+c^2
SWAP DUP * \ -- b^2+c^2 a^2
+
;
FUNC9 x y -- z
z = x^2 + 2*x*y + y^2
Use x^2 + 2xy + y^2 = (x+y)*(x+y).
: FUNC9 \ x y -- z
176
Solutions to Exercises
+ DUP *
;
Solution @.D* >e2ine &orth 4ords 4ith the 2oo4ing speci2ic!tions3
FUNC10 x y -- z
z = x+xy
: FUNC10 \ x y z
OVER * +
;
FUNC11 a b c -- a^2 b^2 c^2
E.pects three st!c7 items, remo8es them 2rom the st!c7, !nd rep!ces them 4ith their
sF#!res3
: FUNC11 \ x y -- z
DUP * \ -- a b c^2
ROT DUP * \ -- b c^2 a^2
ROT DUP * \ -- c^2 a^2 b^2
ROT \ -- a^2 b^2 c^2
;
Solution @.E* >e2ine 4ords O"TAL !nd BINAR$ 4hich 4i set the system to 5!se -
!nd 5!se 2 respecti8ey3
: OCTAL ( -- ) 8 BASE ! ;
: BINARY ( -- ) 2 BASE ! ;
: .BASE \ --
BASE @ DUP DECIMAL . BASE !
;
: .BIN \ n --
BASE @ SWAP \ -- base n
BINARY U.
BASE !
;
Solution @.F* )he 4ord .2 is present in ! &orth ! systems, 5#t c!n yo# de2ine yo#r
o4n 8ersion #sing the &orth 4ords descri5ed so 2!rD C! yo#r 8ersion M$.2 !nd test it3
: MY+! \ n addr --
SWAP OVER @ + SWAP !
;
: MY+! \ n addr --
DUP @ ROT + SWAP !
;
Solution @.G* >e2ine 8!ri!5es TEMP !nd PRESSURE !nd ! 4ord "HE"* 4ith the
2oo4ing speci2ic!tion3
-- flag
177
Solutions to Exercises
&!g is tr#e i2 the 8!#e stored in TEMP is ess th!n 700 !nd the 8!#e stored in
PRESSURE is 5et4een 1200 !nd 2200 inc#si8e3 M!7e s#re th!t yo#r de2inition o2
"HE"* prod#ces the 2oo4ing res#ts3
600 TEMP ! 1200 PRESSURE ! CHECK . ( -1 ok )
2200 PRESSURE ! CHECK . ( -1 ok }
2201 PRESSURE ! CHECK . ( 0 ok )
2200 PRESSURE ! 700 TEMP ! CHECK . ( 0 ok )
1199 PRESSURE ! -1 TEMP +! CHECK . ( 0 ok )
"o#tions*
VARIABLE TEMP \ -- addr
VARIABLE PRESSURE \ -- addr
: CHECK \ -- flag
TEMP @ 700 < \ -- flag1
PRESSURE @ 1200 1201 WITHIN \ -- flag1 flag2
AND
;
%tern!ti8e so#tion*
: CHECK \ -- flag
TEMP @ 700 <
PRESSURE @ 1199 > \ -- flag1 flag2
PRESSURE @ 2201 < \ -- flag1 flag2 flag3
AND AND
;
Solution @.?H* >e2ine the 4ord TEST 4ith the 2oo4ing speci2ic!tion3
n -- flag
: TEST \ n - flag
\ Leaves a true flag if n < 50 or n >100, and leaves
\ a false flag otherwise.
DUP 50 < \ -- n flag1
SWAP 100 > \ -- flag1 flag2
OR
;
: TEST \ n -- flag
50 101 WITHIN 0=
;
Solution @.??* >e2ine the 4ords '1 !nd &1 4ith the 2oo4ing specs3
>= \ n1 n2 -- flag
&!g is tr#e i2 n1 is gre!ter th!n or eF#! to n2
<= \ n1 n2 -- flag
&!g is tr#e i2 n1 is ess th!n or eF#! to n2 !nd 2!se other4ise3
178
Solutions to Exercises
: >= ( n1 n2 -- flag ) < 0= ;
: <= ( n1 n2 -- flag ) > 0= ;
Solution @.?@* Code !nd tr!ce the e.ec#tion o2 #+ ,+ MAX, 4here MAX is de2ined !s*
: MAX \ n1 n2 - flag
2dup >
if drop else swap drop then
;
Go# m!y h!8e to per2orm the tr!ce m!n#!y, depending on the 2!ciities o2 yo#r &orth
system3 &or e.!mpe on !n optimised &orth, the 2oo4ing m!chine code m!y res#t3
dis max
MAX
( 0049EB70 3B5D00 ) CMP EBX, [EBP]
( 0049EB73 0F8D0B000000 ) JNL/GE 0049EB84
( 0049EB79 8B5D00 ) MOV EBX, [EBP]
( 0049EB7C 8D6D04 ) LEA EBP, [EBP+04]
( 0049EB7F E903000000 ) JMP 0049EB87
( 0049EB84 8D6D04 ) LEA EBP, [EBP+04]
( 0049EB87 C3 ) NEXT,
( 24 bytes, 7 instructions )
ok
2DUP -- 20 10 20 10
> -- 20 10 -1
IF (true) -- 20 10
DROP -- 20
THEN -- 20
Code !nd test ! de2inition 2or MIN3 )his h!s the speci2ic!tion*
MIN n1 n2 -- n3
=here n3 is the signed minim#m o2 n1 !nd n23
: MIN \ n1 n2 - flag
2dup <
if drop else swap drop then
;
Solution @.?A >e2ine 8ersions o2 MAX !nd MIN 4ith !n IF ... THEN constr#ct, i3e3,
4itho#t #sing !n ELSE3
: MAX \ n1 n2 -- flag
2DUP <
IF SWAP THEN
DROP
;
: MIN \ nl n2 -- flag
2DUP >
IF SWAP THEN
DROP
;
17%
Solutions to Exercises
Solution @.?B* >e2ine 4ords to meet the 2oo4ing speci2ic!tions3
TEST1 n1 -- n2
If $n_1 > 100$
then $n_2 = 2 times n1
else n2 = n1 - 20
TEST2 n1 n2 -- n3
If n1 > n2
then n3 = 1000
else n3 = n1
: TEST1 \ n1 -- n2
DUP 100 >
IF 2 * ELSE 20 - THEN ;
: TEST2 \ n1 n2 -- n3
OVER <
IF DROP 1000 THEN
;
Solution @.?C* "#ppose the 8!ri!5es TEMP !nd HEATERSWIT"H h!8e 5een dec!red
!s p!rt o2 !n ind#stri! sim#!tion3 TEMP hods ! sim#!ted temper!t#re !nd HEATER
SWIT"H hods ! 8!#e th!t indic!tes 4hether ! sim#!ted he!ter is on or o223 Code !
4ord ST" (QQsim#!te temper!t#re ch!ngeOO) 4hich h!s the 2oo4ing spec3
62 the 8!#e hed in HEATERSWIT"H is non :ero, !dd 2 to the 8!#e hed in TEMP
other4ise s#5tr!ct 1 2rom the 8!#e hed in TEMP3
: STC \ --
HEATER-SWITCH @
IF 2 ELSE -1 THEN
TEMP +!
;
Solution @.?D* >e2ine ! 4ord .B (QQprint 5ooe!nOO) 4hich remo8es the top st!c7 item
!nd prints QQtr#eOO i2 its 8!#e is non :ero !nd QQ2!seOO i2 its 8!#e is :ero3 )he 4ord c!n 5e
#sed i7e this*
5 6 < .B <cr> true ok
: .B \ flag --
IF ." true" ELSE ." false" THEN
;
Solution @.?E* )he de2inition o2 ABS c!n 5e 4ritten 4itho#t !n IF, c!n yo# see ho4D
: ABS \ n1 -- n2
DUP NEGATE MAX
;
180
Solutions to Exercises
Go# c!n !so de2ine ABS 4itho#t IF !nd 4ith simper oper!tions th!n MAX (4hich o2ten
cont!ins !n intern! 5r!nch)*
: abs
dup 0< tuck xor swap
;
Ho4e8er, th!t depends on 2s0compement !rithmetic !nd, on m!ny CP's, +& reF#ires
!n intern! 5r!nch3
Solution @.?F*
Code E#cidLs !gorithm in &orth, 4ith the 2oo4ing speci2ic!tion*
GCD x y -- z
: is the gre!test common di8isor o2 . !nd y3
While they are not equal
Arrange pair so smaller is first 16 24 8 16
Put copy of first after second. 16 24 16 8 16 8
Subtract the two rightmost 16 8 8 8
Endwhile
Delete the second number 8
)his c!n 5e coded in &orth !s*
: ORDER \ n1 n2 -- smaller larger
2DUP >
IF SWAP THEN
;
: GCD \ n1 n2 -- n3
BEGIN
2DUP <>
WHILE
ORDER OVER -
REPEAT
DROP
;
Solution @.?G* Code ! 8ersion o2 EC> #sing E#cidOs !gorithm !nd ! BE%IN ...
UNTIL oop3
: ORDER \ n1 n2 -- smaller larger
2DUP >
IF SWAP THEN
;
: GCD \ n1 n2 -- n3
BEGIN
ORDER OVER -
DUP 0=
UNTIL
DROP
181
Solutions to Exercises
;
Solution @.@H* )he com5ined eectric! resist!nce B o22ered 5y t4o resistors 4ith 8!#es
B1 !nd B2 connected in p!r!e is gi8en 5y*
R = {{R1 * R2} / {R1 + R2}}
>e2ine ! 4ord //RES 4ith the 2oo4ing spec*
//RES R1 R2 -- R
Le!8es B, the resist!nce o5t!ined 5y connecting B1 !nd B2 in p!r!e3
>e2ine ! 4ord ///RES 4hich c!c#!tes the 8!#e o2 three resistors connected in
p!r!e3
: //RES ( R1 R2 -- R ) 2DUP + */ ;
: ///RES ( R1 R2 R3 -- R ) //RES //RES ;
Solution @.@?* >e2ine ! %"D 2#nction #sing ! BE%IN ... WHILE ... REPEAT
oop !nd the MOD 2#nction3 %"D sho#d remo8e t4o n#m5ers 2rom the st!c7 !nd e!8e
their gre!test common di8isor3
: GCD \ x y -- z ; z is the gcd of x and y
BEGIN ( -- x y )
DUP ( -- x y y )
WHILE ( -- x y )
SWAP OVER ( -- y x y )
MOD ( -- y mod )
REPEAT
DROP
;
Input9 output and loops
Solution A.?* >e2ine ! 4ord X th!t 4!its 2or ! ch!r!cter to 5e inp#t !t the 7ey5o!rd, !nd
then o#tp#ts the ch!r!cter !nd its %"C66 code3 'sing <"HAR=, de2ine ! 4ord STAR th!t
o#tp#ts !n !steris73 STAR co#d 5e #sed !s 2oo4s*
STAR <cr> *ok
: X \ --
\ Wait for char then output char and its ASCII code
KEY DUP EMIT .
;
: STAR \ --
[CHAR] * EMIT
;
182
Solutions to Exercises
Solution A.@* >e2ine ! 4ord TEST, th!t re!ds ch!r!cters 2rom the 7ey5o!rd !nd 2or
e!ch 7ey entered disp!ys 5oth the ch!r!cter !nd its %"C66 code3 )ermin!te on recei8ing
! c!rri!ge ret#rn code3
: TEST2 \ --
BEGIN
KEY DUP 13 <>
WHILE
DUP EMIT .
REPEAT
DROP
;
>e2ine ! 4ord TEST# th!t re!ds ch!r!cters 2rom the 7ey5o!rd, ignores ! ch!r!cters
th!t !re not #pper c!se etters, !nd 2or #pper c!se etters con8erts % to 9, 9 to C, 333, a to
% !nd then o#tp#ts the res#ting codes to the screen3
: TEST2 \ --
BEGIN
KEY DUP
[CHAR] A [CHAR] Z 1 + WITHIN IF ( upper case )
DUP [CHAR] Z = IF ( Z code )
DROP [CHAR] A
ELSE ( not Z code)
1 +
THEN
EMIT
ELSE
DROP
THEN
REPEAT
;
>e2ine ! 4ord TEST_ th!t re!ds ch!r!cters 2rom the 7ey5o!rd, con8erts #pper c!se
ch!r!cters to o4er c!se, !nd o#tp#ts to the screen3
CHAR a CHAR A - CONSTANT CASE-SHIFT
: TEST3 \ --
BEGIN
KEY DUP 13 <>
WHILE
DUP [CHAR] A [CHAR] Z 1+ WITHIN
IF CASE-SHIFT + THEN
EMIT
REPEAT
;
Solution A.A* >e2ine ! 4ord E)ENS 4ith the 2oo4ing spec*
EVENS n --
Prints ! e8en n#m5ers 5et4een 0 !nd 2n3
EVENS ( n -- )
183
Solutions to Exercises
0 DO I 2 * . LOOP
;
Solution A.B* >e2ine ! 8ersion o2 SPA"ES ( 6 5 c!ed M$SPA"ES th!t de!s
4ith the 0 c!se correcty3 i3e3, + M$SPA"ES sho#d print 0 sp!ces3 =h!t
4o#dIsho#d s#ch ! 4ord do i2 n is ess th!n 0D
: MY-SPACES \ n -- ; print n spaces
DUP IF
0 DO SPACE LOOP
ELSE
DROP
THEN
;
: MY-SPACES \ +n -- ; print n spaces
0 MAX 0
?DO SPACE LOOP
;
Solution A.C* 'sing the 4ord STAR, 4hich yo# c!n de2ine !s*
: STAR ( -- ) [CHAR] * EMIT ;
>e2ine ! 4ord STARS th!t t!7es ! n#m5er 2rom the st!c7 !nd prints th!t m!ny !steris7s3
: STARS ( n -- ) 0 ?DO STAR LOOP ;
Solution A.D* 6n the 2oo4ing e.ercises m!7e #se o2 the 4ords STAR !nd STARS
de2ined in the pre8io#s e.ercise3
>e2ine ! 4ord RE"T th!t prints !n - 5y 5 rect!nge o2 !steris7s !s 2oo4s*
RECT <cr>
********
* *
* *
* *
********ok
: MARGIN ( -- ) CR 5 SPACES ;
: HORIZONTAL ( -- ) MARGIN 8 STARS ;
: VERTICALS ( -- )
3 0
DO MARGIN STAR 6 SPACES STAR LOOP
;
: RECT ( -- ) HORIZONTAL VERTICALS HORIZONTAL ;
Solution A.E* >e2ine ! 4ord "HARA"TERS 4ith the 2oo4ing speci2ic!tion3
CHARACTERS n --
184
Solutions to Exercises
6np#t n ch!r!cters 2rom the 7ey5o!rd (4here nV0) !nd o#tp#t e!ch one to the
screen 5e2ore the ne.t is inp#t3
: CHARACTERS \ n --
0 DO KEY EMIT LOOP ;
Solution A.F* >e2ine ! 4ord SMALL 4ith the 2oo4ing spec3
SMALL n --
6np#t ch!r!cters 2rom the 7ey5o!rd, con8ert #pper c!se !ph!5etic ch!r!cters to
o4er c!se, !nd disp!y the ch!r!cters on the screen #nti !n %"C66 sp!ce is
recei8ed or n ch!r!cters h!8e 5een inp#t3
CHAR a CHAR A - CONSTANT CASE-SHIFT
: SMALL \ n --
0 DO
KEY DUP 13 =
IF DROP LEAVE THEN
DUP [CHAR] A [CHAR] Z 1 + WITHIN
IF CASE-SHIFT + THEN
EMIT
LOOP
;
:emory
Solution B.?* Ho4 do yo# s#ppose ALLOT is de2inedD
Ho4 do yo# s#ppose )ARIABLE is de2inedD M!ny systems cont!in ! 8!ri!5e DP
4hich cont!ins the !ddress o2 the ne.t 2ree sp!ce in the diction!ry3
: ALLOT ( n -- ) DP +! ;
: VARIABLE ( -- ; -- addr ) CREATE 1 CELLS ALLOT ;
Solution B.@* "#ppose 4e de2ine ! 16 5yte 5#22er 4ith*
CREATE BUFF1 16 ALLOT
>escri5e the e22ect o2 e.ec#ting
HEX 1234 BUFF1 C!
He. 8!#e 3, is stored !t the 5yte !ddress BUFF,3 )he 2oo4ing 5ytes !re not ch!nged3
)he top - 5its in the 8!#e 123, !re ignored, ony the o4 - 5its !re #sed3
Solution B.A* >e2ine yo# o4n 8ersion o2 DUMP3 C! it "DUMP3
>e2ine WDUMP 4hich t!7es the s!me !rg#ments !s DUMP 5#t disp!ys the 16 5it
contents o2 co#nt 4ords st!rting !t !ddr3
: CDUMP \ addr n --
0 DO
185
Solutions to Exercises
DUP I + C@ .
LOOP
DROP
;
: WDUMP \ addr n --
0 DO
DUP I + W@ U. \ use @ on 16 bit Forths
2 +LOOP
DROP
;
62 yo# !re #sing ! 32 5it &orth system de2ine LDUMP 4hich t!7es the s!me !rg#ments !s
DUMP 5#t disp!ys the 32 5it contents o2 co#nt 4ords st!rting !t !ddr3
: LDUMP \ addr n --
0 DO
DUP I + @ U.
4 +LOOP
DROP
;
&#rther impro8ements c!n 5e m!de 5y #sing (DO r!ther th!n DO (4hy) !nd 5y #sing 3B
to pro8ide 2i.ed04idth o#tp#t3
Solution B.B* 9ytes o2 d!t! !re compied 4ith "F3 =rite ! speci2ic!tion 2or this 4ord,
!nd sho4 ho4 yo# 4o#d #se it 4hen setting #p ! , 5yte t!5e c!ed NAME cont!ining
the %"C66 codes 2or QQKOO QQ$OO QQHOO !nd QQAOO3
"#ggest ho4 the 4ord QQcomm!OO is de2ined3
ALLOT c I
%ot 1 5yte o2 sp!ce !nd store c in the oc!tion th#s reser8ed3
CREATE NAME \ -- addr
CHAR J C, CHAR O C, CHAR H C, CHAR N C,
Solution B.C* "ho4 ho4 FILL ( addr :e6 3Mar 5 co#d 5e de2ined #sing
"MO)E, not !s ! 5oc7 mo8e, 5#t in the QQ4rong directionOO3 )hen #se FILL to de2ine the
4ords ERASE !nd BLAN*3 )he 4ords FILL, ERASE !nd BLAN* h!8e ! 5een
descri5ed e!rier3
: FILL \ addr n byte --
ROT ( n byte addr )
SWAP ( n addr byte )
OVER ( n addr byte addr )
C! ( n addr )
DUP 1 + ( n addr addr+l )
ROT 1 CMOVE
;
: ERASE ( addr n -- ) 0 FILL ;
: BLANK ( addr n -- ) BL FILL ;
186
Solutions to Exercises
Solution B.D* Consider ! temper!t#re sensor connected 8i! !n % to > con8erter !nd
gi8ing re!dings th!t 8!ry 5et4een 0 !t 5 C !nd 255 !t 160 C3 %ss#ming the 8!ri!tion in
the re!ding is ine!r 4ith temper!t#re de2ine ! 4ord c!ed DE%REES th!t 4i con8ert !
temper!t#re 8!#e in degrees C to the eF#i8!ent % to > con8erter re!ding3
: DEGREES \ y -- x ; convert y to machine units
5 - 255 155 */
;
Solution B.E* >e2ine ! 4ord OFTEMPTABLE 4ith the 2oo4ing spec3
OF-TEMP-TABLE n -- t
t is the temp o2 eement n in the t!5e (0 UW n U 5)3
: OF-TEMP-TABLE ( n -- t )
CELLS TEMP-TABLE + @
;
Solution B.F READIN%'DE%
: READING->DEG ( n -- t )
\ convert a-d reading to scaled temperature
600 -
500 /MOD ( r q )
DUP 1+ ( r q q+1 )
OF-TEMP-TABLE SWAP
OF-TEMP-TABLE SWAP ( r t[q] t[q+1] )
OVER - ( r t[q] t[q+1]-t[q] )
ROT 500 */ ( t[q] {t[q+1]-t[q]}*r/500 )
+ ( t[q]+{t[q+1]-t[q]}*r/500 )
;
*efining words
Solution C.?* >e2ine ! 4ord ."ONSTANT 4hich de2ines 4ords 4hich record ! 16 5it
8!#e !t compie time !nd !dd this 4ord to the 8!#e !t the top o2 the st!c7 !t r#n time3
E.!mpe #s!ge*
5 +CONSTANT PLUS5
10 +CONSTANT PLUS10
100 PLUS5 PLUS10 . <cr> 115 ok
: +CONSTANT \ n -- ; a - a+n
CREATE
,
DOES>
@ +
;
187
Solutions to Exercises
Solution C.@* Compete the 2oo4ing de2inition o2 B$TES3
&or o#r ne.t e.!mpe, 4e cre!te ! de2ining 4ord B$TES 4hich c!n 5e #sed to set #p
t!5es o2 - 5it 8!#es3 E.!mpe #s!ge o2 B$TES is*
10 BYTES BTABLE1
20 BYTES BTABLE2
77 0 BTABLE1 C! ( store 77 in byte 0 of BTABLE1 )
40 1 BTABLE1 C! ( store 40 in byte 1 of BTABLE1 )
"o + BTABLE, ret#rns the !ddress o2 5yte 0 in BTABLE,, , BTABLE, ret#rns the
!ddress o2 5yte 1 in BTABLE,, etc3
: BYTES \ +n -- ; addr - addr+n
CREATE ALLOT DOES> +
;
Solution C.A* Pro8ide de2initions 2or WITEMS !nd LITEMS 4hich c!n 5e #sed i7e
B$TES 5#t de2ines t!5es 4hose eements !re 16 !nd 32 5its 4ide3 &or e.!mpe ,+
WITEMS TABLE, 4o#d de2ine !n !rr!y o2 10 1605it items c!ed TABLE,3
: WITEMS \ +n -- ; addr - addr+2n
CREATE 2* ALLOT DOES> SWAP 2* +
;
: LITEMS \ +n -- ; addr - addr+4n
CREATE ALLOT DOES> SWAP 4 * +
;
Solution C.B* %nother #se o2 "REATE ... DOES' is to de2ine the opcode c!sses 2or
!n !ssem5er3 )he simpest c!ss o2 opcodes 2or !n !ssem5er to h!nde !re those 4hich
h!8e ! 2i.ed opcode3 Here !re some s#ch opcodes 2or the -0-6 instr#ction set
Opcode Mnemonic
C3 RET
FA CLI
FB STI
9B WAIT
F0 LOCK
6n ! &orth !ssem5er e!ch o2 the mnemonics s#ch !s RET !nd "LI 4o#d 5e de2ined !s
! &orth 4ord3 =hen e.ec#ted these 4ords compie their !ssoci!ted 1 5yte opcode into
the ne.t 2ree 5yte o2 diction!ry memory3
"#ppose the 4ord "LASS, is #sed to de2ine the gi8en instr#ctions3 's!ge 4i 5e*
HEX
C3 CLASS1 RET
FA CLASS1 CLI
...
188
Solutions to Exercises
>e2ine "LASS,3
: CLASS1
CREATE
C,
DOES>
C@ C,
;
Aote3 )his de2inition 4o#d 5e 2or !n !ssem5er 4hich !ssem5ed code into &orthLs
memory sp!ce3 Modern &orth systems o2ten !ssem5e code into ! di22erent !re! o2
memory to conser8e the &orth memory sp!ce3 )he de2inition o2 "LASS, 4o#d then 5e
sighty di22erent3 )he "F in the r#n time !ction 4o#d 5e rep!ced 5y ! non st!nd!rd
4ord to compie the opcode into the ne.t 2ree 5yte in the code !re!3
:iscellaneous
Solution D.?* "#ppose the 2oo4ing de2initions !re o!ded3
: TEST1 ." old version " ;
: TEST2 TEST1 ;
: TEST1 ." new version " ;
=h!t 4i 5e the o#tp#t gener!ted 5y*
TEST1 TEST2
TEST1 TEST2 <enter> new version old version
18%
Adopting and managing Forth
21 Adopting and managing Forth
)his F#estion !nd response 4!s posted on the comp3!ng32orth ne4sgro#p !nd e.presses
m!ny o2 the concerns o2 potenti! #sers, p#s some typic! responses 2rom #sers3
>The main thing I'm trying to get a better idea of here:
>In what cases should Forth be seriously considered?
My opinion:
1. Limited memory.
2. Lack of need for certain language-pervasive features (garbage
collection, strong typing).
3. Management willingness to train people rather than expecting
them to hit the ground running (this is actually a fundamental
software engineering principle, but it's especially important to
Forth if the reason discussed in #4 is true in your case, and can
be important due to the scarcity of pre-trained Forth
programmers).
4. The problem being solved has its own well-understood language
and terminology, so that Forth can be used to create a computer
language which resembles the problem's description language.
5. The problem being solved is not well understood, but can be
explored interactively (for example, a hardware component for
which a controller is being written).
6 s!8ed this post !s it r!ises so m!ny iss#es3 )he rest o2 this ch!pter is !n !ttempt to pic7
o#t some !ns4ers !nd e.p!nsions on the points r!ised here3 %p!rt 2rom disc#ssing the
5ene2its (!nd perh!ps some imit!tions) o2 &orth, 6 !so 4!nt to indic!te ho4 to se
&orth into !n en8ironment th!t is possi5y resist!nt to ch!nge3
)he essence o2 4h!t m!7es &orth gre!t is inter!cti8ity !nd e.tensi5iity in ! sm!
p!c7!ge3 % p!rtic#!r di22ic#ty in t!7ing to CIC++ progr!mmers 4ho h!8e not
e.perienced tr#e inter!cti8ity or e.tensi5iity is th!t the progr!mmers donLt 7no4 th!t
they might need inter!cti8ity or e.tensi5iity3
Interacti+ity and e(ploration
Em5edded systems !re o2ten h!rd to de5#g 4itho#t inter!cti8ity3 6n this en8ironment,
the !5iity to test ;5ottom #p< m!7es ! signi2ic!nt contri5#tion to progr!m rei!5iity,
eimin!ting the coection o2 h!c7s !nd 7#ges reF#ired !t higher !yers to o8ercome
imit!tions !t o4er e8es3 % second!ry 5ene2it is sm!er code3
6nter!cti8ity c!n rep!ce ! !rge coection o2 e.pensi8e de5#gging toos3 =e once 4ere
!s7ed to 2ind ! pro5em in ! 5!n7 note sorting m!chine3 )he comp!nyLs engineers h!d
spent t4o 4ee7s 4ith in0circ#it em#!tors !nd their non0inter!cti8e de8eopment system3
=e inst!ed ! simpe &orth system in EPB$M J#st #sing the seri! ine, CP' !nd
memory !nd st!rted in8estig!ting3 =e 4rote ! 8ery simpe oop th!t poed !n 6I$
de8ice #nti ! 7ey 4!s pressed3
1%1
Adopting and managing Forth
VARIABLE ADDRESS
: T \ --
begin adress @ c@ drop key? until
key drop
;
B#nning this 4ord !nd #sing ! simpe oscioscope pro5e re8e!ed th!t there 4!s ! sm!
gitch in one o2 the !ddress decoders3 )he in0circ#it em#!tor pre8io#sy #sed h!d
sighty di22erent timing 4hich mo8ed the pro5em ese4here3 % F#ic7 2i. !nd the
pro5em h!d gone3 %2ter 2itting the &orth (one ho#r) the pro5em 4!s 2i.ed in ,0
min#tes3
6nter!cti8ity pro8ides toos 2or r!pid de5#gging !nd 2oc#ssing on the correct iss#es3 Go#
h!8e to e.perience it to 5eie8e it3
6n ! des7top PC en8ironment, once yo# !re in ! p!ce 4here ! c!nned i5r!ry (=indo4s
>LL, Lin#. sh!red i5r!ry) c!nnot 2i. yo#r pro5em, yo# !re 2!ced 4ith #nderst!nding
the oper!ting system %P63 >espite the 5est e22orts o2 ! concerned, %P6 doc#ment!tion
is !0to0o2ten incompete !nd sometimes J#st 4rong3 $per!ting system 5#gs do e.ist3
6nter!cti8e e.por!tion in the PC en8ironment is m#ch 2!ster 2or the s!me re!sons !s in
the em5edded en8ironment3 % modern &orth 2or =indo4s c!n pro8ide ! 8ery rich
de5#gging en8ironment, not ony 2or &orth progr!ms, 5#t !so 2or de5#gging >LLs3
E.por!tion (#n2ort#n!tey c!ed ;p!ying< 5y 2!r too m!ny engineers) is ! 8it! p!rt o2
prod#cing 5etter systems3 6n !n #n2!mii!r 4ord, se!rching 2or 5etter techniF#es !nd
!gorithms p!ys 5ig di8idends3 6nter!cti8ity pro8ides toos to do this3
'(tensibility and notation
6n m!ny o2 the Jo5s 6Lm in8o8ed 4ith, 6 4or7 4ith eectronic !nd mech!nic! engineers
!nd 5om5 dispos! o22icers on em5edded systems, or 4ith constr#ction engineers, 8ideo
peope or !m5#!nce cre4s on des7top PCs3 )hey ! h!8e their o4n J!rgon !nd
terminoogy3
&orthLs !5iity to pro8ide ! !ng#!ge t#ned to the 4!y end0#sers thin7, p#s itLs !5iity to
pro8ide r!pid prototyping, en!5es me to #se code to t!7 to them !5o#t 4h!t they re!y
4!nt, !nd then to pro8ide the 2!ciities they need in the 2in! !ppic!tion3
)he ;spir! i2ecyce< !ppro!ch th!t is so common enco#r!ges this !ppro!ch3 =e simpy
#se e.tensi5iity !nd not!tion to impro8e the speed !t 4hich e!ch t#rn o2 the spir! is
per2ormed3
6imited memory
&orth enco#r!ges the #se o2 sm! de2initions, i2 2or no other re!son th!n th!t h!8ing too
m!ny items on the st!c7 m!7es ! de2inition h!rd to #nderst!nd !nd di22ic#t to m!int!in3
)he &orth e.ec#tion mode me!ns th!t !ddition! 4ords do not cost m#ch !t e.ec#tion
time, !nd modern &orth compier technoogy c!n e8en eimin!te th!t 5y inining sm!
de2initions3
1%2
Adopting and managing Forth
"m! de2initions !re e!sy to re#se !nd e!ch re#se s!8es memory3 )he em5edded
Po4erAet )CPI6P st!c7 is considered 5y one comp!ny to 5e !t e!st h!2 the si:e o2 !ny
other #nmodi2ied commerci! st!c73 "o m#ch so, th!t it 4i 2it in the 5oot B$M o2 !
c#stom CP' 4ith !n open &orth system3
)his is not J#st ! tr!it o2 sm! sc!e em5edded systems3 6n the mo5ie phone !ren!, one
comp!ny s!8ed 30` o2 their B$M sp!ce 5y con8erting the g!mes to ! c#stom &orth3
62 yo# !re dei8ering code eectronic!y 2or remote #pd!tes, the cost o2 dei8ery m!y 5e
domin!ted 5y phone 5is or on0ine costs3 )his is !n incre!singy common reF#irement3
6t m!y not seem m#ch !t e!ch #po!d, 5#t 4hen yo# !re #pd!ting tho#s!nds o2 #nits, it
is not #ncommon to h!8e to tr!ns2er se8er! gig!5ytes to #pd!te ! #nits3 Aot ! #nits
!re connected 5y 2i.ed ines or 5ro!d5!nd connections3 )he to7enised &orth #sed 5y
E#rop!yLs $pen )ermin! %rchitect#re 4!s estim!ted to p!y 2or itse2 2or ony one
#pd!te per ye!r3
6n the des7top en8ironment, o4 memory 2ootprint c!n h!8e ! s#rprising imp!ct on
per2orm!nce3 >espite the h#ge !mo#nt o2 memory th!t is commony 2itted to des7top
PCs, 2irst !nd second e8e c!che is 8ery restricted3 Commony, the di22erence 5et4een
CP' !nd m!in memory speeds is !5o#t 10*13 $n des7top PCs, the r!tio c!n 5e 100*13
=hen ! &orth !ppic!tion c!n 2it entirey into c!che, e8en !n od02!shioned thre!ded
&orth impement!tion c!n r#n 2!ster th!n ! !rge compied !ppic!tion3 )his h!s 5een
o5ser8ed !t "#n Microsystems3 )he tr!deo22s 5et4een !ppic!tion per2orm!nce,
interpret!tion !nd memoryICP' 5!nd4idths h!8e 5een e.pored in some det!i in
;6nterpret!tion !nd 6nstr#ction P!th Coprocessing< 5y Eddy H3 >e5!ere !nd K!n M3 @!n
C!mpenho#t, M6) Press, 6"9A 0026200,107033
7hy not the common language>
)he simpest !ns4er to this F#estion is th!t one si:e does not 2it ! sit#!tions3 )he
!rg#ments !re not re!y !5o#t &orth, the re!sons to #se the common !ng#!ge !re !so
#sed !g!inst P!sc!, Mod#!02, "m!t!7, Ei22e !nd e8en >ephi3 )hese !re o2ten c!ed
minority !ng#!ges, !nd m!n!gers tend to 5e sc!red o2 them3 )he iss#e o2 progr!mmer
tr!ining !nd m!n!gement is disc#ssed !ter3 &or the moment 4e 4i stic7 to more
technic! iss#es, p!rtic#!ry those !22ecting time !nd st!22 costs3
L!ng#!ges 2rom the C, C++ !nd P!sc!I>ephi gro#ps (sometimes c!ed the P!sgo
gro#p) do not h!8e inter!cti8ity or e.tensi5iity3 )he inter!cti8ity is mosty pro8ided 5y
in8!si8e toos th!t #pset per2orm!nce, especi!y in re!0time systems o2 !ny description3
>e5#gging se!ed remote !ppic!tions is 8!sty more di22ic#t th!n connecting to !
r#nning &orth !ppic!tion o8er ! seri! ine or ! )enet session3 E.tensi5iity in the
P!sgo !ng#!ges is !rgey con2ined to compie0time #se o2 the preprocessor3 )his
contri5#tes in t#rn to the #se o2 !ddition! e.tern! toos (%47, Per, M, !nd so on) to
pro8ide 2!ciities th!t c!n 5e integr!ted 8ery e!siy into &orth3
%n e.!mpe o2 this 4!s the need to pro8ide ! scripting too 2or ! prede2ined !ng#!ge3
&or m!ny ye!rs 4e h!8e #sed ! deri8!ti8e o2 9r!d Bodrig#e:L e.ceent 9A& p!rser
impement!tion in &orth3 % 9A& p!rser is ! too th!t !o4s yo# to de2ine the gr!mm!r
o2 ! !ng#!ge together 4ith the code reF#ired to h!nde it3 )he 5!se 9A& p!rser is ess
th!n 100 ines o2 so#rce code3 )his sm! si:e m!7es it per2ecty 2e!si5e to em5ed !
scripting system inside !n !ppic!tion !nd then de2ine c#stom !ng#!ges 2or end0#sers3
>oing this 4ith ! !ng#!ge th!t is neither inter!cti8e nor e.tensi5e reF#ires the
prod#ction o2 c#stom p!rsers !nd compiers3
1%3
Adopting and managing Forth
6n em5edded systems, memory is e.pensi8e3 62 yo# !re m!7ing 10,000 #nits per ye!r,
the cost o2 #sing more memory is signi2ic!nt3 62 yo# !re m!7ing 100,000 or 1,000,000
#nits per ye!r, the cost o2 !ddition! memory m!y m!7e the di22erence 5et4een
commerci! s#ccess !nd 2!i#re3
62 yo# !re m!7ing o4 8o#me systems 4hich inter!ct 4ith ! poory de2ined or
#nderstood o#tside 4ord, !n inter!cti8e !ng#!ge c!n 5e ! i2es!8er3 6n one m!chine
contro !ppic!tion, 4e re4rote the motor dri8ers three times in ! 2e4 d!ys !s 4e
incre!singy #nderstood 4h!t imp!ct the 4or7ing en8ironment (4!ter, m#d !nd grit) h!d
on the mech!nics (!ir ines, motors, e!dscre4s !nd so on) !nd ho4 to compens!te 2or
8!ri!5iity !s the m!chine 5edded in3
)he essence o2 4h!t m!7es &orth gre!t is inter!cti8ity !nd e.tensi5iity in ! sm!
p!c7!ge3 62 yo#r !ppic!tion c!n t!7e !d8!nt!ge o2 or reF#ires inter!cti8ity, yo# c!n see
impro8ements in prod#cti8ity o2 t4o or three times3 "t!y 4ith the h!5it o2 4riting sm!
4ords, !nd yo# 4i 4rite test!5e (!nd hence rei!5e) code 4ith good code density
(2#nction!ity per 7io5yte)3
7e used Forth 1$ years ago9 but ...
)here !re re!y t4o re!sons 2or enco#ntering this 7ind o2 o5Jection*
1) =e #se CIC++ no4!d!ys M itLs the common !ng#!ge3 )his h!s !re!dy 5een
disc#ssed3
2) "omeone !t the comp!ny h!d ! 5!d e.perience 4ith ! &orth proJect ong, ong !go3
Beco8ering ! 5r!nd 2rom ! 5!d rep#t!tion is 2!r h!rder th!n seing to ! ne4 cient3 62
yo# h!8e to go do4n this ro#te 5e prep!red 2or ! di22ic#t se3 )he common opinions
!nd !ss#mptions 4e see !s p!rt o2 the second response !re*
1) $#r progr!mmer 4rote his o4n &orth3 =hen he e2t 4e co#dnLt m!int!in the &orth
or the code3
2) &orth is interpreted !nd so43
3) )he system 4e 5o#ght then 4!s not good eno#gh 2or tod!yLs reF#irements3 Go#rs
m#st 5e the s!me3
,) &orth peope !re ! #nm!n!ge!5e3
5) Go# c!nLt do C, G, or a in &orth3
6) Go# c!nLt 4rite !nd m!int!in !rge progr!ms in &orth3
7) Ao5ody #ses &orth !ny more3
(ur programmer wrote his own =orth. "ome 15 or 20 ye!rs !go peope 5#it their
o4n hi02i systems3 )he technic! ho55ies o2 tod!y !re 8ery di22erent 2rom the technic!
ho55ies o2 then3 )here !re no4 m!ny good &orths 2rom commerci! or open0so#rce
s#ppiers3 M!n!gement m#st decide 4hether the 5ene2its !nd !ssoci!ted costs o2 too0
m!7ing J#sti2y 7eeping too0m!7ing in0ho#se3 6n the 8!st m!Jority o2 c!ses, 5#ying in !
compier !nd perh!ps getting ! 2e4 d!ys cons#t!ncy is the che!pest option3
1%4
Adopting and managing Forth
>oc#ment!tion is ! m!n!gement iss#e, !nd these d!ys peope 7no4 ! ot more !5o#t it
th!n they did 15 ye!rs !go3
=orth is interpreted and slow. Modern &orths 2rom commerci! s#ppiers #se
!ggressi8e code gener!tors3 "ome !re 5!sed on 8ery simi!r techniF#es to those #sed 5y
m!ny C compiers !nd the 5enchm!r7 res#ts re2ect this3 )he ony 4!y to pers#!de
some peope is to pro8ide some n#m5ers3 $#r 5enchm!r7s !nd some tests 5y #sers sho4
th!t the c#rrent 5!tch o2 &orth compiers !re o8er 10 times 2!ster th!n those 5!sed on
thre!ded code3
%he system we bought then was not good enough for todayJs requirements. )he
;5!d then, 5!d no4< !rg#ment is simi!r to ! proo2 5y !ssertion3 )he e!siest 4!y to
o8ercome it is to !s7 them i2 they 4o#d #se ! 15 ye!r0od C compier3 P!rt o2 the
pro5em is th!t some peope do contin#e to #se 15 ye!r0od o5soete !nd #ns#pported C
compiers3
=orth people are all unmanageable3 =e J#st h!8e to 2!ce 2!cts3 Progr!mmers (in !ny
!ng#!ge) h!8e ! rep#t!tion o2 5eing di22ic#t to m!n!ge3 M!n!ging g#r# e8e
progr!mmers is comp!red 4ith herding c!ts3 %5o#t ten ye!rs !go 6 he!rd the m!n!ger o2
! !rge K!p!nese comp!nyLs rese!rch !5s s!y*
-he pro#lem %ith 0EE is that it re'uires guru programmers2 and guru programmers
don=t do maintenance..
6 h!8e 4or7ed on &orth proJects 4ith #p to 30 progr!mmers3 =hether s#ch proJects
4or7 is ! m!tter o2 m!n!gement, ! topic 4e 4i come to !ter3 6n pr!ctice, m!ny
m!n!gers !re m#ch 5etter !t so2t4!re m!n!gement th!n they #sed to 5e3 Go# h!8e to 5e
!4!re th!t so2t4!re m!n!gement is ! 8it! p!rt o2 constr#cting so2t4!re reg!rdess o2 the
!ng#!ge in8o8ed3
0ou canJt do KL 0L or M in =orth. 6t m!y 5e tr#e3 9#t it m!y !so 5e ignor!nce3 6 come
!cross this opinion 2!r too o2ten3 =hen 6 sho4 them th!t it is no onger tr#e, the pro5em
goes !4!y3 %s 4ith m!ny other hostie opinions, the 5est 4!y to de! 4ith them is to
sho4 them the n#m5ers or gi8e re2erences to s#ccess2# proJects th!t !ct#!y do 4h!t
they s!y c!nnot 5e done3
0ou canJt write and maintain large programs in =orth3 Get !g!in, point to !rge
&orth proJects3 )he constr#ction estim!tion p!c7!ge prod#ced 5y Constr#ction
Comp#ter "o2t4!re p!n h#ge constr#ction proJects s#ch !s the ne4 Hong (ong !irport3
6n 200, it cont!ined o8er -50,000 ines o2 &orth so#rce code3 "ee http*II4443ccss!3com
2or more det!is o2 4h!t the system does3 Ho4 they m!n!ge it is 8ery m#ch 5!sed on the
techniF#es descri5ed in ;)he Mythic! M!n0Month< 5y &red 9roo7s3 9ig proJects need
m!n!gement3 62 yo# donLt m!n!ge them, they will 2!i3
1obody uses =orth any more3 %p!rt 2rom peope i7e 69M, "#n Micro"ystems, %ppe,
!nd A%"%3 "ide iss#es 2or this disc#ssion !re th!t progr!mming !ng#!ges !re not the
topic o2 disc#ssion th!t they #sed to 5e !nd th!t some !rge !nd s#ccess2# comp!nies
#sing &orth consider it to 5e ! tr!de secret o2 their s#ccess3 %t e!st one o2 o#r cients
sod their comp!ny !nd 5ec!me 8ery rich on the 5!c7 o2 technoogies de8eoped 4ith
&orth3
1%5
Adopting and managing Forth
:anaging Forth proAects
62 yo# do not 5eie8e ho4 import!nt so2t4!re proJect m!n!gement is, re!d ;)he
Mythic! M!n0Month< 5y &red 9roo7s3 )here !re !so se8er! 5oo7s !8!i!5e !5o#t
so2t4!re dis!sters !nd 4h!t to e!rn 2rom them3 'nti 2!iry recenty, m!ny comp!nies
tre!ted so2t4!re proJects di22erenty 2rom those in other engineering discipines3
M!n!ging ! proJect 4ritten in &orth is no di22erent 2rom m!n!ging !ny other so2t4!re
proJect3
$ne o2 the consider!5e 5ene2its o2 the s#rgic! te!m !ppro!ch promoted in ;)he
Mythic! M!n0Month< is th!t the proJect m!n!ger c!n ret!in technic! competence (!nd
hence respect) o2 the progr!mmers3 )he te!m !dministr!tor is the one 4ho does the
spre!dsheets3
:anagers
% spit 5et4een ;the m!n!gement< !nd the engineering st!22 is ne8er prod#cti8e3 6t is
p!rt o2 the process 2or one to ed#c!te the other3 )he e22ecti8e po4er is #s#!y in the
h!nds o2 the m!n!gement 5ec!#se they contro the 5#dgets3 E.perienced m!n!gers h!8e
5een sc!mmed 5y technic! st!22 m!ny times in their c!reers !nd !re righty c!#tio#s on
occ!sion3 =h!t con8inces them !re cost !nd time n#m5ers3 Con8incing them 5y
!ssertion r!rey 4or7s3 6ndic!ting 4h!t yo# h!8e done !nd 4hy it 4or7s m!y 5e
e22ecti8e3
6n m!ny dep!rtments there 4i 5e !n opinion0m!7er in the engineering te!m3 "#ch
peope !re 8!#!5e !ies, 5#t it is o2ten not o58io#s 4ho they !re3 M!7ing cont!ct 4ith
them is import!nt3
6n e!ding or 5eeding edge proJects, ens#ring the soci! cohesion o2 ! progr!mming
te!m is 8ery import!nt3 6n one m#tin!tion! proJect 6 4!s in8o8ed in, o#r (6rish) proJect
o22icer rem!r7ed one e8ening th!t proJects th!t st!rted 4ith ! good p!rty 4ere more
i7ey to s#cceed3
Programmers
=hen progr!mming 4!s the ne4 technoogy o2 the time, 8ery 2e4 peope 7ne4
!nything !5o#t it3 =e e!rned 5y doing !nd m!de ! 8!st n#m5er o2 mist!7es, some o2
4hich sti i8e to h!#nt #s3 =h!t ch!r!cterised progr!mmers then 4!s !n e!gerness to
do !nd e!rn something ne43 =e h!d to 5e soci!5e 5ec!#se 4e h!d to e!rn 2rom o#r
peers3 =e !so h!d to 5e c!p!5e o2 oc7ing o#rse8es into ! room 4ith ! comp#ter 2or
ho#rs !nd ho#rs M there m!y h!8e 5een no5ody to te!ch #s 4h!t 4e needed to 7no43
M!n!gers sho#d 5e !4!re o2 the dyn!mics o2 their te!m !nd seect st!22 !ccordingy to
prod#ce ! 5!!nced te!m3
M!ny proJects in the em5edded !ren! 4ere done 5y engineers 4ho h!d e!rnt
progr!mming !s !n !dJ#nct to their m!in Jo53 M!ny o2 them too7 on more th!n they
co#d che4, !nd m!n!gement !re no4 J#sty c!#tio#s o2 etting ! non0speci!ist h!8e
their he!d3
M!ny c#rrent &orth progr!mmers !so come 2rom !n eectronics or scienti2ic
5!c7gro#nd3 &orthLs good rep#t!tion in em5edded systems is !rgey ! res#t o2 ho4 it
gre4, r!ther th!n in !ny tr#th !5o#t 4h!t it is good 2or3
1%6
Adopting and managing Forth
Ao4!d!ys, progr!mming 2or m!ny peope is J#st ! Jo53 6t !so co8ers ! h#ge r!nge o2
!ppic!tions3 P#tting ! K!8! progr!mmer onto ! h!rd re!0time !ppic!tion h!ppens, 5#t it
is ! ris73
Li7e m#ch other engineering !nd pro2ession! pr!ctice, so2t4!re is !s m#ch ! cr!2t !s
!nything ese3 E.perience co#nts 2or ! ot3 E8en more 8!#!5e is e!rning 2rom th!t
e.perience3
Training
=hen peope st!rt #sing &orth, there is ! e!rning c#r8e3 9ec!#se &orth is ! di22erent
type o2 !ng#!ge comp!red 4ith the ones they h!8e pro5!5y #sed 5e2ore, the e!rning
c#r8e con8erting 2rom CIC++ to &orth is !rger th!n th!t o2 con8erting 2rom CIC++ to
>ephi3 % typic! &orth tr!ining co#rse needs 2rom three to 2i8e d!ys, mosty depending
on ho4 good the progr!mmers !re !nd ho4 m#ch time they h!8e !8!i!5e3 )he
commerci! 8endors c!n pro8ide st!nd!rd or t!iored co#rses3
%2ter s#ch ! co#rse, it 4i t!7e ! month or so to 5ecome com2ort!5e in &orth3 %2ter th!t
prod#cti8ity rises3 )he import!nt point o2 ! co#rse is to do eno#gh coding in &orth so
th!t they ;get it<3 % progr!mmer #sed to C 4ho does not ;get< &orth 4i pro5!5y 4rite
&orth in ! C stye !nd 4i sho4 itte or no prod#cti8ity g!ins in the !re!s 4here &orth
co#d other4ise pro8ide m!Jor g!ins3 E.pos#re to other &orth progr!mmers heps here3
%n interested progr!mmer 4i e!rn m#ch 2!ster th!n someone 4ho h!s J#st 5een sent
on the co#rse3 ConseF#enty, moti8!tion on the 5ene2its o2 &orth is !n essenti! p!rt o2
co#rses3
)he costs o2 tr!ining !re o2ten r!ised !s !n iss#e, especi!y 2or ne4y hired
progr!mmers3 Le!rning ! progr!mming !ng#!ge t!7es m#ch ess time th!n e!rning the
5#siness o2 ! comp!ny3 $8er the i2etime o2 ! proJect, the cost o2 tr!ining (i7e the cost
o2 the so2t4!re toos) is ! 5#t ost in the noise3
Portability
"ince the introd#ction o2 %A" &orth, the port!5iity o2 code h!s impro8ed consider!5y3
Ho4e8er, J#st !s in !ny other !ng#!ge, porting code 5et4een di22erent &orth systems
reF#ires !ttention to det!i3 %2ter 5eing in8o8ed 4ith se8er! !rge ports o2 #p to
-00,000 ines o2 &orth so#rce code, the 7ey iss#es !re sep!r!tion !nd m!n!gement3
"ep!r!tion in8o8es deciding 4hich code c!n 5e ch!nged !nd 4hich code c!nnot3
>#ring the e!ry st!ges o2 the proJect yo# 4i 4!nt to r#n the ne4 system !ongside the
od3 )his in8o8es spitting the code into se8er! !yers3
1) $pplication M this code is e2t #nch!nged
2) %ools M yo# e!8e this code #nch!nged i2 !t ! possi5e, 5#t depending on the
#nderying 7ernes, some ch!nge m!y 5e reF#ired3 C!re2# #se o2 condition!
compi!tion heps here, 5#t too m#ch #se o2 it e!ds to m!inten!nce iss#es3
3) 'arnesses M pro8ide one 2or e!ch &orth system yo# !re #sing3 )he Jo5 o2 the
h!rness !yer is to tr!ns!te 2rom the #nderying &orth 7erne so th!t the too !nd
!ppic!tion !yers reF#ire (ide!y) no ch!nge3 =hen yo# decide to !5!ndon the
e!rier 7erne, ony then sho#d yo# permit 2#rther ch!nges to the too !nd
!ppic!tion !yers3
1%7
Adopting and managing Forth
,) =orth 6ernel M e!8e it !oneT 62 yo# need it to 5e modi2ied cons#t the s#ppier3 6t is
! m!Jor pro5em i2 the 7erne yo# #se is not the one th!t yo#r s#ppier is shipping3 62
yo# m#st h!8e ch!nges, m!7e s#re th!t the s#ppier is prep!red to t!7e o8er
m!inten!nce o2 the ch!nges3
)he m!n!gement iss#es in porting !re ens#ring th!t yo# do one thing !t ! time !nd
ens#ring peope do not get too enth#si!stic3 M!7ing ! m!Jor 2e!t#re enh!ncement d#ring
! port is ! recipe 2or dis!ster3 >oing the port !nd then doing the 2e!t#re enh!ncement
4i 5e F#ic7er3 Porting p#ts the te!m m!n!ger !s ! 5!rrier 5et4een the di22ering
o5Jecti8es o2 the so2t4!re de8eopment te!m !nd the s!es !nd m!r7eting gro#p3
6ifecycle
"#ccess2# so2t4!re prod#cts e8o8e, so ch!nge is ! const!nt o2 their i8es3 Ch!nging
so2t4!re me!ns th!t someone h!s to 5!c7 !nd re8isit code 4ritten se8er! ye!rs !go3
Code m#st 5e doc#mented to cope 4ith this3 %n in0ho#se stye gre!ty e!ses the
pro5ems o2 code m!inten!nce3
9e prep!red 2or the iss#es in8o8ed in porting yo#r code3 H!rd4!re p!t2orms do not !st
2or e8er, !nd neither do oper!ting systems3 )he prod#ct yo# !re de8eoping m!y h!8e !
commerci! i2e 4e 5eyond th!t o2 the h!rd4!re !nd so2t4!re p!t2orms yo# !re
c#rrenty #sing3
"ome o2 the prod#cts 6 !m c#rrenty m!int!ining st!rted i2e #nder CPIM, 4ere ported to
16 5it >$", 32 5it >$", =indo4s 331 !nd then to the =indo4s A) 5!sed oper!ting
systems3 )he code in8o8ed h!s e8o8ed o8er ! period o2 ne!ry 25 ye!rs !nd is sti
4or7ing3 6t h!s o#ti8ed ch!nges in CP', oper!ting system, !nd host &orth system3
1%8
,egac& issues
22 6egacy issues
%s 4ith !ny progr!mming !ng#!ge, &orth h!s e8o8ed o8er time3 )his ch!pter disc#sses
some o2 the eg!cy iss#es3
Forth -tandards
&o#r &orth st!nd!rds h!8e 5een signi2ic!nt* &6E0&orth, &orth07/, &orth0-3 !nd %A"
&orth3 %A" &orth is the c#rrent st!nd!rd3 &6E0&orth !nd &orth07/ !re #ni7ey to 5e
enco#ntered, so this section de!s 4ith con8erting code 2rom &orth0-3 to %A" &orth3
9ec!#se the %A" st!nd!rd 8ery dei5er!tey !8oids speci2ying impement!tion
techniF#e, there h!s 5een !n e.posion in &orth compier technoogy since the
introd#ction o2 the %A" st!nd!rd in 1//,3 )his section !so disc#sses the imp!ct o2
con8erting 2rom ! thre!ded code impement!tion to ! modern optimising code gener!tor
s#ch !s MPELs @&C systems3
;ati+e Code Compilers
&arnal 6nowledge is dangerous
E.tr! c!re sho#d 5e e.ercised 4ith !ny so#rce code 4hich reF#ires 7no4edge o2 the
#nderying !rchitect#re3 )his 4i p!rtic#!ry imp!ct de2initions 4hich c!#se
compi!tion, !nd !ssem5er 2r!gments3
&omma does not &ompile
M!ny &orth0-3 impement!tions !o4ed compi!tion 5y Pcomm!0ingP ! C&% into the
diction!ry3 )his is no onger ! 8!id method o2 gener!ting code3 )he %A" 4ord
"OMPILEF sho#d 5e #sed inste!d3 %so the system m#st 5e in Pcompie st!teP 4hen
"OMPILEF is #sed3
Con+erting from ForthE!
MPEism: COMPILE is now IMMEDIATE
7revious M7, implementations have used a non9immediate version of COMPILE %hich
has FunpickedF the follo%ing 0"LL instruction at run9time. -his #ehaviour has no%
#een changed. Most uses of COMPILE and [COMPILE] can #e replaced #y
POSTPONE.
&(5(1 and &urrent
'nder %A" &orth, the "ONTEXT de2initions 4ordist (the #sed 4hen oo7ing #p 4ord
n!mes) is not modi2ied 5y : (coon)3 )he imp!ct o2 this ch!nge is th!t yo# do not need
to !dd !n e.tr! ALSO to protect the se!rch order3 %so note th!t : (coon) is no onger
immedi!te in most impement!tions, 4hich m!y !22ect some compie0time error
chec7ing3
1%%
,egac& issues
$1S Error 'andling
Error h!nding is done #sing the %A" speci2ied "AT"H !nd THROW mech!nism3 )he
de2initions ERROR !nd (ERROR 2rom &orth0-3 !re no4 !i!ses 2or THROW !nd (
THROW3 Pe!se re!d the section on e.ception h!nding 5oth in this m!n#! !nd the %A"
&orth "t!nd!rd3
-creen files
% screen (!so c!ed ! 5oc7) is ! #nit o2 &orth so#rce code th!t consists o2 16 ines o2 6,
ch!r!cters3 )he re!sons 2or this #nit !re !most ost in the depths o2 comp#ting history, 5#t
stem 2rom #sing ! si:e th!t 2itted e22icienty onto ! dr#m store, !nd !so 2itted onto c#rrent
screen si:es (most peope #sed mech!nic! teetypes !s termin!s)3 )his con8ention h!s
5een ret!ined, p!rty 5y con8ention, !nd p!rty 5ec!#se it heps to en2orce 4riting code in
sm! ch#n7s3
MPEism2 -he description in the remainder of this section is specific to M7, products.
62 yo# sti need to m!int!in screen 2ies, MPELs &orth "t!rter (it inc#des PC Po4er&orth
P#s !nd Mod#!r &orth3 )hese pro8ide ! speci!ised screen 2ie editor c!ed &BE>,
4hich is the editor yo# get 5y typing EDIT or FRED3 Go# c!n see 4h!t is in ! screen 2ie
5y #sing ! &orth con8ention3 %ccording to this con8ention the top ine o2 e8ery screen (!
#nit o2 so#rce code) is #sed ony !s ! comment ine descri5ing the contents o2 ! screen3
)he 4ord INDEX c!n then 5e #sed to disp!y ! these comment ines3 )he phr!se*
0 100 INDEX
4i inde. the comment ines o2 screens 0 to 1003
Go# c!n then see 4h!t is in screen 23 5y typing*
TOOLS ( loads module TOOLS.MD3 )
23 LIST ( lists screen 23 )
Aotice ho4 the 4ord TOOLS is #sed to o!d the mod#e )$$L"3M>3 th!t cont!ins m!ny
h!ndy #tiities3 )he 4ord 1 4i sho4 yo# the Ae.t screen, !nd the 4ord P 4i sho4 yo#
the Pre8io#s screen3 "creens !re org!nised !s 16 ines o2 6, ch!r!cters, !nd !re edited
#sing the 2# screen editor3 =hen yo# 2ind ! screen yo# 4!nt to compie (s!y screen 7),
yo# c!n compie it #sing the 4ord LOAD*
7 LOAD
"creen 7 4i 5e compied3 62 screen 7 cont!ins 4ords th!t o!d other screens, they too 4i
5e compied3
Files
62 ! screen 2ie 4!s speci2ied 4hen &orth 4!s o!ded, it 4i 5e opened !s &orth signs on3
)o ch!nge to !nother 2ie, #se*
USING NEW.SCR
62 the 2ie AE=3"CB does not e.ist the system 4i !s7 yo# i2 yo# 4!nt the 2ie cre!ted,
!nd i2 so, the 2ie 4i 5e cre!ted !nd opened3 )he screen 2ie is #sed 5y ! the 4ords
200
,egac& issues
!22ecting so#rce code, !nd 4hen yo# type EDIT or FRED, the editor is o!ded !nd !cts on
the c#rrent screen 2ie3 %2ter the 4ord EDIT screen 0 is edited, or i2 the editor h!s 5een
#sed 5e2ore, the screen !st edited is edited !g!in3
EDIT ( edits screen 0 or last screen )
25 FRED ( edits screen 25 )
201
!ther (ooks and "esources
2! /ther 2ooks and 0esources
6 e!rned &orth 5y #sing it, t!7ing to other peope !nd 5y re!ding e8erything !5o#t it
th!t 6 co#d !y my h!nds on !nd !22ord3 %s 4ith e8ery ne4 s#5Ject, 6 2o#nd th!t 6
needed more th!n one 5oo7, !nd o2ten 6 needed di22erent 5oo7s !t di22erent st!ges in my
e!rning3 6 c!nnot pretend th!t this 5oo7 is the ony one yo# 4i need, so here !re some
o2 them th!t 6 h!8e 2o#nd #se2#3
)he 2irst t4o 5oo7s !re 5y Leo 9rodie !nd !re c!ssics3
-tarting Forth H 6eo 2rodie
"!dy o#t o2 print, 5#t i2 yo# 2ind ! copy, especi!y o2 the second edition, 5#y it3 % 4e5
8ersion 5y M!rce Hendri. is descri5ed !s ! tri5#te to this gre!t 5oo7 !nd is !8!i!5e !t*
http://home.iae.nl/users/mhx/
Thinking Forth H 6eo 2rodie
% P>& o2 this 4onder2# 5oo7 is !8!i!5e 2rom*
http://thinking-forth.sourceforge.net/
)he 2oo4ing is t!7en 2rom the description there3
-hinking Forth is a #ook a#out the philosophy of pro#lem solving and programming
style, applied to the uni'ue programming language Forth. 7u#lished first in 1GH@, it
could #e among the timeless classics of computer #ooks, such as Fred 8rooks3 -he
Mythical Man9Month and :onald Inuth3s -he "rt of 0omputer 7rogramming.
Many soft%are engineering principles discussed here have #een rediscovered in
e;treme 7rogramming, including *re+factoring, modularity, #ottom9up and incremental
design. Bere you3ll find all of those and more 9 such as the value of analysis and design
9 descri#ed in Leo 8rodie3s do%n9to9earth, humorous style, %ith illustrations, code
eamples, practical real life applications, illustrative cartoons, and intervie%s %ith
Forth3s inventor, 0harles B. Moore as %ell as other Forth thinkers.
/f you program in Forth, this is a must9read #ook. /f you don3t, the fundamental
concepts are universal2 -hinking Forth is meant for anyone interested in %riting
soft%are to solve pro#lems. -he concepts go #eyond Forth, #ut the simple #eauty of
Forth thro%s those concepts into stark relief.
(o flip open the #ook, and read all a#out the philosophy of Forth, analysis,
decomposition, pro#lem solving, style and conventions, factoring, handling data, and
minimiCing control structures. 8ut #e prepared2 you may not #e a#le to put it do%n.
Forth ProgrammerGs "andbook H Conklin I 0ather
% second e8e 5oo7 4e reg!rded 5y m!ny3
http://www.forth.com/forth/fph.html
203
!ther (ooks and "esources
Forth Application Techni@ues H 0ather
From first9day Forth eercises to advanced techni'ues many programmers never learn
on their o%n, this course note#ook is filled %ith pithy, succinct discussion and eercises
developed and refined over the years to 'uickly teach, test, and reinforce Forth
language skills..
http://www.forth.com/forth/fat.html
/ther 0esources
Forth Interest ?roup
)he &orth 6nterest Ero#p 4e5 site !t*
http://www.forth.org
cont!ins in7s to ! h#ge !mo#nt o2 in2orm!tion !5o#t &orth3 6t !so h!s ! repository o2
compiers, so#rce code !nd doc#ment!tion 4hich yo# m!y 4e 2ind #se2#3 Go# c!n
!so 2ind in7s to oc! s#pport gro#ps in se8er! co#ntries3
5senet news groups
comp.lang.forth
comp.lang.forth.mac
Conferences
M!ny o2 the sm!er &orth con2erences h!8e 5een s#perseded 5y the ne4s gro#ps3 )he
!nn#! E#ro&orth con2erence is the 5est o2 the c#rrent con2erences3 6t is in7ed !t
http://www.forth.org
!nd is hed in nice p!ces !ro#nd E#rope3 "e8er! sm!er con2erences !re hed in "iicon
@!ey, Ho!nd !nd Eerm!ny3
AmaFon
)he onine 5oo7seer h!s ! se!rch!5e section #nder Progr!mming*L!ng#!ges*&orth
204
Index
2# Inde(
0UV333333333333333333333333333333333333333333332
0W33333333333333333333333333333333333333333333332
2VB33333333333333333333333333333333333333333330
2>B$P333333333333333333333333333333333333330
2>'P33333333333333333333333333333333333333330
2$@EB333333333333333333333333333333333333330
2B13333333333333333333333333333333333333333330
2BV33333333333333333333333333333333333333333330
2"=%P33333333333333333333333333333333333330
%9$B)333333333333333333333333333333-7, /1
%9$B)d33333333333333333333333333333-7, /1
%9"33333333333333333333333333333333333333333331
%CCEP)3333333333333333333333333333,2, 5,
%>>B333333333333333333333333333333333333101
%E%6A33333333333333333333333333333333333333-
%L6EA33333333333333333333333333333333333107
%L6EAE>333333333333333333333333333333107
%LL$)333333333333333333333333333360, 107
%L"$333333333333333333333333333333333333333,5
%BM33333333333333333333333333333333333333133
!ssem5er33333333333333333333333333333333103
%""EM9LEB33333333333333333333333310/
9%"E333333333333333333333333333333333333333/7
9EE6A33333333333333333333333333333333333333-
9ernd P!ys!n33333333333333333333333333331/
96A333333333333333333333333333333333333333333/3
9L$C(3333333333333333333333333333333333122
5oc7sO333333333333333333333333333333333333121
9$>GV3333333333333333333333333333333333127
5oo7s33333333333333333333333333333333333333203
5ottom#p design3333333333333333333333316
5r!c7ets33333333333333333333333333333333333320
9'&&EB33333333333333333333333333333333123
C,3333333333333333333333333333333333333360, 107
CT33333333333333333333333333333333333333333333333
C1333333333333333333333333333333333333333333333
C%"E3333333333333333333333333333333333333333/
C%)CH333333333333333333333333333333333333-7
C>%)%3333333333333333333333333333333333107
CELL33333333333333333333333333333333333333320
CELL"333333333333333333333333333333333333333
CH%B33333333333333333333333333333333333333,2
CH%B"33333333333333333333333333333333333333
chidren33333333333333333333333333333333333323
CL$"E0&6LE333333333333333333333333333/3
CL"33333333333333333333333333333333333333333353
C$>E3333333333333333333333333333333333333103
comment3333333333333333333333333333333333323
Comments33333333333333333333333333333315,
C$MP6LE,3333333333333333333333333333333-1
compied code333333333333333333333333127
compier3333333333333333333333333333315, 21
C$MP6LEB33333333333333333333333333310/
con2erences3333333333333333333333333333320,
con2ig#r!tion33333333333333333333333333135
C$A")%A)33333333333333333333333333333,
Const!nts33333333333333333333333333333333333,
contro str#ct#re3333333333333333333333335
C$'A)33333333333333333333333333333353, 5,
CB3333333333333333333333333333333333333325, 53
CBE%)E333333333333333333333333335/, 127
CBE%)E0&6LE333333333333333333333333/3
>!te @!id!tion333333333333333333333333,/
de5#gging3333333333333333333333333333333331,
de2ining 4ords3333333333333333333315, 5/
>e2ining 4ords333333333333333110, 155
>E&6A6)6$A"3333333333333333333333333,5
>ELE)E0&6LE3333333333333333333333333/,
>eterminism33333333333333333333333333313,
>i!ry333333333333333333333333333333333333333363
diction!ry33333333333333333333333333333333315
>iction!ry333333333333333333333333333333125
>6E6)33333333333333333333333333333333333333357
>$3333333333333333333333333333333333333333333336
>$E"V333333333333333333333333333333333333360
>P3333333333333333333333333333333333333333331-5
>PL333333333333333333333333333333333333333333,,
>B$P3333333333333333333333333333333333333332/
>)C33333333333333333333333333333333333333312/
>'P333333333333333333333333333333333333333332/
editors33333333333333333333333333333333333331,6
EL"E333333333333333333333333333333333333333336
205
Index
Em5edded "ystems3333333333333333107
EM6)333333333333333333333333333333333333333353
EMP)G9'&&EB"33333333333333333123
EA>C%"E33333333333333333333333333/, ,0
EA>6&3333333333333333333333333333333333333335
EA>$&3333333333333333333333333333333333333/
e.ception h!nding3333333333333333333-7
ECEC')E333333333333333333333333375, -1
E.ec#tion )o7ens33333333333333333333375
E.ercises33333333333333333333333333333333161
EC6)333333333333333333333333333333333333333336
&!ctoring333333333333333333333333333333333322
&6LE0P$"6)6$A3333333333333333333333/,
&6LE0"6aE3333333333333333333333333333333/,
&ies333333333333333333333333333333333333333333/3
&6A>33333333333333333333333333333333,6, 127
&L$%>333333333333333333333333333333333333/5
2o!t st!c73333333333333333333333333333333100
2o!ting point33333333333333333333333333100
&L'"H33333333333333333333333333333333333123
&L'"H0&6LE333333333333333333333333333/,
&orth "cienti2ic Li5r!ry3333333333100
&orth 8irt#! m!chine3333333333333331-
goss!ry33333333333333333333333333333333333315
H!r8!rd !rchitect#re33333333333333310-
HEBE333333333333333333333333333333360, 107
H$")333333333333333333333333333333333333310/
H$")N)%BEE)333333333333333333110
6I$ redirection3333333333333333333333333357
6>%)%33333333333333333333333333333333333107
6&333333333333333333333333333333333333333333333335
6MME>6%)E3333333333333333333333333337/
6mmedi!te 4ords33333333333333333333337/
6ACL'>E33333333333333333333333333333333/5
6ACL'>E0&6LE3333333333333333333333/5
6ACL'>E>33333333333333333333333333333/5
6ndenting33333333333333333333333333333333156
6A6)0M'L)63333333333333333333333333333/-
6nteroc7s33333333333333333333333333333333116
interpreter333333333333333333315, 21, 135
6A)EBPBE)EB33333333333333333333310/
interr#pt response time33333333333133
interr#pts3333333333333333333333333333333311,
6A@EB)3333333333333333333333333333333333333
6)C3333333333333333333333333333333333333333312/
6C133333333333333333333333333333333333333333132
K!8!3333333333333333333333333333333333333333131
(EG3333333333333333333333333333333333353, //
(EGD3333333333333333333333333333333333333335,
(6"" method333333333333333333333333333327
(oopm!n33333333333333333333333333333333131
LE%@E33333333333333333333333333333333333336
eg!cy33333333333333333333333333333333333331//
L6)EB%L333333333333333333333333333333333-2
oc! !rr!ys33333333333333333333333333333101
oc! 8!ri!5es333333333333333333333333101
!8oiding33333333333333333333333333333102
per2orm!nce33333333333333333333333102
4hen to #se333333333333333333333333103
4riting C in &orth333333333333333101
Loc! 8!ri!5es33333333333333333333333101
L$C%)E3333333333333333333333333333333310,
L$$P33333333333333333333333333333333333333336
L"H6&)33333333333333333333333333333333333333
m!n!gement3333333333333333333333333331/1
M%C333333333333333333333333333333333333333331
MicroCore333333333333333333333333333333132
M6A33333333333333333333333333333333333333333331
Mi.ed !ng#!ge progr!mming
3333333333333333333333333333333333333333333333310,
M$>333333333333333333333333333333333333333331
M#tit!s7ing33333333333333333333333333333/7
A%MEV333333333333333333333333333333333127
AC,0003333333333333333333333333333333333132
ACC33333333333333333333333333333333333333312-
AEE%)E333333333333333333333333333333333331
AEC)C%"E33333333333333333333333333333,0
A6P33333333333333333333333333333333333333333332/
not!tion33333333333333333333333333333333333323
Ao8i.3333333333333333333333333333333333333132
A'M9EBD333333333333333333333333333333357
$5Ject oriented progr!mming3103
$&333333333333333333333333333333333333333333333/
$ALG33333333333333333333333333333333333333,5
$PEA0&6LE33333333333333333333333333333/3
$B3333333333333333333333333333333333333333333332
$B>EB333333333333333333333333333333333333,6
$@EB3333333333333333333333333333333333333332/
P%EE33333333333333333333333333333333333333353
206
Index
P!r!meter st!c73333333333333333333333125
phone 5oo7333333333333333333333333333331,0
Phone 9oo733333333333333333333333333333367
phr!sing3333333333333333333333333333333333153
Poets3333333333333333333333333333333333333333315
post2i.333333333333333333333333333333333333331/
P$")P$AE33333333333333333333333333333-2
H'EBG333333333333333333333333333333333333,3
H'6)3333333333333333333333333333333333333333-7
B1333333333333333333333333333333333333333333330
BI$3333333333333333333333333333333333333333333/3
BV3333333333333333333333333333333333333333333330
BE%>0&6LE33333333333333333333333333333/,
BE%>0L6AE3333333333333333333333333333/,
BEPE%)33333333333333333333333333333333333/
BEP$"6)6$A0&6LE33333333333333333/,
BE"6aE0&6LE33333333333333333333333333/,
Bet#rn st333333333333333333333333333333333125
B$)333333333333333333333333333333333333333332/
B"H6&)33333333333333333333333333333333333333
B)C2000333333333333333333333333132, 133
"%@E9'&&EB"33333333333333333333123
"E%BCH0=$B>L6")333 3,6, 127
"o#tions33333333333333333333333333333333175
"$'BCE333333333333333333333333333333333355
st!c7333333333333333333333333333333333333333333333
comments3333333333333333333333333333323
st!c7 2!#t333333333333333333333333333333333//
st!c7 m!chines33333333333333333333333131
"t!c7s3333333333333333333333333333333333333331/
")%)E3333333333333333333333333333333333333-2
")C333333333333333333333333333333333333333312-
string33333333333333333333333333333333333333333333
ch!r!cter3333333333333333333333333333333,2
co#nted333333333333333333333333333333333,3
strings333333333333333333333333333333333333333,1
"tr#ct#res33333333333333333333333333361, -3
"=%P333333333333333333333333333333333333332/
t!5s333333333333333333333333333333333333333331,6
)%BEE)3333333333333333333333333333333310/
)%BEE)0$ALG33333333333333333333110
tethered33333333333333333333333333333333333117
)HB$=33333333333333333333333333333333333-7
)693333333333333333333333333333333333333333333,3
)$333333333333333333333333333333333333333333101
))C3333333333333333333333333333333333333333130
)'C(3333333333333333333333333333333333333332/
)GPE3333333333333333333333333333333333,3, 53
'U3333333333333333333333333333333333333333333332
'V3333333333333333333333333333333333333333333332
'>%)%3333333333333333333333333333333333107
'MX3333333333333333333333333333333333333333331
'MIM$>33333333333333333333333333333333331
'm5iic!33333333333333333333333333333333117
'AL$$P33333333333333333333333333333333337
'A)6L33333333333333333333333333333333333333-
'A'"E>3333333333333333333333333333333107
'P>%)E33333333333333333333333333333333123
'"EB333333333333333333333333333333333333333/7
'ser 8!ri!5es3333333333333333333333333125
'"EB 8!ri!5es333333333333333333333333/7
8!#e3333333333333333333333333333333333333333335
@%L'E3333333333333333333333333333333,, 35
@%B6%9LE333333333333333333333333333333,
8!ri!5es333333333333333333333333333333333333,
@ectors333333333333333333333333333333333333375
@H>L333333333333333333333333333333333333132
8irt#! m!chine33333333333333333333333333333
C 1-
@oc!5#!ries33333333333333333333333333333,,
8oc!5#!ry3333333333333333333333333333333315
@$C%9'L%BG3333333333333333333333,5
@$C"333333333333333333333333333333333333333,6
=T333333333333333333333333333333333333333333333,
=133333333333333333333333333333333333333333333
=H6LE33333333333333333333333333333333333333/
=6)H6A3333333333333333333333333333332, 50
=6)H6AD33333333333333333333333333333333350
=$B>3333333333333333333333333333333,3, 55
4ordists33333333333333333333333333333333333,5
=ordists3333333333333333333333333333333333,6
4ords333333333333333333333333333333333333333315
de2ining3333333333333333333333333333333321
immedi!te333333333333333333333333333321
=$B>"3333333333333333333333333333327, ,5
=B6)E0&6LE333333333333333333333333333/3
=B6)E0L6AE333333333333333333333333333/3
CC%LL333333333333333333333333333333333310,
207
Index
C$B3333333333333333333333333333333333333333332
33333333333333333333333333333333333333333333333325
033333333333333333333333333333333333333333333333330
0B$)333333333333333333333333333333333333333330
,3333333333333333333333333333333333333333333333335/
T33333333333333333333333333333333333333333333333333
D>$33333333333333333333333333333333333337, 3-
D>'P33333333333333333333333333333333333333332/
DLE%@E3333333333333333333333333333333333336
D$&333333333333333333333333333333333333333333,0
3B333333333333333333333333333333333333333333333356
3"333333333333333333333333333333333333333333333320
[CH%B_333333333333333333333333333333333333,2
[C$MP6LE_3333333333333333-2, -5, 1//
1333333333333333333333333333333333333333333333333
X3333333333333333333333333333333333333333333333331
XI333333333333333333333333333333333333333333333331
I33333333333333333333333333333333333333333333333331
^33333333333333333333333333333333333333333333333,3
^V333333333333333333333333333333333333333333333,3
^"333333333333333333333333333333333333333333333,3
+3333333333333333333333333333333333333333333333330
+T333333333333333333333333333333333333333333333333
+L$$P333333333333333333333333333333333333336
U3333333333333333333333333333333333333333333333332
U^333333333333333333333333333333333333333333333,3
UW33333333333333333333333333333333333333333333332
UV33333333333333333333333333333333333333333333332
W3333333333333333333333333333333333333333333333332
V3333333333333333333333333333333333333333333333332
VW33333333333333333333333333333333333333333333332
V9$>G3333333333333333333333333333333333127
VA%ME333333333333333333333333333333333127
VB3333333333333333333333333333333333333333333330
208

You might also like