SILICON COMPOSERS

Introduces the SC/FOXm Single Board Computer32 Using the SC32'" Forth Chip

0000000000000000000000000)SC~F~X~ooo~ooooooooooooooooooooo50 O~~~~~OOOOOOOOOOOOOOOOOOOO~,,SBC~~,~OOOOOOOOOOOOOOOOO~~OOOOO~~~O

EPROM

SRAM

SRAM

000000

SC/FOX SBC32 (Single Board Computer32) SC/Forth32 Interactive Language -16, 20, or 24 MHz lnput clock operation. *Forth 83 standard with 32-bit extensions -64K to 512K bytes 0-wait-state SRAM *Vectored I/O and recursion. -64K bytes of shadow EPROM. *Supports ASCII text file or block source code. *SC/Forth32 in EPROM included. -Double number (64-bit) support. -56-Kbaud RS2.32 . .Extended control structures. *Two 50-pin applicat~onheaders. *Byte, word, and long word access -4 Layer, Eurocard size lOOmm by 160mm. *Microcode support for custom SC32 instructions *Optional prototyping plug-on board *Easy turnkey system generation .Retall from $995 wyi SC/Forth32 *Compatible with SC/Forth for RTX 2000

SC32 Forth Chip SC/FOX Development System -32-bit CMOS nucroprocessor in 85-pin PGA. *MS DOS screen editor with pull-down menus .I-cycle instruction execution. *Load and run from editor capabil~ty .Nan-multiplexed 32-b~tadr bus & data bus .Program spawning wth exit back to editor 16 Gbyte contiguous data space. .Multiple file loading. -2 Gbyte non-segmented code space -Advanced block copy and move feature Ideal for embedded-systems control, high precision numercial processing, data acquisition, and process control applications. For additional information, please contact call us at: SILICON COMPOSERS INC, 208 California Avenue, Palo Alto, CA 94306 (415) 322-8763

Forth Dimensions 2 Volume XII, Number 3 FORTH D IMENSI ONS

rn DYNAMIC VIRTUAL MEMORY MANAGEMENT - ANTERO TANALSAARI 7 With these virtual memory management extensions to Forth, persistent storage space for data items can be allocated and deallocated dynamically. A simple heap-based memory compaction mechanism is used, and the extensions are proven functional in F83 (but they should be quite portable). rn DYNAMIC MEMORY ALLOCATION - DREAS NIELSEN 17 Many programs handle data elements of indeterminate size or number, but you needn't statically allocate a buffer capableofholding the largest possible datum. Explicit control of dynamic memory allocation is a powerful tool. Many f algorithms-and data structures like linked lists, queues, and trees-are difficult to implement efficiently without it. m SMART RAM -ROB CHAPMAN 28 The concept of smart RAM can be applied in many other areas. When developing a new Forth, the author used it to interactively and incrementally test the Forth, monitor the performance of each word, and tune it for the 68000. It could also be used to speed up slow RAM, even to intercept slow instructions or data moves and do them while the processor t is not using memory. m TESTING TOOLKIT - PHIL KOOPMAN, JR. 31 Forth supports interactive development and testing, but interactive testing isn't always enough. Sometimes we want a permanent record of test cases for Forth words to serve as documentation. A full suite of test cases ensures that a change in one part of the program does not disturb other parts. m FORST: A 68000 NATIVE-CODE FORTH - JOHN REDMOND 34 This is the second in a three-part series about a 32-bit, subroutine-threaded Forth for the Atari ST, whose OS "...is pretty much a 68000 clone of MS-DOS."The system has a number of interesting and unique characteristics, but attention has been given to compatibility with existing source code. This installment may cure your C envy!

m Editorial Reference Section 4 39 Letters Ad Index 5 41 Best of GEnk FIG Chapters 3 7 42-43

Volume XII, Number 3 3 Forth Dimensions Forth Dimensions Published by the Forth Interest Group Volume XII, Number 3 Septernber/October 1990 Editor Marlin Ouverson Advertising Manager Kent Safford Design and Production Berglund Graphics

Ifyou haven't paid close attention to Speaking of Glen Haydon (of MVP- Forth Dimensions welcomes editorial mate- the growth of on-line Forth activity, you FORTH, WISC, etc.), he has completed a rial, letters to the editor, and comments from its readers. No responsibility is assumed for accu- may be surprised. Forth programs, debates, significant revision of his book All About racy of submissions. questions, news, and insights are being Forth. It has long been popular as the Subscription to Forth Dimensions is in- working reference volume of definitions, shared between several BBSs and larger cluded with membership in the Forth Interest communication systems-including some implementation examples, and relevant Group at $30 per year ($42 overseas air). For international ones-thanks to their respec- details about a widely used set of Forth membership, change of address, and to submit tive sysops and to both electronic and words. But the recent, greatly revised and items for publication, the address is: Forth Inter- manual gateways between systems. There expanded version makes the book an anno- est Group, P.O. Box 8231, San Jose, California is more reason than ever to tune in to the on- tated glossary of practically allForth words 95155. Administrative offices and advertising line Forth community. FD's "Reference in common usage, in all the primary dia- sales: 408-277-0668. Section" lists the electronic resources we lects. Implementation examples are given Copyright O 1990 by Forth Interest Group, find and, despite some past problems, we in high-level Forth or 8086/88 assembly Inc. The material contained in this periodical try to keep it both current and complete. language to help clarify the text of a word's (but not the code) is copyrightedby the individ- (You can help by informing us of changes definition. When in doubt, just look it up! ual authors of the articles and by Forth Interest and additions.) This essentially new book is, in my opin- Group, Inc., respectively. Any reproduction or If you didn't log on in August, you ion, an important contribution to every use of this periodical as it is compiled or the ar- missed meetings scheduled with Bill Forth programmer's workbench. Look for ticles, except reproductions for non-wmmer- Ragsdale and Glen Haydon. To further it on the FIG Mail Order Form. cia1 purposes, without the written permission of encourage your virtual presence on at least Forth Interest Group, Inc. is a violation of the one of these electronic venues, upcoming Copyright Laws. Any code bearing a copyright guest conferences on GEnie's Forth If you live in Memphis, notice, however, can be used only with permis- RoundTable include: don't blame us.. . sion of the copyright holder. Publishing News reported that seventy- Dick Miller, President of Miller Micro- five percent of monthly magazines were About the Forth Interest Group The Forth Interest Group is the association computer Services delivered late in early 1990, an increase of programmers, managers. and engineers who DOS" over last year. Memphis, Tennessee had the "To DOS or Not to create practical. Forth-based solutions to real- Thursday, September 20 worst record (none delivered on time) and worldneeds. Many research hardware and soft- 9:30 p.m. Eastem/6:30 p.m. Pacific San Mateo, California had the best record ware designs that will advance the general state (one hundred percent). of the art. FIG provides a climate of intellectual JefRaskin, originator of the Apple Mac and exchange and benefits intended to assist each of the Canon Cat -Marlin Ouverson its members. Publications, conferences, semi- "What Happened to the Cat?" Editor nars, telecommunications, and area chapter Wednesday, October 17 meetings are among its activities. 9:30 p.m. Eastern/6:30 p.m. Pacific

(Note that the October conference is on Wednesday instead of the usual Thursday.) "Forth Dimensions (ISSN 0884-0822)is published bimonthly for $24/36 per year by the Forth Interest Group, 1330 S. Bascom Ave., Suite D, San Jose, CA 95128. Second-class postage paid at San Jose. CA. POSTMASTER: Send address changes to Forth Dimensions, P.O. Box 8231, San Jose, CA 95155."

Forth Dimensions 4 Volume XII, Number 3 Language of Choice can do much more is beside the point. the "Forth Dictionary" tends to be- Dear Sir, Koopman's request for programmers to come a dialect of the programmer, Iagree with Philip Koopman Jr.'s call to go public with their experiences in Forth making it almost impossible to read and market Forth for what it is, the premier projects is good. We may think Forth is be maintained by any other program- controller language (FD XII/l). I'm not a great, but it would help a lot if some hard mers... professional programmer, but I am a fan of facts about time and money would back up Forth. that opinion for businesses to act upon. It does seem that embedded systems, Koopman hits the mark by spotlighting For publicity, I believe a Forth version withoutakernel, that can beused to mecha- the perception of Forth. I'm looking at a of Steve Ciarcia's "Circuit Cellar, Ink." nizeoperations for well-defined situations, well-balanced article written by Dara would be an ideal showcase. The Forth could help. With enough systems or parts Pearlman and published in the September chips are out there. So why not encourage available that can easily be used with all 1983 issueof Popular Computing. It led me the Forth hackers? The Forth hardware CPUs, use could not help mutl increase to send for the fig-FORTH listing years people should take a good look at this. acceptance. ago, But the article's title says it all: "Forth Koopman calls us to actively promote It's not the whole answer.. . Inspires a Fanatic Following-But Why Forth now. The expansion of microcompu- Hasn't It Taken the World by Storm?"Next ters into everything gives Forth a rare op Phil Chadwick to it is a color photograph of the original portunity to be like those caterpillars that 358 Thompson Mill Road FIG five in their FIG t-shirts and waving march around in a circle until they die. It New Hope, Pennsylvania 18938 copies of Forth Dimensions. I fear that, in does need to focus on a single marketing the public's mind. Forth is a strange lan- goal. Why not the one for which it was Standards Notwithstanding guage promoted by even stranger fanatics. created? I have been using Forth continuously The perception of a language is its Yours truly, (but not exclusively) since 1975. I started theme, the one-sentence statement that with my own creation, which has grown defines the problem it solves for the com- Walter J. Rottenkolber into a very viable system. I have also used puting public (preferably a large segment P.O. Box 936 the most notable commercial versions. of it). BASIC, for example, was created to Visalia, California 93279 Chuck Moore's statement ("Best of introduce computers to Social Science stu- GEnie," FD XI/5) inspires the following dents at Dartmouth. It fulfilled the need of Dear Editor, comments based upon experience: the novice for an easy way to learn to use a I agree with most of Philip Koopman, computer. That BASIC can now be found Jr.'s article. To me, additional definitions 1. Classic Forth consists of a few ele- as a complex, structured, compiled lan- are so logical and not too hard to follow, but mentary definitions ( ' is tick an address, ! guage is beside the point. others seem to consider it witches' brew. is store a word, etc.), a philosophy of pro- The result, Koopman points out, is a Consider the Forth definition in Gespac's gramming tasks, and a definite form in lack of marketing focus in promoting Glossary of Technical Terms (1989): which the program is expressed (numbers Forth. This has caused Forth to lose the precede commands, names follow, and synergism from a strong, consistent mar- Forth is a high level language that is space is the only delimiter). The philoso- keting sponsor. Where would BASIC be if based on a very small kernel. It allows phy seems to be the hard part to grasp for not for Dartmouth, Microsoft, Apple, and user[s] to define instructions which can the uninitiated, perhaps because it is al- all the other home computer companies and then be used to define other, higher level ways cryptically demonstrated and is sel- universities who found in BASIC an ideal instructions, which can be used to define dom simply expressed. vehicle to sell their products and services? higher level instructions and so on .... 2. Complex operations do not survive Forth has to be marketed for what it is, the Experienced Forth users worship that the test of time. Simpler ways evolve, or ideal way for a business to save time and language. Forth, however, has been they are returned to the vocabulary. money programming controllers. That it banned by most corporations because 3. VOCABULARY has a purpose only if

Volume XII, Nwnber 3 5 Forth Dimensions it speeds up compilation and FORGET^^^. ation (in a conniving sense). Methods using EMIT (C -- ) It is great for task management. Other uses logic operations are often much more ELSE ( -- ) are probably abuses. efficient. SHIFT and 2". 2/, 4*, 4/, 8*, DROP (c--) 4. My Forth has been recreated just 8 /, etc. are often better choices if you THEN (--)

about every year. Little has gone untried, understand what you are doing. I ( -- 1 and useless things have fallen by the way- 14. Floating-point arithmetic is bad. side. This is an inherent part of the life of But it is no joke if its abuses are not ac- The stack comments could be checked to Forth. counted for when calculating something see that all inputs and outputs were prop- 5. Forth and Standard Forth are contra- like the strength of the floor you are stand- erly matched, a big time saver; and it would dictions of definitions (terms). Any par- ing on. Errors can far exceed tolerances. encourage the use of stack comments. ticular Forth contains only the necessary 15. Source code is withheld because of Yours uuly, common definitions, adaptations, and ex- mass commercial intent or because it is not tensions to do a particular job. A Standard presentable (often both). Forth is best used Ken Kupisz Forth would require all definitions to be for customized adaptations which have Ontario Hydro common, even adaptations and extensions little mass commercial appeal. However, 700 University Avenue (as do BASIC, Modula 11, etc.). publish the source code of an interesting Toronto. Ontario 6. Some programmers cannot compre- Forth program-no matter how unpre- Canada MSG 1x6 hend the philosophy of Forth; this relegates sentable-and the Forth community will them to use other languages and lose the correct it, improve it, adapt it, and return it [And remember to account for words that benefits of Forth, or to use aForth compiler for little or no cost. Beat that, if you can. leave a varying number of stack items, that does not require such understanding (if depending on run-time conditions.. .--Ed.] somebody can invent one). Forth is thebest programming language 7. The ideal Forth machine has not yet for those who can master it and bend it to Return to DO-FOREVER been demonstrated. Much of Forth can be their needs. I will be using a flexible, adapt- Dear Marlin, parallel processed (but mostly not in the able version of Forth for the rest of my life Oops, DO-FOREVER as printed in commonly thought-of way). (standards committee notwithstanding). Forth Dimensions XIVl won't even load, 8. QWERTY keyboards (or some sub- much less run. Somewhere in all the stitute) are necessary for common editing Fred F. Kloman changes it correctly acquired an IF but (data-entry stage). All other needs are man- 3533 DeLeone Road failed to acquire a matching ENDIF. The aged better by a logic tree and a very few San Marcos, California 92069 minimal correction would be to insert an keys. Forth is a natural at executing logic END IF immediately before the semi-co- trees. He Wants a New View lon. In my letter of January 23, I tried to be 9. IBM-type PCs are a collection of In the interest of software quality, more elegant and added an error message in design compromises incorporated to lock wouldn't it be nice if there were a utility case the user types an undefined word. [See customers into a commercial operation that which would help in the data-flow analysis Figure One.] continuously requires additional expendi- of a colon definition? Perhaps a modifica- Best wishes, ture for both software and hardware. Ex- tion to VIEWin F-PC. The idea is to have tremely expensive, high-speed processors the colon definition displayed, one word Tom Napier are required to overcome this burden. The per line, with its stack comment. E.g., One Lower State Road efficiency of Forth permits a very inexpen- ) North Wales, Pennsylvania sive, moderate-speed processor to outper- ?EMIT (C -- ) form the IBM type. DUP (C -- c C) 10. Experiment until you fully under- IF (f -- C) stand, and program only what you do fully understand. This demonstrates the defini- tion of "smart." Forth is the most natural execution of this philosophy. 11. Because of its adaptability and ex- : DO-FOREVER ( repeat next word until keyboard input ) tensibility, real Forth is master of what it -FIND has to do. Standard Forth would be master- IF DROP CFA ( this is FORTH ) of-none, but it could become acommercial, BEGIN DUP EXECUTE ?TERMINAL UNTIL DROP I general-purpose master-of-none like most ELSE CR ." Do what?" 1 other standard languages. 12. PUSH and POP are longer words for ENDIF ; >R and R>. Long natural words are for I users of applications; short, cryptic sym- I Figure One. DO-FOREVER as it ought to be. bols are for programmers. 13. Multiply and divide are overused, but require less understanding of the situ-

I Forth Dimensions 6 Volume XII. Number 3 DYNAMIC VIRTUAL MEMORY MANAGEMENT ANTERO TAIVALSAARI - TAMPERE, FINLAND rn

Inthis article we shall present dy- acteristics of Forth is its unique way to With the basic virtual memory com- namic virtual memory management exten- handle virtual memory. In Forth, a virtual mands of Forth, different kinds of database sions to Forth. With the extensions, persis- memory device-typicall y a disk drive-is systems are quite easily implemented. tent storage space for data items can be al- accessed in 1K blocks by using a very However, as typical of most database man- located and deallocated dynamically in limited but powerful set of words. Disk agement systems based on traditional stor- Forth's virtual memory, and the sizes of the blocks can be loaded to main memory buff- age models (hierarchical, network or rela- data items can be changed at any time. A ers by giving a block number and the tional), these database systems tend to be simple heap-based memory compaction command BLOCK. The buffer can then be rather dependent on physical aspects of the mechanism is used in order to keep the examined and modified; the Forth system storage system and data. Such things as file blocks unfragmented. The extensions are will automatically save the buffer into the sizes, data item sizes, and physical loca- proven functional in Laxen & Perry's F83, disk if the user marks the buffer updated. tions of data must occasionally be taken but they should be quite easily portable to into serious consideration at the other Forth models, too. programmer's level. Also, traditional stor- .. .can also be used for age models resmct the modifiability of the Introduction dynamic databases database. For example, the sizes of data Forth is a multidimensional program- items must usually be determined during ming language which has many character- not tied to traditional the creation of the database, which can be istics that are normally related only to the models. very inconvenient if the description . One of the special char- (schema) of the database is to be changed

Screen 0 Screen 20 ...... \ DISKHEAP.BLK Apt 29.10.89 Antero Taivalsaari * Ruovedenkatu 13 D 54 Dynamic virtual memory management.

+ SF-33720 Tampere * FINLAND Example: * Electronic mail: [email protected] (128.214.7.5) ...... variable varl \ defines variables for storing indexes FILE.....: DISKHEAP.BLK variable var2 \ to handles. * PURPOSE..: Dynamic virtual memory management extensions createHeap test.blk \ creates a new diskheap 'test-blk'. * : to Forth-83. 20 allocate varl ! \ allocates 20 bytes referred by varl. * REQUIRES.: F83.COM varl @ area /area type \ types contents of varl. * AUTHOR.. . : Antero Taivalsaari 40 allocate var2 ! \ allocates 40 bytes referred by var2. * DATE.....: 29.10.1989 50 varl @ resize \ resizes data-area of varl to 50 bytes...... var2 @ free \ disposes data-area of var2.

Screen 1 Screen 21 \ Constants, addresses, variables Apt 29.10.89 \ Constants, addresses, variables Apt 29.10.89

0 CONSTANT pointerBlk \ block for persistent pointers DiskHeap contains three different memory areas: pointer block, 6 CONSTANT /handle \ size of handle (= 6 bytes) handle block (s), and data block (s). Block 0 (pointerBlk) 170 CONSTANT handles/blk \ maxf of handles per block contains persistent pointers to handles and data. Handles, 1020 CONSTANT maxBytes/blk \ maxf of databytes per block which are static references to the data-area, begin from block 0 CONSTANT firstHandle \ index of first handle 1. Handle blocks are followed by data blocks which continue : lastHandle pointerBlk block ; \ index of last handle to the end of file. Since one handle block can contain only 170 : firstDataBlk pointerBlk block 2t ; \ blkf of first datablk handles, data blocks must occasionally be moved. When f of : lastDataBlk pointerelk block 4 + ; \ blkl of last datablk handles in the last handle block exceeds 170, a new block is : fofFreeHandles pointerBlk block 6 + ; \ # of free handles requested from DOS and the first data block is moved to this new block. The original first data block can then be used VARIABLE reUseHandles \ determines whether handles may be for storing handles. reUseHandles on \ reused after they are freed. -->

Volume XII, Number 3 7 Forth Dimensions Screen 2 Screen 22 \ Variables, offsets Apt 29.10.89 \ Variables, offsets Apt 29.10.89

VARIABLE currentelk \ blk# of current datablock Handles are referred with a simple 16-bit index, starting I VARIABLE currentHandle \ index# of current handle from 0. Handleindexes must be betweeflfirstHandle-1astHandle'. VARIABLE areasize \ size of current,data area Each handle contains three 2-byte fields, which are: - 'blk blkl of data-area, : 'blk ; immediate ( handleAddress -- *blk ) - 'offset offset to the beginning of data in the block, : 'off set 2t ; ( handleAddress -- 'offset ) - 'size current size of data-area. : 'size 4 t ; ( handleAddress -- 'size ) In the beginning of each data block there are following fields: : free/blk ( -- 'freesize ) - free/blk I of free data bytes in this block, currentelk @ block : - refs/blk reference count to this data block (tells how many handles refer to this data block).

Screen 3 Screen 23 \ handle>virtual inHandleRange? virtual>memory Apt 29.10.89 \ handle>virtual inHandleRange? virtual>memory Apt 29.10.89

Defer doError doError vectored error handling. ' abort is doError

: handle>virtual ( handleIndex -- offset block ) handlewirtual returns virtual address of a handle. handles/blk /mod swap /handle swap 1t ;

: inHandleRange? ( handleIndex -- ) inHandleRange? ensures that handle index is between the firstHandle lastHandle @ 1- between not values of variables 'firstHandlel and IF ." - Not in handle range " doError THEN ; 'lastHandlef . : virtual>memory ( offset block -- address ) block t ; virtual>memory fetches a virtual block to memory and returns I --> the sum of its address and the parameter 'offset'.

Screen 4 Screen 24 \ handle free? roomForNewHandle? tooBig? Apt 29.10.89 \ handle free? roomForNewHandle? tooBig? Apt 29.10.89

: handle ( handleIndex -- handleAddress ) handle fetches a handle from virtual memory and dup inHandleRange? handle>virtual virtual>memory ; returns its address in a disk buffer. I : free? 'blk @ 0- ; ( handleAddress -- flag ) free? tests whether handle is free (that is: field 'blk is zero). : roomForNewHandle? ( -- flag ) roomForNewHandle? 1astHandle @ handle>virtual nip firstDataBlk @ C ; tests whether current handle block has room for one more handle. : tooBig? ( size -- 1 tooBig? ensures that we shall not try to allocate maxBytes/blk > data-areas of over 1020 bytes. IF ." - Cannot allocate over 1020 byte areas ' doError THEN ; -->

Screen 5 Screen 25 \ convertHandles Apt 29.10.89 \ convertHandles Apt 29.10.89

: convertHandles ( oldBlock lastBlock -- ) convertHandles this word is used when a data block is over currentelk ! moved to another block. All references 1astHandle @ to 'oldBlockf are changed to refer to refs/blk @ 0 ?DO 'newBlockf . BEGIN 1- dup handle dup currentHandle ! 'blk @ 3 pick = UNTIL over currentHandle @ 'blk ! update LOOP drop 2drop ; -->

Forth Dimensions 8 Volume XII, Number 3 Screen 6 Screen 26 \ firstDataBlk>newBlk makeNewHandle Apt 29.10.89 \ firstDataBlk>newBlk makeNewHandle Apt 29.10.89

: firstDataBlk>newBlk ( -- ) firstDataBlk>newBlk requests a new block from DOS and copies 1 more the first data block to this new block. 1 1astDataBlk +! update This word is used when old data blocks are firstDataBlk @ 1astDataBlk @ 2dup copy convertHandles changed to handle blocks. 1 firstDataB1k t! update firstDataBlk @ currentelk ! ; makeNewHandle creates a new handle. If there is no room for a new handle in the current handle : makeNewHandle ( -- handlerndex ) block, then 'firstDataB1k>newBlk1 is roomForNewHandle? not executed. IF firstDataBlk>newBlk THEN lastHandle @ 1 1astHandle +! update ; -->

Screen 7 Screen 27 \ findOldHandle giveHandle Apt 29.10.89 \ findOldHandle giveHandle Apt 29.10.89

: findOldHandle ( -- handleIndex ) f indOldHandle finds a free handle from existing 1astHandle @ handles. This word is used if 'reUseHandles BEGIN 1- dup is ON, and lofFreeHandles is > 0. handle free? UNTIL giveHandle gives a free handle. If IreUseHandles' is -1 lofFreeHandles +! update ; OFF or (ofFreeHandles = 0, then a new handle must be created. : giveHandle ( -- handleIndex ) XofFreeHandles @ reUseHandles @ and IF findOldHandle ELSE makeNewHandle THEN ; -->

Screen 8 Screen 28 \ roomInCurrentBlk? makeNewDataBlk >endOfData Apt 29.10.89 \ roomInCurrentBlk? makeNewDataBlk >endOfData Apt 29.10.89

: roomInCurrentBlk? ( size -- flag ) roomInCurrentBlk? tests whether current data block has room free/blk @ > not ; for 'size' more bytes.

: makeNewDataBlk ( -- ) makeNewDataB1 k creates a new empty data block and sets 1 more the relevant pointer values. Initially 1 1astDataBlk t! update there are no handles referring to this 1astDataBlk @ currentBlk ! block ('refs/blkl = 0) and the free space maxBytes/blk free/blk ! in the block is 'maxBytes/blkl. 0 refs/blk ! update ; >endOfData returns the address of the first free byte : >endOfData ( -- address ) in the current data block. b/buf free/blk @ - ;

Screen 9 Screen 29 \ findNextBlk allocateRoorn Apt 29.10.89 \ findNextBlk allocateRoom Apt 29.10.89

: findNextBlk (size-- ) findNextBlk finds the next data block having room false lastDataBlk @ currentBlk @ ?DO for 'size' bytes. This block is then made i currentBlk ! current. If existing blocks do not have over roomInCurrentBlk? enough room, a new block is created. IF drop true leave THEN LOOP nip allocateRoom allocates 'size' bytes from current data not IF makeNewDataBlk THEN ; block and returns the virtual address of this new data-area. 'free/blk' and : allocateRoom ( size -- offset blk ) 'refs/blkl are updated. The allocated >endOfData >r r@ currentelk @ virtual>memory area is erased to all zeros. over erase negate free/blk t! 1 refs/blk t! update

1 1 Volume XII, Number 3 9 Forth Dimensions Screen 10 Screen 30 \ findRoom Allocate Apt 29.10.89 \ findRoom Allocate Apt 29.10.89

: findRoom ( size -- offset blk ) f indRoom locates the next data block that has enough room dup roomInCurrentBlk? not for 'size' bytes and return the virtual address IF dup findNextBlk THEN of this new data-area. allocateRoom ;

: Allocate ( size -- handleIndex ) Allocate allocates 'size' bytes from diskHeap and returns dup tooBig? ************** the handle index of this new data-area. The giveHandle >r new data-area is erased to all zeros. dup findRoom r@handle >r r@'blk 2! This is one of the basic commands in dynamic r> 'size ! update virtual memory management. ( save-buffers ) r> ;

-->

screen 11 Screen 31 \ handleupdate ~~t 29.10.89 \ handleupdate Apt 29.10.89

: handleupdate ( +/-n offset -- ) handleupdate increments or decrements the 'offset' fields of 1astHandle @ handles pointing to the current data block refs/blk @ 0 ?DO according to the parameter 'n' in case BEGIN 1- dup the 'offset' of a handle is >= than the parameter handle dup currentHandle ! 'offset'. This word is used when the size of 'blk @ currentBlk @ = an existing data-area changes. UNTIL Note that thanks to reference counter 'refs/blkl over currentHandle @ 'offset @ > not we don't necessarily have to loop through all IF 2 pick currentHandle @ 'offset t! update THEN the handles. LOOP drop 2drop ;

Screen 12 Screen 32 \ moveData Apt 29.10.89 \ moveData Apt 29.10.89

: moveData ( +/-n handleAddress -- ) moveData moves the data-areas above the data-area referred dup 'offset @ swap 'size @ t by 'handle1ndexf in the current data block 2dup handleupdate upwards or downwards in the block according to >endOfData over - >r the parameter 'n' (positive n = upwards, negative currentBlk @ virtual>memory = downwards). The 'offset' fields in handles are tuck + r> move update ; also updated (handleupdate) . This word is used when the size of an existing data-area changes.

Screen 13 Screen 33 \ Free Apt 29.10.89 \ Free Apt 29.10.89 ************** : Free ( handleIndex -- ) Free frees existing data-areas. The data block is dup handle >r r@free? +************* compressed by moving the rest of data in the IF r> 2drop ." - Handle already free " doError THEN block downwards; the counter 'free/blk' is r@'blk @ currentBlk ! incremented with the size of freed data-area, r@'size @ negate r> moveData and the reference counter 'refs/blkf is handle dup 'blk off update decremented by one. The handle to the 'size @ free/blk t! deallocated data-area is marked free by storing -1 refs/blk t! update '0' into the 'blk' field of the handle. Then the 1 XofFreeHandles t! update number of free handles is incremented by one. ( save-buffers ) ; This is one of the basic commands in dynamic virtual memory management.

I Forth Dimensions 10 Volwne XII, Number 3 Screen 14 Screen 34 \ area /area Apt 29.10.89 \ area /area Apt 29.10.89 **.t*tt** : area ( handlelndex -- address ) area thls word is used to fetch a data-area from virtual handle dup free? ********* memory into a disk buffer. The word returns the IF drop ." - Handle not in use " doError THEN address of the first byte of data into the parameter dup 'size @ areasize ! stack. A pointer to the size of the data-area is 2@ virtual>memory ; stored to the variable 'areasize' for the word '/area ********* /area returns the size of the current data-area. ***.*.*** These are basic commands in virtual dynamic memory management. -->

screen 15 Screen 35 \ expandCurrentB1 k Apt 29.10.89 \ expandcurrentelk Apt 29.10.89 expandCurrentBlk expands the data-area referred by the : expandcurrentelk ( sizeMore handleIndex -- ) 'handleIndexr 'sizeMore1 bytes. dup handle >r r@'size @ The expansion is accomplished by moving IF over r> moveData all the data-areas that are located higher ELSE >endOfData currentelk @ r> 'blk 2! in the block 'sizeMoree bytes upwards in THEN the block. The reserved new data space is over negate free/blk +! erased to all zeros. dup area /area + 2 pick erase update handle 'slze t! update ;

Screen 16 Screen 36 \ moveToOtherBlk Apt 29.10.89 \ moveToOtherBlk Apt 29.10.89 moveToOtherB1k moves an existing data-area to another : moveToOtherBlk ( sizeMore handleIndex -- ) block and at the same time expands the 2dup handle 'size @ + dup data-area 'sizeMore' bytes. findNextBlk allocateRoom \ allocate new room This command is used when the free space 2dup >r >r virtual>memory \ fetch to memory in the original block is insufficient over area swap /area cmove update \ move to new room for 'sizeMore' byte expansion. The data dup handle >r re 'blk @ currentelk ! \ space in the original block is freed. r@ 'size @ negate r> moveData \ free existinq space handle >r r@ 'size @ free/blk +! \ in the original -1 refs/blk t! update \ block r@'size +! r> r> r> rot 'blk 2! update ; \ update handle

--> ( huh, but it works! )

Screen 17 Screen 37 \ expanarea Apt 29.10.89 \ expandArea Apt 29.10.89 expandArea expands the data-area referred by the : expanarea ( slzeMore handleIndex -- ) handle 'handleIndexl 'sizeMored bytes. If swap 0 max over there is not enough free space in the handle >r re 'size @ over + tooBig? original block, the data-area 1s moved r> 'blk @ currentBlk ! to another block. When needed, a completely tuck roomInCurrentBlk? new block is requested from DOS. IF expandCurrentBlk Remember that the size of a data-area cannc ELSE moveToOtherB1k exceed 1020 bytes. THEN ( save-buffers ) ;

I J Volume XII, Nwnber 3 11 Forth Dimensions Screen 18 Screen 38 \ shrinkArea Resize Apt 29.10.89 \ shrinkArea Resize Apt 29.10.89 shrinkArea shrinks the data-area referred by the : shrinkArea ( sizeLess handleIndex -- ) 'handleIndex' 'sizeLessf bytes. This is swap 0 max over accomplished by moving all the data-areas handle >r r@'size @ min negate swap higher in the block downwards 'sizeLessf r@'blk @ currentBlk ! bytes in the block. over r> moveData ******************* over negate free/blk t! Resize resizeahedata-areareferredbythehandle handle 'size +! update ( save-buffers ) ; ******************* 'handleIndexl to 'newsize' bytes.

: Resize ( newsize handleIndex -- ) This is one of the basic commands in >r r@handle 'size @ 2dup <> dynamic virtual memory management. IF Zdup > IF - r> expandArea ELSE swap - r> shrinkArea THEN ELSE 2drop r> drop THEN ; -->

Screen 19 Screen 39 \ createHeap useHeap Apt 29.10.89 \ createHeap useHeap Apt 29.10.89 ************** : createHeap ( -- ) \ usage: createHeap filename createHeap creates a new diskHeap. The size of a new heap 3 create-file ************** is three blocks (0 = pointer block, 1 = handle 0 1astHandle ! block, 2 = data block). 2 firstDataBlk ! ************** 2 lastDataBlk ! useHeap takes an existing diskHeap in use. firstDataBlk @ currentelk ! ************** 0 XofFreeHandles ! update maxBytes/blk free/blk ! 0 refs/blk ! update save-buffers ;

: useHeap ( -- ) \ usage: useHeap filename open firstDataBlk @ currentBlk ! ;

frequently later. data blocks unfragmented and the size of be operating system extensions to Forth; Our original intention in the develop- the database moderate. older overlay systems, for example, could ment of these dynamic virtual memory be rather easily and more elegantly reim- management extensions has been to create In the literature, many different ap- plemented with dynamic virtual memory persistent object storage for the author's proaches to object-oriented database sys- extensions. One of our future visions has object-oriented, Forth-based language tems have been presented (see, for ex- also been to build a dynamic persistent Kevo [Tai89, Tai901 (the language was ample, MS086, Bee87, LiS88, and Forth, completely based on dynamic vir- previously called Cool, but was renamed Low88). By analyzing several alternatives, tual memory. because other languages under that name we concluded that a simplified version of a appeared to exist already). In the develop- heap-based storage system [ACCS 1, Har88 Main Ideas ment of such a storage system the following p.261 would be quite sufficient for our pur- We shall not explain the function of the design goals were listed: poses. For main memory management, extensions very carefully. The basic prin- heap extensions to Forth have already been ciples of heap memory management are Allocated data items (objects) should presented by Dress [me861 and Pountain quite well documented already [Dre86]. persist between different sessions and [Pou87]. Therefore, our main task has actu- Furthermore, our code is rather well com- programs. ally been to modify the existing heap mented and thereby should be easy to The objects should be referred to by mechanisms to work with virtual buffers understand. A brief description of the main using only a simple identifiers (values) instead of main memory. technical details is given, though. that canbe easily passed as parameters or These extensions have proven to be stored to other data structures. functional as persistent object storage. Storage areas Physical aspects such as file sizes, loca- However, they should be useful in any In a heap memory management system, tions of objects, and sizes of objects application where the sizes of virtual data the storage space is usually divided into should be unimportant to the user. items are to change frequently. Such sys- two different regions. The first one con- Data objects could be allocated and deal- tems include, for example, textual data tains handles: statically located references located dynamically "on the fly." bases or hypertext applications. The exten- to the data items. The actual data items are The sizes of objects must be able to sions can also be used as a kernel for new located in another memory region called change dynamically. kinds of dynamic databases not bound to the data area. The locations of items in the A simple but effective garbage collection any of the traditional database models. data area may vary, since access to the mechanism must be provided to keep the Other interesting application areas might items takes place indirectly via handles. 1 Forth Dimensions 12 Volume XII, Nwnber 3 In a virtual heap system ("diskheap"), the current size of the data area (see Figure always located in the end of the block. both the handle and data areas must be Two). If the data area referred to by a Since the size of adata block is only 1Kand located in virtual memory. In addition to handle is deallocated, a zero value is stored the compaction is done in a main memory these memory areas, some persistent point- to the block number field (first two bytes) to buffer, the compaction can be done very ers and indexes to the handle and data mark the handle free. The special variable quickly. Of course, when moving data, the blocks are also needed. Therefore, in our reUseHandles can be used to specify virtual data addresses (blocks, offsets) of system the disk file (heap) is divided into whether free handles may be reused. When the handles referring to the affected blocks three different regions: pointer block, reUseHandles is turnedoff,thesystem must also be changed, and that is more handle blocks, and data blocks. The pointer may work a bit faster but, at the same time, time-consuming. block is located at block zero and is fol- will need more space for the handles. The When a data area is expanded, it may lowed by the handle blocks and data blocks, default is reUseHandles on. happen that the free space in the data block whichcontinue to theendof file (seeFigure Since one Forth disk block is 1024 becomes inadequate. In that case, free One). bytes, it can contain a maximum of 170 space will be searched for in the blocks handles. In case the number of handles in a following the current data block (cur- Handles handle blockexceeds 170,anew disk block rent~lk). If a data block that has room Handles are references to the data area. is automatically requested from DOS and for the expanded data area is found, the data The location of a handle is always static, so the first data block is moved to the new area is moved and expanded into that data the handles can be safely referenceddespite block; the original data block then becomes block. The storage space in the original the fact that the actual locations of data may a new handle block. data block is then freed and compacted. In vary. In our extensions, the handles are case no data blocks having enough room referenced via simple two-byte indexes. Data areas exist, a new block is requested from DOS. When a new data area is allocated, an index Data blocks are located after the handle Note that we have not implemented any to that new data area is returned. This index blocks. In the beginning of each data block, special mechanisms for finding free space must thereafter be remembered somehow, four bytes are reserved for system usage. in the existing data blocks. A heap opera- since it will be the only way to access the The first two bytes (£ ree/blk) tell the tion (allocation, deallocation, or resizing) data area. Because handle indexes are number of free bytes currently in the block. always leaves the latest affected block cur- simple values, they can be easily stored as The next two bytes (ref s /blk) hold a rent, and free space is then searched up- variables or passed as parameters. In order reference count telling how many handles wards beginning from this current block. to create complex persistent data struc- are currently refemng to this data block. For our purposes, this mechanism has tures, the handle indexes can. of course, be This simple reference count mechanism is proven to be fair and fast enough. stored to other data areas in the heap. Val- used to rev up theresizing of data areas. The The extensions do have some restric- ues of handle indexes range from zero (the rest of the block (1020 bytes) is used for tions. Since virtual memory handling is constant firstHandle) to the current storing data. done in 1K buffers, the size of a data area maximum handle index value, which is To avoid the need for complex garbage may not exceed 1020 (maxByt e s / ~lk) kept in the persistent variable last- collection mechanisms, the data blocks are bytes. This restriction can, though, be Handle. kept compacted all the time. Each time the avoided by defining higher-level words Handles are six bytes long. Each handle size of a data area changes or a data area is that will automatically allocate two or consists of a four-byte virtual address field deallocated, the rest of the data in the block more handles when the size of a data area (block, offset) telling the location of the is moved upwards or downwards in the exceeds 1020 bytes. One data area may data area, and of a two-byte field holding buffer, so the free space in a data block is then be physically composed of several

Blk # 0 Blk # 1 Blk I Blk-ff(~+l) Blk n

block number

offset

Pointer block Handle blocks Data blocks data area size ( max 1 70 handles/block) (Contents * free byte count * reference count * 1020 bytes of data)

Figure One. Structure of a diskheap Figure Two. Structure of a

Volume XII, Number 3 13 Forth Dimensions separate data areas. This kind of mecha- nism has been implemented in the author's Kevo system, but since the mechanism is more application dependent, we will not discuss it here. When implementing such extensions, we must of course keep in mind that in Forth the virtual memory blocks will not necessarily be loaded to a contiguous memory area.

Example A new diskheap is created simply by saying

createheap test.hea

This creates a new disk heap called test .hea which is initially three disk blocks long. Data areas can now be allo- cated by using the command allocate. In this simple example, we shall at first create two Forth variables and allocate data areas of 20 and 40 bytes. The handle in- dexes of the data areas are stored to the variables.

variable datal 20 allocate datal !

variable data2 40 allocate data2 !

The allocated data areas are initially erased to all zeros. To fill a data area with text we can use, for example, the standard Forth input word EXPECT which takes two para- Embedded Controller FORTH for the 8051 Family meters: the address where the string is to be W.H. Payne stored and the maximum number of input characters. These parameters are provided This book presents the technology required to develop hardware and software by the extension words area and /area. for embedded controller systems at a fraction of the cost of traditional methods. Included are hardware schematics of 805 1 family development systems (single datal @ board and bussed 805 1 microcontroller), as well as source code for both the 8086 I and 805 1 family FORTH operating systems. Binary images of the operating area /area expect systems can be generated from the source code using the metacompiler also update contained in the book. The book can be seen as a "toolbox" including all the necessary hardware and data2 @ software information to be used in constructing 805 1-based controller systems. , area /area expect September 1990, 528 pp., $49.95/ISBN: 0-12-547570-5 update flush To see the contents of the data areas we can use,for example, theForth word TYPE: Order from your local bookseller or directly from datal @ D AC AD EMIC PRESS Harcourt Brace Jovanovich, Publishers area /area type @ Book Marketing Dept. #35090,1250 Sixth Avenue, San Diego, CA 92101 data2 @ CALL TOLL FREE FAX I-31 4-528-5001 1-800-321 -5068 area /area type Quote this reference number for free postage and handling on your prepaid order b 35090 Prices sublecl to change wlthout notlce 81990 by Academlc Press. lnc. All Rlghls Reserved TCIMJD -35090.

ForrhDirmnrionr14 Volume XII, Nuder 3 The data areas were originally 20 and40 especially deallocation and resizing, if the M.P., Buneman, P., Morrison, R. bytes long. If we now want to change the disk heap is large. This is mainly because (eds): Data Types and Persistence, first data area to be 50 bytes long and the heap compaction may require going Springer-Verlag, 1988, pp.2 1-30. second data area to be 30 bytes, we can through all the handles in order to find the simply use the word RES I ZE: ones whose respective data areas are to be [LiS88] Linds~irn,Y., Sjibrg, D. "Data- moved during the compaction; more intel- base concepts discussed in an object- 50 datal @ resize ligent algorithms for handle management oriented perspective." In Gjessing, 30 data2 @ resize might be worth investigating. However, the S., Nygaard, K. (eds):Proceedings of efficiency can be much improved by adding ECOOP'88 European Conference Existing data areas can be deallocated more resident disk buffers to the Forth on Object-Oriented Programming by using the word FREE: system, thus decreasing the need for physi- (Oslo, Norway), 1988, pp.300-3 18 cal disk operations. A minimum of four datal @ free buffers is needed, but when using very ILow881 Low, C. "A shared, persistent data2 @ free dynamically changing disk heaps the rec- object store." In Gjessing, S., flush ommended number of buffers is at least Nygaard, K. (eds): Proceedings of eight. Since the extensions use the disk ECOOP'88 European Conference Note that we must remember to use the heavily. the speed of the disk device is also on Object-Oriented Programming word UPDATE to mark the buffer updated crucial. Although the extensions work cor- (Oslo, Norway), 1988, pp.390-408. whenever the contents of an existing data rectly on files, a hard disk- area are changed; the words FLUSH or preferably a fast oneisrecommended. [MS086] Meier, D., Stein, J., Otis, A., SAVE-BUFFERS CtIUSt also be occasion- The main reason for implementing Purdy. A. "Development of an ob- ally used. Before ending the use of a these virtual memory management exten- ject-oriented DBMS." In Meyrowitz, diskheap, FLUSH should always be exe- sions has been to create a persistent object N. (ed): OOPSLA'86 Conference cuted. storage kernel for the Kevo system; I have Proceedings (Portland, Oregon), An existing diskheap can be reopened had neither time nor the interest to optimize 1986, pp.472-482. with the command USEHEAP, e.g.: this low-level code yet. I would, however, [Pou87] Pountain, D. Object-oriented be grateful to receive any suggestions to Forth: implementation of data struc- useheap test.hea improve the code. tures. Academic Press, 1987. About Coding Acknowledgements [Tai89] Taivalsaari, A. "Cool - unifying Our code should be standard Forth-83. Many thanks to Mike Elola and Michael class and prototype inheritance." To Only a few F83-specific words are used. Perry for reading and commenting on the appear in Proceedings of FORML'89 Such words are MORE which is used to previous version of this article at Conference on Forth and object-ori- request more disk blocks from DOS, and FORMLY89.Without their encouragement ented programming (Pacific Grove, COPY which is used to copy a disk block to I may not have sent this article for publica- California), 1989. another. Other non-standard words are tion. [Tai89] Taivalsaari, A. "Implementing CREATE -F I LE to Create a new DOS file class inheritance without explicit and OPEN to open existing files. Of course, References classes." Submitted paper, 1990. the underlying Forth system must support [ACC81] Atkinson, M.P., Chisholm, KJ., block-oriented 110. Cockshott, W.P. "PS-Algol: An Al- In some definitions, the return stack is gol with a persistent heap." ACM Antero Taivalsaari is a Ph.D. student used heavily; the code could perhaps be SIGPLAN Notices Vol. 17 no. 7, of computer science at the University made more readable if more variables were 1981, pp.24-31. of Jyvaskyla, Finland. He has been used. However, we have tried to minimize an avid Forth programmer for seven the number of potentially shared variables [Bee871 Beech, D. "Groundwork for an years, the last two of which have in order to keep the definitions re-entrant. object database model." In Shriver. found him interested in object-ori- This is to allow the extensions to be used in B., Wegner, P. (eds): Research direc- ented programming, the theme of his future multiprogramming environments. tions in object-oriented program- doctoral dissertation. In the present form, however, multipro- ming, MIT Press, 1987, pp.317-354. gramming is not supported. [Dre86] Dress, W.B. "A Forth implementa- Efficiency tion of a heap data structure." Journal For our purposes, the extensions have of Forth Application and Research proven to be efficient enough. Accessing a Vol3. no. 3, 1986, pp.39-50. data area requires at most two physical disk reads: reading the handle and the data [Har88] Harper, R. "Modules and persis- block. Data area allocation, deallocation, I tence in standard ML." In Atkinson, or resizing, in turn, may take more time-

Volume XII, Number 3 15 Forth Dimension! HARVARD SOFTWORKS NUMBER ONE IN FORTH INNOVATION (513) 748-0390 P.O. Box 69, Springboro, OH 45066

MEET THAT DEADLINE ! ! ! WAKE UP ! ! ! HS/FORTH runs under MSDOS or ( PCDOS, or from ROM. Each level Use subroutine libraries written for Forth is no longer a language that includes all features of lower ones. Level upgrades: $25. plus price difference other languages! More efficiently! tempts programmers with "great between levels. Sources code is in Combine raw power of extensible expectations", then frustrates them ordinary ASCII text files. languages with convenience of with the need to reinvent simple carefully implemented functions! tools expected in any commercial All HSlFORTH systems support full Yes, it is faster than optimized C! language. megabyte or larger programs & data, and Compile 40,000 lines per minute! run faster than any 64k limited ones even without automatic optimization -- which Stay totally interactive, even while HEYFORTH Meets Your Needs! accepts almost anything and accelerates to compiling! near speed. Optimizer, Program at any level of abstraction Don't judge Forth by public domain assembler, and tools can load transiently. from machine code thru application products or ones from vendors Resize segments, redefine words, eliminate specific language with equal ease primarily interested in consulting - headers without recompiling. Compile 79 and efficiency! they profit from not providing needed and 83 Standard plus F83 programs. Alter routines without recompiling! tools! Public domain versions are STUDENT LEVEL $145. Use source code for 2500 functions! cheap - if your time is worthless. text & scaledlclipped graphics in bit blit Use data structures, control Useful in learning Forth's basics, windows,mono,cga,ega,vga, fast ellipses, structures, and interface protocols they fail to show its true potential. splines, bezier curves, arcs, fills, turtles; from any other language! Not to mention being s-1-o-w. powerful parsing, formatting, file and Implement borrowed feature, often device 110; shells; interrupt handlers; more efficiently than in the source! We don't shortchange you with call high level Forth from interrupts; single step trace, decompiler; music; Use an architecture that supports promises. We provide implemented compile 40,000 lines per minute, stacks; small programs or full megabyte functions to help you complete your file search paths; formats into strings. ones with a single version! application quickly. And we ask you PERSONAL LEVEL $245. Forget chaotic syntax requirements! not to shortchange us by trying to software floating point, trig, transcen- Outperform good programmers save a few bucks using inadequate dental, 18 digit integer & scaled integer stuck using conventional languages! public domain or pirate versions. We math; vars: A B * IS C compiles to 4 (But only until they also switch.) worked hard coming up with the words, 1..4 dimension var arrays; automatic optimizer-machine code speed. ideas that you now see sprouting up PROFESSIONAL LEVEL $395. HSIFORTH with FOOPS - The in other Forths. We won't throw in hardware floating point - data structures only flexible full multiple the towel, but the drain on resources for all data types from simple thru inheritance object oriented delays the introduction of even better complex 4D var arrays - operations language under MSDOS! tools. Don't kid yourself, you are not complete thru complex hyperbolics; just another drop in the bucket, your turnkey, seal; interactive dynamic liier for foreign subroutine libraries; round Seeing is believing, OOL's really are personal decision really does matter. robin & interrupt driven multitaskers; incredible at simplifying important In return, well provide you with the dynamic string manager; file blocks, parts of any significant program. So best tools money can buy. sector mapped blocks; x86&7 assemblers. naturally the theoreticians drive the PRODUCTION LEVEL $495. idea into the ground trying to bend The only limit with Forth is your Metacompiler: DOS/ROMldiredlindirect; all tasks to their noble mold. Add on own imagination! threaded systems start at 200 bytes, OOL's provide a better solution, but Forth cores at 2 kbytes; C data structures & stmct+ compiler; only Forth allows the add on to blend You can't add extensibility to Turbowindow-C MetaGraphics library, in as an integral part of the language fossilized compilers. You are at the 200 graphidwindow functions, Postscript and only HSFORTH provides true mercy of that language's vendor. You style line attributes & fonts, viewports. multiple inheritance & membership. can easily add features from other languages to HS/FORTH. And using PROFESSIONAL and PRODUCTION Lets define classes BODY, ARM, and our automatic optimizer or learning a LEVEL EXTENSIONS: ROBOT, with methods MOVE and very little bit of assembly language POOPS+ with multiple inheritance$ 75. RAISE. The ROBOT class inherits: makes your addition zip along as well 286FORTH or 386FORTH $295. INHERIT> BODY as in the parent language. 16 Megabyte physical address space or HAS> ARM RightAnn gigabyte virtual for programs and data; HAS> ARM LeftArm Speaking of assembly language, DOS & BIOS fully and freely available; If Simon, Alvin, and Theodore are learning it in a supportive Forth 32 bit address.operand range with 386. robots we could control them with: environment turns the learning curve BTRIEVE for HSIFORTH (Novell) $199. ROMULUS HSIFORTH from ROM$ 95. Alvin 's RightArm RAISE or: into a light speed escalator. People FFORTRAN translatorlmathpak $ 75. +5 -10 Simon MOVE or: who failed previous attempts to use Compile Fortran subroutines! Formulas, +5 +20 FOR-ALL ROBOT MOVE assembly language, conquer it in a logic, do loops, arrays; matrix math, Now that is a null learning curve! few hours or days using HSLFORTH. FFT, linear equations, random numbers.

Forth Dimensions Volume XII. Number DYNAMIC MEMORY ALLOCATION DREAS NIELSEN - BELLEVIEW, WASHINGTON

Manyprograms require the ability example, are difficult to implement with- General Principles to mani~ulatedata elements of indetermi- out it. A prerequisite for dynamic memory al- nate size or number. Text strings are an This article provides an introduction to location is a pool of contiguous available example of one such type of data: each the implementationof dynamic memory al- memory from which smallerblocks can be string may be a different length, and it is location, covering a few of the principles allocated. This free memory space is gen- usually neither feasible nor economical to and providing examples for illustration. erally called the heap; dynamically allo- statically allocate (at compile or assembly This is a topic that does not seem to be well cated subsets of it commonly are referred time) a buffer capable of holding the largest covered in the literature; indeed, Knuth to as blocks. The physical location of the possible string. Programs that manipulate (1973) and Aho, Hopcroft, and Ullman heap and the way in which it is isolated arrays of numbers often need to establish (1983) seem to be the only commonly from other features of the run-time envi- their memory requirements dynamically- available references that treat it in depth. ronment are dependent on the language in that is, at run time, without the use of a On the other hand, why would you want to use and, often, its implementation. These statically allocated buffer. Creation of know anything more about the implemen- details will not be considered here. (Dy- linked lists, trees, and other more complex tation of such an arcane feature, particu- namic allocation of space for local vari- data structures also typically cannot be larly if you are not writing a compiler or ables, which typically uses the stackrather carried out with statically allocated mem- operating system? First of all, you may than a heap, will also not be considered.) ory. The solution to this problem is to need (or want) to use a language which does Other issues related to dynamic memory provide the program with a means to dy- not intrinsically provide this feature but allocation, such as the identification of namically allocate memory at run time. does have the systems-programming capa- free blocks within the heap, the applica- Dynamically allocated memory is drawn bility to implement it. Secondly, the mem- tion interface, and efficiency considera- from the pool of main memory remaining ory allocation functions provided by a lan- tions, are more general. The following after a program has been loaded and the guage or standard library may not exactly discussion will address these topics. Note stack (and other language-specific data suit your needs. Curiosity, of course, may that although the principles described may structures) has been established. Dynamic be sufficient reason in and of itself. apply, for instance, to BASIC's dynamic memory allocation requires more complex - - string handling, they will not necessarily run-time support than static buffers (which allow you to add new dynamic memory require none), but provides greater flexibil- The heart of any mem- functions to BASIC or some other lan- ity. 1f the available memotis to be re-used guages. repeatedly for different purposes, the spe- ory allocation ioutine cial-purpose code needed to manipulate a a data structure. The Free List statically allocated block may beequiva- - - - - The heart of any memory allocation lent in size and complexity to that for gen- Despite the relative paucity of informa- routine is a data structure that identifies eral-purpose dynamic memory allocation. tion, dynamic memory allocation is not as the location of all free blocks of memory; Dynamic memory allocation is used by complex as it may seem. Furthermore, an this is conventionallycalled the "free list." many common languages. In some of these, understanding of the techniques and costs Typically it takes the form of a singly it is solely under the control of the language involved can help you decide when a gen- linked list in which each node identifies itself (e.g., strings in BASIC and dBase, all eral-purpose routine is suitable, when a the location of a block of available mem- objects in Smalltalk and Lisp); in others, specialized routine may be better, and ory, the size of the block, and the position partial or complete control is given to the when to do without dynamic memory allo- of the next node in the list. At first glance, programmer (e.g., Pascal, C, and Modula- cation. Source code for both a simple gen- allocation of storage space for the free list 2). Explicit control of dynamic memory eral-purpose routine and a more efficient itself would seem to be a problem. Ini- allocation is a powerful tool, and funda- specialized routine is provided for illustra- tially, all free memory would be in one mental to effective implementation of tion. The implementation of dynamic block, requiring only one node-but after many useful algorithms. Data structures strings is used as an example application of a series of allocations and de-allocations, such as linked lists, queues, and trees, for the general-purpose routine. the list may contain any number of nodes.

Volume XII, Number 3 17 Forth Dimensions Where and how, then, is the free list stored? Listing One One answer is to store the pointers to free memory in the free memory itself. This Screen 1 sounds a bit like a snake swallowing its own 0. ( Dynamic Menwry Allocation -- Screen 1 ) tail, but is actually quite simple and 1. ( Each block of free space begins with a 4-byte control block. straightforward to implement. A small The first word contains the address of the next free block portion of each free block is used to store [or 0 if none] and the second contains the number of bytes in the current block [including the control block]. ) the block size and pointer to the next node, as shown in Figure One (page 23). The ( Create pointer to begi~ingof free space, w/ size=O. ) pointers to the free blocks are therefore im- 2VARIABLE FREELIST 0 0 E'REELIST 2! plicit--the address of each node is itself the address of a free block. One consequenceof ( Initialize memory pool. ) this method of storage is that free blocks : DYNAMIC-MEM ( start-addr length -- ) OVER DUP FREELIST ! ( Save starting addr. ) cannot be smaller than a node of the free 0 SWAP ! ( Set null pointer. ) list. In Figure One the nodes are shown SWAP 2+ ! ( Save length in 1st control block. ) sorted from low to high addresses. This ar- rangement makes ddlocation easier, as shown below, but it is not the only scheme that can be used. Nodes may be sorted by Screen 2 block size, for example, to make allocation 0. ( Dynamic Memry Allocation, Screen 2: MALtOC ) 1. ( Returns pointer to n free bytes, or 0 if there is no space. simpler. 2. Word before returned address holds size of block. No free Other methods may also be used to store 3. blocks of less than 4 bytes are allowed. ) the free list. The second example shown 4. :MALLCC (n--n) below uses a bit map, an approach made 5. 2+ FREELIST DUP possible by the fact that blocks are of a fixed 6. BEGIN size and the total number of blocks is 7. WHILE DUP @ 2+ @ ( Size ) 2 PICK U< known. 8. IF @ @ DUP ( get new link ) 9. ELSE DUP@ 2+@ (size) 2PICK- 4MAX DUP 4 = lo. IF DROP DUP @ DUP @ ROT ! Types of Dynamic Memory Allocation 11. ELSE 2DUP SWAP @ 2+ ! SWAP @ + There are several important distinctions 12. THEN 2DUP ! 2+ 0 ( store size, bump pointer, ) among memory allocation systems. As 13. THEN ( and set exit flag ) mentioned previously, one of these is the 14. REPEAT SWAP DROP ( dump #bytes ) ; issue of implicit versus explicit control- whether language features alone can make Screen 3 use of this resource or whether the pro- 0. ( Dynamic Memory screen 3: FREE ) grammer can use it too. Although implicit 1. ( Deallocates memory. Pointer passed mst be from MALUX: ) and explicit control of memory allocation 2. : E'REE ( ptr -- ) are not generally found together, they are 3. 2-DUP @ SWAP 2DUP 2+ ! FREELISTDUP not mutually exclusive. The dynamic string 4. BEGIN DUP 3 PICK U< AND package presented here, for example, auto- 5. WHILE @ DUP @ 6. REPEAT ( at exit: ( size block ptrl ) matically allocates and de-allocates mem- 7. DUP @ DUP 3 PICK ! ?DUP ( sz blk ptrl 0 -or- ptr2 ptr2 ) ory to carry out its functions, but can coex- 8. IF DUP 3 PICK 5 PICK + - ( size blk ptrl ptr2 t/f ) ist with user programs that make explicit 9. IF DUP 2+ @ 4 PICK + 3 PICK 2+ ! @ 2 PICK ! use of the same functions. 10. ELSE DROP THEN ( sz blk ptrl ) When a language has sole access to 11. THEN ( sz blk ptrl ) memory allocation functions it can control 12. DUP2+@OVER+ 2PICK- ( sz blk ptrl t/f ) all pointers to allocated space, and so need 13. IF OVER2+ @ OVER2+DUP @ ROT + SWAP ! SW@ SWAP ! 14. ELSE ! not replace each deallocated block back 15. THEN DROP ; into the free list as soon as the application program releases it. This technique of de- I layed reclamation of de-allocated space Listing Two ("garbage collection") allows programs to -- as as Screen 1 run faster, long there is sufficient free 0. ( ASCII2 string manipulation routines ) memory in the heap, at the expense of a 1. : TEXT ( c -- ) ( Parse text to mtching char, put in PAD ) relatively lengthy delay for garbage collec- 2. >IN @ TIB @ + C@ OVER = IF DROP 0 PAD C! 1 >IN +! PAD tion whenever the heap becomes ex- 3. ELSE WORD THEN COUNT DUP PAD + 0 SWAP C! PAD SWAP CMOVE ; hausted. Lisp is an example of a language 4. that manages memory using garbage col- 5. : SCAN0 ( s -- z ) ( Returns address of terminating null. )

Forth Dimemiom 18 Volume XII. Nwnber 3 Listing Two, continued lection. The technique is particularly ap- propriate for programs that require dy- 6. BEGIN DUP C@ WHILE 1+ REPEAT ; namically allocated memory but are ex- 7. pected to ordinarily require less than the 8. : STRISN ( s -- n ) ( Return length of string in bytes ) total amount of memory available. This 9. DUP SCAN0 SWAP -- ; article describes only immediate recla- 10. mation of de-allocated memory; Knuth 11. : CHARS ( n -- ) ( Define a string buffer of n chars. ) and Aho et al. should be consulted regard- 12. CREATE 0 C, ALLOT DOES> ; 13. ing strategies for garbage collection. 14. : STRCPY ( sl s2 -- ) ( Copies from sl to s2 ) Another important distinction be- 15. OVER STRLEN 2DW + 0 SWAP C! CMOVE ; tween memory allocation schemes is re- Screen 2 lated to the need for fixed- or variable-size 0. ( ASCIIZ string extensions ) memory blocks. An application that cre- 1. ates and destroys only a single type of 2. ( Return the address of a string literal compiled into uniformly sized structure may use a dif- 3. the dictionary. ) ferent strategy than one which manipu- 4. lates structures of many different sizes. 5. : (") (--s) 6. R> DUP BEGIN DW C@ WHILE 1+ REPEAT 1+ >R ; Implementations satisfying these differ- 7. ent needs may vary greatly in complexity 8. :" ( -- s ) ( Example: ' This string." State-smart. ) and efficiency. Some of these differences 9. 34 TEXT PAD STATE @ IF COMPILE (") are illustrated by the examples described 10. DUP STFUEN 1+ HERE SWAP ALLOT STRCPY below. 11. THEN ; IMMEDIATE A third important factor is the se- 12. quence of allocation and de-allocation 13. : PRINT ( s -- ) ( Print the ASCIIZ string at the addr. ) 14. BEGIN DUP C@ DUP WHILE EMIT 1+ REPEAT 2DROP ; requests that will be generated by an 1 application. If de-allocation proceeds in Screen 3 the inverse order of allocation (i.e., like a 0. ( More char and ASCIIZ string extensions ) stack), specialized routines tailored for 1. : UCASE ( c -- c ) ( Uppercases character. ) the purpose may be made much more 2. DUP 96 > OVER 123 < AND IF 223 AND THEN ; efficient than general-purpose memory 3. allocation functions. Other patterns of 4. : CFROM ( a1 a2 -- a1 a2 c ) ( Gets char from pointer under.) 5. oVER C@ ; allocation and de-allocation requests can 6. : CFROM+ ( Like CFROM, but increments pointer ) lead to varying fragmentation of the free 7. CFROM ROT 1+ -ROT ; list; memory allocation routines can also 8. : CTO ( a1 a2 c -- a1 a2 ) ( Puts char at top pointer.) be optimized to cope with a high or low 9. OVER C! ; degree of fragmentation. 10. : CTW ( Like CTO, but increments pointer. ) 11. CTO 1+ ; Application Interface 12. : CWS+ ( a1 a2 -- al+l a2+1 ) ( Transfers a char. ) 13. CFROM+ CTW ; A simple example of dynamic mem- 14. ory use is a program which sorts or counts 15. : EOS? ( a1 -- f ) C@ NOT ; values in an input file by constructing a binary tree in memory as the file is read. A Screen 4 new node of the tree would be allocated 0. ( More character and ASCIIZ string extensions. ) every time a new item is found in the file. 1. :C@C= (caddr--f) C@= ; 2. The sorted output can then be written to 3. : STRPOS ( c zstr -- n ) ( Returns position of c in zstr, ) another file during an in-order traversal of 4. 0 >R BEGIN 2DUP C@C= NOT ( 0-based, or -1 if not found. ) the tree. A simple application such as this 5. OVER EOS? NOT AND WHILE 1+ R> 1+ >R REPEAT needs only to be able to allocate additional 6. C@C- IF R> ELSE R> DROP -1 THEN ; memory as needed. Any application 7. much more complicated than this, how- 8. : INSTR ( c zstr -- f ) ( T if c in zstr, F otherwise ) ever, will generally need to de-allocate 9. STRPOS -1 = NOT ; 10. memory as well. If the program described 11. : STRCAT ( zstrl zstr2 -- ) ( appends zstrl to zstr2 ) above is extended to read several files in 12. SCAN0 STRCPY ; succession, the tree should be de-allo- 13. cated before the next file is read, to reduce 14. : TOUPPER ( zstr - ) BEGIN DUP EOS? NOT WHILE the risk of running out of memory. This 15. DUP C@ UCASE OVER C! 1+ REPEAT DROP ; application is still simple enough, how- ever, that performance can be improved by reclaiming the entire heap at once

I I Volume XlI, Number 3 19 Forth Dimensions rather than de-allocating the tree node-by- node. 1 Listing Three Application programs generally make use of dynamic memory allocation, there- Screen 1 0. ( Dynamic strings, screen 1. DYNAMEM package must be loaded.) fore, via two routines: one to allocate 1. : STRVAR ( Create pointer to dynamic string. ) memory and one to release it. These rou- 2. CREATE 0 , ; ( a VARIABLE by another name ) tines are known to C programmers by the 3. names "malloc" and "free" and to Pascal 4. STRVAR -SYSSTR ( Save ptr to created/modified strings. ) programmers as "new" and "release." Ini- 5. tialization of the dynamic memory buffer 6. : LEN ( dstr -- ) @ STRLEN ; and routines is performed by the standard 7. 8. : RELEASE ( dstr -- ) DUP @ ?DUP IF FREE THEN 0 SWAP ! ; run-time code for these languages. If you 9. writ. your own memory allocation rou- 10. : STRSAVE ( zstr dstr -- ) ( Assigns zstr to dstr ) tines, you will have to take care of this 11. SWAP DUP STRLEN 1t MALLOC ( dstr zstr mem ) detail yourself, providing a third (initializa- 12. SWAP OVER STRCPY SWAP DUP RELEASE ! ; tion) interface to application software. The 13. initialization routine is responsible for 14. : S! ( dstrl dstr2 -- ) ( Stores 1 in 2, making a copy ) marking the entire contents of the heap as 15. SWAP @ SWAP STRSAVE ; available; it may carry out other tasks also, Screen 2 depending upon the needs of the allocation 0. ( Dynamic strings, screen 2 ) and de-allocation routines. 1. 2. : LEFT ( dstrl n -- dstr2 ) ( Returns left n chars of dstrl) Efficiency 3. OVER LEN OVER MIN 1t MALLOC DUP >R ROT @ SWQ ROT The efficiency of dynamic memory al- 4. ( zstr memn -- ) 2DUP t 0 SWAP ! CMOVE 5. SYSSTR RELEASE R> SYSSTR ! -SYSSTR ; location is principally a function of the time - 6. required to grab and release a chunk of 7. : RIGHT ( dstrl n -- dstr2 ) ( Returns right n chars of dstrl) memory. The amount of overhead space 8. OVER LEN SWAP -- 0 MAX SWAP @ + SYSSTR STRSAVE SYSSTR ; (i.e., the number of extra bits required for 9. each allocated block) is also an efficiency 10. : SUBSTR ( dstrl nl n2 -- dstr2 ) consideration, but one that is likely to be 11. ( Substring of dstrl starting at char nl, of length n2 ) less important than that of time. Factors that 12. ROT @ ROT 1- OVER STRLEN MIN t -SYSSTR STRSAVE can affect the time required to allocate or 13. -SYSSTR SWAP LEFT ; free a block of memory are: Screen 3 0. ( Dynamic strings, screen 3. S+ SAY UPPER ) Amount of free space available. 1. 2. : St ( dstrl dstr2 -- dstr3 ) ( Appends 2 to 1 ) Pattern of previous allocation and de- 3. OVER LEN OVER LEN t 1+ MALLOC DUP >R ROT @ OVER allocation requests; that is, the degree of 4. STRCPY SWAP @ SWAP STRCAT SYSSTR RELEASE I0 -SYSSTR ! fragmentation of the free space. 5. -SYSSTR ; Size of the block(s) to be allocated. 6. Algorithms used. 7. : SAY ( dstr -- ) 8. @ PRINT ; Clearly, these all interact in ways that 9. may differ from one application to another 10. : UPPER ( dstrl -- dstr2 ) ( Makes an uppercased copy ) and even from one data set to another. If 11. -SYSSTR S! -SYSSTR @ TOUPPER SYSSTR ; you are concerned about efficiency, your Screen 4 best approach is to evaluate the first three 0. ( Dynamic strings, screen 4. S" ) factors as best you can and use them to 1. select appropriate algorithms. Generally 2. STRVAR -SYSSTR2 applicable analyses of these interactions (s") ( For pre-incrementing NEXTs ) are probably not possible, although the in- I0 DUP BEGIN DUP C@ WHILE 1t REPEAT 1+ >R -SYSSTR2 dividual factors may be examined (see STRSAVE SYSSTR2 ; Knuth, for example, for a discussion of the effect of memory fragmentation). S" ( -- dstr ) ( Accepts text from input stream ) Choice of an appropriate algorithm can ( into anonpus dynamic string. ) 34 TEXT PAD STATE @ IF COMPILE (S") greatly affect the efficiency of an applica- DUP STRLEN 1+ HERE SWAP ALLOT STRCPY tion. The two techniques presented here ELSE provide an illustrative contrast. The gen- -SYSSTR2 STRSAVE -SYSSTR2 eral-purpose routine requires two bytes of THEN ; IMMEDIATE overhead per block, and the time required to allocate or de-allocate a block depends

Forth Dimensions 20 Volume XII, Number 3 Listing Four a linked list. Each node of the list identifies the position of a free block, its size, and the Screen 1 location of the next block in the list. Gener- 0. ( Dynamic mem. alloc. for fixed node size, screen 1. ) ally, this linked list is stored within the free 1. space itself, as shown in Figure One. The 2. VARIABLE NODESIZE ( Size of each node ) address of each node therefore identifies 3. VARIABLE NODEMAP ( Pointer to bit map of nodes ) 5. VARIABLE NODEBUF ( Pointer to memory buffer ) the position of the associated free block, 6. VARIABLE SRCHPTR ( Node # at which to start search for free) and this information need not be explicitly 7. stored. 8. : >MASK ( -l IF 1 SWAP 1- 0 DO 2* LOOP THEN ; location, the free list is generally kept 10. sorted in order of increasing addresses. By 11. : NODE ( n -- m a ) ( n=node #, m-sk, a=address ) using a doubly linked list, it is possible to 12. 8 /MOD NODEMAP @ + SWAP >MASK SWAP ; 13. make de-allocation slightly more efficient 14. yet (the typical de-allocation strategy is 15. discussed below). Because each allocated block may be of Screen 2 a different size, and because de-allocation 0. ( Dynamic mem. alloc. for fixed size nodes, screen 2. ) routines are typically passed only the ad- 1. dress of an allocated block, the size of each 2. : >BYTES ( n -- n2 ) ( Converts bits to bytes. ) 3. 8 /MOD SWAP O= NOT ABS + ; block must be stored when it is allocated. 4. HEX (Modula-2, however, requires the size of 5. : CLEARNODES ( -- ) the block to be passed to the standard deal- 6. #NODES @ >BYTES 0 DO FF NODEMAP @ I + C! LOOP location routine.) It seems that the extra 7. 0 SRCHPTR ! ; DECIMAL space needed to store the size could be 8. eliminated if the de-allocation routine were 9. : NODEBUFSIZ ( nl n2 n3 -- ) ( nl = address of buffer ) 10. DUP NODESIZE ! ( n2 = size of buffer, b ) passed the size as well as the address but, as 11. 1+ / DUP #NODES ! ( n3 = size of node, b ) discussed below, in some cases more space 12. >BYTES OVER + NODEBUF ! is actually allocated than is requested, 13. NODEMAP ! unknown to the calling routine. For this 14. CLEARNODES ; reason, it is important to store the amount 15. of space actually allocated rather than that Screen 3 requested. 0. ( Dynamic mem. alloc. for fixed size nodes, screen 3. ) 1. HEX Fitting Strategies 2. : GETNODE ( -- a ( a = 0 if no space available ) When searching for a free block to sat- 3. 0 ( accumulator ) #NODES @ 0 DO I SRCHPTR @ + 4. #NODES @ MOD DUP NODE C@ SWAP AND ( free? ) isfy an allocation request, the memory allo- 5. IF DUP 1+ #NODES @ MOD SRCHPTR ! cation routine can select either: 6. DUP NODE DUP C@ ROT FF XOR AND SWAP C! 7. SWAP DROP NODESIZE @ * NODEBUF @ + LEAVE the first free block that is large enough 8. ELSE DROP (first fit) or 9. THEN LOOP ; the block that is closest in size to that 10. 11. : RELEASENODE ( a -- ) ( a as returned by GETNODE ) needed (best fit). 12. NODEBUF @ - NODESIZE @ / 13. DUP SRCHPTR ! The first-fit strategy is generally re- 14. NODE DUP C@ ROT OR SWAP C! ; garded as superior, as the number of small 15. DECIMAL blocks tends to proliferate when using the best-fit method. In addition, because it usually must examine more (often all) of the free list for each allocation request, the best-fit method is slower. upon the pattern of previous requests. The General-Purpose Memory Allocation If allocation requests fall into a known specialized routine for fixed-size blocks The most important feature of a general- pattern, however, you may find that the requires only one bit of overhead per purpose memory allocation scheme is the best-fit method, or some variant of it, is block (approximately), in many cases re- flexibility to satisfy an indeterminate num- more memory efficient. For example, sup- quires near-constant (and minimum) time ber of requests for blocks of varying sizes. pose that your application most often re- to allocate a block, and constant time to The most appropriate structure for main- quests blocks of 30,50,or 70 bytes. After de-allocate a block. taining the free list under these conditionsis some period of use, most of the free blocks

I 1 Volume XII, Nwnber 3 21 Forth Dimensions are likely to also be of these sizes. In such PL-1 family-<, Pascal, Modula-2, and a case, your best strategy may be to choose Ada-could profitably broaden their hori- the first free block of appropriate size, re- zons by learning something different: ducing the number of useless 20-byte Forth, Lisp, Prolog, APL, and Smalltalk all (approximately) free blocks created. embody unusual approaches to comput- ing.) This code is written for a 16-bitForth- NGS FORTH Eliminating Small Blocks 83 Standard system. A FAST mm, Wasted space is created whenever a free The free list in this implementation is a OPTIMIZED FOR THE IBM block is created that is smaller than the singly linked list in which each node occu- PERSONAL COMPVTER AND application is likely to request. The exis- pies four bytes. Each node contains a link to MS-DOS COMPATIBLES. tence of too-small free blocks slows down the next, followed by the sizeof the block in the memory allocation routines, as their bytes. No free blocks smaller than four STAM)ARD FEATURES nodes must be examined each time the free bytes are allowed. If satisfying a request INCLUDE: list is traversed. Although it is not always from an available block would leave fewer possible to prevent this waste of space, it is than four bytes, the extra bytes are included 079 STANDARD possible to eliminate its effect on perform- in the block being allocated. Except for this I .DIRECT 1/0 ACCESS ance. This is done by including the "extra" limitation, there is no minimum size im- I ( .FWLL ACCESS TO MS-DOS space with the allocated block that would posed on either the allocated or free blocks. FILES AND FUNCTIONS otherwise have left the bytes behind. The Free blocks are selected by the fust-fit strat- I I I actual size of the allocated block, including egy. .ENVIRONMENT SAVE the extra bytes, must be recorded in its The word DYNAMIC-MEM, in screen I & IDAD 11 reference cell, and the troublesome node one, is used to initialize the heap. It should .MULTI-SEGMENTED FOR can then be eliminated. be passed the starting address and size of the LARGE APPLICATIONS heap in bytes. The heap itself may either be I .EXTENDED ADDRESSING I I An Example of General-Purpose compiled directly into the Forth dictionary I I I Memory Allocation or placed in free memory above the diction- .MEMORY ALLiOCATION An implementation of a general-pur- ary. (If you choose the latter course, take I CONFIGURABLE ON-LINE I 1 pose memory allocation scheme is shown care to avoid conflicts with PAD, TIB, .AUTO LOAD SCREEN BOOT in Listing One. Forth encourages the con- block buffers, and the parameter and return I 1 1 struction of application-specificlanguages stacks,) I .LINE P SCREEN EDITORS of arbitrarily high level, yet is unsurpassed DYNAMIC-MEM creates a single node or ODECOMPILER AND I1 for the direct memory manipulation needed control block at the beginning of the heap DEBUGGING AIDS to implement system routines. In keeping space, setting its size to that of the entire with the Forth philosophy of providing heap. The address of this fust node is stored e8 08 8 ASSEMBLER simple tools to build custom applications, in the double variable FREELIST, which GRAPHICS & SOUND there are no standard Forth words for dy- has the same format as a node but, having a ONGS ENHANCEMENTS namic memoryal1ocation.Theexamplesin fixed address, serves as the root, always I I I these listings are presented in the same pointing to the first real node in the free list. I ODETRIIED MANUAL spirit: although they are fully functional, The size cell of FREELI ST is always zero; I I they should be regarded as examples only. it exists so that FREE does not have to treat I .INEXPENSIVE UPGRADES I I You should modify, improve, or replace the root node as a special case. I oNGS USER NEWSIEITHl them as appropriate to the needs of your Each block of allocated memory is pre- I I own applications. Heed the dictum about ceded by a cell containing the block's size. A CrmPLETE mmH not reinventing the wheel, but be advised to This information is needed to de-allocate DEVEIX)PMEXV SYSTEM. trade in your standard steel-belted radials the block. Each allocated block is therefore I I for racing slicks when the competition gets actually two bytes larger than its nominal / PRICES SnaT AT $70 hot. size. This overhead cost should be consid- I I The two principal interface words, ered if you wish to use the smallest possible NEW-HP-150 & BP-110 MALLOC and FREE, are shown in screens heap, based upon your knowledge of the VERSIONS AVAILABLE I / two and three of Listing One. These rou- number and size of blocks needed. I tines have the same calling conventions, as The word MALLOC is used to reserve a well as the same names, as their C counter- block; it is passed the numbei of bytes parts, so even if you know nothing but C, desired and returns the address of an appro- you should be able to make some sense of priately sized block, or zero if the request 1 the Forth code. (Some of the more avid pro- cannot be satisfied. The first thing this word NEXT GENERATION SYSTEM8 ponents of other languages would say that does is increase the requested size by two P-0.BOX 2987 if you know nothing but C, you know noth- bytes to allow for the sizecell. A sequential BANTA CLARA, CA- 95055 ing at all; that'sarather harsh judgment, but search of the free list is then performed, (408) 241-5909 I would agree that users of languages of the which is terminated when a block of suffi- , Forth Dimensiom 22 Volume XII, Nwnber 3 - cient size is found or the end of the free list is reached. Either of these conditions is signaled by a zero on the stack; the test for this value occurs at the beginning of line I I Allocated memory seven. During this search, two values are kept on the stack: the number of bytes needed and the address of the node that contains the address of the node currently being examined. The address of the node "one back" must be maintained so that its node's link address can be adjusted in case Free the current node is entirely allocated and list must be dropped from the free list. links Line seven of screen two fetches the size of the current block and tests it against the request. Line eight performs two fetches to get the link to the next block if the size is insufficient. Line nine evaluates whether the entire block should be allo- cated; if so, the pointers are adjusted in line ten, otherwise the size of the current block is reduced in line 11. In either case, the address of the block is left on the stack. Line 12 stores the size for later use, incre- Root ments the pointer past thesizecell, and sets pointer a zero flag on the stack to terminate the loop. Release of an allocated block may or may not result in the addition of another 1 Figure One. Linked list in the heap. node to the free list. Blocks above and below the one to be de-allocated may themselves be either free or reserved. The - four possibilitiesare shown in Figure Two. Only when the memory configuration is as shown in Figure Two-a will a new node be added to the free list. The situation shown in Figure Two-b will result in the creation of a new node within the newly de-allo- cated block, and the removal of the node above, for no net change. The link address previously pointing to the node to be re- moved must also be modified. When the situation isas shown in FigureTwo-c,only the size of an existing node need be changed. If free memory bounds the de- allocated block on both sides, as in Figure Two-d, then the size of the lower node must be changed and the upper one elirni- nated. The need to examine the blocks on both -1 -1 Free block sides of the one to be de-allocated is why Allocated block the free list is kept sorted by address. To Block to be de-allocated find the address of the preceding free node, a sequential search is performed for a node which has an address lower than that of the L- - / one to be de-allocated, but a link address Figure Two. De-allocating a block; surrounding memory. that is higher. If the size and address of the lower node sum to the address of the one to be de-allocated, then the situation in either I Volume XII, Nwnber 3 23 Forth Dimensions Figure Two-c or Two-d applies. To find the contains several standard words for ma- strings of any length (within the limits of address of the following block (which will nipulating counted strings (using a single the heap space) to be stored or modified have a free-list node if empty), it is only byte for a count), but is not limited to this without any concern on your part about necessary to sum the sue and address of the form of storage. I prefer to use zstrings, as overrunning a statically allocated string block to be de-allocated, if the resulting ad- they allow you to scan a string more easily; buffer. These words mimic some of the dress appears in the free list, then the situ- the remainder of the string can always be string-manipulation functions of dBase in ation in either Figure Two-b or Two-d represented by a single stack element rather name and application. applies. than by an addresscount pair, as is neces- Dynamic strings are represented by a Evaluation of the memory configura- sary with counted strings. The words in pointer to a zstring; the zstring itself is tion and removal of the indicated node are Listing Two are therefore designed to cre- stored in the heap, rather than in the Forth performed by the word FREE in Listing ate and manipulate zstrings rather than the dictionary. A dstring can be converted to a One, screen three. This word begins by more usual (for Forth) counted strings. zstring simply by a fetch (@)operation. fetching the size of the node and storing it Because this is an illustration and not With that in mind, andan explanation of the in the second cell, creating the size cell of a central to the point of this article, the words role of SYSSTR,the words in Listing valid node header. A sequential search of in Listing Two will not be described in Three should be easy to interpret. the free list is then performed (lines 34, detail. A few points are worth noting, Several of the dynamic string manipula- ending with the address of the free node however. In particular, the words TEXT tion routines create new unnamed below the one to be de-allocated. Note that and (") may be found in existing Forth sys- dstrings-that is, ones which do not di- this may be the root (FREELIST)which, tems with slightly different actions. Typi- rectly replace one of the dsmngs passed as because of the extracell allocated to it, may cally these create and return counted aparameter. The words LEFT, RIGHT, and be treated exactly like any other node strings, whereas the versions shown here S+ are examples. This new, unnamed header. are designed for zstrings. If possible, you dstring is left on the stack, where you may In line nine, the link address held by the should rewrite SCAN0 in your native as- save it (with S ! ), display it (with SAY),or next-lower free node is stored in the block sembly language, as it may amount to only otherwise dispose of it. The pointer to the to be de-allocated, completing the valid a single instruction. The words in Listing heap space allocated for this smng must not node header for this block. Nothing yet Two do not form a complete set of tools for be lost, however, or the space will be unre- points to this header, and it may eventually handling static strings, but they include all coverable. -S YS STR is used to store this be abandoned. Construction of the header those used to illustrate dynamic smng han- pointer. Note that the pointer is stored only at this step is more efficient, however, if the dling in Listing Three as well as a few until the next operation which creates anew node is not to be abandoned. Lines eight others. unnamed dsuing; at that point, the space is 1 through ten evaluate whether the node to be The words in Listing Three integrate de-allocated and the pointer reassigned. In de-allocated is immediately followed by a those in Listings One and Two. They allow some situations, this limits the operations free node; if so, the size cell of the newly ' created node header is increased by the size of the following free block and the link address is set to that contained in the fol- lowing header. Lines 12-14 evaluate whether the block to be de-allocated is precededby a free block; if so, the link and size cells of the preceding header are modi- fied appropriately, and if not, the link ad- dress of the preceding header is set to that of the de-allocated block.

An Example Application The use of these words is illustrated by a set of routines for manipulation of dy- namic strings. Listing Two contains a set of static string-handling words, and Listing Three ties these together with the dynamic memory words in Listing One. Strings are generally stored in memory in one of two ways: with the string length in the first byte or word, or with the end of the string marked with a sentinel character, usually an ASCII zero. For simplicity, I will refer to these alternatives as counted strings and zstrings. Dynamic strings will be referred to henceforth as dstrings. Forth

1 Forth Dimensions 24 Volume XII, Number 3 that can be successively carried out on an although unnecessary, may save computa- in the map. To allocate a block, it is neces- unnamed dstring. Consider the following tion time. Tailor the tools to the task. sary to scan the map for such a bit and sequence of commands: calculate the address to which it corre- Special-Purpose Memory Allocation sponds. To increase efficiency when a STRVAR COMPOST If there is anything Systematicabout the sequ,nce of successive allocation requests Gardeners rarely grow cabbage. " size that be needed* the may be performed, each search of the map COMPOST STRSAVE number Of allocation requests*Or the pat- begins where the previous one left off. To COMPOST 3 LEFT tern of allocation and de-allocation, you increase efficiencywhen an altaating se- COMPOST 5 RIGHT may be &'I? performance and quence of allocation and de-allocation st save memory by using a sWCial-~urpose requests is performed, a pointer is set memory a~~~tionroutine- Whereas whenever ablock is de-allocated so that the The result of this would be garbage, but general-purpose next search will begin with that block and not the "Garbage." that you might expect. tines probably be based on a so will be satisfied immediately. In some Both of the phrases COMPOST 3 LEFT somewhat like that presented above, you c=s,only one of these fine-tuningmecha- and COMPOST 5 RIGHT lc?ave a pointer afepretty muchon~ourownwhen it comes nisms may be appropriate; both are shown to an anonymous zstring, but only one to designing a sp=ial-purpose here for illustration. anonymous pointer (SYSSTR) is al- Knuth and Aha, Hopcroft* and Ullman The housekeeping information is kept lowed. Thus, the two arguments passed to describe a technique known as the in the five variables shown in Listing Four, st will both beSYS STR, and the result system? which isasortof general-purpose screen one. The first three words (>MASK, will always be toconcatenate the rightmost s~ecial-~ur~osesystem* suitable when NODE, and >BYTES)manage the conver- five-charactersubstring of COMPOST with only a limited number of sizes of blocks sion between the bit map and actual ad- itself. The solution to this problem is to use will be meded. Its advantage is that it can dresses. The word >MASK("to-mask") another dstring defined with STRVAR for be customized for different combinations takes a bit number and converts it into a intermediate storage of the lefunost sub- of sizes of blocks. mask that can be used to test or set the bit suing. Considerations of fitting saategies and with AND Or OR. hi^ is a good candidate Any number of successive operations the~roblemso~smallblocksdonotpertain for coding in assembly language. on a single, unnamed &ring may be car- when a11 blocks are the Same size. It is, in Initialization of the bit map and house- ried out, however. For example: fact, easier to design an appropriate solu- keeping infomation is performed by the tion for a single s~ial-~ur~osea~~lica- COMPOST 6 LEFT UPPER SAY word NoDEBUFS I Z. The beginning of the tion than it is to design a good general- memory buffer is set aside for the bit map; These routines are written so that purpose memory allocation routine. this routine calculates the number of nodes SYs STR maybe one of their arguments, The technique described here is One that will fit and the size of the map needed. and space for the resulting shng will be that is suitable only when blocks of asingle ~h~ map always occupies an integral allocated before -SYSSTR is de-allo- size will be needed. But for this limitation, number of bytes. ~~~~~di~~upon the cated. it has a number advantages Over the buffer and node sizes, up to seven bits of the Another way of reducing conflicts be- general-purpose routine described above: last byte of the map may be unused. ~h~ tween uses of -' STR is to use a differ- The time required to allocate a node is overhead per block may therefore be ent system string for each routine. This ap- likely to be much less. slightly more than one bit. proach is sen with the word s" (Ihe . nerime required to de-allocate a node The word CLEARNODES has been fac- dsuing counterpart to "), simply to allow is constant. tored out of NODEBUF S I Z so that it may the convenience Of ente'ng a sbing The overhead is only one bit per block, be used to re-initialize the buffer without an unnamed dstring resides on the stack. rather than two bytes. the need to use RELEASENODE to de- The drawback is that heap space may re- allocate each block. This word must be main allocated long after the unnamed These advantages are conferred by the used with great care, and subsequent refer- dstring's no longer needed by the applica- representation of the free list as a bit map ence to dangling pointers should be tion. rather than as an actual linked list. The bit avoided. map consists of a series of bytes long GETNODE (Listing Four, screen three) The technique of implementing dy- enough so that their total number of bits is allocates space by looping over the total namic strings shown in Listing Three is at least as great as the number of nodes that number of nodes; the phrase only an example. Counted strings could be can be accommodated by the heap. The I sRCHPTR @ + used instead of zstrings. The count could state of each bit (set or reset) indicates the #NODES@ MOD also be kept in the dstring header, whether availability of a corresponding node. The counted strings or zstrings are used. This code for this implementation is shown in translates a relative node number into an last approach may be most suitable when Listing Four. The words NODEBUFS I Z, actual node number based upon a non-zero you want to use zstrings for mostpurposes GETNODE, and RELEASENODE are starting position. If a free block is found, but your application frequently needs to ~M~O~OUSto DYNAMIC-MEM, MALLOC, the starting point for the next search is set evaluate the length of strings; the extra and FREE in Listing One. (line five), that entry in the map is marked space devoted to storage of the string size, A free block is indicated by a set (1) bit as allocated (line six), and the actual ad-

Volume XII, Number 3 25 Forth Dimensions I I dress of the block calculated (line seven). I The word RELEASENODE de-all& cates space by calculating the node nurn- ber (screen three, line 12) and setting the PROCEED! appropriatebit (line 14). In addition, it sets the starting point of the next search to the (1 (1 1989 Rochester Forth Conference node just de-allocated (line 13). I N D U S T R I A L on IndustriulAutomatwn . . . $25. Because of the uniform block size, this A O A I O 6 invitedpapers and Slpresentedpapers on all approach lends itself to compressed dis- mpec, of Forth processors, applications and plays of the allocation map more easily object oriented technology, including: than does the first. A simple word to dis- June 20 - 24th, 1989 + SwissForth, A Development and *I Simulation Environment for Industrial play this map may be defined as follows: and Embedded Controllers : SHOWMAP Klaus Flesch, FORTH System - Angelika #NODES @ o DO + Forth-based Control of an Ion Implanter I NODE C@ AND IF Don Berrian, VarianlExaion ." 1 " ELSE + :Cel lmate/TOOLBOX Hardware/Software ,, - rt WorkstationILanguage DOES7 Autmtive/Aerospace THEN PowertrainIVehicle LOOP ; Development/Testing ; Bob McFarland, Diplos, Inc. Summary +Events and Objects: Industrial Control The examples shown in this article, al- by Hierarchical Decomposition though useful in their own right, are in- Dean Sanderson, Forth, Inc. tended principally to illustrate a point. + Brraklhrough in Knowledge Management That is: you can improve the performance Bjorn J. Gruenwald, ACA, Inc. of your application programs by tailoring , memory allocation routines to their sw- 1990 Rochester Forth Conference cific ne-eds. "E M B E D D E D on EmbeddedSystems . . . . $30. Several changes could be made in the S Y S T E M S Over 7Opapers on the state of the art in Forth general-purpose routine which might im- and threaded inrmretive lanmtaaes," -. inchidinn prove its suitability for certain applica- I 1 com~akonsof d, ADA and Forth for em': bedried syst-, ahd eleven papers &om the tions. For example, each search could be Soviet Union. started wherever the previous one termi- + ShBoom on ShBoom: A Microcosm of nated, as is done with the specialized rou- Hardware and Software Tools tine. Also, backward links in each node Mr. Charles Moore, Computer Cowboys header would eliminate the need for a se- quential search when a block to de- +Using Forth to Analyze and Debug is be Kernel-less Embedded Systems allocated. Mr. Darrel Johansen, Orion Inmumoly Inc. If the size of blocks is known at com- pile time (which is very often the case), the +Active Messages and Passive Objects: An Object Oriented View of Forth special-purpose routine could be im- IZE Mr. Rod Crawford, MPE, Ltd proved by making NODES a constant rather than a variable. Depending upon the +The Forth System Behind VP-Planner: actual block size (e.g., for powers of two), JUNE12 - I~TH,1990 Designing for E~ciency UN\VERSITYOF ROCHESTER in the Face of Compkxity other changes may also increase perform- Dr. Kent Brothers, Stephenson SofSwore ance. See the references. Other special cases of memory alloca- +The Future of Forth in Astronomy tion, such as a series of LIFO requests, may Please add $5 shipping & handling for each Dr. Arne Henden, Ohio State Univ. book ordered. Send name, full address and be handled by techniques very different phone number. Check or money order in US *Ada and Forth: How Do Stnck from either of the examples shown here. funds, or, VISAMC # and exp. date. Dr. James D. Basile, Long Island Univ. Although the standard libraries of most To: conventional languages provide routines Institute for Applied Forth Research EMail: GEnie ...... L.Forsley only for general-purpose memory alloca- 70 Elmwood Avenue BIX ...... LForsley tion, you can still take advantage of oppor- Rochester, NY 14611 USA Delphi ...... LFORSLEY tunities to create special-purposeroutines (716) 235-0168 (716) 328-6426fax as needed. If you cannot supplant the stan- dard routines, they can at least be used to

L Forth Dimensiom 26 Volume XII, Nwnber 3

SMART RAM ROB CHAPMAN - EDMONTON, ALBERTA, CANADA

1first heard of smart RAM from Bob La nals onto the RTX-2000 gio bus, where a peeps and pokes. Quey. It was one of those amusing things to data exchange protocol takes care of mov- As well, data reads and writes may be throw out for discussion when you sat ing data between the 68000 and RAM. ignored by just asserting dtack. Instruction down to chew the fat. We tossed the idea Developing a smart RAM language reads may be skipped by writing a no-op to around a lot but never had an application for required a lot of fiddling (as is usual, and the data bus and asserting dtack. it Until now. very much apart of Forth), but it eventually broke down into primitives to deal with the Debugging Tools Breeding Forths 68000 signals; words to transfer data be- The debugging tools consist of a trans- After spending six months creating and tween RAM and the 68000, and a debug- action monitor with single-stepping and a tuning a real-time kernel for the RTX- ging language which would allow for register content editor. 2000, I wanted to port it to other processors. single-stepping, peeping and poking into The transaction monitor displays each Since we had a lot of 68000s kicking the 68000 registers, and monitoring the transaction between the 68000 and smart around at work, I decided that the first port 68000 transactions. RAM. The status is displayed before each would be to a familiar processor: an 8 MHz dtack. Filters allow selective viewing of 68000. The traditional, well-known instruction reads, data reads/writes, or method of building a 68000 system of both. There are also filters for disassem- ROM, RAM, SIO, and a processor with the Smart RAM concepts bling and decompiling. If the disassembler burn-EPROM-plug-it-in-doesn't-work- can be applied in is enabled, each 68000 instruction is dis- edit-swear-try-again method didn't really played. appeal to me, so I figured there must be a many areas.. . If the decompiler is enabled, the high- better way. A bolt of lightning struck and I level Forth words being executed are dis- thought, maybe this is an opportunity to use played. The monitor can be adjusted to smart RAM. That would allow me to inter- Data Exchange Protocol show any depth of nesting. After a word is actively and incrementally test the Forth, All data exchanges are initiated by the tested, a summary of the transaction and the monitor the performance of each word, and 68000 asserting address strobe low. This status of the Forth registers is displayed. tune it for the 68000. qualifies all the signals. All data exchanges This summary and status may also be are then terminated by the smart RAM turned off. The monitor output may be 68000 and Smart RAM asserting dtack low. stopped by touching any key. An escape Being a Forth-bred minimalist, I didn't There are three types of exchanges: will then abort the execution of the current want to build a lot of hardware (or software) instruction-read, data-read, and data-write. word, while any other key will resume to achieve a smart RAM system. The result- If r/-w is high and p/-d is high, the 68000 is status display. ing hardware configuration consists of a doing an instruction read. If pld is low, it is When single-stepping is enabled, either 68000, interface logic, a bot, and a laptop. doing a data read. If r/-w and p/-d are low, by an out-of-bounds readlwrite or by user The laptop connected to the bot pro- it is doing a data write. selection (SSTEP), execution is stopped vides file storage, an editor, and a terminal. During a data write, a check is per- just before each dtack. Execution may be The bot (bundle of technology) is a formed to make sure it falls within the area aborted by pressing the escape key, or concept that, in itself, is worth another reserved for the 68000 Forth. During an continued by pressing any other key. paper. For the scope of this paper, though, instruction read, the instruction doesn't The register content editor serves two a bot is a minimal RTX-2000 system, have to come from RAM, it can come from purposes. The seven registers used by the which consists of an RTX-2000, RAM, the stack. Feeding the 68000 instructions virtual Forth machine may be viewed, and SIO, 96-pin expansion connector, and a from the stack allows instruction sequences any of the registers may be altered. This Forth. This, bundled with some software, to be inserted, and if followed by a jump basic peeking and poking is accomplished emulates smart RAM. back to the original address these se- by feeding instruction sequences to the The interface logic maps the 68000 quences are essentially transparent. This 68000 followed by a jump back to the address bus, data bus, and the control sig- technique is used for unobtrusive register address it started from.

Forth Dimensions 28 VolwneXII, Number 3

68000 Forth Model I chose a Forth model for the 68000 which is similar to the RTX-2000. Techni- cally, it is a 16-bit, subroutine-threaded, stack-cached Forth. The top two parameter stack items are --+Y&- cached on chip in registers, just like the RTX-2000. The top of stack is an address Figure One. The smart RAM system consists of a laptop, an RTX-2000 bot, and aprototype register to allow for quick fetchesand board. The laptop serves as a terminal, an editor, and provides file storage. The RTX-2000 stores. The next stack item is keptin adata bot emulates smart RAM and runs Forth. The prototype board contains the 68000 and the register for quick ALU operations. interface logic which multiplexes the 68000 signals onto the RTX-2000 16-bit gio bus. Since subroutine threading is used, it allows the mixing of assembler and Forth OlO mp FFFF~Ymoyn*p IF within the same definition (the mini-as- ta bwt p(n r"d.wwd sembler was written to support this by *npc, not Wed making the assembler words immediate). 4.:1-a.4"hd4 - notused status Subroutine threading also allows for in-line Mstw dtack optimization of assembler instructions. enlulstw \ dtack One interesting dilemma resulted from 68k ~~r(h dam mlle -1. using subroutine threading and 16-bit address bus dam ned stacks: every subroutine call pushes a 32- 21, Form data bus -1s bit address onto the return stack and, like- WOO Is dwd wise, every exit pulls a 32-bit address from the return stack. Since Forth allows for Figure Two. All the 68000 signals are mapped onto the RTX-2000 gio data bus. Only the modifying control flow via direct access to 15 least significant address lines are used. This, with -uds and -Ids, gives an effectiveaddress the return stack (R>,R, and R>),there was range of 64K bytes. dtack is the output of a flip-flop which is set by the address strobegoing an immediate compatibility problem. This low, and is reset through the gio bus. Address, data-read, data-write, control signals, and is solved by allowing the return stack be dtack map to five out of the possible eight addresses on the gio bus. The signal p/-d (actu- 32 bits, while keeping the parameter stack ally FCl) allows differentiation between opcode and data fetches. The boot pin is used to as 16 bits. R>,R, and R> take care of the control reset and halt. The clock input is fed tclk divided by two, so that the 68000 receives translation. a 5 MHz clock. The model uses five other registers, as well as the two top parameter stack items. @&m smart RAM @Q!a Yd.k smart RAM Two address registers are used for the stack addr status -as addr, status. -as pointers. Adata register is used for interme- s - ADDR @ >DATA DATA ADDR I diate results. An address register is used for > A dtack some pointer operations. The FOR ... / DTACK A DTACK NEXT loop uses a data reaister to hold the 7%; index. previous contents of the index Figure Three. Exchanges between the 68000 and smart RAM are initiated by the 68000 register is pushed onto the return stack by asserting address strobe and terminated by smart RAM asserting dtack. FOR and is restored by NEXT. This model, coupled with a good peephole optimizer to minimize off-chip stack flow, should run fast. All the stack primitives are one or two opcodes (except ROT),which means that it is cheaper to in-line them than to do a sub- :F~~,r\.",.x*.i".-r.* Tr%w-sv**>!.;r)mls-r* routine call. Smart RAM 1 Interactive Development I started with the Forth I wrote for the Figure Four. The 68000 Forth uses seven out of 16 registers. The top two data stack items RTX-2000, or 2K-Forth, and defined eve- (top and next) are kept in registers to quicken most Forth operations. Two pointers are rything in high level except about 20 primi- needed to keep track of the stacks in memory. The index register is only used for FOR .. . tives. These include stack and mathflogic NEXT loops. When it is used, the previous contents are pushed onto the return stack. Two operators, memory access, and a test opera- extra registers (spare data and spare addr) are needed for some intermediate calculations. tion:

1 Volume XII, Number 3 29 Forth Dimensions ok: S R t top 0000 4271 -0 0000 5472 next 0000 48?8 - AND sp0 - 4816 o*: rm mn! OR XOR S-ry: depth 0 calls 0 coda* 4 storst 1 fetches I dtacka 6 top 0000 48?6 -0 0000 502 NOT 2* next 0000 4271 ~pe- 4sr8 2 / @ oL:WYIllSI1-Macl! ap0 alu --a ROT P/-D 8 R/-n 2 -AS 0 .:34C6 d:3016 C@ ! M lp( P/+D 8 R/ir 2 -AS 0 a:34C8 d:3C87 C! 11 top next move P/-D 0 R/+ 2 -AS 0 a:34CA d:3EOD o= a1u top wve P/-D 8 R/-W 2 -AS 0 a:34CC d:3A40 s-ry: depth 0 calls 0 codes 4 scorer 1 fetches 1 dtaska 6 cap 0000 48?8 rp0 0000 5472 The modified 2K-Forth was tested by meta- next 0000 48?6 rp0 - 4211 compiling it on the bot. ok: Mu rm acl! spe .in WW~ ROT 91-D B R1-W 2 -AS 0 a:34C6 d:3016 Once I had pared the Forth down to a next sp0 move 91-0 8 R/-w 2 -AS 0 a:34C8 d:3C87 fetch P/-D 0 R/-W 2 -AS 0 a:330C d:4271 few primitives, it was very simple to rede- top next move P/-D 8 R/-w 2 -AS 0 a:34CA d:3IOD store P/-D 0 R/+ 0 -A3 0 a:330C d:48?6 fine them for the 68000. Adjustments had alu tap more P/-D 8 R/-n 2 -AS 0 a:34CC d:3A4O 5rrmmary: depth 0 calls 0 codes 4 stores 1 fetches 1 dtacka 6 to be made to the metacompiler to compile tap 0000 4E71 rp@ 0000 5472 next 0000 4818 the 68000 subroutine calls and returns. 3~0- 48?6 Headers, byte ordering, and word align- ment stayed the same. The metacompiler Figure Five. This is a listing of four Uace monitor outputs of ROT with different filters kept track of which definitions consistedof selected. All input has been highlighted [and follows the ok: prompts]. Initially, the status fewer than four words, so that they could be of the Forth registers is shown by the command S. ROT is then run with aU output filtered. in-lined (this mega-simplified the return The summary that comes back displays how deeply nested the calls got (in this case zero, stack definitions). Since there were very since ROT is just four instructions); how many subroutine calls were made; how many few primitives, a mini-assembler was built opcodes were fetched; how many stores to RAM; how many data fetches from RAM, and, (they could have been hand coded, but the finally, how many dtacks (one for each memory cycle). The third run has disassembling and assembler provided a creative outlet). decompiling enabled, for a maximum trace depth of one. The code is displayed first and the Development proceeded rapidly by Forth code is displayed after it. The decompiler considers the four opcode instructions to executing each primitive on the 68000, be ROT. In the fourth run, RAM accesses are traced as well, and we can see the fetch from monitoring bus activity, and checking the stack and the store back to stack (the fetch and store don't happen right away, because of Forth registers when done. Operations like the internal architecture of the 68000). The display on the right is theactual signals that exist SWAP took one opcode and no memory on the 68000 busses before a dtack. Non-zero values represent a logical one, while zero access. I represents a logical zero. 1 Once I had the twenty primitives work- ing, I started testing the other definitions. olr: Trn wrr-moz Since I was monitoring bus activity, I could : %SSET-INOVI ( ? ) keyq oa NO in ! tib 2 + tib ! No MPol C! keyq sro-in ! emitq do-out ' ' COLLECTOR Dm ULL >BARON ; see just how long it took to execute the ok: -)9( UST -11l1 1 +IY3 -ST PIS--INPW keyq P/-D B R/-w 2 -AS o .:5426 d:3D07 *.-I 0 0 words. This motivated me to code some of P/-D 8 R/-n 2 -AS 0 .:5428 d:3EOD -17,-L 0 0 P/-D 8 R/-W 2 -AS 0 .:542A d:3A7C Q,-L 0 0 these words in assembler. When I needed P/-D 8 R/-W 2 -AS 0 a:542C d:439A +,-I 0 0 09 P/-D 8 R/-w 2 -AS 0 .:5422 d:4EB8 +I,-L 0 0 more 68000 instructions, I added them to P/-D 8 R/-U 2 -AS 0 .:3176 d:4E75 *,-I 0 0 my assembler and disassembler as well. P/-O 8 R/-+ 2 -AS 0 a:3?78 d:0034 -0,-L 0 0 NO P/-D 8 R/-w 2 -AS 0 .:5432 d:3D07 -17.-L 0 0 The development actually was done in P/-D 8 R/-Y 2 -AS 0 a:5434 d:3EOD -w,-L 0 0 P/-D B R/-W 2 -AS 0 .:5436 d:3A7C -Q.-L 0 0 parallel. When a problem occurred in the P/-D B R/-W 2 -AS 0 a:5438 d:OOOO -0,-L 0 0 in P/-D 8 R/-W 2 -AS 0 02543A d:3D07 -U,-L 0 0 68000 Forth, I created a new tool to solve it P/-D 8 R/-W 2 -AS 0 .:543C d:3EOD -0.-L 0 0 P/-D 8 R/-W 2 -AS 0 *:543E d:3A7C -0,-L 0 0 on the smart RAM. Sometimes this made P/-D 8 R/-n 2 -AS 0 .:5440 d:495C -0,-L 0 0 P/-D 8 R/-n 2 -AS 0 a:5442 d:4E88 -0,-L 0 0 matters worse, since one bug can some- P/-D 8 R/-W 2 -AS 0 a:3642 d:4E75 -0.-L 0 0 times hide another. But perseverance paid ( - SPACE to proceed ISC to abort. - ) off, since I now have most of the tools I Figure Six. RESET-INPUT is decompiled with TSEE and then the first five Forth words need. are traced. The output has been temporarily halted to view the results. In this tram, we are Finally came the steak dinner test: does only interested in the highest-level calls. it work? To test the whole kernel, I con- nected the input and output queues from the 68 11 from Motorola. When the processor requests the data, it is 68000 Forth to the 110 port of the bot. The The concept of smart RAM can be ap- already in the latch. The stacks are easy to 2K-Forth serviced the 110 port and took plied in many other ateas as well. It could predict, but programs wouldbe harder. But care of RAM transactions. The euphoria be used as a way to speed up slow RAM in by knowing what the branch or jump in- came when it all worked. a system, with the addition of some fast structions are ahead of time, the smart Prospects latches (one for the data stack, one for the RAM could make an intelligent choice for The next few processors to be con- return stack, and one for instructions). The what to put into the latch. nected to the smart RAM are the 68020, a smart RAM would prefetch the next needed To take things to an extreme, the smart microcontroller from National Semicon- value from RAM before the processor actu- RAM could intercept slow instructions or ductor and, possibly, apopcorn part like the ally requests it, and store it in the latch. (Continued on page 36.)

Forth Dimensions 30 Volume XII, Number 3 TESTING TOOLKIT PHIL KOOPMAN, JR. - WEXFORD, PENNSYLVANIA

I Oneof Forth's strong points is its sup- 1 I port of interactive deveioiment and test- \ Forth testing support \ By Philip Koopman Jr., for Harris Semiconductor ing. Sometimes1 however, interactive test- \ Derived f test code used for the RT* ,-hip f akly ing is not enough.During the \ Developed on F-TZ (an F-PC and F-83 derivative) version 3 .Xll of low-level software for the RTX family, we wanted a method to Create a permanent VARIABLE #STACK -1 #STACK ! \ Saves number of stack elements for testing record of test cases for Forth words. This / / CREATE R-SAVE 8 ALLOT \ Note: F-TZ uses 32-bit return addresses! I / record serves as documentation for users and maintainers. In addition, a full suite of : GET-DEPTH ( ..stack.stuff.. - ..stack.stuff.. ) DEPTH #STACK @ -- #STACK ! ; test cases for a program provides a way to be sure that a change in one part of-the : DS( (-- $BAD1 $BAD2) program does not disturb other parts of the \ Init RS to -1 so that '-' will know it is a DS input program. \ Uses hex OBADl and hex OBAD2 as sentinel values for DS -1 #STACK ! $BAD1 $BAD2 ; How to Use It : RS ( ( -- $BAD3 $BAD4 ) Each test case consists of code that \ Uses hex OBAD3 and hex OBAD4 as sentinel values for RS places elements on the data and return DEPTH #STACK ! $BAD3 $BAD4 : stacks, creates and executes a test defini- tion, then verifies that the correct results . -- ( nl n2 n3 .. n.n - nl n2 n3 .. n.n sentinel ) were placed on both stacks. For example, a #STACK @ O< NOT IF ( if RS ( ) GET-DEPTH THEN ; test case for the word DUP would be: : ?DATA ( nl n2 -- ) = NOT ABORT" DATA STACX ERROR" ;

: ?RETURN ( nl n2 -- ) The test case can be = NOT ABORT" RETURN STACK ERROR" ;

any sequence of Forth . -- ( --I words. DEPTH #STACK ! ; : PERCOLATE ( rl n.n .. nl -- n.n .. nl rl ) #STACK @ ROLL -1 #STACK +! ; DS( 1111 -- RS( -- : )RS ( r.n .. r3 r2 r.1 nl n2 n3 .. n.n -- ) TEST: DUP ;DONE GET-DEPTH #STACK @ IF BEGIN PERCOLATE ?RETURN #STACK @ O= UNTIL THEN )RS -- $BAD4 ?RETURN $BAD3 ?RETURN -1 #STACK ! ; -- 1111 1111 )DS : )DS (r.n .. r3 r2 r.1 nl n2n3 .. n.n --) The first line of the test case specifies that GET-DEPTH #STACK @ the data stack input to the test is the number IF BEGIN PERCOLATE ?DATA #STACK @ O= UNTIL THEN 1111. The second line specifies that no $BAD2 ?DATA $BAD1 ?DATA -1 #STACK ! ; elements are to be placed onto the return n.n .. n.2 n.1 ) stack. The third line creates and executes a : REVERSE ( n. . . -- DUP O> IF 0 DO I- ROLL LOOP ELSE DROP THEN ; temporary Forth word with a body of DuP, I I carefully handling the data and return stack : INIT-TEST ( ..DS.stuff.. ..RS.stuff.. -- . .DS.stuff.. ) contents before and after the test. The (RS: -- ..RS.stuff.. ) fourth line specifies that no values should

I Volume XII, Number 3 31 Forth Dimensions be left on the return stack, and generates an error message if this is not the case. The CR ." TEST-" fifth line specifies that two values of the #STACK @ O< ABORT" You mst specify both DS ( and RS (." R> R-SAVE ! FD R-SAVE 2+ ! \ Save return address number 1111 should be returned from the #STACK @ REVERSE test, again generating an error message if BEGIN #STACK @ O> WHILE >R -1 #STACK +! REPEAT this is not the case. It is very important that R-SAVE 2+ @ >R R-SAVE @ >R ; \ Restore return address the test cases be written in exactly this : FINISH-TEST ( .. DS. stuff .. -- ..DS.stuff.. ..reversed.RS.stuff.. ) order, with no missing items, for proper ( RS: ..RS.stuff.. -- ) operation. R> R-SAVE ! FD R-SAVE 2+ ! \ Save return address The body of the test case between \ Transfer return stack contents onto data stack for later compare 0 >R TEST : and ;DONE can be any sequence of BEGIN FD FD SWAP 1+ >R DUP $BAD3 = UNTIL Forth words, including primitives that ma- R> REVERSE nipulate the return stack. The words R-SAVE 2t @ >R R-SAVE @ >R \ Restore return address INIT-TEST and FINISH-TEST are automatically compiled with the test case to handle the data and return stacks for proper \ TEST and DONE use F-TZ specific words to compile a short execution. \ definition containing the word to be tested, execute that In order to be sure that a word is working \ definition, then FORGET it from the dictionary. \ This borrows a compilation idea from Rick van Norman's RTX test code properly, it is not enough to simply place CREATE MARKER 4 ALLOT the required number of parameters on the : TESTER ; stack and then see if the correct results are : TEST: ( --) returned. The problem is that a word may XHERE 2DUP MARKER 2! PARAGRAPH + DUP XDPSEG ! 0 XDP ! XSEG @ -- [ '1 TESTER >BODY ! cause unexpected side effects (such as cor- COMPILE INIT-TEST ] ; ruption of elements on the data and return stacks) that are not detected immediately. : ;DONE In order to handle this case, the test words COMPILE FINISH-TEST COMPILE EXIT place two "sentinel values" onto both the STATE OFF TESTER MARXER 2@ XDP ! XDPSEG ! ; data stack and the return stack. then check IMMEDIATE to ensure that no corruption h& occurred. While side effects are usually not a problem \ Test ROT for proper operation DS( 1111 2222 3333 -- in high-level code, they can easily create RS ( -- problems when dealing with assembly lan- TEST: ROT ;DONE guage or microcode word implementa- -- )RS tions. -- 2222 3333 1111 )DS

Ideas for Further Refinements \ Test >R for proper operation The test capability presented here is DS ( 5555 -- rather simple, in order to keep the code RS ( -- (somewhat) understandable. Features that TEST: >R ;DONE -- 5555 )RS could be added to improve its usability -- )DS include: allowing RS ( ) RS to be optional, so tests that deal only with data stack opera- tions could automatically generate and test \ Any combination may go between TEST: and ;DONE return stack sentinel values; more sophisti- DS( 1111 2222 3333 -- RS( 7777 2222 9999 -- cated error messages that show exactly TEST: SWAP FD ROT >R ;DONE what is wrong with a stack when an error -- 7777 2222 3333 )RS does occur; methods to ensure that only -- 1111 2222 9999 )DS desired memory locations are modified for words that perform fetches and stores; and \ Null test to be sure it works methods to ensure that only desired on-chip DS( -- registers are modified for assembly lan- RS( -- guage definitions. TEST: ;DONE The code is written for F-TZ, a version -- )RS of F-PC, developed by Tom Zimmer. F-PC is a descendent of F-83, but allows using a dictionary space of greater than 64K bytes. The code presented should be relatively (Continued on page 41 .) 1 I Forth Dimensions 32 Volume XII, Number 3 Twelfth Annual FORML CONFERENCE The original technical conference for professional Forth programmers, managers, vendors, and users.

Following Thanksgiving, November 23-25, 1990 Asilomar Conference Center Monterey Peninsula overlooking the Pacific Ocean Pacific Grove, California U.S .A. Conference Theme: Forth in Industry Papers are invited that address relevant issues in the development and use of Forth in industry. Papers about other Forth topics are also welcome. Mail abstract(s) of approximately 100 words by October 1, 1990 to FORML, P.O. Box 8231, San Jose, CA 95155. Completed papers are due November 1, 1990. Conference Registration Registration fee for conference attendees includes conference registration, coffee breaks, and note- book of papers submitted, and for everyone rooms Friday and Saturday, all meals including lunch Fri- day through lunch Sunday, wine and cheese parties Friday and Saturday nights, and use of Asilomar facilities. Conference attendee in double room-$285 Non-conference guest in same room--$I60 * Children under 17 in same room-$120 Infants under 2 years old in same room-free Conference attendee in single room-$360 Register by calling the Forth Interest Group business office at (408) 277-0668 or writing to: FORML Conference, Forth Interest Group, P.O. Box 8231, San Jose, CA 95155. About Asilomar The Asilomar Conference Center combines excellent meeting and comfortable living accommodations. It is situated on the tip of the Monterey Peninsula overlooking the Pacific Ocean. Asilomar is part of the California State Park system; it occupies 105 secluded acres of forest and dune. If you like, you may jog on the beach before breakfast, join an informal discussion under a cypress tree after lunch, and exchange stories in front of a fireplace at the nightly wine and cheese parties. Guests of conference at- tendees may enjoy sightseeing along the beautiful Big Sur coast, visiting the new Monterey Aquarium, or shopping in nearby Carmel.

Volume XII, Nwnber 3 33 Forth Dimensions Part Two I FORST: A 68000 NATIVE-CODE FORTH JOHN REDMOND - SYDNEY, AUSTRALIA. m

Ihave very mixed feelings about using structions to a nesting level of seven. This attempted. READ retums the actual num- C. The syntax is dense and helps maximize is a powerful and convenient approach, ber of characters read successfully and the typing errors, but the statements are power- analogous to that of standard Forth, but it #chars fields are set appropriately. Then a ful. As normally used, it falls far behind uses a special system stack to keep track of character is fetched from the buffer, the (say) Pascal as an algorithmic language, the nesting. If a compilation error occurs, character pointer advanced and the #chars but it is used much more often. It seems to all open files are automatically closed. decremented. This will be continued until be the most popular applications language, #chars is zero, when another READ will be despite the flab which most systems insist File Structure necessary. In the event that the buffer is on adding to the code. Finally, the code is FILE is a very simple defining word: empty and READ returns 0 characters, usually tolerably fast and, for Forth pro- GETC returns -1 instead of a character. grammers, it is the language to beat! : FILE PUTC carries out its operations in a In their enthusiasm to push the CREATE 24 ALLOT DOES> ; very similar way. Whenever the buffer is enormous advantages of their own lan- full, it is flushed to the disk before insert- guage, Forth programmers opt for a system The six 32-bit fields within the structure it ing a new character. When FCLOSE is which is at once powerful, malleable, creates are used in the following way: used, it will flush the buffer contents to the comfortable and primitive. And they con- disk before using the lower-level MFREE demn themselves to forging, for the most offset 0: #chars in buffer to deallocate the memory buffer and part, their own tools while the Unix/C 4: character pointer CLOSE to close the file and free the system environment has all thosepowerful utilities 8: buffer pointer file handle for further use. Using this ap- with the ridiculous names. And, above all, 12: system file handle proach, forty (!) disk files can be open at C has access to enormously powerful and 16: file any one time. flexible 110 functions. As ForST took (O=input,l =output) shape, I decided that it just had to include 20: #chars read or written from/ TOS File Handles the I10 functions, its best feature, from C. to buffer so far The available handles number 0-45, of Much has been written, many times, which 645may be allocated to disk files. about Forth blocks and screens. Disk I/O is (Using 32 bits for each field is wasteful, but These are the non-standard handles. Stan- based on (usually) 1024-byte chunks of simple to follow.) dard handles 0-5 are allocated to hardware disk space. No operating system directory devices by ForST, in accordance with the is used and there is often a problem of Opening a File TOSdesignations: reconciling Forth's use of the disk with that When FOPEN is used, it expects on the of the resident system. The F83 use of stack the address of a file structure and the blocks within DOS files, for instance, is operating mode. If the mode is non-zero, a handle 0: console input rather contrived. file will be created using FMAKE;other- 1: console output ForST's approach is to use buffered wise, the low-level word OPEN is used to 2: serial port (AUX) TOS files, which permits fully redirectable open an existing file for reading. If success- 3: (PRN) 110 basedon (wait for it!) GETC and PUTC. ful, it will return asystem file handle, which 4 & 5: dummies Once these functions are incorporated, it is is then kept in the file structure. Then MAL- extremely simple to cany out file copy and LOC is used to allocate a 1024-bytebuffer It is easy to confuse the different labels filtering functions. in heap memory. The buffer address is associated with files. The file 'handle' is returned and stored in the two pointer fields the file descriptor of C and is stored in the System File Usage of the file structure. Finally, the #chars array (structure) at the address returned by As normally configured, ForST has fields are cleared ready for a read or write. a named file, e.g.. eight file structures available for its own When a file is accessed with GETC for use. When source code is compiled from the first time, it attempts to fetch a character FILE FILE 1 (define the file) I thedisk(using LOAD ),the from the allocated buffer. When it fails, a FILE1 0 FOPEN (openitforinput) source code can include nested LOAD in- 1024-byte disk READ into the buffer is

Forth Dimensions 34 Volwne XII. Nwnber 3 From this point, the address given by with SRC and adds DEST to redirect normal F ILE2 - 10 1 LSEEK FILE^ + 12 will hold the descriptor, for output. When the system looks for input and winds the access position back 10 bytes, later use; but most programs will not need BLK contains zero, it will go to the key- FI LEI - 4 5 2 LSEEK to use it. At the user level, FILEl is the boardbuffer; butif ~~Ccontainstwo,itwill sets the access position input to 45 bytes only file label used. fetch a character from the serial port. Simi- back from the end. larly, if DEST contains a non-zero value Block Operations less than six, it will direct output to a hard- FTELL returns the present access posi- Although byte-buffered operations are ware device. If the value in SRC or DEST is tion of the input or output file. FDUP dupli- usually the most convenient, block opera- six or higher, it will be interpreted as a file cates a standard handle with a disk file tions are also available with READ and structureaddress(eg,~1~~1)anddiskI/O handle, and a non-standard handle and WRITE. To keep their use intuitive for will be carried out. FORCE forcibly redirects I/O. Forth programmers, their parameters are as LOAD is an important user word which Finally, a point about string for CMOVE, e.g., uses system file stuctures: compatibility: TOS expects a pointer to an uncounted, null-terminated string for any FILE1 LINEBUFFER LINELENGTH LOAD of its arguments. A terminal space-such READ as is added by WORD-has been acceptable LINEBUFFER FILE2 LINELENGTH The system responds by pushing the value for all cases SO far tried, but ForST users WRITE in SRC onto the input stack and replacing it should be aware (see NAMEARG in the code with the address of the file structure it has below). These functions are much faster than byte- allocated to the source file. If the file, in A few simple file utilities are given to buffer YO, but GETC and PUTC still oper- turn, contains LOAD commands, the proc- illustrate use of the primitives. COPY is a ateat upwards of 30 Kbytes per second with ess is repeated. good model for more complex filter func- a hard disk. ForST allows access to other TOS file tions, such as case conversion and charac- utilities. LSEEK allows a buffer to be set to ter substitution. The conversion between a any point in the input file: hybrid F83 file and a normal text file, for System Redirection example, is trivial. BLK holds the source descriptor in a FILE1 0 0 LSEEK Next time, the final chapter of this se- standard Forth system. ForST replaces this is equivalent to rewind, ries: the use of named, automatic stack I 1 WE'RE LOOKING FOR A FEW GOOD Total control with LMI FORTHTM brProgramming Professionals: an expanding family of compatible, high- performance, compilers for For Development: Interactive Forth-83 InterpreterICompilers for MS-DOS, OSl2, and the 80386 16-bit and 32-bit implementations Full screen editor and assembler Uses standard operating system files 500 page manual written in plain English Su~~ortfor araphics.floatina mint, native code generation 1 . . -. -. - 1 I For Applications: Forth-83 Metacompiler ~nicqietable-drivenmulti-pass Forth compiler Compiles compact ROMable or disk-based applications Excellent error handling Produces headerless code, compiles from intermediate states, and performs conditional compilation Crosscompiles to 8080,Z-80,8088,68000,6502,8051,8096, 1802,6303,6809,68HC11,34010,V25, RTX-2000 ASSOCIATES No license fee or royalty for compiled applications Forth Recruiters r Laboratory Microsystems Incorporated Ftst OfficeBox 10430, Marina del Rg: C4 90295 Phone Credit Card Orders to: (213) 306-7412 I 70 Elmwood Ave./ Rochester, NY 1461 1/(716) 2354168 I FIX: (213) 3014761 I Volume XI!, Number 3 35 Forth Dimensions variables and an analysis of their advan- tages in writing a floating-point package. 0 CONSTANT RD 1 CONSTANT WR FILE FILEl FILE FILE2 John Redmond is an Associate Pro- fessor of Organic Chemistry at : NAMEARG 32 WORD 0 OVER COUNT + C! l+ ; Sydney's Macquarie University. He I I is a ". ..sometimes-evenings-when-I- ( File dump utility which uses unbuffered file i/o) I I have-time programmer" whose chief : .HEX <# # # #> TYPE SPACE ; disappointment of 1988 consisted of : .ADDR CR <# [ASCII] : HOLD attending a plant pathology confer- # # # # # # #> TYPE 2 SPACES ; ence in Acapulco while Forth's own : .BYTES PAD SWAP 0 Charles Moore was visiting Sydney. DOCOUNT.HEx 17.. Mr. Redmond welcomes letters from IF SPACE THEN LOOP DROP ; FD readers: 23 Mirool Street, West : .CHAR DUP 32 < IF DROP [ASCII] . THEN EMIT ; Ryde, NSW2114, Australia. : .CHARS PAD SWAP 0 DO COUNT .CHAR LOOP DROP ; : DLINE DUP .BYTES SPACE SPACE .CHARS ;

( Dump a file of any type, opened by low-level OPEN) : DUMP NAMEARG RD OPEN CLS HEX 0 ( offset) BEGIN DUP ( off set) .ADDR 16 + ( bump offset) OVER ( file handle) PAD 16 READ (Continuedfrom page 30.) DUP ( bytes read) DLINE 16 last block) KEY data moves, and be doing them during the = NOT ( 3 = OR UNTIL DROP ( off set) CLOSE ; time that the processor is not using mem- ( example dump a:\forth\forst.tos) ory- As a poor man's emulator, it is aproven ( Utilities which use buffered file i/o) concept. Since not all of us have access to a I I $40,000 analyzer or emulator, the smart ( list a text file) RAM is a very powerful way to debug a : LIST FILEl RD NAMEARG FOPEN CR BEGIN FILEl GETC system. One thing that would be interesting DUP O< ( EOF) NOT WHILE EMIT REPEAT would be to unplug the RAM from a normal DROP ( EOF char) FILEl FCLOSE ; system and plug in the smart RAM (along ( example: LIST <£name>) with the appropriate handshake signals). This is the inverse of what most emulators ( copy any file) do, since they unplug the processor and : COPY FILEl RD NAMEARG FOPEN emulate it. I think RAM is easier to emu- FILE2 WR NAMEARG FOPEN BEGIN FILEl GETC DW O< ( EOF) NOT late. WHILE FILE2 PUTC REPEAT DROP FILEl FCLOSE FILE2 FCLOSE ; ( example: COPY ) Rob Chapman is a software engineer at IDACOM. He has used a 32-bit : CD NAMEARG CHDIR CU IF ." cannot set up path ' THEN ; Forth in several large projects over ( example: cd a:\forth\examples ) the last twoyears, but now he ismuch : BLKNAME CXTDTA 30 + 12 32 FILL ; happier witha simpler Forth running : FIRST NAMEARG 47 SFIRST ; on a Forth engine. : .FNAME GETDTA 12 TYPE ;

: DIR BLKNAME FIRST CU ( error) NOT IF CR .FNAME BEGIN BLKNAME SNEXT O< ( error) NOT WHILE .E'NAME REPEAT THEN ;

I ( example: dir a:\*.tos)

I Forth Dimensions 36 Volume XII. Number 3 BEST OF GENIE

Newsfrom the GEnie Forth Now, how to implement it.. . forms of alloc. Enlightenment please?) RoundTable-As the working BASIS First, let's keep it simple. Two words, Let me make one further suggestion: in being modified by the X3/J14 ANS Forth DALLOT and UNALLOT. All this does is real-time environments it is beneficial to Technical Committee comes closer to a return an address of n items and then returns force compactionlgarbage collection at a final document, some of the debate sur- this address to a pool. Most of the work in convenient (idle) time, rather than at the rounding Forth's future standard seems to DA is easily accomplished using RAM past usually critical moment when an alloca- be heating up. Recently, one of the hot HERE, and then feeding the memory back tion runs out of room. (Assuming here that potatoes has been dynamic memory allo- (keeping a linked list of deallocated mem- your system needs compaction or garbage cation. There are those who think the cur- ory chunks) to HERE after UNALLOT. collection,and you're desperate enough to rent tools used in Forth are more than Any specialized memory management use such in a real-time problem.) Perhaps sufficient, and there are those who would could be handled by the individual system, a third word, COLLECT, should be de- 'borrow' concepts incorporated in C. only the standard words need to be there for fined. Easy to makeitano-op when it'snot Read along in the two topic areas de- the programmers. needed. voted to this exchange, and once you have But.. . this should not be bound up with drawn your own conclusions, make them the notions of "what is theForth language" known. You have only yourself to blame if (like Lisp). This should be a standardized acourse is followed you do not agree with. Colleges may not libraryfunction. Morepower totheX3J14 teach Forth because it TC for moving in this direction! Category 10 Forth Standards 1 leaves out dynamic memory allocation. 1 Message 13 (Portedfrom XCFBS) Topic 36 / To: DAVID BREEDING ~emoryspaces and position-independent From: DARRYL BIECH code Subject: Dynamic allocation Message 12 Maybe I'm getting a little technical Message 11 (Portedfrom xCFBs) From: B.RODRIGUEZ2 here, but I'm wondering if you were im- From: DAVID BREEDING Huh. I guess C and Pascal aren't "mod- plying that theapplication will take careof Subject: Dynamic allocation em" languages. Certainly there is no dy- shrinking its claim on system memory Although 1 consider dynamic alloca- narnic memory allocation "within the lan- (say .COM files, for example) and moving tion to be one of the highest priorities in the guage itself' in C; it's part of the function the stack out of the way, etc., prior to deal- new standard, I have yet to read anything library. A distinction with a difference! locations? about it. I keep waiting for someone to And, while it's been years since I dusted off --d.b. bring it up, but somehow no one ever does, my Jensen & Wirth, I seem to recall static NET/Mail: British Columbia Forth Board so I've finally gotten down to writing allocation in Pascal, too. Burnaby, B.C.. Canada myself. All of the so-called "" lan- Local variables are dynamically allo- 604-434-5886 guages support some form of dynamic allo- cated in both languages, but this topic is cation within the language itself. This called "local variables" in X3J14 circles. Message 14 (Portedfrom xCFBs) memory can be called from fast RAM, Not to say that dynamic allocation is To: DARRYL BIECH cache, or even disk. All of this is transpar- unnecessary. Nick Solntseff and I recently From: DAVID BREEDING ent to the user. implemented such a system for our Forth Subject: Dynamic allocation One of the reasons, I heard, why col- work, using the same words with different That could all be handled on a system leges don't use Forth for teaching is that it names: ALLOC and RELEASE. Soon to be level and does not need to be addressed at leaves out this very thing. I'm not saying published in JFAR, we're told. the "standards" level. There are a lot of that adding DA will make colleges and uni- I agree, these seem to be the essential ways to implement DA, but a lot of it versities start teaching Forth, but I bet primitives. (Damfino why C has so many depends on the hardware setup of the sys- they'll sit up and notice.

Volume XII, Nwnber 3 3 7 Forth Dimensions tem. All I am proposing is a standard way Why not have dynamic allocation as an wait until BASIS12 is put online.) of doing DA. All of the particulars (like extension or "standard option," which -Doug caching and extended memory use) could would be palatable to both small and large P.S. This reminds me somewhat of the al- be handled by the programmers of the implementations of the language? loca controversy for C. (Allocate memory compiler. The only thing that makes sense --d.b. on the stack so that procedure exit/ to me is the inclusion of the two words NETNl: British Columbia Forth Board longjmp will automatically reclaim it.) DALLOT and UNDALLOT. Which returns Burnaby, B.C., Canada an address for use, or returns it to the 604-434-5886 "hap." Message 2 (Ported from UseNet) It is a truly exciting subject... when I Category18 From: [email protected] (Gary Corby) was in college, we used DA extensively 'comp.lang.forth Newsgroups: comp.lang.forth (this was about five years ago). Using DA Subject: Re: C memory allocation and recursion, you can do some truly great Topic 86 things that deal with huge amounts of data. Subject: Dynamic memory allocation Mitch Bradley writes: I have always regretted not having DA as a "(Damfino why C has so many forms part of the Forth language. Message 1 (Portedfrom UseNet) of alloc. Enlightenment please?)" Path: willett!dwp Message 15 (Ported from xCFBs) From: [email protected] (Doug Philips) Some reasons: To: B RODRIGUEZ2 Newsgroups: comp.lang.forth 1) History. From: RAY DUNCAN Subject: Re: global storage of setjmp()l 2) C library functions are not arbitrarily Subject: Memory and PIC lonimpo constrained to be the "most primitive Dynamic memory allocation is very possible" functions. useful. All of the LMI Forth systems have Mitch Bradley writes: 3) Different alignment requirements for had this for several years. But I agree that it "(. ..personally I find a "mal1oc"ed army different data types. should be viewed as an extension to the of jmp-buf s treated as a stack of recov- language rather than part of the core lan- ery points more useful than the potential Another reason: The actual system guage (similar to its implementation as part uses of "foo," but that's just me.)" calls used to change data segment space of the RTL in C) -it doesn't make any allocation are brk(2) and sbrk(2). The first sense to require that this be supported in a Which is exactly the point. ANS Forth sets an absolute boundary and the second ROMmed ANSI Standard Forth kernel, for CATCH and THROW implicitly perform this alters the boundary relative to the current example. stacking action for you, for free. You don't one. MallocO, calloc0, talloc0, free(), NET/Mail : LMI Forth Board have to synthesize your own stack. The and friends all come down to brkO and Los Angeles, California nested handlers go on the return stack in a sbrk() in the end. There are "most primi- 213-306-3530 very natural and easy-to-implement fash- tive possible" functions. So primitive, in ion, and they are automatically removed fact, that nobody in their right mind wants Message 16 (Ported from xCFBs) without any special care on the part of the to use them if malloco or something like it To: JEFF CYNX programmer. is available. From: RAY DUNCAN For free? --Gary Subj: Comment Catch frames must interfere with uses of Gary Corby (Friend of Elvenkind) My injunction against this is both the return stack in the same way that DO Softway Pty Ltd worldly and spiritual. If you want your LOOP indices do. ACSnet: [email protected] program to run properly under multitasking There must either be: UUCP: .. . !uunet!softway.oz!gary environments such as DesqView, Win 3, 1) A pointer to the top-most catch be. OS12's DOS box, etc., you should be well- 2) A unique tag to mark catch frames on the Message 3 (Portedfrom UseNet) behaved in your use of memory. Not using return stack. From: [email protected] MALLOC means that you will not be able to (Mitch Bradley) use new capabilities such as SHELL" and Since no special care on the part of the Newsgroups: comp.lang.forth that your program will not be easily port- programmer is required, the first option Subject: C memory allocation able to the higher-performance UR/ would require support in NEXT and the Sender: FORTH systems for DOS, OSl2, or 32-bit second option would restrict the kinds of [email protected] 80386 protected mode. temporaries shoved on the return stack. NET/Mail: LMI Forth Board I don't see how it is free. Still, I suppose Gary Corby writes: Los Angeles, California that having a separate CatcNThrow stack Another reason: The actual system calls 21 3-306-3530 wouldbe exceeding thecharter of X3J 14. In used to change data segment space al- fact, the scheme you describe must have location are brk(2) and sbrk(2). The Message 17 (Ported from xCFBs) had some "common practice" to be first sets an absolute boundary and the To: DAVlD BREEDING adopted, or is this not true? second alters the boundary relative to From: DARRYL BIECH I would like to hear more details about Subject: Dynamic allocation how it's supposed to work. (Maybe1should 1 (Continued on page 41 .; i Forth Dimensions 38 Volume XII, Nwnber 3 REFERENCE SECTION

Forth Interest Group 1987 Marlin Ouverson David C. Petty The Forth Interest Group serves both 1988 Dennis Ruffer Digitel expert and novice members with its net- 1989 Jan Shepherd 125 Cam bridge Park Dr. work of chapters, Forth Dimensions, and Cambridge, MA 02140-23 1 1 conferences that regularly attract partici- ANS Forth pants from around the world. For member- The following members of the ANS Forth Instruction ship information, or to reserve advertising X3J 14Forth StandardCommitteeareavail- Los Angeles-Introductory and inter- space, contact the administrative offices: able to personally carry your proposals and mediate three-day intensive courses in Forth Interest Group concerns to the committee. Please feel free Forth programmingare offered monthly by P.O. Box 823 1 to call or write to them directly: Laboratory Microsystems. These hands- San Jose, California 95155 on courses are designed for engineers and 408-277-0668 Gary Betts programmers who need to become profi- Unisyn cient in Forth in the least amount of time. Board of Directors 301 Main, penthouse #2 Telephone 213-306-74 12. Robert Reiling, President (ret. director) Longmont, CO 80501 Dennis Ruffer, Vice-President 303-924-9193 On-Line Resources John D. Hall, Treasurer To communicate with these systems, set Wil Baden Mike Nemeth your modem and communication software Jack Brown CSC to 300/1200/2400 baud with eight bits, no Mike Elola 10025 Locust St. parity, and one stop bit, unless noted other- Robert L. Smith Glenndale, MD 20769 wise. GEnie requires local echo. 301-286-8313 Founding Directors GEnie William Ragsdale Andrew Kobziar For information, call 800-638-9636 Kim Harris NCR Medical Systems Group Forth RoundTable Dave Boulton 950 Danby Rd. (Fortmet link*) Dave Kilbridge Ithaca, NY 14850 Call GEnie local node, then type M710 John James 607-273-5310 or FORTH S ysOps: Dennis Ruffer (D.RUFFER), In Recognition Elizabeth D. Rather Scott Squires (S.W.SQUIRES), Le- Recognition is offered annually to a FORTH, Inc. onard Morgenstern (NMORGEN- person who has made an outstanding con- 11 1 N. Sepulveda Blvd., suite 300 STERN), Gary Smith (GARY-S) tribution in support of Forth and the Forth Manhattan Beach, CA 90266 MACH2 RoundTable Interest Group. The individual is nomi- 213-372-8493 Type M450 or MACH2 nated and selected by previous recipients of Palo Alto Shipping Company the "FIGGY ." Each receives an engraved Charles Keane SysOp: Waymen Askey (D.MILEY) award, and is named on a plaque in the ad- Performance Packages, Inc. ministrative offices. 5 15 Fourth Avenue BIX (ByteNet) Watervleit, NY 12189-3703 For information, call 800-227-2983 1979 William Ragsdale 5 18-274-4774 Forth Conference I 1980 Kim Harris Access BIX via TymeNet, then type j 1 1981 Dave Kilbridge George Shaw I forth 1982 Roy Martens Shaw Laboratories Type FORTH at the : prompt 1983 John D. Hall P.O. Box 3471 SysOp: Phil Wasson (PWASSON) 1984 Robert Reiling Hayward, CA 94540-3471 LMI Conference 1985 Thea Martin 4 15-276-5953 Type LMI at the : prompt 1986 C.H. Ting Laboratory Microsystems products

Volume XII, Nwnber 3 39 Forth Dimensions Host: Ray Duncan (RDUNCAN) PC Board BBS's devoted to Forth 5 12-323-2402 (Fortmet links*) StarLink node 1306 on TymNet CompuServe East Coast Forth Board SysOps: S. Suresh, James Martin, Anne For information, call 800-848-8990 703-442-8695 Moore Creative Solutions Conference StarLink node 2262 on TyrnNet Harris Semiconductor Board Type !Go FORTH PC-Pursuit node dcwas on TeleNet 407-729-4949 SysOps: Don Colburn, Zach Zachariah, SysOp: Jerry Schifrin StarLink node 9902 on TymNet (toll Ward McFarland, Jon Bryan, Greg British Columbia Forth Board from Post. St. Lucie) Guerin, John Baxter, John Jeppson 604-434-5886 Computer Language Magazine Confer- SysOp: Jack Brown Non-Forth-specific BBS's with extensive ence Real-Time Control Forth Board Forth Libraries Type !Go CLM 303-278-0364 Twit's End (PC Board) SysOps: Jim Kyle, Jeff Brenton, Chip StarLink node 2584 on TymNet 501-771-0114 Rabinowitz, Regina Starr Ridley PC-Pursuit node coden on TeleNet 1200-9600baud SysOp: Jack Woehr StarLink node 9858 on TymNet Unix BBS's with forth.conf (Fortmet SysOp: Tommy Apple links* and reachable via StarLink node Other Forth-specific BBS's College Comer (PC Board) 9533 on Tyrn.Net and PC-Pursuit node Laboratory Microsystems, Inc. 206-643-0804 casfa on TeleNet.) 21 3-306-3530 300-2400 baud WELL Forth conference StarLink node 9184 on TymNet SysOp: Jerry Houston Access WELL via CompuserveNet PC-Pursuit node calm on TeleNet Psymatic BBS or 415-332-6106 SysOp: Ray Duncan Sunnyvale, California Fairwitness: Jack Woehr (jax) Knowledge-Based Systems 408-992-0372 Wetware Forth conference Supports Fifth 300 - 2400 baud 415-753-5265 409-696-7055 This is a programmer's board with a Fairwimess: Gary Smith (gars) Druma Forth Board large Forth area.

The development sys- tem consist's of a t\;o- UPPER DECK FORTH $49 board set. The target board can be used in a stand alone mode as Based on Forth-83 Standard asin ech~unitwith Fully segmented architecture a FO%TH'&mel and u to 32K byte on- Uses ordinary ASCII text files clip eprom and 2K Direct threaded code with top of stack in ram or with a piggy- back memory expan- register for fast execution sionboardanth either Compiles 32K file in 6 seconds on 4.77 MHz 64K bytes of 16 bit ramlrom memory, IBM PC 64K bytes of 8-bit Built-in multi-file full screen editor ramlrom f32W32K) Assembler, decompiler, source-level debugger of 8-bit ram memory. -- - Turnkey application support, no royalties MmUBIsM m- Complete documentation The target board has two RS232/RS422 serial ports, sockets for 8 buffer IC's, two40 in headers for For IBM PCIXTIAT and compatibles with 256K, UO or expansion, and batterybackup for both the memow on tRe CPU and all hard disk or floppy, DOS 2.0 or later of the expansion board ram.- The 16-bit single chi Mitsubishi M37700 family has eight 16-bit timers, a watchdog timer, 68 1/8 lines, two UARTS (synch or asynch), hardware multip- Add $3 for shipping and handling (outside USA $15). ly and divide, nineteen interrupts, and an 8-bit A-D converter with an 8 chan- nel multi lexer, all with a typical power dissipation of 30 mW.They are available CA residents add sales tax. in both 8Rhz and 16 Mhz versions and with 512 to 2K bytes of onchip ram and up to 32K bytes of on-chip ROM or EPROM. Also available is a very low cost ($125) prom programmer that can be used with the development system to bum either 27xx series of EPROM's or, with an ada ter, the eprom version of the 7700 chips. Full development systems with FO~source code for assembler, disassembler, editor, prom prommmer .* - - - and many other utilities as well as P.O. Box 263342, Escondido, CA 92026 a 6K FORTH kernel in rom are (619) 741-1075 available NOW! Tareet Board 33122 181st. Ave. S.E. prices start at $200.00: Package prices and quantity discounts available also. I /

Forth Dimemiom 40 Volume XII, Nwnber 3 International Forth BBS's (Continued from page 32 .) (CoMinuedfrom page 38.) Melbourne FIG Chapter (03) 809-1787 in Ausualia portable to other 83-Standard Forths, as the current one. Malloc(), calloco, tal- 61-3-809- 1787 international long as the return-address-save sequences lot(), free() and friends all come down SysOp: Lance Collins in INIT-TEST and FINISH-TEST are to brk() and sbrk() in the end. So there Forth BBS JEDI changed to save and restore only a single are "most primitive possible" func- Paris, France return stack element for most other Forths. tions. So primitive in fact that nobody 33364315 15 Also, TEST : and ;DONE should be rede- in their right mind wants to use them if 7 data bits, 1 stop, even parity fined for use with other dictionary struc- malloc() or something like it is avail- Max BBS (ForthNet link*) tures. able. United Kingdom Interactive testing is important and use- 0905 754157 ful (and, in fact, there is no reason why Note that, while this is true in Unix, it is SysOp: Jon Brooks these tools cannot be used as an interactive not necessarily true in other operating sys- Sky Port (ForthNet link*) testing format). However, once initial test- tems. Consequently, while sbrk() is cer- United Kingdom ing is done, it is often useful to have a tainly the primitive memory allocation 44-1-294- 1006 permanent test suite in a consistent and operation for Unix, it does not necessarily SysOp: Andy Brimson readable format. Portions of many pro- even exist on all C implementations. In SweFIG grams are so crucial to system operation particular, I would expect that it would be Per Alm Sweden that they merit a full validation suite to difficult to properly implement sbrko on 46-8-7 1-35751 NEXUS Serviciosde Informacion, prove correct operation. At Harris, valida- the (probably the Amiga C library S. L. tion suites are being used on the instruction simulates it with some restrictions). sbrko Travesera de Dalt, 104-106, Entlo. sets of some of the RTX processors. The assumes that each process has its own ad- 4-5 tools presented here provide astarting point dress space, which is not generally true. Use 08024 Barcelona, Spain for creating a validation suite for a variety of sbrk() is not necessarily portable. + 34 3 2103355 (voice) of applications. By the way, since brk() can be imple- + 34 3 2147262 (modem) mented in terms of sbrk(), sbrk() is the true SysOps: Jesus Consuegra, Juanma primitive on Unix systems. In many Unix Barranquero Philip Kooprnan Jr. is a senior scien- implementations, sbrk() is the true system [email protected] (preferred) tist at Harris Semiconductor and an call, and brk() is implemented as a library barran@ nsi.es adjunct professor at Carnegie Mel- routine, a thin veneer around sbrk(). barran (on BIX) lon University. The opinions in this -Mitch Bradley article are his, and do not necessar- This list was accurateas of August 1990. If ily reflect the views of Harris Serni- you know another on-line Forth resource, conductor. To suggest an interesting on-line please let me know so it can be included in guest, leave e-mail posted to GARY-S this list. I can be reached in the following on GEnie (gars on Wetware and the ways: Well),or mail me a note. I encourage anyone with a message to share lo Gary Smith contact me via the above or through P. 0. Drawer 7680 the offices of the Forth Interest Little Rock, Arkansas 72217 Group. Telephone: 501-227-7817 GEnie (co-SvsOv. Forth RT and Unix

...... --.. a- - 1 ( 1 Academic Press, Inc. 14 Institute for Applied 26,27 1 I Forth ~esearch- *ForthNet is a virtual Forth net- Dash, Find Associates 3 5 work that links designated message Laboratory Microsystems 35 bases in an attempt to provide Forth Interest Group 44 greater information distribution to Miller Services 24 the Forth usersserved. It isprovided FORML 33 Next Generation Systems 22 courtesy of the SysOps of its various Home Electonics, Inc. 40 Silicon Composers 2 Harvard Softworks 16 Upper Deck Systems 40

Volume XII, Number 3 41 Forth Dimensions FIG CHAPTERS

The FIG Chapters listed below North Bay Chapter Tampa Bay Chapter MASSACHUSETTS are currently registered as active 2nd Sat., 10 a.m. Forth, A1 1st Wed.. 7:30 p.m. Boston Chapter with regular meetings. If your 12 Noon Tutorial. 1 p.m. Forth Terry McNay (813) 725-1245 3rd Wed., 7 p.m. chapter listing is missing or incor- South Berkeley Public Library Honeywell rect, please contact Kent Safford at George Shaw (415) 276-5953 GEORGIA 300 Concord, Billerica the FIG office's Chapter Desk. Atlanta Chapter Gary Chanson (617) 527-7206 This listing will be updated in each Orange County Chapter 3rd Tues., 7 p.m. issue of Forth Dimensions. If you 4th Wed., 7 p.m. Emprise Corp., Marietta MICHIGAN would like to begin a FIG Chapter Fullerton Savings Don Schrader (404) 428-081 I DetroitIAnn Arbor Area in your area, write for a "Chapter Huntington Beach Bill Walters Kit and Application." Forth Inter- Noshir Jesung (714) 842-3032 ILLINOIS (313) 731-9660 est Group, P.O. Box 8231, San Cache Forth Chapter (313) 861-6465 (eves.) Jose, California 95155 Sacramento Chapter Oak Park 4th Wed., 7 p.m. Clyde W. Phillips, Jr. MINNESOTA U.S.A. 1708-59th St., Room A (708) 713-5365 MNFIG Chapter ALABAMA Bob Nash Minneapolis Huntsville Chapter (916) 487-2044 Central Illinois Chapter Fred Olson Tom Konantz Champaign (612) 588-9532 (205) 88 1-6483 San Diego Chapter Robert Illyes (217) 359-6039 Thursdays, 12 Noon MISSOURI ALASKA Guy Kelly (619) 454-1307 INDIANA Kansas City Chapter Kodiak Area Chapter Fort Wayne Chapter 4th Tues., 7 p.m. Ric Shepard Silicon Valley Chapter 2nd Tues., 7 p.m. Midwest Research Institute Box 1344 4th Sat., 10 a.m. up Univ. Campus MAG Conference Center Kodiak, Alaska 99615 H-P Cupertino B71 Neff Hall Linus Orth (913) 236-9189 Bob Ban (408) 435-1616 Blair MacDermid (219) 749 -2042 St. Louis Chapter ARIZONA Stockton Chapter 1st Tues., 7 p.m. Phoenix Chapter Doug Dillon (209) 931-2448 IOWA Thornhill Branch Library 4th Thurs., 7:30 p.m. Central Iowa FIG Chapter Robert Washam Arizona State Univ. * COLORADO 1st Tues., 7:30 p.m. 91 Weis Drive Memorial Union. 2nd floor Denver Chapter Iowa State Univ. Ellisville. MO 6301 1 Dennis L. Wilson 1st Mon., 7 p.m. 214 Comp. Sci. (602) 381-1 146 Clifford King (303) 693-3413 Rodrick Eldridge NEW JERSEY (515) 294-5659 New Jersey Chapter ARKANSAS CONNECTICUT Rutgers Univ.. Piscataway Central Arkansas Chapter Central Connecticut Chapter Fairfield FTG Chapter Nicholas Lordi Little Rock Charles Krajewski 4th Day, 8:15 p.m. (201) 338-9363 2nd Sat.. 2 p.m. & (203) 344-9996 Gurdy Leete (5 15) 472-7077 4th Wed.. 7 p.m. NEW MEXICO Jungkind Photo. 12th & Main FLORIDA MARYLAND Albuquerque Chapter Gary Smith (501) 227-7817 Orlando Chapter MDFIG 1st Thurs., 7:30 p.m. Every other Wed.. 8 p.m. Michael Nemeth Physics & Astronomy Bldg. CALIFORNIA , Herman B. Gibson 1 (301) 262-8140 Univ. of New Mexico Los Angeles Chapter (305) 8554790 Jon Bryan (505) 298-3292 4th Sat., 10 a.m. Hawthorne Public Library Southeast Florida Chapter 12700 S. Grevillea Ave. Coconut Grove kea I Phillip Wasson John Forsberg (305) 252-0108 (213) 649-1428 I I Forth Dimensions 42 Volume XII, Number 3 NEW YORK Dallas Chapter Sydney Chapter HOLLAND Long Island Chapter 4th Thurs., 7:30 p.m. 2nd Fri., 7 p.m. Holland Chapter 3rd Thurs., 7:30 p.m. Texas Instruments John Goodsell Bldg., RM Vic Van de Zande Brookhaven National 13500 N. Central Expwy. LG19 Finmark 7 Laboratory Semiconductor Cafeteria Univ. of New South Wales 3 831 JE Leusden AGS dept., bldg. 91 1, lab rm. Conference Room A Peter Tregeagle A-202 Clif Penn (214) 995-2361 10 Binda Rd. ITALY Irving Montanez Yowie Bay 2228 FIG Italia (5 16) 282-2540 Houston Chapter 02/52-7490 Marco Tausel 3rd Mon., 7:30 p.m. Usenet Via Gerolarno Forni 48 Rochester Chapter Houston Area League of PC [email protected] 20161 Milano Odd month, 4th Sat., 1 p.m. Users 1 021435249 Monroe Cornrn. College 1200 Post Oak Rd. BELGIUM Bldg. 7, Rm. 102 (Galleria area) Belgium Chapter JAPAN Frank Lanzafame Russell Harris 4th Wed.. 8 p.m. Japan Chapter (716) 482-3398 (713) 461-1618 Luk Van Loock Toshi Inoue Lariksdreff 20 Dept. of Mineral Dev. Eng. OHIO VERMONT 2120 Schoten University of Tokyo Cleveland Chapter Vermont Chapter 031658-6343 7-3-1 Hongo, Bunkyo 113 4th Tues.. 7 p.m. Vergennes 812-21 11 x7073 Chagrin Falls Library 3rd Mon., 7:30 p.m. Southern Belgium Chapter Gary Bergstrom Vergennes Union High School Jean-Marc Bertinchamps NORWAY (216) 247-2492 RM 210, Monkton Rd. Rue N. Monnom, 2 Bergen Chapter Hal Clark (802) 453-4442 B-6290 Naliies Kjell Birger Faeraas, Columbus FIG Chapter 0711213858 47-5 18-7784 4th Tues. VIRGINIA Kal-Kan Foods, Inc. First Forth of Hampton = CANADA REPUBLIC OF CHINA 51 15 Fisher Road Roads BC FIG R.O.C. Chapter Terry Webb William Edmonds 1st Thurs., 7:30 p.m. Chin-Fu Liu (614) 878-7241 (804) 8984099 BCIT, 3700 Willingdon Ave. 5F, #lo, Alley 5, Lane 107 BBY, Rm. 1A-324 Fu-Hsin S. Rd. Sec. 1 Dayton Chapter Potomac FIG Jack W. Brown Taipei, Taiwan 10639 2nd Tues. & 4th Wed., 6:30 D.C. & Northern Virginia (604) 596-9764 p.m. 1st Tues. BBS (604) 434-5886 SWEDEN CFC. 11 W. Monument Ave. Lee Recreation Center SweFLG #612 5722 Lee Hwy., Arlington Northern Alberta Chapter Per Alm Gary Ganger (513) 849-1483 Joseph Brown 4th Sat., 10a.m.-noon 46/8-929631 OREGON (703) 47 1-4409 N. Alta. Inst. of Tech. Willarnette Valley Chapter E. Coast Forth Board Tony Van Muyden SWITZERLAND 4th Tues.. 7 p.m. (703) 442-8695 (403) 486-6666 (days) Swiss Chapter Li-Benton Comm. College (403) 962-2203 (eves.) Max Hugelshofer Pann McCuaig (503) 752-51 13 Richmond Forth Group Industrieberatung 2nd Wed., 7 p.m. Southern Ontario Chapter Ziberstrasse 6 PENNSYLVANIA 154 ~usinessschool Quarterly, 1st Sat.. ~ar.:lun., 8 152 Opfion Villanova Univ. Chapter Univ. of Richmond Sep.. Dec., 2 p.m. 01 810 9289 1st Mon.. 7:30 p.m. Donald A. Full Genl. Sci. Bldg., RM 212 Villanova University (804) 739-3623 McMaster University WEST GERMANY Dennis Clark Dr. N. Solntseff German FIG Chapter (215) 860-0700 WISCONSIN (416) 525-9140 x3443 Heinz Schnitter Lake Superior Chapter Forth-Gesellschaft C.V. TENNESSEE 2nd Fri., 7:30 p.m. ENGLAND Postfach 1110 East Tennessee Chapter 1219 N. 21st St., Superior Forth Interest Group-UK D-8044 Unterschleissheim Oak Ridge Allen Anway (715) 394-4061 London (49) (89) 317 3784 3rd Wed.. 7 p.m. 1st Thurs., 7 p.m. Munich Forth Box: Sci. Appl. Int'l. Corp.. 8th F1. INTERNATIONAL Polytechnic of South Bank (49) (89) 725 9625 (telcom) 800 Oak Ridge Turnpike AUSTRALIA RM 408 Richard Secrist Melbourne Chapter Borough Rd. SPECIAL GROUPS (615) 483-7242 1st Fri., 8 p.m. D.J. Neale NC4000 Users Group Lance Collins 58 Woodland Way John Carpenter TEXAS 65 Martin Road Morden, Surry SM4 4DS 1698 Villa St. Austin Chapter Glen Iris, Victoria 3146 Mountain View. CA 94041 Matt Lawrence 03/889-2600 FINLAND PO Box 180409 BBS: 61 3 809 1787 FinFIG Austin, TX 78718 Janne Kotiranta Arkkitehdinkatu 38 c 39 33720 Tampere +358-31-184246

Volume XII, Number 3 43 Forth Dimensl NEW FROM THE FORTH INTEREST GROUP

All About FORTH An Annotated Glossary Glen 6. Haydon

Third Edition REVISED AND UPDATED Includes COMMON USAGE STANDARDS DOCUMENTATION FOUR IMPLEMENTATIONS

STACK COMPUTERS ALL ABOUT FORTH the new wave the 3rd Edition

by Philip J. Koopman, Jr. by Glen B. Haydon

This book presents an alterna- An Annotated glossary of most tive to Complex Instruction Set Forth words in common usage, Computers (CISC) and Re- including Forth-79, Forth-83, duced lnstruction Set Comput- F83, F-PC, MVP-FORTH. Im- ers (RISC) by showing the plementation examples in high- strengths and weaknesses of level Forth and/or 808618088 stack machines. assembler, and useful com- mentary, are given for each entry. $62.00 $90.00 NOW AVAILABLE! SEE ORDER FORM INSIDE

Forth Interest Group P.O.Box 8231 Second Class San Jose, CA 95 155 Postage Paid at San Jose, CA