Home
4 - Forth Interest Group
Contents
1. NEXT AD C LODSW 93 C XCHG AX BX FF C 27C JMP BX gt Screen 11 EXTERN SAVE REGS amp RESTORE REGS 04FEB93 RA 03JAN93 HEX CREATE RG SV 8 ALLOT HERE 89 C 2E C RG SV BP gt RG SV FORTH RP 89 C 1E C RG SV 2 BX gt RG SV 2 FORTH W 89 C 36 C RG SV 4 SI RG SV44 FORTH IP 8C C 06 C RG SV 6 ES gt RG SV 6 C3 C RET CONSTANT SAVE REGS HERE 8B C 2E C RG SV BP 8B C IE C RG SV 2 BX 8B C 36 C RG SV 4 SI 8E C 06 C RG SV 6 ES CIC RET CONSTANT RESTORE REGS gt Screen 12 EXTERN CODE EXTERN 15FEB93 RA 03JAN93 HEX CODE EXTERN out in cfa patch address HERE out in cfa E8 C SAVE REGS HERE 2 CALL SAVE REGS 9A C HERE 0 0 out in cfa patch CALL 0000 0000 ROT DUP IF V out cfa patch addr params clean up the stack in C fashion 83 C C4 C 2 C ADD SP 2 params THEN V out cfa patch addr E8 C RESTORE REGS HERE 2 CALL RESTORE REGS ROT DUP V cfa patch 0 cfa patch n n IF 50 C 1 X PUSH AX 14 Forth Dimensions IF 52 C THEN PUSH DX THEN NEXT gt Screen 13 EXTERN 15FEB93 RA 03JAN93 V HEADER CREATE 2 ALLOT if you need it CREATE EXTERN cfa patch addr HEADER lays down Forth name and link for this word SWAP EXT LINK cfa patch next extern BL WORD X HERE SMOVE HERE include if WORD doesn t work at HERE C 1 ALLOT linker name
2. Screen 19 X SAVE OBJ RECORD TYPES EXTDEF RA 02JAM93 HEX WR EXTDEF 8C REC SIGNATURE gt 1ST XLINK point to the first extern BEGIN CUR XLINK DUP does the extern exist WHILE XLINK gt XNAME BUFS write the linker name Q BUFC type none gt NXT XLINK get to the next extern REPEAT WR REC An EXT DEF contains list of names imported from other modules 16 Forth Dimensions found by stepping through the EXTERN linked list Screen 20 X SAVE OBJ RECORD TYPES PUBDEF RA 29DEC92 HEX WR PUBDEF 90 REC SIGNATURE 0 BUFC X group index 1 BUFC seg index BUF forth 100 BUF offset 0 BUFC type none WR REC gt PUBDEF contains a list of names in this module to be exported to other modules Screen 21 X SAVE OBJ RECORD TYPES LEDATA RA 29DEC92 HEX VARIABLE MEMP MEMP MEMP VARIABLE SEG INX WR LEDATA length OBUF AO BUFC signature byte DUP 4 BUF length SEG INX BUFC MEMP BUF WR REC write header only MEMP V len addr OVER 1 V len addr len chk REC FBUF V len addr lentchk fbuf WRITE V len MEMP gt Screen 22 X SAVE OBJ RECORD TYPES LEDATA RA 03JAN93 HEX WR PATCH TARGET A0 REC SIGNATURE SEG INX BUFC segment by index MEMPG BUF X offset in segment 0 BUF 0 BUF dummy target WR REC 4 MEMP T P gt WR LEDATA writes a 1K or smaller chunk of code without any fixups in it WR PATCH TARGET is for those 4 byte se
3. Forth Dimensions 15 other languages are left there forthe callerto clean up Func tions that return values return them in registers in Borland and Microsoft C 16 bit values are returned in AX and 32 bit values in DX AX Since Forth tends to live in single or mul tiple 64K segments the exter nal C or other functions we use will have to be referenced by long calls segment offset and should therefore be com piled in the medium large or huge models or at least be declared as far or huge The huge model though of course slowest is the most straightforward since huge functions save and set the DS register when they re entered and restore it when they leave keeping Forth from having to know where C keeps its data and preventing unexpected access to Forth s own The only data we have to share is passed directly or by refer ence on the stack which had better be big enough So in Forth we need a way to make long calls to places we don t know about in such a way that the Microsoft or Borland linker can fix them up forus Ihave written a defining word EXTERN which lays down code for long calls and links all the words it creates into a forward linked list of external references so they can be found easily when we write out the OBJ file EXTERN takes two param eters on the stack and is fol lowedby two names the Forth word that will invoke the long call and the external reference that the link
4. Although the parser will probably do what you want it to do with a shift reduce define STRING 1 define ERRSTRNG 1 amp NT NnNNJ ANE And 4 n return STRING NU D N0NN JE AN NAn n n return ERRSTRNG RE for a string RE for error Forth Dimensions 35 November 1993 December conflict and you do have rather crude control over which rule is reduced in a reduce reduce conflict it is generally a bad idea to rely on ambiguous grammars Almost any grammar can be rewritten to remove these conflicts Sometimes an operator may have more than one prece dence depending on the context For example in algebraic notation the unary minus operator should be evaluated sooner than the binary minus Indeed it should be evaluated before any binary operator Thus the correct order of evaluation of a amp b where amp is some binary operator should be a amp b and not a amp b which it would be if amp had a higher precedence than yaccallows you to get around this by tagging a production with the precedence it should use with the keyword prec Thus if we define the pseudo terminal UMINUS pseudo because it never appears in a production except as used in the example to have a higher precedence than any binary operator the following frag ment expr expr prec UMINUS will tell yacc that this production should use the precedence of U
5. Maris Ambats forwarded this excerpt from EDN s BBS I have been an editor at EDNfor ten years We have done extensive research on the best ways to reach engineers The Forth community persists in trying to popularize Forth by using the absolutely least effective means Forth proponents have consistently tried to prove that Forth is an effective compact speedy program development system with case histories and proof by repeated assertion In a survey asking engineers to rank 24 kinds of things that could be said about a product the engineers ranked case histories dead last Proof by repeated assertion a style of argumentation en demic to the software world unfortunately needs no comment What do engineers want For a new software system engineers want self taught tutorials that they can use to bring themselves up to speed real world examples that apply to their jobs and libraries of functions routines and schemas that they can plug into their problems I should mention that I have programmed professionally in polyFORTH and that I am quite aware that Forth is indeed an effective compact and speedy software development system Further good Forth programming is simply good programming I find myself using Forth style even when I program in other languages I am saddened and frustrated that Forth usage is in decline among EDN readers EDNis an information provider not creator If the Forth community does not create the kind of
6. Notice that the characters and were preceded by a character This is because the parentheses characters are used for grouping regular expressions To match a ora character they must be either quoted or escaped The character is used as an escape character throughout the UN X operating system It should be interpreted as ignore the special meaning of the following character for metacharacters or add a special meaning to the following character for ordinary characters To enable the rules with specific start states the macro BEGIN is used followed by the name of the start state BEGIN is a C preprocessor macro In essence it expands to start state To disable rules with Start states use the phrase BEGIN 0 Finally the function yymore is used to tell ex not to discard the buffer it saves matched input in but to append whatever is matched later to the buffer This is necessary because by default ex will discard the buffer it is using at the end of an action At this point I should probably point out a few things Since ex was designed to be used with the UN X operating System and the only truly well supported language on UN X Figure Two a is C lex will produce a C language file and the actions for the associated patterns must be in C The definition section is separated from the ex language section by a line that contains two characters and only two characters Literal C code can
7. write the new image right back there There are three steps to this finding the EXE file on disk finding the location of the Forth image in the EXE file and writing the Forth image from memory back into the EXE file without destroying the fix up records To find on disk the EXE file ofthe program that is actually running we need to find what the DOS books call its fully qualified filename The string representing this filename which includes the canonical path drive and path from the root directory with any re directions imposed by APPEND resolved can be found at the end of the running program s environment block We can find the program segment prefix PSP of the running program through a DOS call int 21h function 51h or 62h At offset 2Ch of the PSP is the segment address of the environment The environment consists of a series of null terminated strings terminated depending on how you look at iD by a zero length string or an extra null Right after the environment is another set of strings First there is a count of these strings which may always be one followed by a null then by the string representing the fully qualified filename we re looking for No matter what we ve renamed it no matter where it is on our path or how we ve called it this string can be used to locate the file and open it FIND PROGNAME finds this string moves it with its null termina tor to HERE and leaves its address and count on the
8. 2 80 x y 36 6 9 13 x y 36 12 36 25 y 36 12 25 Procedamus in pace Wi Baden Costa Mesa California Another Vote for natOOF Dear Marlin I really enjoyed the article from Markus Dahm about natOOF FD XV 2 I second the comments that were made by Mark Martino CLetters ED XV 3 Mark is a good guy and his enthusiasm is contagious I hope that Markus Dahm makes his natOOF and other developments available As Mark said I am ready to pay money for natOOF now When can I get it Thanks to everyone who supports the Forth Interest Group You folks have been a real contribution to my life Gus Calabrese President Denver Colorado Total control with MI FORTH For Programming Professionals an expanding family of compatible high performance compilers for microcomputers For Development Interactive Forth 83 Interpreter Compilers for MS DOS 80386 32 bit protected mode and Microsoft Windows Editor and assembler included Uses standard operating system files 500 page manual written in plain English Support for graphics floating point native code generation For Applications Forth 83 Metacompiler Unique table driven multi pass Forth compiler Compiles compact ROMable or disk based applications Excellent error handling Produces headerless code compiles from intermediate states and performs conditional compilation Cross compiles to 8080 Z 80 64180 680X0 fam
9. 399 hardware floating point data structures for all data types from simple thru complex 4D var arrays operations complete thru complex hyperbolics turnkey seal interactive dynamic linker for foreign subroutine libraries round robin amp interrupt driven multitaskers dynamic string manager file blocks sector mapped blocks x86 amp 7 assemblers PRODUCTION LEVEL 499 Metacompiler DOS ROM direct indirect threaded systems start at 200 bytes Forth cores from 2 kbytes C data structures amp struct compiler MetaGraphics TurboWindow C library 200 graphic window functions PostScript style line attributes amp fonts viewports ONLINE GLOSSARY 45 PROFESSIONAL and PRODUCTION LEVEL EXTENSIONS FOOPS with multiple inheritance 79 TOOLS amp TOYS DISK 79 286FORTH or 386FORTH 299 16 Megabyte physical address space or gigabyte virtual for programs and data DOS amp BIOS fully and freely available 32 bit address operand range with 386 ROMULUS HS FORTH from ROM 99 Shipping system US 9 Canada 21 foreign 49 We accept MC VISA amp AmEx November 1993 December mand When first wrote these routines I used both IMAGE BOT SEG and IMAGE TOP SEG but could never get the halves to align Anchoring the image relative to IMAGE BOT SEG in both GET IMAGE and PUT IMAGE works around this confusion Much still is left to learn HS Forth already has graphics commands that perhaps may int
10. DUP 5 U R 2 SPACES 16 0 DO 2DUP C L 3 U R 1 LOOP 16 2 SPACES 16 0 DO 2DUP CGL DUP BL OVER ASCII OR IF DROP ASCII EMIT ELSE EMIT THEN 1 LOOP KEY LEAVE 16 LOOP 2DROP R gt BASE gt RA 16JAN93 12 Forth Dimensions Screen 5 BOOTZ to avoid default drive problem BOOTZ FBUFS INIT FYLO FYL SET BREAK SET DRIVES BOOT gt RA 23JUL93 Screen 6 USEFUL THINGS DECIMAL SET BOOT sets boot up variables BOOTZ IS BOOT default drive ON SET BOOT 02JAN93 RA 29DEC92 LATEST 8 ORIGIN top nfa boot HERE 22 ORIGIN fence up HERE 24 ORIGIN dp literals VOC LINK 26 ORIGIN voc list HEX GET MSGS CS 1000 0 CS FIRST 200 CMOVEL addrl addr 2 SWAP SWAP NIP SWAP DROP if you need it UMIN ul u2 umin 2DUP U lt IF DROP ELSE NIP THEN gt Screen 7 V ZSTRING RA 05FEB93 SMOVE Sadr dest moves string including count OVER C 1 CMOVE Z ASCII WORD HERE MOVE 1 HERE C HERE CR ALLOT 0 C Z COMPILE Z COMPILE DROP IMMEDIATE COMPILE ONLY Z compiles an in line string and appends a byte of 0 At run time it leaves the address of the first byte of the string on the stack suitable for passing as a character string pointer to a C function It is thus comparable to which in this Forth leaves address and count and of course doesn t append a 0 byte Screen 8 FINDING THE PSP AND ENVIRONMENT SEG 15FEB
11. Knuth s which uses circularly linked lists The technique shown here is com posed of singly linked lists but the spirit is close to that described in Algorithms The fundamental component of the sparse matrix storage structure is shown in Figure One This sparse matrix element as I will refer to it for the remainder of this article is itself a data structure consisting of e Rowand column coordinates which specify the elements position within the array Rightand down pointers which are the means by which elements are chained to one another The payload which is the actual data You can see how this data structure can be used to build a sparse matrix if you examine Figure Two which shows a portion of a sparse matrix As mentioned above the sparse matrix elements are placed into two singly linked lists one connecting all elements in the same column the other connecting all elements in the same row The heads of these linked lists are two one dimensional arrays of integers I ll call anchor arrays so named because they anchor the lists of rows and columns Hence the zero th element of the row anchor array points to the first Figure Two Inside a sparse matrix Members of the row anchors array are the heads of the lists linking elements inthe same row Similarly column anchors point to lists of elements in the same column COLUMN ANCHORS Figure One Sparse
12. are accessed by CMOVEL when needed Conse quently before the Forth image is saved whether by SAVE FORTH SAVE OBJ or SAVE EXE these messages have to be moved back into the FIRST block buffer or they will be lost With SAVE EXE they will be lost only indirectly since they remain in the file but will be over written by whatever happens to be in the FIRST block buffer when the system boots This is the function of GET MSGS A consequence of this location for the messages is that in order to have them I had to define a segment to keep them in In WR OBJ RECORDS the second invocation of WR SEGDEF defines a 0 5K segment for the messages with and this is important the same class and segment names as the main Forth segment The size is different and the B bit of the ACBP byte is turned off but since these two segments have the same pair of names and since their ACPB bytes indicate that they cannot be combined the linker will see that they are concatenated in the order in which they are declared This is just what I needed and it suggests that ifyou wanted for example a four segment Forth with separate 64K segments for code lists data and headers you could define their segments in this kind of way Note that no LEDATA records or LIDATA records a type not discussed here are written for this segment it just reserves space for Forth to put its system messages Conclusion I hope this relatively simple recipe for accessing
13. based source code in the books and the file based source code in F PC 3 If you are interested in using F PC and getting the most out of your PC for a specific project you need to know more about the structures and the special features of F PC such as the DOS interface file access mechanism color control on the display hardware input and output interrupts etc For this you need a complete F PC system for exploration My following manuals can be of great help F PC User s Manual Offete Enterprises 1989 20 F PC Technical Reference Manual Offete Enterprises 1989 30 F PC System Disk Set Offete Enterprises 25 F PC User Contributions Disk Set Offete Enterprises 25 November 1993 December 26 The F PC materials are also available from Forth Interest Group P O Box 2154 Oakland CA 95621 510 89 FORTH The address of Offete Enterprises is 1306 South B Street San Mateo CA 94402 415 574 8250 4 For commercial and professional applications you may want to consider buying a commercial Forth system which is supported by a real software company You will get documentation and you can get help when in trouble A few of the commercial Forth vendors are Forth Inc 111 N Sepulveda Blvd Manhattan Beach California 90266 213 372 8493 Laboratory Microsystems Inc P O Box 10430 Marina del Rey California 90295 213 306 7412 Miller Microcomputer Services 61 Lake Shore Road Natick Massachusetts 01760
14. example we can define a call to printf as 0 0 EXTERN PRINTF printf printf doesn t return any thing which accounts for the first zero above and it takes an indeterminate number of pa rameters which accounts for the second zero which causes all input parameters to be left on the stack for us to clean up afterwards This is the best we can do The parameters to printf are a pointer to a formatting string and zero or more arguments The format ting string is a standard C null terminated string with embed ded escape sequences such as Mn which indicates a new November 1993 December line and format specifiers such as d which says to print the top stack word as a decimal integer When printf executes it prints the string acting on the escape sequences and replacing the format specifiers with values from the argument list If you re thinking of linking Forth and C you already know this and know that the fragment int x x 1234 printf NnHere s an integer value WMnx d x will print Here s an integer value x 1234 We can go partway with this in Forth The following sequence PRINT INT Z nHere s an integer value nx d PRINTF 1234 PRINT INT will yield nHere s an integer value nx 1234 Cis either to exit through the bottom of the main function or to call exit explicitly with a parameter that tells DOS what the exit condition was zero means good anyth
15. external functions and libraries from Forth will prove helpful to those who feel isolated in our high performance ghetto or who feel they have to work in some less attractive language just to get work done Its value for some may be as a method for gluing together other things in a way that provides familiar control and semi interactive development and testing But it would be foolish for me to guess the uses of this tool if it is a good one it will find homes My interest has so far mainly been in learning how to do it rather than finding something to do with it I feel confident that the techniques I ve used writing main in C using exit for BYE using huge functions to isolate data segment references have pro Forth Dimensions 25 duced a sound method of linking C and Forth in a way that is less annoying than might have been expected Extensions to this method might include 1 creating a segmented linkable Forth with for example data in a segment addressed by DS code referenced from CS lists from ES and a stack segment big enough to handle the hungriest set of C functions 2 object linking to other more interesting languages such as Prolog and Lisp 3 linking to extended or new exe format files such as those used by Windows and OS 2 Have fun Bibliography f Ray Duncan ed The MS DOS Encyclopedia Microsoft Press 1988 Ray Duncan Advanced MS DOS Programming Microsoft Press 1986 Mark
16. fix up fields We don t need a thread field The four bytes between the signature and the checksum in our FIXUPP record make a single fix up field It s identified as such by having the high bit set in the first byte The other bits in that byte and the next indicate that the fix up field is segment relative and refers to a segment offset at offset zero of the LEDATA record it Forth Dimensions follows The other two bytes are called the fixdat field The bits in the first indicate that the frame is determined by the target and that the target is specified by an external index Trust me this is what we want What this comes to so far is the three bytes CC 00 56 The last byte before the fake checksum is an index into the list of external references in the previous EXTDEF record indicating which external function is to be resolved to this patch address The MODEND record is the simplest of all since the Forth object module isn t going to be the main program module itwon t contain the entry point for the EXE file it only marks an end and is just one byte of zero between the length and the checksum Most of these object records get constructed in memory before being written to disk SAVE OBJ sets up this buffer andcreates and opens a DOS file to put the records in Almost everything in this word is implementation dependent and already explained SET BOOT and GET MSGS are imple mentation peculiarites that will be discussed lat
17. for the newline character 6 When a metacharacter must be used literally in a regular expression for example you want a regular expression to match 8 3 it can be escaped with the V metacharacter 7 Toinclude non graphic characters in the alphabetin a regular expression these escape sequences are used X matches the tab character n matches the newline character The space character may be included in a character class literally or it may be escaped with the metacharacter Thus Jisacharacter class that willonly match the space character November 1993 December 34 Forth Dimensions Another advantage to using start states is the ability to recognize an erroneous construct without needing an explicit regular expression for it If the above example had been written using only regular expressions it would look like that in Figure Two b Which would you rather debug Start states are also useful if a regular expression can be used in more than one way For example the C convention of enclosing comments in pairs can cause confusion with arbitrary pathnames used in C preprocessor statements such as this include lt sys h gt Although this does have the potential for causing prob lems they can be avoided either by using start states or by realizing that the scanner will have to return a token coresponding to the string lt sys h gt rather than a com ment starting with h However if the
18. in the regular set of the second expres sion For example this ab would match astring composed ofthe character a followed by the character b A regular expression may be extended under the operation of Kleene closure This means zero or more concatenations of the original regular expression Kleene closure will be symbolized by appending the metacharacter to the original regular expression The regular set of the new regular expression will consist of all strings that can be decomposed into one or more substrings each a member of the original regular set and the null string For example this a would match a string composed of zero or more instances of the character a The null string may be added to any regular set This is symbolized by appending the metacharacter to the corresponding regular expression For example a would match a string of zero or one a characters Aregular expression may be delimited by matching paren theses These are used for grouping If the regular sets corresponding to two regular expressions are identical the regular expressions are said to be equiva lent For example these expressions are equivalent a b I ab ab i a b and they both match strings composed of either zero or more a characters followed by a single b character or a single a character followed by zero or more b characters From these basic definitions several properties shoul
19. last row in memory The arcane method of calculating the paragraph s segment of the first row of the image is shown next in the code Fetching the IMAGE BOT SEG paragraph starts the process Indexing to the very first image row requires moving the pointer down 879 rows One VAR receives the segment value another receives the offset Mapping x and y coordinates to the image byte containing the pixel uses the command XY gt ADR Notice the use of high level words to write a machine language command using the HS Forth OPT command XY gt ADR converts y into a paragraph segment by multiplying y by minus five and November 1993 December adding the result to the location of row zero which is last in memory Dividing x by eight converts the pixel number into the byte number in the row Adding that to the offset indexes into the image row For several reasons the beginning offset of each of the image rows is zero so some of these steps are superfluous for the images we are accessing The remainder of x divided by eight points to the pixel as shown below x8MOD Q 1 2 8 4 5 6 7 bit position 7654321 0 The above is performed inside the PIXEL command by 8 MOD obtaining the bit position and the data structure CLEAR BIT CLEAR BIT provides a mask for ANDing the bit clear i e to zero thus forcing the pixel lit In our case Paintbrush thinks a zero pixel is lit black while a pixel equal to one is white PIXEL
20. list and leaves that element s identifier on the stack This identifier is a unique handle to the element and is the means by which the pro gram references an element whether it is in the array or on the available list You load the returned element s payload with the appropriate value and execute INTO_SMATRIX This word wires the element into the sparse matrix at the row and column coordinates speci fied on the stack Afan element is already in the matrix at the given coordinates the system exits with an error condition The word amp SMATRIX_VAL provides access to the pay load It expects an element identifier on the stack and returns the address of that elements payload component As you perform mathemat ics on the matrix members pivoting operations for exam ple some elements payloads will be reduced to zero You ll have to decide what a zero is for your particular applica tion It might mean anything from an honest to goodness zero to a very small num ber In that case your code should call OUTOF_SARRAY This word accepts on the stack a sparse matrix element iden tifier the element is presumed Text and code ontinue on page 38 November 1993 December 0 SMATRIX AVAIL BASE X Anchor first element SMATRIX ELEMS 1 0 DO I 1 Each entry points to next higher I amp SMATRIX RIGHT W Store address in right pointer LOOP NIL Acts as terminator SMATRIX ELEMS 1
21. lt character were left out a rare but possible error the scanner will probably scan the string sys return it andthenscan in h followed by the rest of the file until either the end of the file or until it finds a closing which will have the effect of comment ing out whatever is in the intervening code Although this provides quite a bit of motivation for start states this error syndrome is not quite as bad as it looks I ll take this up later in the discussion of yacc Since any legal C statement can appear in the action part ofa pattern action pair a common usage of lexis to generate lexical analyzers for compilers from a set of regular expres sions describing the lexical elements of the language being compiled The typical usage is 1 The lex generated scanner which is usually called by the parser recognizes a lexical element of the language The actions section for the particular regular expression does whatever miscellaneous setup and conversion is necessary The last action in the action section returns a small integer or token to the caller Typically a ex generated lexical analyzer is used as the front end for a yacc generated parser yacc is a utility that turns a grammar specification into a C function that will accept a statement that is grammatically correct The specification for the grammar is written in a modification of Backus Naur Form usually called modified BNF see the sidebar
22. material that engineers are looking for then we cannot obviously pass it along Charles H Small Senior Technical Editor EDN Pipe Dreams I very much enjoyed the FSAT Project article FD XV 2 I m not sure how compatible BLOCKs are with POSIX but the idea of melding ideas from Forth UN X and POSIX and possibly the GNU Project seems attractive Despite the fact that UNIX systems tend to involve evil things like preemptive multi tasking dynamic memory man agement and stream files note that my tongue is firmly in my cheek there are some qualities similar to those of Forth Diverse sets of tools Systems for getting the tools to communicate with one another in order to create applications In Forth one uses words compiled into a dictionary arranged in vocabular ies such as FORTH ASSEMBLER EDITOR that tend to communicate through two stacks In UNIX one uses November 1993 December programs la bc grep awk tr myprog a out arranged in directories such as bin usr bin ucb bin usr local bin Wcbbrowne bin that tend to communicate via pipes I don t know of a precise parallel to CREATE DOES other than the UNIX concept of little languages but then I also am not sure about what to do with RCS or make which are things that I tend to want to use with Forth and often can t Opinionated hackers Religious wars I think that in order for Forth to survive it needs t
23. matrix element structure RIGHT ROW ANCHORS DOWN dq Lo CuuLm L M S orsa 22d to next member in row PAYLOAD to next member in column Forth Dimensions 7 November 1993 December element of the zero th row in the sparse matrix the zero th element of the column anchor array points to the first ele ment of the zero th column in the sparse matrix and so on The right pointer of each sparse array element leads to the next element in the same row Similarly the down pointer of each sparse array element points to the next element in the same column A special constant 65535 defined as NIL acts as an end of list indicator Space Considerations In terms of physical space a sparse matrix element as I have defined it requires 16 bytes Each row and column entry is one byte allowing matrices with logical dimen sions up to 256 rows by 256 columns You caneasily extend this limit by changing the row and column entries to 16 bit words and modifying specific constants in the source code The right and down pointers are 16 bits each allowing fora total of 64K elements The payload in my implementation is a ten byte extended floating point as defined in Apple s SANE docu mentation Consequently each sparse array element requires six bytes beyond an element in a standard array implementation When should you use a sparse matrix storage method like the one shown here Let a equal the number of rows in a m
24. module represented as segment offset pairs relative to the beginning of the load module This is exactly enough information to find the locations n the file that need to have their con tents adjusted In fact this is all very simple the hard work is done by the linker and before that by the language com piler translatorthat creates the OBJ files 3 External References Functions written in C are accessed by calls The basic format of these calls is de scribed in the mixed language programming sections of C and assembler manuals and books where you can also find details of calling conven tions for Pascal Fortran BA SIC etc Parameters are passed on the stack and unlike most November 1993 December VARIABLE LAST XLINK pointer to last extern in linked list VARIABLE 1ST XLINK pointer to first extern 0 DUP 1ST XLINK LAST XLINK mark list empty EXT LINK install the link LAST XLINK DUP is there already at least 1 extern IF HERE SWAP store fwd link in previous extern ELSE HERE 1ST XLINK or in linked list base pointer THEN HERE LAST XLINK store current link in head pointer Que V terminate list gt Screen 10 EXTERN LINKED LIST TRAVERSAL RA 03JAN93 XLINK gt FIXADR ext link patch adr 2 XLINK gt XNAME ext name xname adr 2 VARIABLE CUR XLINK VARIABLE XREF gt 1ST XLINK 1ST XLINK CUR XLINK 1 XREF gt NXT XLINK CUR XLINK 8 CUR XLINK Q 1 XREF
25. regular ex pression that matches an identifier in most programming languages The definitions section is also used to declare start states These are used to specify what is known as left context Although some left context basically what s hap pened to the left of the current position in the input can be specified by the metacharacter which matches the beginning of a line in general a regular expression can t remember what happened before it got to the point where it is at now This has important consequences For instance there is no regular expression that can match the set of all strings of balanced parentheses This is nota regular set lex lets you get around this by specifying a start state For example the ex file in Figure One will recognize balanced parentheses Forth Dimensions Figure One Start AA Start BB int pnest 0 define MATCHED 1 define ERROR 0 8 9 9 5 lt BB gt pnest if pnest BEGIN 0 else yymore lt AA gt pnest if pnest BEGIN 0 else yymore BEGIN BB lt BB gt fprintf stderr improper nesting n return ERROR lt AA gt pnesttt yymore BEGIN AA pnest yymore fprintf stderr c not a parenthesis n yytext return ERROR return MATCHED return MATCHED The rules that are active in a start state are preceded by the start state name surrounded by the characters lt and gt
26. stack The next thing we want to do is open this file for reading and writing We can do this because although we are running the program contained in the file the file is not now open In a multi user or multi tasking system someone could come along and delete rename or remove the file before we get to it The word OPEN PROGFILE does all this November 1993 December 24 The phrase OFBUF Z gt BUF OFBUF FREOPEN OFBUF FYL which is highly implementation dependent moves the filename to the FBUF OFBUF opens the file and makes it current so that BLOCK will refer to blocks in this file Your technique may vary The important thing is to open the EXE file so we can read its header There s lots of possibly interesting information in the header but really all we need to know is how big it is so we can find the rest of the file The number of 16 byte paragraphs inthe header is stored in the word at byte offset 8 in the header We also know the address in memory of the PSP for our program and the segment address from CS of the Forth segment Since the PSP is 256 decimal bytes long and resides just before the image of the EXE program in memory and since we know and trust that the code portion of the EXE file is the same as the memory image less the fix ups to specific addresses in it finding the Forth portion of the EXE file is just arithmetic FORTH OFFSET performs this arithmetic and stores the result in the variable FORTH
27. the source as well Why wait for second hand versions when the original inspiration is more complete and available sooner Of course what you really want to hear about is our SUMMER SALE Thru August 31 only you can dive into Professional Level for 249 or Production Level for only 299 Also for each utility purchased you may select one of equal or lesser cost free Naturally these versions include some recent improvements Now you can run lots of copies of HS FORTH from Microsoft Windows in text and or graphics windows with various icons and pif files available for each Talk about THE tool for hacking Windows But face it what I really like is cranking up the font size so I can still see the characters no matter how late it is Now that s useful Of course you can run bigger faster programs under DOS just as before Actually there is no limit to program size in either case since large programs simply grow into additional segments or even out onto disk Good news we ve redone our DOCUMENTATION The big new fonts look really nice and the reorganization along with some much improved explanations makes all that functionality so much easier to find Thanks to excellent documentation all this awesome power is now relatively easy to learn and to use And the Tools amp Toys disk includes a complete mouse interface and very flexible menu support in both text and graphics modes Update to Revision 5 0 including new documen
28. went to sleep during this and the last article please bear with me My next two articles will be about extending Forth to support porting C programs In the articles that follow that I ll be discussing a compiler that turns C programs into Forth The introductory article describing the FSAT Project which aims to provide the advantages of both Forth and UN X appears in FD XV 2 the first part of the discussion of UN X tools appears in FD XV 3 The author s e mail address is jim8netcom com He d appreciate your comments about the project and will reply to all messages sent to that address provided they pertain to technical aspects of the project and not motivational aspects and a type value If neither YYSTYPE is defined nor the keyword union is used the Stoken FILENAME type will default to int 1 Of course we d be in a pretty sorry state if our compil 8 ers couldn t handle syntax er rors yacc does have a way to easily integrate error handling however It uses the psuedo terminalerror error stands Qo oo token INCLUDE include token include lex h lex function definitions file include file INCLUDE FILENAME do include 2 INCLUDE error eprint badly formed preprocessor filename gt S Forth Dimensions 37 November 1993 December Sparse matrices continued from page 10 to be currently active in the sparse matrix OUTOF_SARRAY unwires the element from t
29. you to do this kind of pattern matching In fact almost all of the stream based text processors will do this If you wanted to print out all the lines of a file that started with a letter followed by any combination of letters or digits this is one of many commands that would work grep a zA Z a zA 20 9 filex The group of symbols in the quotes is a regular expression see the sidebar Regular Expressions The RE regular expression in the example says At the beginning of a line match a string composed of an instance of a character in the set lower case a to lower case z inclusive or upper case a to upper case z inclusive followed by any number of instances of characters in the set above plus the digits to the end of the line Thus if filex contained This is a line in the file filex which contains a lot of different types of lines 99xx9 xx99sdf the command in the example would print filex a xx99sdf Regular expressions are very important in the area of automated text processing They are useful whenever you wish to find a list of possible strings that match a specific pattern Because it is easy to construct a routine that matches RE s most UN X text utilities will allow you to specify RE s November 1993 December 32 to be matched and manipulated Additionally UN X has a utility to create programs that recognize and manipulate strings that match regular expressions Thi
30. 617 653 6136 For easy access to many of the materials listed here refer to the mail order form included as the centerfold in this issue of Forth Dimensions Other vendors of Forth products may be located via their advertisements in our pages Ed J Dr C H Ting is a noted Forth authority who has made many significant contribu lions to Forth and the Forth Interest Group Forth Dimensions HS ForTH Drawing BMP Files Hank Wilkinson Greensboro North Carolina Microsoft provides with Windows the useful drawing program Paintbrush Paintbrush drawings may be directly printed inserted or otherwise linked to other documents Forth pixel drawing performed in memory and stored in a file may be handled as if it were a Windows Paintbrush file Simplifying assumptions make this process easy enough to conceive do and perhaps explain One use of computer generated drawing is graphing math ematical results Dr J V Noble s Scientific Forth A Modem Language For Scientific Computing Mechum Banks Publish ing 1992 provides a college graduate level text in numerical methods using Forth Though not upto the quality of Dr Noble s text rudimentary methods discussed below expose a founda tion for graphing into Windows Paintbrush files Programming is the process of discovering and commu nicating details necessary for desired functionality Forth routines used to discover the details presented here are not shown My general go
31. 93 RA 16JAN93 HEX CODE PSP psp seg B8 C 00 C 51 C mov ax 51h CDs C 21 C int 21h 5336 push bx NEXT END CODE ENV PSP 2C QL CODE DS 1E C NEXT END CODE CODE ES 06 C NEXT END CODE Screen 9 EXTERN LINKED LIST RA 03JAN93 Forth Dimensions 13 stack is embedded in a word before a compiled counted string Its action is to leave the address and count of the string on the stack and to skip over it to the word follow ing the string Its definition is as follows addr count R gt COUNT 2DUP gt R COMPILE ONLY I explain these details so that you will know how to write equivalent words in the Forth you use if you don t already have them and or understand my code well enough to adapt it Nothing is portable except ideas in C Forth or for that matter life 2 EXE Files And Link ACOM file is just a memory image with the restriction that it cannot be more than 65 178 bytes in length An EXE file by contrast consists of two parts a header and a load module The load module is approxi mately a memory image of the executable program repre sented by the EXE file The reason the memory image is approximate has to do with the way the 80x86 processors address memory in real mode Any reference CALL JUMP etc toa memory address more than 64K away has to include an actual segment reference These segment references can not be known at compi
32. BYCOL Find by column ELSE S BYROW Find by row ENDIF B November 1993 December 40 Forth Dimensions Letters continued from page 6 term 1 term term term term term 9 term 11 term 13 term 15 term 17 term 19 term 21 term 23 term 25 13 oU t H UNSNAP sqrt 0 DO 2x THEN 2 LOOP NIP x y 180 x y 180 x y 180 x y 180 x y 180 x y 180 x y 180 Forth Dimensions Typing 180 sqrt 0 ooo C00 variable BUG FALSE bug variable TRACE TRUE trace t chr parse bug if please S CR else 2drop then immediate snap trace bug immediate unsnap FALSE bug immediate The comparison of what you say is on the stack with what is actually there usually identifies the problem very quickly You can also trace just to see what s going on If you type snap and recompile SQROOT typing 180 Sqroot gives you To avoid too much output in SQRT I bracket the stack comments I want printed with snap and unsnap radicand root radicand root OVER I RSHIFT OVER 2 1 0 ADDRESS UNIT BITS CELLS 2 x y s x y snap X y unsnap root ooooo cno gives PRPRPPRRPR NEGATE UNDER 1 lt NOT IF DUP x 2 1 I LSHIFT x y y nsn x y 41 x 13 x y 180 001 x y 180 001 x y 180001 x y 180 00 1 x y 180001 x y 18002 1 y 180 0 64 x y 116 27 5 y 116
33. CHOR ARRAY Initialize the sparse matrix memory SMATRIX_ELEMS 16 _NEWPTR DUP 0 ABORT Sparse array alloc error SMATRIX_BASE BUILD SMATRIX AVAIL KKK KKK KKK KKK ok KKK KKK KK KKK KK KKK KKK KKK KKK KK Ck kk ek e ke ke I kv e kx x x Dispose of all the memory space taken up by the sparse matrix 10 Forth Dimensions FonrH 83 Forth and the Rest of the DOS World Richard Astle La Jolla California Most computer languages implemented for MS DOS on the IBM PC have a compile link cycle which interferes with interactivity but allows them one advantage Forth rarely has the ability seamlessly to include functions written in other languages It has been said with some justification that this foreign code is often of poor quality unsuitable and slow and if we really want to do it right we should do it ourselves But blind self reliance can be expensive Sometimes time is too tight or sources unavailable And sometimes we actually can t do it better In these cases at least it would be nice to be able to use other people s libraries and code particulary if we can do so without losing the interactive incremental Soul of Forth There are several ways to go about using the resources of other languages from within Forth One is to put functions procedures or subroutines written in the other language s into a TSR and have Forth communicate with them through an interrupt or a jump table at a known location in memor
34. EXTERN out in ax dx ax OVER 0 2 WITHIN 0 IF INVALID OUT PARAMS ABORT THEN CODE EXTERN cfa patch addr CREATE EXTERN gt USAGE out in EXTERN DOG _ dog creates Forth word DOG to execute external dog with in params on stack before and out after Screen 14 X SHOW FIXUPS UTILITY WORD 4H R BASE SWAP HEX 4 R BASE SHOWLFIXUP xlink RA 17JAN93 DUP 4H R 2 SPACES X XLINK XLINK gt FIXADR DUP 4H R 2 SPACES V FIXADR 2 SWAP 4H R 4H R SPACE FIXUP DUP 2 COUNT TYPE SHOW FIXUPS CR FIXUPS CR XLINK FXADR SEG OFF label CR 1ST XLINK BEGIN Q8 DUP WHILE DUP SHOWIFIXUP CR REPEAT gt Screen 15 X SAVE OBJ OBJ RECORD WRITING 03JAN93 RA 29DEC92 HEX FFFF CONSTANT TOP ADDR we save up to this addr 64K VARIABLE RECBUF X holds address of record buffer VARIABLE RECBUFP pointer into record fbuffer OBUF RECBUF RECBUFP Q sets pointer to beginning of buf REC HERE RECBUFP a minor convenience BUFS Sadr move and comma in a string REC HERE MOVE REC HERE C8 1 RECBUFP BUF X based on R gt DUP COUNT gt R BUF COMPILE ONLY BUF COMPILE BUF p IMMEDIATE COMPILE ONLY BUFC c REC HERE C 1 RECBUFP BUF n REC HERE 2 RECBUFP DMP REC RECBUF 8 REC HERE OVER DUMP Screen 16 X SAVE EXE WR REC RA 29DEC92 VARIABLE REC FBUF other Forth DOS interfaces use a handle
35. Get address of last guy amp SMATRIX RIGHT W Attach terminator KKK KKK KKK KKK KKK KKK KKK KEK KKK KKK KKK KK KKK KKK KK KKK KK Following are a couple of low level definitions that provide access to some Macintosh traps These traps allow us to allocate and release non relocatable chunks of memory a aa a a _NEWPTR allocates n bytes and returns pointer to the memory location Returns NIL on failure CODE NEWPTR n ptr 0 POPDO MAC NEWPTR W PUSHAO NEXT DISPOSPTR releases the allocated memory CODE _DISPOSPTR ptr POPAO MAC DISPOSPTR W NEXT KKK KKK KKK KKK KKK KKK KKK KKK KKK KKK KKK KKK KKK KKK KKK KK KKK kckokoko kokok Initialize an anchoring array the row or column anchors arrays addr is the address if the base variable andn is the number of elements INIT ANCHOR ARRAY addr n DUP 2 V of bytes to allocate _NEWPTR Allocate memory DUP 0 Allocation failed ABORT Anchor array alloc error ROT OVER SWAP Save base address X Now set all elements to OxFFFF SWAP 0 DO NIL OVER I 2 W LOOP DROP Clean stack KK KKK KKK KR KEK KKK KR KKK KKK KKK KKK KKK KKKKKKKKKKK KKK KKK KKK KK KK Initialize a sparse matrix Presumes SMATRIX_ROWS and SMATRIX_COLS have been properly initialized INIT SMATRIX V Initialize the rows array ROWS ARRAY SMATRIX ROWS INIT ANCHOR ARRAY Ceres Initialize the columns array COLS ARRAY SMATRIX_COLS INIT AN
36. IMAGE OFFSET After we ve found this offset we use SEEK to get to the right place in the file and then write the memory image in much the same way we wrote LEDATA records The operations are similar enough that I ve used the same loop vectoring the action words that handle the code and fix up parts of the operation the differences are that the pieces of memory we write go directly into the EXE file instead of into OBJ file records and instead of writing four byte fix up targets we just carefully skip their places in the file The reason we have to be careful about these fix ups is that they no longer contain zeros either in memory or in the EXE file Further their contents in memory and in the file are different In the EXE file these locations contain segment offset addresses relative to the beginning of the executable portion of the file while in memory these addresses are fixed up to actual addresses So now we have two ways to save Forth when we ve added new external references with EXTERN we save it as an OBJ file and use LINK including re linking all the things we ve linked before when we have no new references to link we can just save the image into the current EXE file A simple extension would be a word which would check the fix up list to see whether we have to use SAVE OBJ or can get by with SAVE EXE There are two small problems with SAVE EXE one is the checksum in the EXE header which doesn t get updated by thi
37. K Rk kk Rk ok Prepare to place a sparse matrix element in a vector i is the sparse matrix element We assume that amp SMATRIX NEXT and amp SMATRIX IDX have been set properly Returns flag 0 if i is NOT in the vector flag 1 if i is in the vector flag 2 if someone else is in the vector where i wants to be n predecessor of i in the vector NIL if i is or should be the head member of the vector WHERE IN VECTOR i n flag DUP amp SMATRIX IDX C8 S X Search the vector PREV ELEM W ROT Save previous element DUP NIL Was i found IF 2DROP 0 Nope ELSE Yes izzit me Or someone else IF 1 It s me ELSE 2 X It s someone else ENDIF ENDIF 38 Forth Dimensions ee a Na RRR KKK KKK KE KKK KR KK KKK IKK KKK KK KKK KR KKK KEK KKK KKK KKK KK KK Locate i in row See WHERE IN VECTOR for results on parameter stack WHERE IN ROW i n flag NEXT IS RIGHT Set NEXT function IDX_IS_COL Index to modify is COL WHERE IN VECTOR Find him KKK KKK KK KKK KK AK KK KKK KKK KKK KKK KKK KKK KKK KKK KK KK KKK Locate i in column See WHERE IN VECTOR for results on parameter stack WHERE_IN COL i n flag EN rere eee a8 t8 NEXT IS DOWN IDX IS ROW WHERE IN VECTOR Set NEXT function X Index to modify is ROW Find him Ck ck ck ke e ook Ck Cx KC kk Ck e C Sk e ek kx xk o INSERTING REMOVING MATRIX ELEMENTS C kk ook oo e Ck ck e ke e ke S x A kk ko k
38. LS ARTICLE2 BLNKPAGE BMP GBS C WINDOWS DOCS TOOLS ARTICLE2 RESULTS BMP PBS TESTI T1 880 0 DO 640 0 DO I J PIXEL LOOP LOOP PB PUT IMAGE TEST2 640 0 DO I I PIXEL LOOP TEST3 880 0 DO I 2 I PIXEL LOOP TEST4 880 0 DO I 3 I PIXEL I 2 I PIXEL 0 I PIXEL I 639 lt IF I 879 I PIXEL THEN LOOP DO TEST T1 TEST2 TEST3 TEST4 PBS PUT IMAGE T1 ADVERTISERS INDEX The Computer Journal 25 een haen dol Forth Interest Group 44 Harvard Softworks 29 Laboratory Microsystems 41 Miller Microcomputer Services i i 31 Forth Dimensions MAKE YOUR SMALL COMPUTER THINK BIG it since 1977 for IBM PC XT AT PS2 Mi 85 80 models 1 4 amp 4P THIRTY DAY FREE OFFER Free MMSFORTH GAMES DISK worth 39 95 with purchase of MMSFORTH System CRYPTOQUOTE HELPER OTHELLO BREAK FORTH and othi November 1993 December Part 2 UN X Tools Used on the FSAT Project Jim Schneider San Jose California As you will recall I concluded the last article with a discussion of m4 1 This is a continuation of that article While m4 is very powerful indeed I use it instead of masm 1 s macro processor everything has to be spelled out explicitly For example there s no practicable way to match a string that starts with a letter and is followed by any combination of letters or digits UN X provides many tools that allow
39. Ludwig The Little Black Book of Computer Viruses American Eagle Publications 1991 I am indebted to this book for its discussion of the structure of EXE files particulary the function of the relocation index table Turbo Assembler 3 0 Users Guide Borland International 1991 Richard Astle has been programming in Forth for about eight years most of that time developing and maintaining a rather large database management set of programs In the process he has re written the underlying Forth system more than once for speed and capacity He has a bachelor s degree in mathematics from Stanford University a master s in creative writing from San Francisco State and a Ph D in English literature from the University of California San Diego FORTH and Classic Computer Support For that second view on FORTH appli cations check out The Computer Journal If you run a classic computer pre pc clone and are interested in finding support then look no further than 7CJ We have hardware and soft ware projects plus support for Kaypros S100 CP M 6809 s and embedded controllers Eight bit systems have been our mainstay for TEN years and FORTH is spoken here We provide printed listings and projects that can run on any system We also feature Kaypro items from Micro Cornucopia All this for just 24 a year Get a FREE sample issue by calling 800 424 8825 PO Box 535 Lincoln CA 95648 November 1993 December Fo
40. MINUS instead of The yacc parser generator can do more than just recog nize grammatically correct statements It can also operate on them To do this you can add actions to the productions The actions are C language statements that are enclosed in curly braces If the action is at the end of the production the action is triggered when the rule it corresponds to is reduced If the BNF Backus Naur Form is a compact way of describing the syntactic structure of a language It describes what is known as under examination doesn t depend on what has come previously A grammar may be specified as follows 1 A set of terminal symbols is given These correspond to the lexical elements of the language and can either be called tokens or terminal symbols 2 Asetof nonterminal symbols is given These correspond to the grammatical elements of the language These can be called nonterminals or nonterminal symbols 3 A set of rules is given that map a string of symbols either terminal or non terminal to nonterminals These are called productions There may be more than one production for a nonterminal 4 A special nonterminal symbol called the start symbol is given All productions must eventually map to the start symbol The production is said to produce the or reduce to the corresponding nonterminal A sequence of symbols containing terminals and nonterminals can be transformed into an equiva lent sequence of symbols by rep
41. OP IMAGE BOT SEG 440 5 0 440 80 R WRITEH DROP R gt CLOSEH set up pointer to memory location of first row of image IMAGE BOT SEG segment of last row 879 80 16 80 bytes 16 segments per row VAR FIRST ROW SEG 0 VAR FIRST ROW OFF 5 VAR 5 given X and Y divine a paragraph and offset address CODE XY gt ADR X Y PARAGRAPH OFFSET OPT 5 FIRST ROW SEG SWAP 8 FIRST ROW OFF END CODE V To convert x 8 MOD POWER into bit mask x 8 MOD yields the bit of the byte to bit position of pixel BIT gt POSITION 8 1VAR CLEAR BIT 127 0 IS CLEAR BIT 191 1 IS CLEAR BIT 223 2 IS CLEAR BIT 239 3 IS CLEAR BIT 247 4 IS CLEAR BIT 30 Forth Dimensions 251 5 IS CLEAR BIT 253 6 IS CLEAR BIT 254 7 IS CLEAR BIT given X and Y light the pixel CODE PIXEL x y set pixel at x y OPT OVER gt R XY gt ADR DDUP C L R gt 8 MOD CLEAR BIT AND ROT C L END CODE 8 1VAR SELECT BIT 128 1 IS SELECT BIT 64 2 IS SELECT BIT 32 3 IS SELECT BIT 16 4 IS SELECT BIT 8 5 IS SELECT BIT 4 6 IS SELECT BIT 2 7 IS SELECT BIT l0 TS SELECT BIT given X and Y CODE PIXEL see if pixel is lit xy f TRUE x y pixel lit V FALSE X Y pixel dark OPT OVER gt R XY gt ADR C L R gt 8 MOD SELECT BIT AND 0 END CODE V to put the file names in CREATE GB 128 ALLOT for GETB file CREATE PB 128 ALLOT for PUTB file Tl GB GET IMAGE C WINDOWS DOCS TOO
42. PRINTF RA 05FEB93 0 0 EXTERN PRINTF printf we ll have to clean up stack TEST STRING cse Z HERE S A PRINTSTRING TEST seg addr TEST PRINTSTRING TEST STRING PRINTF TS2 CS Z nHERE S A NEWLINE OR NOT TS3 CS Z HERE S AN INT d OKAY r TEST2 TS2 PRINTF TEST3 12345 TS3 PRINTF gt Xn not handled but d is Screen 33 X EXTERN TEST WORDS CGA GRAPHICS DECIMAL 0 2 EXTERN LINETO lineto 0 1 EXTERN SETCOLOR _setcolor 1 0 EXTERN RAND _rand GTEST2 CGA INIT 1000 0 DO RAND 200 MOD RAND 300 MOD LINETO RAND 4 MOD SETCOLOR LOOP KEY DROP GCLOSE gt Screen 34 MORE OBJ GRAPHICS WORDS DECIMAL 0 0 EXTERN VGAINIT _vgainit GTEST3 VGA INIT 1000 0 DO RAND 480 MOD RAND 640 MOD LINETO RAND 16 MOD SETCOLOR LOOP KEY DROP GCLOSE Forth Dimensions 21 possible between the count and the checksum it contains only a counted string in our case FORTH The linker uses this name in error messages The LNAMES record con tains a list of group and or segment names other records will refer to by number count ing the first as one not zero For us only SEGDEF records refer to this list Imitating other object modules I ve examined I ve included as the first name in the list a blank name of length zero This isn t really necessary using an index of zero seems to have the same effect as using an index of one to point to this zero length string The other two names will be used
43. RDS WR THEADR WR LNAMES 32 0 62 WR SEGDEF 3 2 200 60 WR SEGDEF a little room for Forth msgs 1ST XLINK IF WR EXTDEF THEN WR PUBDEF WR CODE WR MODEND 03JAN93 RA 29DEC92 Screen 26 X SAVE OBJ SAVE FORTH AS OBJ FILE HEX SAVE OBJ PAD 100 RECBUF set buffer address OFBUF REC FBUF REC FBUF FILENAME FORTH OBJ REC FBUF MAKE create file REC FBUF DUP FREOPEN FYL open amp make current EMPTY BUFFERS FLUSH SET BOOT GET MSGS EMPTY BUFFERS FLUSH WR OBJ RECORDS REC FBUF FCLOSE X flush it to be sure CR OBJECT FILE WRITTEN DECIMAL RA 29DEC92 Screen 27 X SAVE EXE NAVIGATING THE ENVIRONMENT RA 16JAN93 OSKIPL seg addr seg addr skip past end of zstring at seg addr BEGIN 2DUP C L WHILE 1 REPEAT 1 OLENGTHL seg addr len get length of zstring at seg addr 2DUP OSKIPL seg addr seg addr NIP SWAP NIP len OOSKIPL seg addr seg addr skip past double zero at end of environment variables BEGIN 2DUP L WHILE 1 REPEAT 2 gt Screen 28 X SAVE EXE FIND PROGNAME FORTH OFFSET 18JAN93 RA 16JAN93 DECIMAL 2VARIABLE FORTH IMAGE OFFSET FIND PROGNAME addr zien ENV 0 OOSKIPL seg name addr OSKIPL get past sring count 2DUP OLENGTHL seg name addr zlen Forth Dimensions 19 about this code body are 1 that it is laid down in memory before rather than after its header which makes finding other things in the header easier and 2 tha
44. T COL BASE Set column base pointer R WHERE IN COL Search for i in column vector 1 i has to be there IFR UNWIRE Disconnect ELSE Error removing from column CR ABORT ENDIF R DROP X Clean return stack C CK Ck ke eO Ck IC CCCII e ke kk ko KKK KK KKK SEARCHING FOR MATRIX ELEMENTS FOR RTI IOI ROI I ck ck k kk ck Kk k k k kk k koe kk a k Ck o C Ce ce C Oe Oe ke e C e ke kk KKK KKK KKK KKK KK Ck ck Cc Ck ko ck kckckckck kk kckck kk Look for a sparse matrix element at row col by row That is the search begins at the base of the row and proceeds across Return i or NIL if nothing exists at that location S BYROW row col i IDX IS COL X Watch column index NEXT IS RIGHT X Scan along a row SWAP SET ROW BASE Set the row column base lt S gt Go git it V oc x Ck ox oec Ck ck CK C 0k eo KR KKK koc 0k KK KKK KKK KKK V Look for a sparse matrix element at row col by col That is the search begins at the top of the column and proceeds down Return i or NIL S BYCOL row col i IDX IS ROW Watch row index NEXT IS DOWN Scan along column SET COL BASE Set the row column base S 1 Go git it KK KKK KKK Ck e KEK KK KKK KK KK KKK KKK KKK KKK KK KKK KKK KK RR KKK Kk xxx Find a sparse matrix element at row col This routine selects a search by row or column depending on which index is smaller SC row col i Search by row or by column 2DUP gt IF S
45. TRIX BASE 8 DISPOSPTR KKK KKK KKK KKK kk kc KR KKK KKK KKK KKK kk kk ck koc kk KKK KKK KKK Place a sparse matrix element on the available list ON SMATRIX AVAIL i SMATRIX AVAIL BASE OVER amp SMATRIX RIGHT W SMATRIX_AVAIL BASE Fetch old head Store it Element is new head OK KK ke kk ce ck ck ke kk kk OO OR kkk Ok kk kk kkk kk Fetch a matrix array element from the available list FROM SMATRIX AVAIL 7 1 SMATRIX AVAIL BASE DUP NIL ABORT No more array space DUP amp SMATRIX RIGHT W SMATRIX AVAIL BASE Fetch head of list List empty Fetch pointer to next KAR KKK KK KR KAKA KK KKK KKK KKK KKK KKK KKK KKK KKK KK KKK KA KAKA KKK KKK Return the element number of an element at index idx ina vector Returns i element if found NIL otherwise This word also sets the PREV ELEM variable for attaching detaching elements from vectors lt S gt idx i R C BASE WQ DUP PREV ELEM W X Fetch base of vector Initial previous element BEGIN DUP NIL X At end IF SWAP DROP EXIT Return NIL if so ENDIF 2DUP amp SMATRIX IDX CQ Fetch index 2DUP Did we find a match IF 2DROP SWAP DROP Clear stack if so EXIT ENDIF gt Are we past where we should look WHILE DUP PREV ELEM W amp SMATRIX NEXT We REPEAT 2DROP NIL Save previous element Fetch next element Didn t find it return NIL CK KR KK KR RK KKK RK Ok koko kK kok Rk ORR Kok Kk OR KK RK kok kK Kok k
46. The EXTDEF record contains a list of external references names of functions defined elsewhere that will be called from Forth in other words an imports list We want to put the linker names here from the words we defined with EXTERN The linker will use these names to resolve our patch addresses with the addresses of C functions with the same linker names Each name in the EXTDEF record is followed by a type index byte but since we have no TYPDEF records these bytes are all just set to zero The PUBDEF record contains the names of symbols exported by the OBJ file In this case we have only one forth which will be used to resolve the calling address of a C function called forth Before the name field in the PUBDEF record are a group index and a segment index and after the name are an offset into the indicated segment and a type index We have no GRPDEF or TYPDEF records and don t need them so these bytes are set to zero The segment index is set to one for the first segment and since this Forth began life as a COM file the offset into the segment is set to hex 100 Using this information the linker can link forth to a C function called forth so that calling that function November 1993 December will execute our familiar Forth image almost as though it were still a COM file You will notice that by making C call Forth we are in some small way giving precedence to C We could in fact put the symbol main rather than for
47. V 2 More on OER ances Ly Numbers Ting bsien sheng was very kind RAMS f OVER 2 1 x y in attributing an algorithm for square root to 3 lt NOT IF x y me It was in fact invented by the ancient Greek mathematicians as well as the Chi ie d MORE eat n MAL E 2 1 I LSHIFT NEGATE t UNDER It is the classical method for calculating P 1 square roots by taking the sum of odd THEN integers It works for all unsigned numbers i OP from 0 to FFFFFFFF or FFFF Try NIP root 1 sqroot x I discovered the Forth code when imple November 1993 December Forth Dimensions FortH 83 Sparse Matrices Rick Grehan Peterborough New Hampshire The program presented here is a spin off of some research I was doing for BYTE magazine s lab The project involved linear programming which had me dealing with potentially very large matrices In most cases the matrices in question were sparse matrices described below and I developed this program as a means of handling these data structures Simply put a Sparse matrix is a large 2D array that s mostly zeroes If you store such a matrix in standard fashion i e elements stored row order in a large buffer of contiguous bytes a substantial portion of memory will be filled with well nothing In his now legendary Fundamental Algorithms D Knuth suggests an alternate storage structure for sparse matrices I based my implementation loosely on
48. XE file CS PSP 16 UM offset of Forth from PSP in memory 256 D subtract psp size D FORTH IMAGE OFFSET 2 Screen 29 SAVE EXE WRITE FORTH IMAGE SAVE EXE RA 20JAN93 WRITE CHUNK len MEMP SWAP DUP MEMP OFBUF WRITE SKIP FIXUP X SEEK would be useful here 4 MEMP FORTH IMAGE OFFSET 28 MEMP 0 D OFBUF SEEK WRITE FORTH IMAGE FORTH OFFSET FORTH IMAGE OFFSET 28 OFBUF SEEK WRITE CHUNK IS WR SEG SKIP FIXUP IS WR FIX WR CODE OPEN PROGFILE FIND PROGNAME SAVE EXE OPEN PROGFILE SET BOOT GET MSGS WRITE FORTH IMAGE OFBUF FCLOSE OFBUF Z gt BUF OFBUF FREOPEN OFBUF FYL Screen 30 0 OrPPN EXTERN TEST WORDS 1 EXTERN C EXIT exit GOOD BYE 0 C EXIT returns code to DOS use C s cleanup 0 EXTERN CORELEFT coreleft dPars 2 EXTERN SETBLOCK setblock 1 EXTERN MALLOC malloc 1 EXTERN FREE free gt Screen 31 1 0 EXTERN TEST WORDS 2 EXTERN GETPIXEL getpixel 6 EXTERN GR INIT _initgraph 0 3 EXTERN PUTPIXEL _putpixel 0 0 EXTERN GCLOSE _closegraph VARIABLE GMODE VARIABLE GDRIVER GINIT CS Z BORLANDC BGI CS GMODE CS GDRIVER GR INIT 20 Forth Dimensions VGAHI 9 GDRIVER 2 GMODE CGAC3 1 GDRIVER 3 GMODE CGA INIT CGAC3 GINIT VGA INIT VGAHI GINIT DECIMAL GTEST CGA INIT 100 30 DO 100 30 DO IJ 8 MOD I J PUTPIXEL LOOP LOOP gt Screen 32 EXTERN TEST WORDS
49. age in its own right is used to create programs that recognize and manipulate strings It is normally used in conjunction with the yacc 1 parser generator But yacc can do more than just recognize grammatically correct statements it can operate on them Qu 0 91 Departments 4 Editorial A wholly unlikely alliance 5 Letters Forth s real problem Pipe dreams Amended attribution amp a snap able stack Another vote for natOOF 31 Advertisers Index 42 Fast Forthward Preparing a press release Forth Dimensions 3 November 1993 December sq jtoriall A Wholly Unlikely Alliance Is it ime for the Forth Interest Group and Forth vendors developers to link arms and walk into the future or even the present side by side as a team There is something to be said for an alliance of forces within the global Forth community Vendors could pool some resources to generate more collective clout and a larger market presence than they can achieve individually The non profit sector Cof which FIG is the largest and oldest representative could do the same reducing redundant overhead by consolidating operations that support publishing and conferences although retaining the autonomy and unique flavor of each organization More could be said in favor of collaboration between the non profit and for profit sectors of our industry Profitable enterprises could underwrite develo
50. ailable at any price Forth innovation often has come from the grass roots like the language itself public domain systems sometimes introduce technology that actually benefits commercial enterprise by preventing stagnation and by pushing the state of the art One also must wonder how many successful vendors actually could be sustained by sales to the relatively small number of people who acquire only such inexpensive systems But what if professional programmers use those freebies as the basis of programs developed for their employers and clients They should realize that the overall health of the Forth industry will sooner or later affect their ability to sell Forth based solutions Over the long haul we succeed or fail together Clients should acquire as part and parcel of any software they contract for a legitimate license to an underlying commercial Forth system Any community can founder on the shoals of special interests but it can also navigate around such hazards and find open water As significant as our differences may be there is more to gain by focusing on our common interests and concerns and by concentrating on how our unique strengths can complement one another Related material from Don Kenney and from Charles H Small senior technical editor at EDN is printed in this issue s Letters Please read them closely and respond to us with a letter of your own Further food for thought was offered by Tyler Sperry in an editori
51. al published in Embedded Systems Programming Atthe other end of the political spectrum the anarchists who embrace Forth can expect an interesting year as well The usage of Forth by Embedded Systems Programming readers has dropped significantly in the last few years The reasons are many but they include the Forth user community s sporadic support of vendors its blind acceptance of substandard tools simply because they re free or shareware and most damning of all its hesitation to adopt programming conventions that the rest of the programming world has long taken for granted The coming year will probably bring Forth s last chance for respectability as the appearance of the ANS Forth standard brings with ita new understanding of how Forth should work in embedded systems If the Forth community decides not to adopt the standard however that s fine with me By not working in embedded systems they ll clear the way for more happening languages such as Smalltalk and APL Marlin Ouverson November 1993 December 4 Forth Dimensions Volume XV Number 4 November 1993 December Published by the Forth Interest Group Editor Marlin Ouverson Circulation Order Desk Frank Hail Forth Dimensions welcomes editorial material letters to the edi tor and comments from its readers No responsibility is assumed for accuracy of submissions Subscription to Forth Dimensions is included with membership in the Fo
52. al is to use Forth in Windows Black and white drawing into a file represents only a small increment toward this goal Black and white pixel drawing simplifies the general case of Paintbrush files while allowing enough drawing to be of practical use A blank drawing created and saved using Paintbrush serves as the Starting point When Paintbrush Saves an image on disk it tries to give the filename an extension of BMP These BMP files contain a 62 byte header consisting of attributes describing the image Loading an image restores the attributes from its header For this article we use black and white images that are 640 pixels wide and 880 pixels tall Except to copy we ignore the header The image directly follows the header with its rows ordered sequentially from 879 to zero i e the rows are in reverse order Conceptually the image is the set of x y points ranging from 0 0 to 639 879 One bit represents one pixel for black and white images When the pixel value equals zero the pixel is shown as black on both the printed page and the screen With the bit equal to one the pixel is displayed as white on the screen and is not printed on the page For completeness we represent below a sheet of paper with a black and white image dimensioned 640 pixels wide and 880 pixels tall Forth Dimensions 27 Rudimentary drawing into Windows Paintbrush files requires the following functions a Loading file
53. am very skeptical that anecdotal evidence of Forth s virtues is going to influence corporate American but I ve been wrong before The problem isn t The community persists in trying to popularize Forth by using the absolutely least effective means Forth but the fact that every language monger claims the same virtues and has lots of anecdotal evidence to back up their claims This is not to say that good stories about Forth s capabilities don t have their place But I fear that place may be in quelling customer doubts rather than in arousing initial interest In working the customer rather than in getting them to bite So I think things are hopeless No actually I don t There are niche markets where I think Forth could do well were they systematically targeted Some examples memory constrained applications dead iron situations new hardware with no software prototyping independent software developers Forth Dimensions I think the real problem is how to orchestrate a systematic marketing effort for a language when there is no large organization with unlimited funds to structure the effort prioritize targets pay its employees to write articles pay for advertising Possibly the Forth Interest Group would help at least by serving as a clearing house for identifying markets and thoughts on what is needed to penetrate them Sincerely Don Kenney Essex Junction Vermont Ona related note
54. ample since a C statement must end with a character this production would recognize an erroneous statement statement error This works by getting tokens from the lexical analyzer until the token or tokens following the psuedo terminal error are seen These tokens are discarded This is very handy for resynchronizing the input stream after an error condition Although this won t correctly handle the case described above where the opening character is left off a file name it will make it possible to pinpoint the source of the error For example the code in Figure Three would suffice One final note on yacc In specifying a context free grammar for a language it is necessary to specify the goal of the language The grammar needs a start symbol This should not be confused with a exstart state Then any token string that can be reduced to the start symbol is a sentence in the generated language In yacc this symbol can be declared with the start directive in the declarations section If the start symbol is not declared yacc will use the first nonterminal in the language section as the start symbol by default This brief introduction to a few UN X tools should not be taken as definitive as a definitive treatment would take at least an article of this length for each of the tools I ve briefly described Again if you want to learn more there are several good books on the UN X operating system For those of you who
55. ases in this guide provide us with a glimpse of the broad campaign that Win Win Marketing has undertaken to estab lish its credibility Topics covered in the guide s introduction include when to write press releases how to target the presses to which you send informational releases and some journalistic guidelines that help you write a press release The book by Strunk and White The Elements ofStyleis referenced Besides re emphasizing various journalistic guidelines guidelines are also offered that apply to press releases exclusively In any case you can t afford to ignore basic advice that you ve already heard over and over such as Use short sentences and short paragraphs of no more than 50 or 60 words As an aside here s how the press releases I read for Product Watch fared Five out of six violated the 60 word maximum paragraph length in their lead paragraph One started with a paragraph of 134 words One had a short letter that referenced new products described in a catalog Jf they don t bother to give tbeir new products a journalistic treat ment why should P For its professionalism and conformance to guidelines the news release I liked best was from a small company announcing a holder for H P DeskJet Writer Ink Jet cartridges so that they are less likely to dry up It consisted of about four or five short and simple paragraphs that easily fit onto one sheet of paper Win Win Marketing suggests that you write a pr
56. at the end of the article we define three SEGMENTs HEADER SEG IMAGE BOT SEG and IMAGE TOP SEG IMAGE BOT SEG holds image rows 879 through 440 while IMAGE TOP SEG holds rows 439 through zero Recall that Paintbrush reverses the order of the image rows To get an image of the Paintbrush BMP file into memory we use GET IMAGE First GET IMAGE uses HS Forth s OPEN Rto find the file whose file spec address is passed and OPEN R obtains a file handle The handle is stored on the return stack O gt xmax image ymax Using HS Forth s READH command GET IMAGE then fills the respective memory areas with a file s contents READH expects a memory paragraph segment offset file handle and number of bytes to read It returns on the stack the number of bytes it read into the memory location GET IMAGE anchors the image at IMAGE BOT SEG In other words after the first half of the image is loaded into memory the location of the second half is computed relative to the first Math for the last segment takes advantage of the fact that eighty divided by sixteen equals five CLOSEH consumes the file handle as it closes the file PUT IMAGE works analogously to GET IMAGE Neither command tests the header or image but simply moves the data Both commands need rewriting for better error han dling if needed 0 xmax image ymax The image is accessed relative to its first row which happens to be its
57. atrix and 6 equal the num ber of columns in a matrix If you re going to use a sparse matrix then some of the ele November 1993 December Listing One Sparse matrix code N KKK KKK KKK KKK ck Cook C C CC kc Ck 0 e Ik e e e e e I xk x amp Each sparse matrix element consists of 5 components 1 A row value byte 2 A column value byte 3 A right pointer points to next member in same row word 4 A down pointer points to next member in same column word 5 A payload the actual value In this implementation the payload is a 10 byte floating point number The total size of an element is 16 bytes KKKKKK KKK KK k kk KKK NV CONSTANTS Cckckckckckckck kckck ko KKK kk 65535 CONSTANT NIL Indicates end of list ckckckckckckckck kokck ck kk kk VARIABLES Ckokckckckck kc ck k k kk kk SMATRIX BASE holds the base address of the memory block holding the sparse matrix elements VARIABLE SMATRIX BASE Sparse matrix elements not in use are kept on an available list SMATRIX AVAIL BASE is the root pointer of that list VARIABLE SMATRIX AVAIL BASE X 4SMATRIX ELEMS holds the number of elements in the sparse matrix VARIABLE SMATRIX_ELEMS X We need two 1 dimensional arrays to anchor the sparse matrix one anchors the rows the other anchors the columns X These are arrays of 16 bit words VARIABLE ROWS ARRAY X Pointer to base of row anchor
58. be included in the definition section by including it between two lines of the form f and 99 Although there is no literal section in this file if one were present it would be delimited from the language section the same way the definition section is delimited from the language section lex stores the string it is processing in the character array yytext and the length of the string in the integer variable yylen Although start symbols are useful for extending lex to allow it to recognize things that are not regular expressions the primary use is for simplifying regular expressions For example the regular expression to recognize a quoted string in C is quite complicated Vr NAnNNJ NN T Nn NnNN X VP A somewhat easier to recognize way of recognizing quoted strings is shown in Figure Two a Start QT1 Start QT2 sf define STRING 1 define ERRSTRNG 1 for incorrectly terminated strings XT BEGIN QT1 yymore QT1 NAnNN BEGIN QT2 yymore lt QT2 gt n BEGIN QT1 yymore lt QT2 gt BEGIN 0 lt QT2 gt n BEGIN 0 start of a quote all but newline a escape return STRING return ERRSTRNG or a terminating error newline Forth Dimensions 33 November 1993 December Regular Expressions Regular expressions are a powerful way of specifying groups of related strings The lexical elements
59. blications that are available and a short bibliography Overall this guide offers a quick schooling in the subject of press releases It introduces you to all the essential writing elements for various types of press releases as well as all the essential format elements of all press releases such as the date of release the requested release date the headline the continuation header the continuation footer the story end indication and a possible dateline which is the city and state where the story originates when it is being released to a broad geographic area On the down side I had a jarring experience when I tried to jump from the table of contents to the examples section I became confused because I never saw the Examples chapter headline that I expected to see In most respects the publication has a professional appearance with the possible exceptions of its binding and its use of one sided printing Even though the body text is in large size fonts the pages still have room for an inside margin containing occasional quotations The guide is printed on standard U S letter size stock that is three hole punched to fit into a report folder Although it doesn t lie flat your arms should not tire even if you read it without a break The number to call for further information about either the guide or a subscription to the Win Win Marketing Newsletter is 408 247 0122 or 1 800 292 8625 or write to Win Win Marketing 662 Cre
60. c ko k k k kk KAKKKKK KK KKK KEK KKK RK KK KKK KK KKK KK KKK KKK KK KKK KKK KKK KKK KK KKK KKK KKK Wire a sparse matrix element into a row or column vector i is the sparse matrix element n is the predecessor in the vector n NIL if i is to be wired in at the head of the list WIRE IN n i OVER NIL Wiring in at head IF SWAP DROP R C BASE W OVER amp SMATRIX NEXT W R C BASE Q W Discard NIL Get old head Old head is our next We are new head a a an an E ELSE OVER amp SMATRIX NEXT W Fix our next OVER amp SMATRIX NEXT W SWAP amp SMATRIX NEXT W Fix predecessor next ENDIF KKK KIRK KR IKK KKK RIKKI KK KK KKK KKK KKK KKK KKK KKK KKK KKK KKK KK ROKK KK Unwire a sparse matrix element from a row or column vector Stack acts same as WIRE_IN UNWIRE n i OVER NIL IF SWAP DROP amp SMATRIX NEXT WR R C_BASE W amp SMATRIX NEXT W Our next SWAP amp SMATRIX NEXT W NV is predecessor s next Are we head Discard NIL Our next is new head ELSE ENDIF Ck Kok ok KKK KKK C KKK KKK KKK KKK KKK KKK KK KKK KKK KKK KK KKKKKKKKKKKK Given i index to a sparse matrix element link this element into the sparse matrix at row col INTO SMATRIX row col i gt R Save i Set the row amp column members OVER R amp SMATRIX ROW C Set row DUP R amp SMATRIX COL C Wire element into row a Set column SWAP SET ROW BASE Set the row base address R WHERE IN ROW Locate w
61. called Grammar The yacc file also consists of three sections the declarations section the rules section and the last section which is copied verbatim into the output file Figure Two b Although a set of productions written in BNF is a concise description of a grammar BNF is not without some draw backs The two major ones are It s hard to tell which tokens are terminals and which are nonterminals using ordinary character sets It s also difficult to construct an unambiguous efficient grammar that obeys the precedence rules of the language it defines yacc gets around these limitations by requiring that all terminal tokens be declared in the declarations section and adding precedence declaratation rules Additionally the conventions of using all upper case letters for terminals and all lower case letters for nonterminals are often used In yacc a token is declared by using the keyword token in the declarations section More than one token can be declared on a line This line would declare the tokens bar and baz Stoken bar baz To determine the precedence of a terminal Cor operator the keywords 1eft right and nonassoc are used depending on whether the operator is left right or non associative The first declared operators in the file are the ones with the lowest precedence and operators declared on the same line have the same precedence If more than one production can be used to reduce the input stream the
62. cate that you haven t yet been able to illuminate your product in words and ideas that capture its value Failures may also lead to new insights If You need the equivalent of a bullet s dense packaging when you tell about the benefits of a product or service your surefire appeal fails to motivate the prospects you have targeted you may be able to glean from its failure a better understanding about the values of that particular market segment Perhaps you will discover a way to reposition your product to appeal to those values A press release offers you a chance to haul out those carefully honed stories and refined messages that you believe best capture your product or your service I like the metaphor of a rifle shot to describe highly prepared marketing mes sages You should be fashioning those messages at least as carefully as you do your products You don t just write them you engineer design them If your product can offer significant benefits for your target customers then you ought to be able to find a way to express that potential so that the November 1993 December 42 words rise up from the page like a rifle shot whizzing by You need the equivalent of a bullet s dense packaging when you tell about the benefits of a product or service Concise and direct expression can pick up the reading pace Fast pacing gives your messages increased impact Before you reach for those favorite stories and mes
63. changes all the segment registers including SS to point to itself losing in the process the return address left on the stack the function orth will never return therefore to be really safe we need to redefine BYE as a call to the C function exit This is redundant but it s important After we write the OBJ file all that remains is to call LINK or TLINK I won t go into detail about this except to note November 1993 December that our object file FORTH OBJ or whatever should be put in the TLINK command line just like a C object file after the initialization module COH OBJ or COFH OBJ for TLINK If you want to link Forth and C you already know how to use LINK and probably MAKE and if you don t there are far better explanations even in the Borland and Microsoft compiler manuals than I can give here but just as an example here s the makefile I used FORTH EXE FORTH OBJ GINIT OBJ FORTHC OBJ TLINK d m s Tde COfH FORTHC FORTH CGA EGAVGA GINIT FORTHC CH LIB GRAPHICS LIB FORTHC OBJ FORTHC C BCC mh c FORTHC C GINIT OBJ GINIT C BCC mh c GINIT C 6 Saving Without Re linking Once we have C routines linked into FORTH EXE we might want to go away from the C environment and still be able to add words and save the image It would be inconvenient to have to use LINK in these circumstances and if we re careful we don t have to What we do have to dois figure out where in FORTH EXE the Forth image is and
64. ctions of code that require a fixup to a segment offset of a long call to another object module This is the simplest way to do it The word that writes the code to the OBJ file just steps through the memory image writing the two kinds of records as it comes to them Mt an ia i an n Screen 23 X SAVE OBJ RECORD TYPES FIXUPP HEX WR FIXUPP 9C REC SIGNATURE RA 02JAN93 Forth Dimensions 17 ence the linker name of the C function we want to call when we execute GETPIXEL Note the leading underscore The actual C function is getpixel but the C com pileradds theunderscore when it creates the object module containing the code for the function soitisas getpixel that the linker recognizes it Other languages may mangle their function procedure or subroutine names in different ways C is particularly elabo rate which you ll wantto know about if you plan to link with them According to my experi ments I can access most any C function with this technique There are some restrictions Some functions in the Borland library reference aren t really functions but macros For ex ample you can tuse Borland s random which is a macro but you canuse rand which is a function Other functions require examination to use correctly Some list parameters which have symbolic names These are of course really numbers usually listed in header files Others are ini tially surprising or perhaps peculiar For
65. d also be obvious il Any finite set of strings is a regular set If the strings are symbolized 1 s2 etc acorresponding regular expression for the set is s 1ls21 2 Aregular expression may be extended under the operation of positive closure This is similar to Kleene closure except that the regular set does not contain the null string This is equiva lent to RERE but is symbolized by appending a metacharacter In layman s terms one or more instances of the preceding regular expression 3 If we consider the character to symbolize equality the O character to symbolize the null string and the characters R S and T to sybolize arbitrary regular expressions then a RIS SIR b RIS IT RI SIT c RS T R ST d R SIT RSIRT and RIS T RTIST e 0OR RO R f R R g R R Although as many levels of parentheses as wanted are allowed they tend to reduce the readablility of the regular expression To remove the need for them UN X adopts certain conventions 1 Alloperators and operations on regular expressions are taken to be left associative 2 The closure operations symbolized by and have the highest precedence Although the operation symbolized by is not properly aclosure it also has the highest precedence 3 Theconcatenation operation has the next highest precedence 4 The alternation operation has the lowest precedence Thus a b c i
66. e MS DOS Encyclope dia says is unused and should always be zero The three bytes after the length bytes are indexes into CR the list in the LNAMES record to assign segment class and overlay names to the segment Actually the overlay index is ignored so pointing it at a blank string as I have done is LOOP 0000 0006 OFBUF SEEK 0000 0018 OFBUF SEEK TABLE OFFSET 0 OFBUF SEEK TABLE ENTRIES 2 OFBUF READ TABLE OFFSET 2 OFBUF READ TABLE ENTRIES 0 DO TABLE ENTRY 4 OFBUF READ TABLE ENTRY 2 4H R SPACE 4H R I 1 8 MOD 0 IF CR ELSE SPACE THEN superfluous The other names appear in MAP files and help control segment ordering and combination Unless its normal operation is overridden with command line switches LINK will combine segments with the same segment and class name and concatenate seg ments with the same class name in the order in which the linker encounters them This order is controlled within an OBJ file by the order of their declarations within it and among object files by the order in which they re listed as parameters to LINK on the command line or in the makefile In our case our CODE segment will be concatenated with other CODE segments from other object modules but it won t combine with anything that is not also called PORTH TEXT WR SEGDEF which writes this record takes its param eters name indexes length and ACBP byte from the stack to make it easier to define multiple segments
67. e end more tedious than difficult The record types for OBJ files are described completely if not quite lucidly in the MS DOS Encyclopedia though I must add that the formats of these records are twisted enough that they perhaps can not be described clearly The important thing for us is that there are things about them we do not need to know and some that we do All OBJ records begin with a one byte signature and a two byte length and end with a checksum byte The Borland and Microsoft linkers at least the versions I ve used ignore the checksum so we don t have to care what s in it The length is the length of the record after the length in other words three less than the length of the whole record in bytes The contents of ob ject records between the count and the checksum are strings tightly packed bit field bytes index bytes pointing at or into other records and for two record types data des tined to compose the memory November 1993 December further information or to puzzle it out yourself consult the MS DOS Encyclopedia For clarification consult the code The THEADR or translator header record I m using names given from the MS DOS Encyclopedia just gives the module a name and must be first It s almost the simplest CS HERE ROT DUP gt R CMOVEL HERE R gt HEADERPARS n 0 BLOCK 8 Q FORTH OFFSET dOffset HEADERPARS 16 UM offset of code portion in E
68. ed C and just leaves the ASCII value of the following character on the November 1993 December Screen 0 This file converts Guy Kelly s PC FORTH 1 46 an 83 Standard Forth implementation from a COM to an EXE file with links to external functions written in C Since the program began as a COM file when it becomes an EXE the area from below 100h is available for scratch data Richard Astle POBox 8023 La Jolla CA 92038 619 456 2253 Screen 1 USEFUL THINGS HEX ONLY FORTH ALSO DOS ALSO FORTH DEFINITIONS 02JAN93 RA 29DEC92 IFNDF OFBUF FBUF OFBUF ENDIF X fbuf for this work WALL marker for FORGET RE BYE 4C BDOS 0 BDOS is for com files gt Screen 2 USEFUL THINGS DOS READ WRITE SEEK WRITE addr len fbuf ROT WRITE 0 IF CR WRITE ERROR READ addr len fbuf ROT READ 0 IF CR READ ERROR QUIT THEN SEEK dOffset fbuf SEEK 0 IF CR SEEK ERROR MAKE fbuf MAKE 0 IF CR MAKE ERROR QUIT THEN gt 10FEB93 RA 29DEC92 QUIT THEN QUIT THEN Screen 3 V REDEFINITIONS redefinitions to correct parameter order RE L seg off n SWAP L RE CGL SWAP C L RE L n seg off SWAP L RE C L SWAP C L RE CMOVEL seg off seg off len gt R SWAP 2SWAP SWAP 2SWAP R gt CMOVEL RA 16JAN93 Screen 4 X USEFUL THINGS L amp c DUMPL DECIMAL DUMPL seg adr cnt BASE gt R HEX 0 DO CR OVER 5 U R
69. ependence human machine interface source management and version control help facilities editor development interface source and object libraries source block and ASCII text independence source browsers including editors tree displays and source data base run time browsers including debuggers and decompilers networked development target systems Completed papers are due November 1 1993 Registration fee for conference attendees includes registration coffee breaks notebook of papers submitted and for everyone rooms Friday and Saturday all meals including lunch Friday through lunch Sunday wine and cheese parties Friday and Saturday nights and use of Asilomar facilities Conference attendee in double room 380 e Non conference guest in same room 260 Children under 18 years old in same room 160 Infants under 2 years old in same room free Conference attendee in single room 490 eee Forth Interest Group members and their guests are eligible for a ten percent discount on registration fees e John Hall Conference Chairman Robert Reiling Conference Director Register by calling fax or writing to Forth Interest Group P O Box 2154 Oakland CA 94621 510 893 6784 fax 510 535 1295 This conference is sponsored by FORML an activity of the Forth Interest Group Inc FIG
70. er I ve defined a set of words to compile bytes words and strings into this buffer In some implementations it might be possible to construct these records at HERE by saving and restoring the DP each time in that case you could just use comma C c comma and Gif you have it comma quote instead With these core words I ve defined words which compile the record signature fake checksum and length into the record and then actually write it out These words make writing most records easy and uniform The exceptions are the EXTDEF record which contains the linker names of the external references defined by EXTERN and the LEDATA and FIXUPP records which contain the actual Forth image machine code The variables CUR XLINK current external link MEMP memory pointer and XREF external reference number are used to keep track of what s been written from the Forth memory image to the OBJ file The words gt 1ST XLINK and gt NXT XLINK step CUR XLINK through the linked list of words defined with EXTERN and keep a count in XREF CUR XLINK always points to the next external reference that needs to be written or to zero to indicate that none are left WR EXTDEF uses these words to find the linker names and WR CODE uses them to find the patch addresses The EXTDEF record is composed in the same buffer as the other records WR CODE works a little differently Except for the signature length and fake checksum of each LEDATA
71. er will use to re solve the address of the call with the appropriate C func tion The usage is EXTERN lt Forth name gt lt external reference gt out in as in November 1993 December 1 2 EXTERN GETPIXEL _getpixel This expression defines a Forth word GETPIXEL which has a stack picture GETPIXEL y x color The parameters to EXTERN indicate that GETPIXEL takes two 16 bit values from the stack and returns one Note that these are not parameters in the C sense but rather the number of 16 bit values that make up those parameters an int is worth one 16 bit param eter a double two a far pointer also two Since a C function returns at most one parameter and in Borland C at any rate the maximum size of that pa rameter is 32 bits the first parameter to EXTERN can be only 0 1 or 2 There can of course be any number of in put parameters The reason EXTERN wants to know how many there are is so that the word it defines can clean up the stack by adjusting SP be fore it pushes its return value if any This is the way C does it Of course EXTERN could be written more simply even more generally to leave the input parameters on the stack and push both AX and DX on top of them For those few functions like printf which take a variable number of parameters we ll have to clean up the stack in high level anyway but we re Forth pro grammers we can handle it Note that C unlike Pascal fo
72. erface to a Paintbrush file The BMP file s header needs to be understood as well Surely the desire to use color will become overwhelming Additionally different rules for drawing like XOR OR NAND etc could be accommodated Solvingthese requirements will open the way for error han dling range checking and optimizing for speed How ever as they are the routines shown here draw November 1993 December 11 19PM 1 29 93 by Hank Wilkinson Code for drawing into Windows Paintbrush BMP files Reads and writes black and white 640 by 880 images Draws via PIXEL x y Assumes BMP image 640 bits wide and 880 bits long amp page header first 62 bytes of file T V GO T DECIMAL FIND SEQ FND 0 FLOAD C HSFORTH FASTCOMP FLOAD C HSFORTH AUTOOPT FLOAD C HSFORTH TOOLBOX X FLOAD C HSFORTH 8088ASM FLOAD C HSFORTH DOSEXT FLOAD C WINDOWS DOCS TOOLS GETPUT FTH TASK HANK code below is for article 62 1 SEGMENT HEADER SEG header 440 80 VAR 440 80 440 80 1 SEGMENT IMAGE BOT SEG top half 440 80 1 SEGMENT IMAGE TOP SEG bottom half Use path filename GET IMAGE GET IMAGE adr OPEN R gt R HEADER SEG 0 62 R READH DROP IMAGE BOT SEG 0 440 80 R READH DROP IMAGE BOT SEG 0 440 5 0 440 80 R READH DROP R CLOSEH Use path filename PUT IMAGE PUT IMAGE adr MKFILE gt R HEADER SEG 0 62 R WRITEH DROP IMAGE BOT SEG 0 440 80 R WRITEH DR
73. erminal These derivations are known as respectively left sentential form and right sentential form the example was derived in right sentential form A viable prefix is a string of symbols that coresponds to a proper prefix of a sentential form Ci e it contains up to the first n 1 symbols where n is the total number of symbols in the sentential form There are two general methods of constructing parsers from grammars The first is a top down technique called LL which stands for left to right traverse left sentinel form The second is a bottom up technique called LR which stands for left to right traverse right sentinel form An important result of compiler theory states that any language that can be parsed by an LL parser can be rewritten so that it can be parsed by an LR parser Additionally parsing techniques can be characterized by the number of tokens they look ahead into the input stream For example a parser that is able to use everything it has seen so far Cits left context plus the next terminal token to be returned from the lexical analyzer has one token of lookahead This is symbol ized by placing a numeral corresponding to the number of lookahead tokens the parser can use in parentheses after the name of the parsing technique Thus you will see references to LR 0 grammars etc There are three major divisions of LR k parsing where k is greater than zero simple LR or SLR canonical LR abbreviated as LR and looka
74. ers onto the stack Of course in a single segment model they ll all return the same value I also assume the familiar F83 vectored execution mechanism using DEFER and IS For DOS file access I assume the existence of the November 1993 December following words MAKE fbuf FREOPEN fbuf FCLOSE fbuf WRITE addr len fbuf READ addr len fbuf SEEK udOffset fbuf FILENAME fbuf These words call DOS int 21 functions 3C through 40 and 42 They assume the 16 bit addr is relative to DS and that the unsigned double off set for SEEK is from the begin ning of the file The parameter fbuf is a stand in for the DOS file handle In this Forth FBUF is a defining word that creates an object which contains a space fora filename a handle and a few file statistics The word FILENAME is used as in FBUF FBUF1 FBUF1 FILENAME FORTH OBJ to assign a filename to an FBUF since words like MAKE and FREOPEN need a name ratherthan a handle The word FREOPEN is a safety word first it closes a file that might have its handle in the FBUF in question then it opens the file which has its name in the FBUF This prevents a careless loss of handles The word Z which handles the em bedding of null terminated C like strings uses the words ASCII and which aren t quite standard though they or their equivalents must exist in nearly all Forths ASCII is sometimes call
75. ersion that was published sqroot radicand root 1 SWAP OVER DO term 2 DUP LOOP 2 Although it performs very well for small values this algorithm is grossly inefficient for large values If you only need it occasionally for large values that s not important but you should have an industrial strength definition in your library see Figure One below This a direct translation of the pencil and paper method taught in high school Except for FUNDER and NOT the code is ANS Forth I hope that UNDER is a primitive in your system t allows an element on the stack other than the top to be an accumulator without intermediate stack manipulation As UNDER it is recommended by Charles Moore in Leo Brody s Thinking Forth changed the name to be analogous with and other words UNDER ROT SWAP abc atc b A debugging device that ought to be better known is to redefine to be a print instruction followed by a stack dump This turns stack comments into snapshot traces This can be implemented in any Forth butitis particularly easy to do with PLEASE in this Forth Continues on page 41 Yours truly Christopher B Browne ow i Toronto Ontario Figure One Baden s industrial strength square root Ganada 2 sqrt radicand root NEA 0 radicand root Amended AEHIDHHOS 0 ADDRESS UNIT BITS CELLS 2 and a Snap able Stack D6 Co To the Editor and C H Ting 2x T In a recen issue CFD X
76. ess from memory starting from MEMP and stopping at or before the next patch address The format of the FIXUPP record has already been described the important thing here is that the value in XREF is included which tells the linker which name in the EXTDEF record refers to this particular fix up so it can patch its address correctly In all cases WRICODEREC advances MEMP to point tothe first byte of memory not yet written and so long is there is memory left to write the loop repeats 5 Linking Forth and C It is possible to write out a Forth image without any EXTERNS as an OBJ file and use LINK to create an EXE This is the simplest situation and though interesting not very useful except as a step in the development of the method To link inC functions we have to have amain function andlink in the initializaton module and libraries for the huge model We can make Forth the main module by calling it main in the THEADR object record but as mentioned earlier this doesn t quite work In order for C to do its initialization correctly main has to be a C function however trivial The file FORTHC C is just void far forth main forth This is all the C we need We declare forth as a far function that is one that is called with along call and then make the call by invoking the function But C not only has some initialization to do before calling main it also wants to clean up after itself Since Forth
77. ess release to target just one type of medium or a specific publication that you are interested in The guide talks about when to use photos as well as how they should be prepared for the demands of the print medium Besides photographic advice you are offered advice about distributing the press release about how to find the names of editors and about using reprints of articles for your own self promotion That covers the first ten pages of this short guide of about 30 pages You get the idea that a lot of ground is covered quickly The offerings of advice continue with tips from editors of publications They offer an assortment of insights Do you want your envelope to be opened If so hand write it Do you want timely coverage If so understand the lead times for each publication you target The many guidelines and tips offered in the beginning sections eventually make way to reference information in the second half of the guide In between there is an informative section about the various types of press releases you might prepare The last five sections of this guide about a dozen pages are in reference format with an occasional sprinkling of Forth Dimensions narrative These sections include a sequence of example press releases a list of suggestions about how article reprints might be used promotionally a one page press release checklist a list of library resources such as directories which can help you survey the pu
78. f right pointer member amp SMATRIX RIGHT SMATRIX ELEM ADDR 2 Return address of down pointer member amp SMATRIX DOWN SMATRIX ELEM ADDR 4 Return address of paylod amp SMATRIX VAL i addr SMATRIX ELEM ADDR 6 Set the NEXT function to point to down NEXT IS DOWN COMPILE LIT FIND amp SMATRIX DOWN NEXT FUNC Set the NEXT function to point to the right NEXT IS RIGHT Crs COMPILE LIT FIND amp SMATRIX RIGHT NEXT_FUNC Get the NEXT pointer for vector operations amp SMATRIX NEXT i addr NEXT FUNC EXECUTE Set the IDX function to point to ROW IDX IS ROW COMPILE LIT FIND amp SMATRIX ROW IDX FUNC Set the IDX function to point to COL IDX IS COL COMPILE LIT FIND amp SMATRIX COL IDX FUNC Get the IDX member amp SMATRIX IDX i addr IDX FUNC EXECUTE Set the row base pointer SET ROW BASE n 2 2 bytes per 16 bit word ROWS ARRAY Add offset to base address R C_BASE Store Set the column base pointer SET COL BASE n 2 2 bytes per 16 bit word COLS ARRAY Add offset to base address R C_BASE Ck ck KK KKK KKK KE KKK KKK KKK KE KKK KK e I x kx kx kx kk ko Build the sparse matrix available list BUILD_SMATRIX_AVAIL a Forth Dimensions 9 ments are going to be empty Ill represent the number of empty elements with e The point at which it becomes ben eficial to use a sparse matrix is when the follow
79. for the segment name and the class name of oursingle Forth code segment But see the More Implemen tation Details section later The SEGDEF record de fines a memory segment It contains a number of fields an ACBP byte a two byte segment length and three name index bytes which con tain references to names in the previous LNAMES record The ACPB byte encodes various attributes of the seg ment Ours is 62H or 011 000 1 0 The three highest bits indicate the segment alignment which in this case is relocatable and paragraph aligned ie it will begin on a 16 byte bound ary The paragraph alignment is important since we want to set the segment registers to the beginning of the Forth address space The next three bits are the combine type which in this case indicates that the seg ment cannot be combined This is the safest value for this field though 010 which would allow concatenation with an other segment of the same name would work as well The penultimate or B for November 1993 December big bit combines with the following two bytes to give the length of the segment In our case the segment is 10000 hex bytes or 64K supposedly the maximum segmentlength and is what we want The last Screen 35 PRINT FIXUP TABLE FROM EXE HEX VARIABLE TABLE OFFSET VARIABLE TABLE ENTRIES 2VARIABLE TABLE ENTRY RA 15FEB93 PT FIX TABLE OPEN PROGFILE bit is the Page resident flag which th
80. he sparse matrix and places it on the available list Ofcourse actually manipu lating matrix members means your code has to locate a par ticular element within the ma trix You accomplish this with the word S which accepts row and column coordinates atop the stack S will return the sparse matrix identifier of the element at that location or NIL if the coordinates are empty S is only as smart as it can be Notice that the struc ture I ve described allows you to locate a member of a sparse array by walking either the row based linked list to that member or the column based linked list S would be really smart if it followed whatever list had the fewest number of elements between the list head and the target element Of course there s no way S can know this pre cisely without actually count ingthe intervening members but to do that would mean S would have to walk both lists to the target and compare the results So S simply chooses the path most likely to be shortest which is the path identified by the smaller coor dinate Le if the row coordi nate specified is smaller than the column coordinate S searches the row list Conclusion As mentioned above there are plenty of opportunities for extending the code Increasing the row and column compo November 1993 December nas t o8 a ad a a aa m ZAP SMATRIX ROWS ARRAY _DISPOSPTR COLS ARRAY DISPOSPTR SMA
81. head LR or LALR The chief difference between these methods is SLR builds an LR 0 parser and then adds states to the parser to take lookahead into account LR constructs the parser taking lookahead into account in the first place and LALR constructs the parser by using the lookahead and trying to collapse similar productions into the same rule The yacc parser generator uses the LALR approach This will generate an efficient parser for most grammars for which an LR parser can be constructed Ifa parser cannot be generated for a grammar the grammar is said to be not whichever parse technique ts used For example a grammar that can t be converted to an LR parser is said to be not LR November 1993 December 36 Forth Dimensions action is embedded in the production like this reduce foo misc C verbiage bar the action is triggered when the token string leading up to it is seen Notice that this will cause a reduce reduce conflict if two rules have the same viable prefix even if the actions are identical To get around this split the two productions into three and perform the action at the end of the production that is common to both of the originals If the actions required are not identical you either have to find some way to postpone the action to the end of the production or you will have to use some parser generator besides yacc For example this foo footokenl foofunc footoken2 foot
82. here to wire in 0 Flag 0 means slot is free IF R WIRE IN Wire him in ELSE Error attaching to row CR ABORT ENDIF X Wire new element into column SET COL BASE Set the column base address Forth Dimensions 39 nents of an element would allow for truly gargantuan sparse matrices I suppose if you needed sparse multi dimensional arrays you could add the necessary anchoring arrays extend the element structure and add the neces sary words for access to element components Off the top of my head I can t imagine an application for such structures but PH bet there s one out there somewhere Rick Grehan is the Technical Director of BYTE Labs He wrote the code for this article with Creative Solutions MacForth November 1993 December M e PES ott n8 R WHERE IN COL Locate where to wire in 0 As before slot must be free IFR WIRE IN Wire him in the column ELSE Error attaching to col CR ABORT ENDIF CC C Ck eC Ce ke ke ke ke SK Sk Ce ke ck ck ck ck kk KKK KKK KEK Given i index to sparse matrix element unlink him from the sparse matrix OUTOF SMATRIX i gt R Save i Look for this guy in the row R amp SMATRIX ROW C SET ROW BASE Set row base pointer R WHERE IN ROW Search for i in row vector 1 i has to be there IFR UNWIRE Disconnect ELSE Error removing from row CR ABORT ENDIF X Look for this guy in column R amp SMATRIX COL C SE
83. iler can pro 0 BUFC offset in record in AZ LEDATA always 0 cess them before writing the fixdat OBJ file but the format speci 56 BUFC X F 0 frame det by target T 0 ext index fications can only be replaced XREF BUFC by strings representing the WR REC appropriate values at run time gt For further examples of C function calls see the sample code One is particularly important the call to the C Screen 24 X SAVE OBJ WR CODE function exit defined as HEX DEFER WR SEG WR FIX WR PATCH 0 1 EXTERN C EXIT WRICODEREC exit Because a C program sets up certain parameters cap IF 400 UMIN tures various interrupts etc THEN when it starts up and we WR CODE really don t wantto know what 0 MEMP those are we need to exit from Forth in a way that will WR CODE 1 SEG INX CUR XLINK DUP IF XLINK gt FIXADR MEMP DUP ELSE TOP ADDR MEMPG 400 UMIN V For details of the FIXUPP record try the MS DOS ENCYCLOPEDIA OlJAN93 RA 29DEC92 DEFER WR FIX TARGET WR FIXUPP step through the memory image and the EXTERN linked list WR SEG ELSE WR FIX gt NXT XLINK THEN WR SEG gt 1ST XLINK BEGIN WRICODEREC MEMP TOP ADDR U lt 0 UNTIL cause C to clean up after itself WR LEDATA IS WR SEG as well The way to do this in WR FIX IS WR FIX November 1993 December 18 Forth Dimensions WR CODE gt Screen 25 V SAVE OBJ WR OBJ RECORDS HEX WR OBJ RECO
84. ily 80X86 family 80X96 97 family 8051 31 family 6303 6809 68HC11 No license fee or royalty for compiled applications a Laboratory Microsystems Incorporated Post Office Box 10430 Marina Del Rey CA 90295 Phone Credit Card Orders to 310 306 7412 Fax 310 301 0764 November 1993 December A Forum for Exploring Forth Issues and Promoting Forth Past FORT ware Preparing a Press Release Mike Elola San Jose California Press releases can be your most powerful tool to promote business The cost effectiveness of a well received press release is unsurpassed Although advertising guarantees you coverage it does so at a much higher initial cash outlay Furthermore cost recovery for an ad may not be possible even with a mildly successful response You need to be able to pay for advertising with disposable income particularly new advertising for which a response has never been measured The same is true about the overhead for a press release but that overhead is relatively minor The process of creating ads and press releases can be very enlightening That s because it forces you to think like your customers do It also forces you to think about how your product meshes with the industry that you serve Because of their lower overhead press releases can be utilized with more impunity Nevertheless there are impor tant guidelines to follow some of which I will get to shortly A failed press release may indi
85. ing else means bad So instead of BYE we can execute GOOD BYE defined as GOOD BYE 0 C EXIT and avoid having our machine lock up on us unexpectedly while we re in the middle of something else later Portability issues aside the actual coding of EXTERN and later SAVE OBJ and SAVE EXE is also necessarily some what implementation and personal preference dependent I chose an 83 standard indirect threaded Forth for this project because it is probably still the most widely available model and I used Guy Kelly s implementation because it s the single segment version I m most familiar with I could have used F83 with perhaps no changes not already men tioned except the need to use an unfamiliar editor More serious adjustments would have to be made for direct threading or subroutine threading one hesitates to contem plate token threading not to mention other standards including the forthcoming ANS The code works and working should speak for itself but here s a little more detail The defining word EXTERN has two parts CODE EXTERN creates Forth code words by compiling bytes in memory with C This is not a job for CREATE DOES gt since each external reference needs its own code body The only unusual things at least with Borland C This shouldn t have been surprising no thread field since the escape sequences V locat are unambiguous at compile CC BUFC M 1 loc segment offset time the C comp
86. ing array VARIABLE COLS ARRAY X Pointer to base of column anchoring array X Routines that add to and remove elements from the matrix need to know the previous element in the current vector X We ll keep that item here VARIABLE PREV ELEM X Operations on the sparse array usually take place on row or X column vectors This variable points to the address of the anchoring pointer to the current row or column vector we re working in VARIABLE R C BASE The sparse matrix has to know how big it is these variables hold the dimensions VARIABLE SMATRIX_ROWS VARIABLE SMATRIX_COLS Following variables are vectors to functions that indicate whether we re searching down through a column or across V through a row VARIABLE NEXT FUNC VARIABLE IDX FUNC Ck ck ok kc kk kk ck ck e xk ke e e kx kx kx kx LOW LEVEL DEFINITIONS ORR IO RI IOI ICI II I IO A A RI ROT ROT ROT ENDIF COMPILE THEN IMMEDIATE Following words calculate the address of various components 8 Forth Dimensions Av S Se EN EN EM e RP af of a sparse matrix Return address of ith sparse array element SMATRIX ELEM ADDR i addr 16 Get byte offset into memory block SMATRIX BASE Add offset to base Return address of row member amp SMATRIX ROW i addr SMATRIX ELEM ADDR Return address of column member amp SMATRIX COL i addr SMATRIX ELEM ADDR 1 Return address o
87. ing equation is satisfied 10ab gt 2 a D 16Cab e That is using standard tech niques to store a matrix of extended reals requires 10 ab bytes A sparse array would require 2 a b bytes for the anchoring arrays plus 16 ab e bytes for the elements actually active in the array This equa tion assumes a payload of ten bytes and a sparse array ele ment size of 16 bytes You can determine how many empty elements would make using a sparse array prof itable by re arranging the above equation to at b 3ab 8 lt e So for example if you are working with a 50 x 50 matrix it becomes worthwhile to look into using the sparse matrix storage format if more than 950 elements are empty The Code The complete source code appears in Listing One In prac tice the first word your program must call is INIT SMATRIX which allocates space for the sparse matrix elements as well as the anchor arrays via INIT ANCHOR ARRAY INIT SMATRIX also places all sparse matrix elements on an available list the word BUILD SMATRIX AVAILper forms this task yet another singly linked list that holds all unused sparse matrix elements November 1993 December Initially then the two anchor ing arrays point to empty lists all sparse matrix elements are on the available list You build a sparse matrix by repeated calls to FROM SMATRIX AVAIL and INTO SMATRIX FROM SMATRIX AVAIL pulls an unused element from the available
88. into memory b Drawing a pixel C Saving image to disk Knowing a pixel s state may increase utility so we include the following d Reading a pixel To better follow here is my system My computer is a VSI PC 286 name brand compatible with VGA 40 meg hard drive both 5 1 4 and 3 1 2 floppy drives a mouse H P DeskJet 500 a modem and four megs of memory I have DOS 5 Windows 3 1 and HS Forth 4 11 regular i e uses segmented memory Simplifying the drawing process to black and white draw ings 640 pixels by 880 pixels results in an image space of 70 400 bytes 640 880 8 70400 I have no method of accessing this image space without using paragraph offset memory addressing Again I point to Dr Noble s text this time for a lucid explanation of paragraph offset addressing Ofthe ways I have to perform paragraph offset addressing the simplest uses HS Forth s SEGMENT command SEGMENT expects the number of bytes plus one to allocate and creates a named array holding a pointer and other variables Fetching this pointer provides the memory paragraph segment HS Forth provides a large set of commands accessing segmented memory via paragraph and offset However 77 i November 1993 December none were found for bit accessing so we use CGL and C L C L expects paragraph and offset on the stack and returns a byte C L expects a byte paragraph and offset and stores the byte For navigation see code
89. iously last EXTERN are adjusted by EXT LINK What makes this list different from most others November 1993 December in Forth the dictionary the list of vocabularies is that the links point forward rather than backward which is what we want since this is the order we ll need them as we write the records of the OBJ file The words XLINK gt FIXADR and XLINK gt XNAME factored to make redesign easier will be used to find the patch address field and the linker name field from the external link field in each header and gt 1ST XLINK image of the linked EXE file Strings in object records are the kind we re used to beginning with a count byte rather than ending with a null Each record type does one thing well enough We need eight different record types and since they tend to refer to each other order for the most part matters I ll describe each as briefly as possible in the order we need to use them For and NXT XLINK manage stepping through the list In memory EXTERN lays down something like this long call code next name link cfa patch fwd link linker name 4 Object File Records After we create references to external functions we have to save the running Forth im age as an OBJ file Most sys tems have a SAVE FORTH word which saves the Forth image as an executable file either a COM file or a work able facsimile of an EXE with out fix ups What we need is a bit more complicated but in th
90. lacing a nonterminal with a corresponding production This is called a derivation For ex ample if this was the grammar under discussion using the yacc conventions that an upper case string or a quoted single character is a nonterminal lower case strings are nonterminals and nonterminals are separated from their corresponding produc tions by a colon sg e ID e e the nonterminal s which is the start symbol for this example would derive g A sequence of derivations for S might take the form s gt g gt g f gt g e gt g ID gt f ID gt e ID gt ID ID The set of all strings of terminal symbols that can be derived from the start symbol is the language corresponding to the a context free grammar or one where the current fragment Grammar grammar Any string of the set is called a sentence of the language A string containing both terminals and nonterminals that is derivable from the start symbol is called a sentential form of the grammar A language that can be generated from such a grammar is called a context free language Ifthe languages derived from two grammars are identical then the grammars are said to be equivalent A sequence of derivations may replace any nonterminal in a sentential form with an equivalent production but for convenience in classification we may wish to restrict ourselves to derivations that always replace either the leftmost or the rightmost nont
91. le time on the contrary they have to be fixed up when the pro gram is loaded and run It is possible to have an EXE file without fix ups A Forth system I use daily has four 64K segments and sleeps in an EXE file but since only one of these segments con tains executable code there is no need for so called reloca tions whenthe program loads the DS ES and SS registers are set to appropriate offsets from CS and everything runs November 1993 December smoothly This EXE file was not created by LINK how ever and has no way to speak to anything it doesn t compile or metacompile for itself When the linker links OBJ and LIB files to create the EXE it creates an almost execut able image that could run if it could be loaded at the very bottom of memory without a PSP or a memory allocation block below it In other words the linker makes all segment references in the load module relative to the beginning of the load module When DOS loads the load module into memory it always does so on a segment boundary All that is necessary then to fix up the file for execution is to take the load address as a segment value and add it to all segment references in the loaded im age To facilitate this fixing up the EXE header contains a relocation pointer table This table is poorly named noth ing is actually relocated What it actually contains is just a list of pointers to segment refer ences in the load
92. ns saved the new Forth memory image as an object module file and linked that module with C libraries and object modules into an EXE which makes the new functions available as normal Forth words The result is a Forth system which can be extended further via the linker but also via normal Forth compilation 26 Where Do You Go From Here C H Ting The six preceding tutorials have introduced you to a very minimal set of Forth instructions There are different directions in which you may now proceed depending on your needs and interests Here the author points the way for further exploration by listing some of the key reference sources for learning more about Forth and how to use it to solve practical problems in the programming world 27 Drawing BMP Files Hank Wilkinson Microsoft Windows comes with the drawing program Paintbrush which saves filenames with a BMP extension Paintbrush drawings may be printed or inserted and otherwise linked to other documents Forth generated pixel drawings can be handledas if they were Paintbrush files Black and white pixel drawing simplifies the general case while allowing enough functionality to be practical 3 2 UN X Tools Used on the FSAT Project Jim Schneider This article continues toward the goal of building a Forth like environment that incorporates the best of UN X Whether you hate itorlove it UN X does provide many tools for sophisticated pattern matching The ex 2 utility a programming langu
93. o take advantage of those parallels and moreover take advantage of more ideas that were Not Invented Here Dynamic allocation streams and a logical extension to streams pipes being three such Wouldn t it be neat to have a Forth that would automati cally spawn a process for every word invoked from interpre tation mode It might not run happily on an 8051 but then I m trying to figure out a way to get some form of RISC workstation onto my desk I m not thinking about running an 8051 With a suitable tasking model this sort of system might be a real performer as compared to the direct competition which is sh scripts running under UNIX And it might even work on an 8051 What I really would like to see is a Forth like approach to pipes On the Back Burner is always interesting The philo sophical side is neat the educational part on the strange origin of the term dead reckoning was illuminating We are I suspect of somewhat different opinions about some of the other issues I m one of those people who likes to claim that Forth is a language with at easttwo stacks and probably more Thank you for some interesting reading menting the sum of odd integers algorithm It s astonishing how well the Forth primitives work to implement this algorithm So far it s the only good use for the special features of the Forth 83 LOOP I have found I offer my original implementation as more elegant and efficient than the v
94. oard SC FOX PCS32 Parallel Coprocessor Sys 32 bit SC32 industrial grade Forth PGA CPU System speed options 8 or 10 MHz 64 KB to 1 MB O wait state static RAM Full length PC XT AT plug in 6 layer board SC FOX SBC Single Board Computer RTX 2000 industrial grade PGA CPU System speed options 8 10 or 12 MHz 32 KB to 512 KB O wait state static RAM 100mm x 160mm Eurocard size 4 layer board For additional product information and OEM pricing please contact us at SILICON COMPOSERS INC 208 California Avenue Palo Alto CA 94306 415 322 8763 Conuents Features 7 Sparse Matrices Rick Grehan The technical director of BYTE magazine s lab was doing some research dealing with potentially very large sparse matrices two dimensional arrays mostly filled with zeroes which can fill a substantial portion of memory with well nothing Knuth suggests an alternate storage structure on which this Forth implementation is loosely based Here each sparse matrix element is a data structure consisting of row and column coordinates right and down pointers and the payload 4 1 Forth and the Rest of the DOS World Richard Astle Sometimes it is nice to use other people s libraries and code particularly if we can do so without losing the interactive incremental soul of Forth Of several ways to do this the author began not with assembler or C but with Forth itself He added external references to C functio
95. of a language the words of the language are usually most conveniently represented by regular expressions For this discussion an alphabet should be understood to be an ordered set of symbols These symbols are the letters of the alphabet Unless otherwise specified the alphabet under discussion will be a standard computer character set The set of strings specified by a regular expression is known as a regular set A string in a regular set is said to match the regular expression These are the basic properties of regular expressions T Any symbol in the alphabet is a regular expression whose corresponding regular set contains one element a string consisting of the symbol Any two regular expressions may be combined under the operation of alternation The alternation will be symbolized with the metacharacter The regular set corresponding to the new regular expression is the union of the regular sets of the original expressions For example the expression alb would match a string composed of either a single a or a single b character Any two regular expressions may be combined under the operation of concatenation The concatenation will be sym bolized by abutting the two regular expressions The regular setofthe newregular expression will bethe setof strings that can be decomposed into two strings such that the first substring is in the regular set of the first expression and the second substring is
96. okenl foofunc footoken3 must be rewritten as fooprefix footokenl foofunc foo fooprefix footoken2 fooprefix footoken3 and this foo footokenl foofuncl footoken2 footokenl foofunc2 footoken3 must be rewritten to move the action to the end of the productions or at least past the point where the productions share a viable prefix Each token in yacc can have an associated value This value is set in the actions associated with productions for nonterminals or the lexical analyzer for terminals It can be accessed in a similar fashion to the arguments to macros in m4 by some digit where the digit corresponds to the token in the production The value is set by assigning a value to in the action corresponding to the production Thus this expr expr prec UMINUS 2 would set the value of the left hand expr to minus the right hand expr The lexical analyzer can set a token value by assigning something to the global variable yyl val The type of the values 1 etc can either be set by defining the typename YYSTYPE to something or by the command union in the declarations section Since the FSAT project s C to Forth compiler will need to operate on strings and an associated type I ll be using the first method kludged to allow me to store both a string Figure Three for any sequence of input that doesn t form a valid production in the current context For ex
97. one with the highest precedence operator will be used and if there are two or more operators in the same production the one the farthest to the right will set the precedence for the production If the two productions have the same prece dence the associativity rules are used right associative operators reduce the rightmost part first and left associative operators reduce the leftmost part first If the two produc tions have the same precedence and the operator involved is nonassociative or no explicit precedence or associativity rules are given yacc will report a conflict There are two types of conflict a shift reduce conflict or a reduce reduce conflict The conflicts are given their peculiar names because of the way the yaccgenerated parser operates At any given point the parser is in one of several states When the parser gets a token from ex it can do one of two things depending on the token It can use the token to reduce the production it is working on and go to another state or itcan shiftthe token and the current state onto a stack and go to another state Without rules to the contrary when yacc has a choice between shifting and reducing it will choose the shift which means it will attempt to find a longer string of tokens to convert to a nonterminal If yacc has a choice between two reductions it will take the one that corresponds to the earlier production in the file Generally conflicts are best avoided
98. p c o TPI 1293 Old Mt View Alviso Rd Sunnyvale CA 94089 Second class postage paid at San Jose CA POSTMAS TER Send address changes to Forth Dimensions P O Box 2154 Oak land CA 94621 Forth Dimensions Lt ers Letters to the Editor and to your fellow readers are always welcome Hespond to articles describe your latest projects ask for input advise the Forth community or simply share a recent insight Code is also welcome but is optional Letters may be edited for clarity and length We want to hear from you Forth s Real Problem Dear Mr Ouverson I m glad to see that my article Forth in Search of a Job FD XV 1 drew some response Regrettably I seem not to have communicated all that well because Elizabeth Rather spent a lot of time and effort ED XV 2 responding to the wrong issue The issue isn t that I m not especially bright and didn t do my homework The issue is that a very large portion of Forth s potential customer community behaves as if they are rather slow and don t do their homework Possibly corporate America is educable and educating them is worth trying But bear in mind we re dealing with people who for the most part believed until very recently that PCs would never replace their godawful mainframes They are not long on insight or foresight Education if it s possible may take many years Ms Rather s reply consists mostly of anecdotal evidence of Forth s great worth I
99. performs no range checking so either make your own or be careful 0 xmax ymax The PIXEL command works like PIXEL except a flag is returned instead of the pixel being set PIXEL selects a bit then tests it When the pixel tested is zero we say it is lit or true Otherwise PIXEL returns false Finally we have filename buffers and rather uninterest ing test code TEST1 fills an entire Paintbrush page with black pixels in about twenty five seconds on my system PIXEL x y flag 0 xmax ymax TEST2 TEST3 and TESTA draw lines T1 sets the filenames buffers and loads an image GBS is set to a blank page previously created in Paintbrush while PBS is set for keeping results These tests were used to verify PIXEL and oddly enough GET IMAGE and PUT IMAGE Strangely I still haven t completely figured out HS Forth s SEGMENT com Forth Dimensions HARVARD SOFTWORKS NUMBER ONE IN FORTH INNOVATION 513 748 0390 P O Box 69 Springboro OH 45066 You already know HS FORTH gives more speed power flexibility and functionality than any other implementation After all the majority of the past several years of articles in Forth Dimensions has been on features first developed in HS FORTH and many major applications discussed had to be converted to HS FORTH after their original dialects ran out of steam Even public domain versions are adopting HS FORTH like architectures Isn t it time you tapped into
100. pment of Forth marketing tools which have been sorely lacking Non profit groups using those tools to generate broad spectrum interest in Forth could in turn refer new inquiries to the Forth companies that supported the marketing effort And companies that routinely provide FIG literature and mail order forms to their customers could receive preferred placement or special discounts on advertising in FIG publications There would be other less tangible but equally beneficial results from more cooperation Understanding each other better learning from each other s vision of Forth and developing a consistent way of talking about Forth s advantages could create a stronger community and would provide leverage for making Forth s viability obvious to those we wantto reach with our respective messages and products But traditionally there have been obstacles to such cooperation Vendors sometimes have objected to FIG s distribution of free Forth systems The best response I know is that FIG cannot provide the quality control documentation technical support custom programming and other services customers expect of commercial grade systems As any competitive business knows success is based on much more than possession ofa product regardless of its quality Seen this way FIG provides entry level systems to those who aren t convinced or who don t yet need to invest in a commercial product and experimental ones that are otherwise unav
101. r example pushes its func tion parameters on the stack from right to left so that in this example y x GETPIXEL corresponds to getpixel x y The final term in the EXTERN expression _getpixel in the example is the actual external refer November 1993 December REC SIGNATURE b OBUF initialize buffer BUFC signature byte 0 BUF placeholder for length CHKSUM 0 BUFC fake irrelevant checksum WR REC RECBUF REC HERE OVER REC FBUF Q addr len fbuf WRITE RECLEN calculate and store record length in record REC HERE RECBUF 3 RECBUF Q 1 WR REC CHKSUM length of record after count RECLEN WR REC gt write record Screen 17 SAVE OBJ RECORD TYPES THEADR LNAMES MODEND RA 29DEC92 HEX WR THEADR 80 REC SIGNATURE BUF FORTH WR REC WR LNAMES 96 REC SIGNATURE BUF BUF FORTH TEXT WR REC WR MODEND 8A REC SIGNATURE 00 BUFC WR REC signature byte amp space for length content of field a counted string do count and fake checksum amp BUF CODE Screen 18 SAVE OBJ RECORD TYPES SEGDEF HEX WR SEGDEF class index seg index len ACBP 98 REC SIGNATURE BUFC ACBP 62 relocatable para aligned no combine 22JAN93 RA 29DEC92 BUF 0000 64K segment BUFC segment name index These indexes refer to BUFC class name index names in the LNAMES 1 BUFC overlay name index ignored WR REC
102. record WR CODE writes memory directly to the file When WR CODE begins MEMP is set to zero CUR XLINK is set to the contents of 18 T XLINK the first EXTERN and XREF is set to one the index of the linker name associated with the first external reference in the EXTDEF record The variable SEG INX is also set to one to point at the first SEGDEF record since this is the one associated with the memory segment we re writing out to the OBJ file Then WR CODE executes WRLCODEREC in a loop During each pass through the loop CUR XLINK either points at a link or it does not indicated by a value of zero Forth Dimensions If not WR1CODEREC writes a record containing a maximum 1K from memory it may be less if it s the last record starting with the address pointed to by MEMP Before it writes the record WR1CODEREC knows its length so it can write the first three bytes of the record then the 1K or smaller body then the fake checksum This allows the record buffer to be relatively small even though many records will be 1028 bytes If on the other hand there are EXTERNS left to write MEMP either points to the patch address of the next one or it does not ITMEMP has reached a patch address WRICODEREC writes a four byte LEDATA record filled with zeros followed by a FIXUPP record then calls NXT XLINK to advance CUR XLINK and increment XREF otherwise WRLCODEREC writes a record similar to the one described above 1K or l
103. rt TurontAL Lesson 7 Where Do You Go From Here C H Ting San Mateo California This series of tutorials has only scratched the surface of Forth and F PC Its goal is to expose you to a very minimum set of Forth instructions so that you can start to use Forth to solve practical problems in the shortest possible time What is intentionally neglected is why and how Forth works as a language and as an operating system in addition to a host of topics about various features of Forth and F PC There are different directions you may proceed from here depending upon your needs and interests 1 For the practical engineer the next logical step is to work on The Forth Courseby Dr Richard Haskell In fact this tutorial was developed to complement The Forth Course which skims too fast over the elementary Forth instructions and dives too quickly into the advanced topics of an upper level college microcomputer laboratory The Forth Course is available from Offete Enterprises for 25 2 If you are more interested in Forth as a programming language and want to learn more about the language aspects of Forth you will enjoy Leo Brodie s books on Forth Starting Forth Prentice Hall 1982 Thinking Forth Prentice Hall 1984 These two books are classics in the Forth literature and are pleasant reading The only problem is that some of the code examples might not work in F PC without modification because of the difference between the block
104. rth Interest Group at 40 per year 52 overseas air For mem bership change of address and to submit items for publication the address is Forth Interest Group P O Box 2154 Oakland California 94621 Administrative offices 510 89 FORTH Fax 510 535 1295 Advertising sales 805 946 2272 Copyright 1993 by Forth In terest Group Inc The material con tained in this periodical but not the code is copyrighted by the individual authors of the articles and by Forth Interest Group Inc respectively Any reproduction or use of this periodical as it is com piled or the articles except repro ductions for non commercial pur poses without the written permis sion of Forth Interest Group Inc is a violation of the Copyright Laws Any code bearing a copyright no tice however can be used only with permission of the copyright holder The Forth Interest Group The Forth Interest Group is the association of programmers man agers and engineers who create practical Forth based solutions to real world needs Many research hardware and software designsthat will advance the general state of the art FIG provides a climate of intellectual exchange and benefits intended to assist each of its mem bers Publications conferences seminars telecommunications and area chapter meetings are among its activities Forth Dimensions ISSN 0884 0822 is published bimonthly for 40 46 52 per year by the Forth Interest Grou
105. s equivalent to alb c while a I b c is equivalent to alb c Usually certain shorthands are available to simplify the con struction of regular expressions 1 Ifaregular set consists only of strings of single characters an abbreviated regular expression may be constructed by con catenating the strings and enclosing the resulting string in square brackets Thus the set a b c may be symbolized by abc which is equivalent to the regular expression aiblc The resulting regular expression is called a character class 2 If certain characters in a character class form a run in the alphabet i e abcedfg the class may be further con densed by substituting the metacharacter for the intervening characters i e a g is equivalent to abcedfg 3 Since the alphabet is finite the complement of a character class i e all strings of one character not in the regular set of the class is also a regular expression and a character class This is symbolized by inserting the metacharacter as the first character in the class For example abc is a character class corresponding to all the characters in the alphabet except a b or c 4 The metacharacter when prepended to a regular expres Sion matches the beginning of a line The metacharacter when appended to a regular expression matches the end of a line 5 The metacharacter is a character class that consists of all characters in the alphabet except
106. s technique But like the checksums in the OBJ records this one doesn t seem to matter except perhaps to virus checking programs The second problem is that you can t use LZEXE or EXEPACK or any other EXE file compression programs on the EXE file and hope to save the Forth image back into it 7 More Implementation Details A couple of implementation peculiarities of Kelly s Forth Forth Dimensions are encapsulated in the words SET BOOT and GET MSGS The boot up values of LATEST FENCE DP and VOC LINK are stored in low Forth memory in this implementation If they are not set before the image is saved nothing compiled since the previous save will be available when the file is re loaded The words will be in memory but nothing will point to them so they won t be found This can be a useful feature you can for example execute SET BOOT before you compile the code to save the system which will then effectively be discarded by the save However for what I like to think of as simplicty and clarity I have chosen to include SET BOOT in SAVE OBJ and SAVE EXE The other implementation peculiarity GET MSGS is more interesting in the current discussion because of the problem it caused and the solution I found In Kelly s FORTH COM the system messages are in the FIRST block buffer As part of the boot up process the contents of this block buffer actually the first half of it are moved to just beyond the 64K boundary from where they
107. s utility is called lex 1 It is normally used in conjunction with the yacc D parser generator because the lexical elements of a program ming language the words things like identifiers or opera tors can usually be easily represented as regular expres sions lexis a programming language in its own right It can be called a non procedural programming language Instead of a linear sequence of statements or procedures lex uses a list of independent pattern action pairs These patterns are regular expressions and the actions are C statements that more often than not operate on the strings that match the regular expression A program for lex consists of three sections a definitions section a lex language section and a literal section The definitions and literal sections don t have to be present in the file The definition section can be usedto declare frequently used regularexpressions and what are known as start states which will be discussed later The literal section is called that because everything in it is copied verbatim to the output file The language section consists of the set of pattern action pairs lex generates a scanner that will look for the patterns in the input stream and when it finds one it executes the associated action The definitions section of exis an outgrowth of the fact that it is easier to remember and easier to type Ident rather than a zA Z _a zA Z0 9 the
108. sages however you need to ensure that other elements are present An essential factor is newsworthiness or timeliness The element of newsworthiness might be a company milestone such as reaching one million in sales revenue for the first time It might be a promotional event such as an opening celebration after moving into a new facility Often it will be a new product or service that you offer Press releases should also create a trail of product milestones reached A product milestone could be hitting a sales target such as 5 000 000 cheeseburgers sold it could be a market share target such as Apple exceeding IBM in terms of sales market share for one quarter or it could be a performance breakthrough such as the San Francisco Chronicle s ability to publish an earthquake version of their newspaper using backup emergency power only As a reader of press releases I look for a timely element first discarding anything that doesn t have one I have been befuddled by press releases that are little more than product brochures and price lists Without any milestone event a news release is not the news its name would imply If you include coverage of old products with new products you probably reduce your chances of getting press coverage rather than increase them Don t be greedy If you can obtain a paragraph of coverage for a new product and one line mention of existing products or services you have fared well You help immensel
109. stview Drive San Jose California 95117 Proguet Watela SEPTEMBER 1993 FORTH Inc announced a new release of its EXPRESS Event Management and Control System for process control and factory automation applications It features high speed I O scan rates and improved connectivity A new Modbus Plus driver helps achieve scan times under 10 ms The graphical user interface in EXPRESS makes it a comprehensive development system without add on prod ucts Its appearance is similar to that of the OSF Motif standards Like other parts of the development system the GUI is event driven Rules allow events to be generated and handled Rules are similar to C switch statements Constructs of this kind let you implement the state machines that serve most embedded applications Companies Mentioned FORTH Inc 111 N Sepulveda Blvd Manhattan Beach California 90266 6847 Fax 213 372 8493 Phone 800 55 FORTH 43 November 1993 December Following Thanksgiving November 26 November 28 1993 Asilomar Conference Center Monterey Peninsula overlooking the Pacific Ocean Pacific Grove California U S A Theme Forth Development Environment Papers are invited that address relevant issues in the establishment and use of a Forth development environment Some of the areas and issues that will be looked at consist of networked platform independence machine independence kernel independence development system application system ind
110. t it contains a long call to segment offset 0000 0000 which won t work very well if the word is ex ecuted before it s linked While itis laying down code CODE EXTERN consumes the two stack parameters already mentioned and saves two addresses on the stack the address of the beginning of the code word and the address of the null long call The second part of EXTERN CREATE EXTERN creates an extended header for the word being defined The word HEADER in Kelly s Forth is a factor of CREATE and does everything CREATE does except lay down the CFA It can be replaced by CREATE 2 ALLOT for port ability After the header is the CFA which for a code word in an indirect threaded Forth contains the address of the executable code Normally this code immediately follows the CFA so the CFA can be com piled by the phrase HERE 2 For these EXTERNS however the executable code has already been laid down Its address is on top of the stack at this point and can be com piled by comma After the CFA there are two more fields the patch address passed to CREATE EXTERN by CODE EXTERN and the linker name for the EXTDEF record of the OB file which is parsed out of the input stream by WORD The linking of the list of EXTERNS is straightforward Variables point to the first and last elements in the list each element in the list points to the next and each time a new elementis added LAST XLINK anda pointer in the prev
111. tation from all 4 xx revisions is 99 and from older systems 149 The Tools amp Toys update is 15 shipping 5 US 10 Canada 22 foreign Forth Dimensions 29 HS FORTH runs under MSDOS or PCDOS or from ROM Each level includes all features of lower ones Level upgrades 25 plus price difference between levels Source code is in ordinary ASCII text files HS FORTH supports megabyte and larger programs amp data and runs as fast as 64k limited Forths even without automatic optimization which accelerates to near assembler language speed Optimizer assembler and tools can load transiently Resize segments redefine words eliminate headers without recompiling Compile 79 and 83 Standard plus F83 programs PERSONAL LEVEL 299 NEW Fast direct to video memory text amp scaled clipped windowed graphics in bit blit windows mono cga ega vga all ellipsoids splines bezier curves arcs turtles lightning fast pattern drawing even with irregular boundaries powerful parsing formatting file and device I O DOS shells interrupt handlers call high level Forth from interrupts single step trace decompiler music compile 40 000 lines per minute stacks file search paths format to strings software floating point trig transcen dental 18 digit integer amp scaled integer math vars A B IS C compiles to 4 words 1 4 dimension var arrays automatic optimizer delivers machine code speed PROFESSIONAL LEVEL
112. th in this PUBDEF record and let Forth start immediately when the EXE file is loaded The problem with this is it doesn t allow C to perform its initalization correctly and some C functions don t quite work The fact that it makes the MODEND record more difficult to construct is only a minor inconvenience The LEDATA logical enumerated data and FIXUPP records occur together The LEDATA records contain the actual code the contents of the Forth image in memory at the time they are written out This is where our activity most differs from that of a C or other language compiler we re writing code out of memory code that for the most part is actually running while it s being written rather that merely translating text from a source code file The maximum amount of object code one record can contain is 1K so we could write it out as 64 1K blocks if it weren t for the patch addresses we want the linker to resolve Simplicity is a practical virtue the method I ve adopted is to write two kinds of LEDATA records pure object code records which can be up to 1K in length and have nothing to resolve and pure fix up target records which are always four bytes long and all zeros Each fix up target LEDATA record needs to be followed immediately by a FIXUPP record The FIXUPP record type has twelve pages in the MS DOS Encyclopedia with a fairly bewildering variety of options We need only one FIXUPP records can contain thread fields and
113. written in C saved the Forth memory image containing these references as an object module OBJ file and linked that module using Borland s TLINK with C libraries and object modules into an EXE which when run makes those functions available as normal Forth words At the end of this process I have a FORTH EXE which I can extend with further external functions via the linker but also via normal Forth incremental compilation without the linker 1 The Source Forth Every Forth system is idiosyncratic especially at the edges and this topic is pretty edgy The relationships to the operating system to extended memory and to the native machine language of the real machine as opposed to the Forth pseudo machine are not and cannot be made standard The particular Forth I begin with here conforms closely to the Forth 83 Standard having been written as a teaching tool by Guy Kelly the chair of the Forth Standards Team but it of course has certain extensions For memory access outside the 64K Forth segment I assume the existence of the following semi standard words with these stack pictures GL seg offset n CQL seg offset c L n seg offset C L c seg offset CMOVEL source seg source off dest seg dest off len I also assume the existence of a few utility words like CSQ DS and ESQ trivial to define in assembler or directly in machine code with C which push the contents of the segment regist
114. x Q C CY S O Ty M QD E e Volume XV Number 4 10 SILICON COMPOSERS INC FAST Forth Native Language Embedded Computers Harris RTX 2000 16 bit Forth Chip 8 or 10 MHz operation and 15 MIPS speed 1 cycle 16 x 16 32 bit multiply 1 cycle 14 prioritized interrupts two 256 word stack memories 8 channel 1 O bus amp 3 timer counters SC FOX PCS Parallel Coprocessor System RTX 2000 industrial PGA CPU 8 amp 10 MHz System speed options 8 or 10 MHz 32 KB to 1 MB O wait state static RAM Full length PC XT AT plug in 6 layer board SC FOX VME SBC Single Board Computer RTX 2000 industrial PGA CPU 8 10 12 MHz Bus Master System Controller or Bus Slave Up to 640 KB O wait state static RAM 233mm x 160mm 6U size 6 layer board SC FOX CUB Single Board Computer RTX 2000 PLCC or 2001A PLCC chip System speed options 8 10 or 12 MHz 32 KB to 256 KB O wait state SRAM 100mm x 100mm size 4 layer board SC32 32 bit Forth Microprocessor 8 or 10 MHz operation and 15 MIPS speed 1 clock cycle instruction execution Contiguous 16 GB data and 2 GB code space Stack depths limited only by available memory Bus request bus grant lines with on chip tristate SC FOX SBC32 Single Board Computer32 32 bit SC32 industrial grade Forth PGA CPU System speed options 8 or 10 MHz 32 KB to 512 KB 0 wait state static RAM 100mm x 160mm Eurocard size 4 layer b
115. y This method isn t difficult at least on the Forth side and it can be useful in some situations but basically it s just a way Nothing is portable except ideas in C Forth or for that matter life around the fact that most Forths can t link Another method is to write Forth in C or assembler or some other language and link the desired external functions at the beginning or add them later by recompiling Forth has in fact often been written in assembler either as a way of bootstrapping or in the perhaps mistaken idea that assembler is easier or more transparent than meta compilation It would be easy to extend these Forths through the linker One problem is that this method makes it impossible to add new external references withoutstarting again from the assembler source another is that once you ve appropriated external functions it is difficult to save and reload the Forth image without going through the linker step all over again As a consequence you have to keep the LIB or OBJ files containing the object code for the appropriated functions in your working environment and take them with you when Forth Dimensions you travel with your system to another machine A third method the one I shall discuss is to start not with assembler or C but with Forth itself I have taken a straightforward single segment indirect threaded 83 stan dard Forth addeda variety of external references to functions
116. y if you separate your coverage of a new product from your coverage of established products You should at least treat old products differently than new ones I suggest that you limit their discussion to one paragraph Similarly offer distinctly different treatments for a product upgrade and a new product introduction If one follows on the heels of another consider generating more than one press release perhaps a press release for each product that is new or upgraded If a product is complex due to its having many optional components be absolutely clear about what comes and what doesn t come with each product package If one quick reading does not accurately convey the various forms the product can take it s not ready for general consumption Test your press releases and product sheets and brochures by letting someone who is not acquainted with your products read the release then asking them to tell you about your products configurations and options If your information is unclear you can hardly lay claim to Forth Dimensions its being released in a form that can be distributed and still be a service to readers Review Insider s Guide to Getting Your Press Releases Published This slim guide about press releases has been prepared by Win Win Marketing whose mission is to provide market ing advice to small businesses Although they are intended to illustrate various types of press releases the sample press rele
Download Pdf Manuals
Related Search
Related Contents
C165 / C167 AP16032 Kenwood TM-271A Mod for PL Decode Logic Out Astrid Lindgren - Notes du mont Royal Roland VC-300HD TV Converter Box User Manual DeLonghi DBL740 Work Top Blender Réfrigérateur Extrait Copyright © All rights reserved.
Failed to retrieve file