(INTRO TEXT FOR SCREEN ZERO BDK112186)***************************************************************************************************************************************************************************************************** *********** F83 TUTOR AND HELP PROGRAM *********** F83 TUTOR AND HELP PROGRAM *********** *********** *********** Written by Bill Kibler *********** PO BOX 487 Cedarville, CA 96104 *********** *********** ALL Commercial rights reserved *********** **************************************************************************************************************************************( LOAD BLOCK AND START OF TUROR PROGRAM BDK012387) 53 load 23 tree 15 spaces .( PLEASE WAIT WHILE LOADING TUTOR SCREENS..TUTOR.BLK ) CR CR CR CR CR ( variables and display routines ) VARIABLE ETUTOR ( END DISPLAYING TUTOR SCREENS ) VARIABLE STUTOR ( BEGINING SCREEN OF CURRENT GROUP ) VARIABLE NTUTOR ( NEXT TUTOR SCREEN OF GROUP ) : L$$K DUP 36 = IF 1 ETUTOR ! THEN ; ( CHECK FOR $$ ) : DISPLAY ( DISPLAY SCREEN OF TEXT ) 1 ?ENOUGH DUP SCR ! L/SCR 1 DO 5 SPACES DUP BLOCK I C/L * + C/L TUCK PAD SWAP CMOVE PAD SWAP ( >TYPE WITHOUT THE TYPE ) 0 ?DO DUP C@ L$$K EMIT 1+ LOOP DROP ( TYPE WITH L$$K ) CR KEY? ?LEAVE LOOP DROP ; --> ( go get screens of information - gotutor tutor bdk012387): WTPRT ." CURRENT SCREEN IS " SCR ? 2 SPACES ." ESC = EXIT " 2 SPACES ." USE SPACE BAR FOR NEXT SCREEN " ; : ESCCHK DUP 27 = IF 1 ETUTOR ! 32 THEN ; ( SET ESC FLAG ) : WAIT WTPRT 13 EMIT ( PRINT THEN CR WITHOUT LF ) BEGIN KEY ESCCHK 32 = UNTIL ; ( LOOP TIL SPACE KEY ) : GOTUTOR ( DISPLAYS SCREEN ON STACK THEN WAITS ) CR DUP SCR ! 15 SPACES .SCR CR BEGIN DISPLAY WAIT NTUTOR @ 1 + DUP DUP NTUTOR ! 1 ETUTOR @ = UNTIL CR CR 3 SPACES ." REPT = REPEAT LAST LESSON ...GET = NEXT LESSON " ." MENU = MENU " CR CR CR ; : TUTOR ( STORE SCREEN POINTERS THEN GOTUTOR ) 0 ETUTOR ! DUP DUP STUTOR ! NTUTOR ! GOTUTOR ; --> ( INITIALIZE AND START THE LOOPS..GET..REPT.. bdk012987) : GET ( GO GET NEXT GROUP OF SCREENS ) NTUTOR @ TUTOR ; : REPT ( GO BACK AND REPEAT SET OF SCREENS ) STUTOR @ TUTOR ; : START-TUTOR ( START WITH FIRST SCREEN OF TUTOR ) 10 TUTOR ; : HELP ( GIVE INTRO MESSAGE ) 6 TUTOR ; --> ( DEFINING MODULES OF INFORMATION..... bdk012387): INTRO 10 TUTOR ; : CHP1 12 TUTOR ; : CHP2 18 TUTOR ; : CHP3 25 TUTOR ; : CHP4 34 TUTOR ; : CHP5 40 TUTOR ; : CHP6 48 TUTOR ; : CHP7 55 TUTOR ; : CHP8 66 TUTOR ; : CHP9 73 TUTOR ; : CHP10 84 TUTOR ; : CHP11 92 TUTOR ; --> ( MORE ROOM FOR LESSON WORDS.... bdk012387) : MENU 9 DISPLAY ; ( will display infor screen ) : PRTSCR CR ." CURRENT GET SCREEN IS " NTUTOR @ . CR ." REPT SCREEN OF INFORMATION IS " STUTOR @ . CR ; HELP ( PRINT SCREENS FOR TUTOR INFORMATION... bdk012887) FORTH-83 TUTOR PROGRAM AND HELP SCREENS WRITTEN BY BILL KIBLER (c) 1987 ALL COMMERCIAL RIGHTS RESERVED This program will help beginners and past FORTH users alike. The screens contain information on FORTH-83 and are related to the book " STARTING FORTH " by Leo Brodie, which should be used as a textbook with this program. Each chapter or series of screens is organized to present the words used in the chapter in a glossary form. Forth users will find this glossary important to see the differences between F83 and other versions. Typing HELP will repeat these screens, then type ( second intro screen with list of words... bdk012887)the chapter number for the area of help needed. Typing ESC key will exit the screens and return to the system prompt. GET willdisplay next chapter of information, while REPT will start with the first screen of the chapter again. START-TUTOR will start with the introduction chapter. NEW F83 WORDS The following words are important utilities in F83 and may be different from previous versions. WORDS will display a list of F83 words used. OPEN allows use of an existing file, 10 MORE is used to add 10 screens, and 30 CREATE-FILE NAME.BLK (opens 30 screens). INDEX displays a list of line 0, 1 20 INDEX will list screens 1 to 20. 1 30 SHOW will print 6 screens to a page on your printer in condensed mode ( use: ' EPSON IS INIT-PR for epson printers). 1 30 TRIAD prints three to a page if condensed print is not available. 1 30 SHADOW SHOW will print both the ( THIRD PRINT SCREEN OF TUTOR INFORMATION..... bdk013087)regular screens and the information screens on a page (not used in TUTOR but in UTILITY.BLK). SEE xxxx disassembles the word xxxx, while VIEW will open the source file ( on A: drive) and list the screen it is in. VOCS will list the vocabularies in the dictionary, while ORDER displays the path of the directory search. Use DOS WORDS to see a list of the DOS dictionary words.CAPACITY will print the number of screens in a open file. A L will toggle between the shadow and the source screens. N L will display the next screen, L will list current screen, B L will list previous screen. 1 EDIT will invoke the line editor with screen 1 ready to edit. 0 NEW will start editing at line 0 and allow the text to be entered one line after the other. HEX 100 80 DUMP will do a hex dump of memory location 100h to 180h. DEBUG LIST will allow stepping through list when used next as in 1 LIST. Use BYE to exit to DOS. ( last intro screen with list of words... bdk013087) TUTOR WORDS INTRO = introduction CHP1 = fundamentals CHP2 = RPN and STACK CHP3 = editor commands CHP4 = conditionals, nests CHP5 = fixed point operations CHP6 = loops ( & nested) CHP7 = number types CHP8 = var. const. arrays CHP9 = F83 structure CHP10= Input/Output CHP11= extensions GET = next chapter REPT = begin chapter again HELP = repeat these screens START-TUTOR = start at INTRO SPACE BAR = next screen ESC = stops display BYE = EXITS to DOS MENU = displays this screen PRTSCR = GET and REPT pointers $$ (forth tutor program introduction to brodie.... bbdk011687) INTODUCTION Forth is a stack oriented language, a hardware independent programming language and operating system. F-83 is based on the Forth-83 Standard with enhancements to make it a full operating environment. F-83 contains the Forth-83 word set, plus words for debugging, editing, disassembly, assembly, DOS functions and a multitasking system. The F-83 system is available on all standard computers currently being manufactured; providing a complete set of portable system utilities that are independent of hardware. Use this tutor program to learn F-83 and the differencesbetween this version and past or commercial versions of Forth. HELP will display a summary of information about F-83 and this tutor program. ( second intro to brodie... bdk011687) This tutorial uses the well known and popular text "STARING FORTH" by Leo Brodie. Many references are made to the text and it should be used to obtain detailed information about Forth. The program does not cover everything about F83, but only attempts to provide on line help information and instruction. There are two versions of "STARTING FORTH" currently being used. The first edition did not contain any reference to F83 and was printed before 1982. This tutorial will help people withthe first edition see the differences between FIG, Forth-79 and the new F83 (Forth-83). The second edition is mostly the same information with changes for the newer Forth-83. Some minor text changes have been added to improve the understanding of some terms. All the other changes are related to the new or different commands used by F83 or contained in the Forth-83 standard. $$ ( chapter 1 intro to stack operation bdk012887) GLOSSARY OF CHAPTER 1 : xxx yyy ; ( - ) Creates word xxx which does word yyy CR ( -- ) Do a carriage return and line feed SPACES (n -- ) Print n number of spaces SPACE ( -- ) Print one blank space EMIT (c -- ) Transmit a character to output device ." zzz" ( -- ) Print the output string zzz at terminal + (n1 n2 -- sum) Adds n1 to n2 and leaves sum on stack . (n -- ) Print number on top of stack followed by space ( xxx) ( - ) Comment, ignored by the text interpreter TERMS IN CHAPTER 1 COMPILE To generate a dictionary word DICTIONARY Forths list of words or operations EXECUTE To do the operations a word stands for EXTENSIBILITY Ability to modify, add or change words ( CHAPTER 1 MORE WORDS AND TERMS bdk011987)GLOSSARY A list of words defined and explaned in Forth terms INFIX NOTATION Using operators between operands INPUT STREAM Text to be read by TEXT interpreter INTERPRET To compare input text to FORTH words LIFO Last In First Out..how the stack works POSTFIX OPERATION The way FORTH operates..RPN STACK A section of memory used as a data stack STACK OVERFLOW Stack operations used all allocated stack STACK UNDERFLOW Operations tried to read data from empty stack WORD The name of a FORTH definition CHAPTER 1 FUNDAMENTAL FORTH FORTH has two main features, EXTENSIBILITY and INTERACTION. New functions are added to the language by creating new words and adding them to the dictionary of existing words. This ( chapter 1 continued fundamentals bdk012887)operation is called extending the dictionary, and thus the term "extensibility". As each new word is created it can be used immeadiately to see if it functions properly. This instant adding and execution of the word is the reason behind the term "interactive". When Forth is waiting for your input, your terminal will have displayed "ok" on the previous line. This means the interpreter is waiting for your next input. That input can be a direct command such as 42 EMIT which will output the ASCII character * (star) to your terminal. To make a new word for the dictionary, you need to follow the definition structure, this is a colon (:), a space, the name of your word (star), a space, the definitions, a space, and lastly a semicolon indicating the end of the word. Follow the semicolon (;) with the return key and the action you have ( more fundamentals of forth..chapter 1 bdk011287)defined will take place. FORTH is stack oriented, the input string is processed and input which is not a defined word, is assumed to be a numeric input and is pushed onto the stack. Numbers are pushed until a word is found, where upon the functions defined will be performed on the numbers on the stack from the top down. In the line 2 4 + . we have the numbers 2 and 4, a plus signto add the two number on the stack, and a period which prints the top value on the stack. This means 2 is pushed first, then 4 is on top, the + sign is interpreted and Forth adds the 2 and 4 getting 6, and places six on the stack. The next command, the . removes the 6 from the stack and converts it to the ASCII equivalent, before outputting it to the screen. The screen can not print numbers directly, but there is a standard number whichis used to represent the number 6, this is ASCII number 54. ( more fundamental forth chapter 1 bdk011987) To display the manner in which your word handles the stack a standardized convention is used. The ( n1 n2 -- sum ) is used to indicate that the first number ( n1 ) is push on the stack first, followed by n2, the second number. Forth then ( -- ) reads the word and performs the function, placing the results ( sum ) on the stack. The right most item is the one currently on top of the stack, or you read from left to right which corresponds to bottom of stack to the top. This has been a brief summary of fundamental forth as was presented in "Starting Forth", please study it for more details.You can now try some of the samples listed in the book, just wait for the "ok" prompt after you hit the space bar again. Try inputting the line displayed below, to define the new word GREET : GREET CR ." HELLO, I SPEAK FORTH " ; ( space for more work problems.... bdk012187) Create a word that asks for your name. ( $$ ) ( chapter 2 glossary of new words... bdk010587) GLOSSARY OF CHAPTER 2 + (n1 n2 -- sum ) adds two stack items, leave sum on top - (n1 n2 -- diff) subtract n2 from n1, results on top * (n1 n2 -- prod) multiplies n1 times n2 / (n1 n2 -- quot) divides n1 by n2, quotient on top /MOD (n1 n2 -- u-rem u-quot) divides and leaves quot on top, remainder below it MOD (n1 n2 -- u-rem) divides and leaves only the remainder SWAP (n1 n2 -- n2 n1) swap the order of the top two items DUP (n -- n n) make the top two items the same OVER (n1 n2 -- n1 n2 n1) copy second item on top of stack ROT (n1 n2 n3 -- n2 n3 n1) puts third item on top of stack DROP (n -- ) throw away top stack item 2SWAP (d1 d2 -- d2 d1) swap the top two PAIRS of numbers 2DUP (d -- d d) duplicates the top PAIRS of numbers ( chapter 2 more words and start of text bdk010587)2OVER (d1 d2 -- d1 d2 d1) copy second PAIR, push on top 2DROP (d -- ) drop the top PAIR of number off of stack TERMS IN CHAPTER 2 DOUBLE LENGTH NUMBERS Twice the length of the hardwares normal word length. In 16 bit words that would be a 32 bit number and typically is a value of plus or minus 2 Billion SINGLE LENGTH NUMBERS The normal length of words used by this version of Forth, typically -32768 to +32767. These are intergers or whole numbers (no decimal points allowed) ( review of chapter 2 subjects and text bdk011687) Chapter 2 How to get results Forth arithmetic is similar to a number of calculators one can buy. These calculator are usually called RPN or Reverse Pollish Notation calculators. They operate on a stack type structure and require at least two items on the stack before you can add, subract, multiply, or divide. Forth uses the + (plus) sign for addition, - (minus) sign for subtraction, * (star) for multiplication, and / (slash) for division. These procedures are used with interger math, or whole numbers only. On most Forths these are +32767 to -32768. This interger math requires some thought on the users view point. Numbers larger than these require other words or double length operators, which are covered in chapter 7. For now lets look at using whole numbers in division. ( chpt2 text continued div mul bdk011287) Interger math requires more than one step when dividing. Whathappens is the results and the remainder are treated as two separate whole numbers. The operation 20 4 / will divide 4 into 20 and produce the whole results 5. 22 4 / will also produce the same answer 5, the remainder 2 is lost. If we use 22 4 MOD we get remainder only 2. To get both the results and remainder you can use /MOD as in 22 4 /MOD puts 5 on top of the stack the remainder below it. Remeber the . will print the top stack item and make the second item the top element. In most math operations there is a means of specifing the order of operations. With forth being stack oriented order is determined by placement in the stack. A infix presentation of 4+(17*12) would be presented in forth as 17 12 * 4 + . with 208 being displayed. Numbers are pushed onto the stack while the operators are performed in a left to right manner. We see ( chptr 2 continued order and swaps... bdk011287)that 4 17 12 * + is the same as the previous problem. The * is performed first on the top items (17 and 12) then the + is used on the top (204) element and the second, now 4. The . will print the results of 208. There are several ways of handling the stack order and makingchanges to it. If you want the results of a math operation to beprinted but still available for the next operation, you DUP the results before printing it. DUP takes and pushes the top item on the stack down one and makes a copy of it on the top of the stack. OVER will make a copy of the second item and place iton the top, or DUP the second item. To reverse the top two itemson the stack you would use SWAP. To get the third item on top and make items 1 and 2 now 2 and 3 respectiviely you use ROT. Ifyou want to remove the top item we just DROP it off the stack. Later on we will deal with double length number (larger than ( last chapter 2 with sample problem bdk012187)32768), we also have double word or item operators, these are 2SWAP, 2DUP, 2OVER, 2DROP. These perform the same operation as their single counterparts, they just work on two stack items at a time. 2DROP will DROP the first and second items off the stack. For more samples of these operations check the book, or playaround with forth when you see the ok after this screen. Here are some sample problems: if a=4 and b=8 what is a*(a+b) there are two ways to do this if c=3 then evaluate ab - bc again two ways here too make a new word that will return the number of kilometers when the top stack item is number of miles. Try these problems or make up some of your own... ( problem space..... bdk011987) In this screen...number 24 ( $$ ) ( chapter 3 glossary for editor words bdk011987) CHAPTER 3 GLOSSARY ( EDITOR ) LIST (n -) Display screen n and make it current screen LOAD (n -) Load n screen and interpret into dictionary FLUSH SAVE-BUFFERS and de-allocate buffers in memory SAVE-BUFFERS Write all buffers to disk files ( also use W ) UPDATE Mark current screen for save to disk L Display current screen N L Display Next screen B L Display previous (Back one) screen A L Toggle between current and shadow screens T (n -) Make n the current line to edit P xxxx Put the string xxx in the current line U xxxx Insert the string xxxx under the current line K ( -) Exchanges the contents of insert and find buffers ( more chpt 3 glossary words...editor bdk011187)X Delete current line NEW (n -) Input multiple lines starting at n F xxxx Find and move to END of xxxx D xxxx Delete string xxxx and leave cursor at string TILL xxxx Delete all text from cursor to end of xxxx J xxxx Delete till begining of string xxxx EDIT (n -) Invokes editor on n screen EDITOR Makes the editor vocabulary current vocabulary DONE Do flush and return from editor vocabulary ED Return to editing current screen FIX xxxx Find xxxx in unknown screen and start editing it OPEN xxxx Open file xxxx.xxx and make it current file MORE (n -) Add n more screens to the end of current file COPY Copy screens from one file to another CONVEY Move screens around within file ( more glossary words..last screen of them... bdk011987)FORGET name Removes all word definitions back to name THRU (lo hi -) Loads all blocks between lo and hi inclusive TRIAD (n -) Print three blocks around n on a page SHOW (lo hi -) Print 6 blocks to a page in condensed mode VIEW name Find name in source screen and list it WIPE ( -) Blanks the entire screen when editing G ( blk ln -) Gets copy of line from block and insert above current line pushing lines down BRING ( blk lo hi -) GETS range of lines S xxx (n - n) Searches for xxx in blocks n up if found n on topLISTING name Print entire open file including shadows KT xxx Put all text between cursor and xxx in insert buffer O xxx Overwrites xxx onto text of current line SPLIT Breaks current line in two at the cursor JOIN Puts a copy of next line after the cursor ( review of chpt 3 terms bdk012887)QUIT Exit editor WITHOUT updating buffers to disk CHAPTER 3 TERMS ( EDITOR ) BLOCK The means of which files are divided, 1024 characters is one block (BLK) and is used as screens (SCR) in forthBUFFER Temporary space set aside in memory to hold BLKs or SCRsDISK A short term for floppy disk and data stored there EDITOR The forth vocabulary that contains words used by editor FIND BUFFER The buffer containing the find string INSERT BUFFER The buffer containing the insert string LOAD BLOCK The block which loads other blocks or screens NULL DEFINITION A word that has no action, a marker OVERLAY Data that will replace previous data or words POINTER A value or location that points to other data SOURCE TEXT The text which is the original definition of a word( chptr 3 text, information on editing bdk011987) CHAPTER 3 THE EDITOR Forth contains a built in line or screen editor. This editor is not like some commercial word processors, but more like the line editors which come with most operating systems. Forth stores all the source code for itself as plain text in screens. The plain text statements are compiled through a special META compiler to produce the F83 machine code program. Two files contain most of the source code for F83, they are UTILITY.BLK and KERNELxx.BLK. UTILITY contains the higher level utility functions which you use, such as the editor's source code. The KERNELxx contains all the screens necessary for making the main F83 kernel as would be used on xx processor. The xx stands for 86, a short way of saying 8088/86 CPU which is used in the IBM PC line of computers. ( chpt 3 continued editor / changing screens bdk011987) Suppose you want to change some printer directives, which are in the utility files. Currently F83 uses Epson printer codeswhen invoking condensed modes of printing. Your printer uses different codes from the Epson. To find the screen where this code is we use FIX EPSON, after the file has been opened using OPEN UTILITY.BLK. This will display the screen (44) which has the source code word EPSON, and position the editor after this word. You can now use the editor commands to change the control code invoked using the word EPSON. When you have made the changeDONE will exit the editor saving changes. Reloading the sytem will give you the new printer commands. Also you could have entered the minor changes directly from the terminal, but you would have to do this each time you loaded the system. In creating this tutor program, I have created a number of blank blocks by typing 30 CREATE-FILE TUTOR.BLK. This then ( more chpt 3 editor and editing files bdk011287)allows me to do 1 EDIT and start creating the source code for this program. The editor will then ask me for the ID........ and I will type my initials and current date. Becuse not all forths reconize the back slash as comment line I use the ) as mylast item in the ID line. I start my screen with 0 NEW and will type the first entry starting with a ( indicating a comment is next. At this point you can type text one line after the other, watching for the end of the line, the editor does not. 2 blank lines denotes end of NEW lines and you can then go back and correct any mistakes. Some samples of editing are; 3 T to select line 3 to edit. Using P NOW will put NOW on line 3. U NEXT will put NEXT on line4. If we type F T the cursor will be after the T on line 4. Now you can type I TIME and line 4 will have NEXTTIME on it. To get space between the Ts go 4 T again to get back to the begining of( more chpt 3 editing stuff... bdk012187)the line, then F again (no T needed, buffer still has it) and the cursor will be after the first T, do I with two spaces, thereturn will then put a space between the Ts. You can of course start a line with spaces or any items. The editor is not very fancy, but it is in most versions of forth, meaning once learnedyou can use it on any machine your forth is running on. The instructions in the text are similar and do cover the main commands used in most forth editors. F83 uses different commands to move screens around. To load screens from the utility file to this (which is already open and is the current file) you would type FROM UTILITY.BLK 1 10 COPY this will copy screen 1 of utility to screen 10 of TUTOR. Now to copy a string of files you use CONVEY, such as 11 HOP 1 6 CONVEY to copy screens 1 to 6 of TUTOR to 12 to 17 of TUTOR. The HOP means to jump over 11 screen from the first one and start the copying ( last screen of editing chpt 3... bdk012187)there. 1 6 TO 12 CONVEY does the same as 11 HOP. For moving screens between files, we would use the FROM UTILITY.BLK command(after the OPEN TUTOR.BLK) and then 1 20 TO 30 CONVEY and this will copy screens 1 to 20 of utility to 30 to 50 of tutor. You may need to do 20 MORE first, which adds 20 empty screens to thecurrently opened file. If you have made backups of the TUTOR.BLK files, now would be a good time to try editing. If you use 25 35 INDEX you will find out which screens are blanks and you could use one of them.The last screens are blank and ready for your playing around. Try creating some new words and then LOAD the screen, which willadd the words to the dictionary. Another way to find empty screens is 1 IND this will give the index or line 0 of each screen starting with 1 until end of file is reached or you hit the ESC key. Use QUIT if you dont want to save edits........ $$ ( chapter 4 glossary of decision words.... bbdk012887) CHAPTER 4 GLOSSARY ( DECISIONS ) IF xxx IF: (f -) If f is true execute xxx, otherwise do yyy ELSE yyy continue with zzz regardless, the ELSE yyy THEN zzz is optional. = (n1 n2 - f) Return a true flag if n1 and n2 are equal <> (n1 n2 - dif) Returns true if n1 and n2 are not equal < (n1 n2 - f) Returns true if n1 is less than n2 > (n1 n2 - f) Returns true if n1 is greater than n2 0= (n - f) Returns true if n equals zero 0< (n - f) Returns true if n is negative 0> (n - f) Returns true if n is positive NOT (f - f) Reverse the results of the last test (0=) AND (n1 n2 - and) Returns the logical AND of n1 and n2 OR (n1 n2 - or) Returns the logical OR of n1 and n2 ( chptr 4 more glossary and terms bdk011987)?DUP (n - nn) or (0 -0) Duplicate only if n is nonzero ABORT" xxx " Abort operation and print xxx error message (f -) also clear users stacks, if false no action XOR (n1 n2 -xor) Exclusive or, true if both n not true CHAPTER 4 TERMS ( DECISIONS ) ABORT Abruptly cease operation if procedure isn't acceptableAND Output is true if both inputs are true BRANCHING If input condition occurs jump to another routine COMPARISON Check and flag if two items are the same CONDITIONAL Different operation if flag true than when false FLAG A variable when set equals true, reset equals false LOGIC Using operators like AND, OR, NOT to make statements NESTING Branching routines within branching routines OR If either of two inputs are true the results is true ( chptr 4 text on decisions.... bdk012887) CHAPTER 4 DECISIONS, CONDITIONALS In any computer language, terms are used to express math forms and types. We like to compare items and say how one is larger or smaller than an other. You may also base an action on the results of such a comparison. Forth can also do the same types of comparisons. We can tell forth to do something IF some condition is met. The proper term for this is IF THEN statements. To help make these comparisons there are several operators we can use. They can be = for equals, < 2nd stack itemis less than top item, > 2nd item is greater than top item, 0= the top item is equal to zero, 0< the top is less than zero, 0> the top is greater than zero. All of these operations depend on setting a FLAG variable. This flag is a special indicator set as either true or false. ( chptr 4 more text..logic, decisions... bdk012887)IF THEN logic operations work by checking the flag to see if it is true or false. If true THEN do xxx ELSE if false do zzz. The IF statement can be any form of testing, including regular math operations. A sample math operation is comparison <> where if two items are the same, the results will be zero, and so the flag will be set false (treated as subtraction). There are non math operators that can do comparison based onlogic operations. These logic operators are AND, OR, and NOT. AND sets the true flag if both stack items are also true, OR if either stack items is true, while NOT reverses the flag setting.Forth has some words which contain conditional tests within themABORT" and ?STACK. ABORT" print the statement contained within the " " if the flag is set, leaves the current program and resets all stacks before the Forth ok. ?STACK flags true if the stack is empty, as when waiting for keyboard input. ( some chptr 4 samples/ problems bdk012187) Lets do a simple IF THEN routine to show the forth way of handling conditionals. Lets test to see if a pupil answers a question correctly when faced with four choices; : ckansw ( check the answer and prompt accordingly ) DUP 1 = IF ." WRONG" CR 12 TUTOR ELSE DUP 2 = IF ." CLOSE BUT REREAD QUESTION " ELSE DUP 3 = IF ." GOOD CHOICE " ELSE DUP 4 = IF ." BETTER LUCK NEXT TIME.. " ELSE ." ENTER VALUE OF 1 2 3 or 4 ONLY " THEN THEN THEN THEN DROP ; This new word CKANSW, checks the item on top of the stack to seeif it matches or equals the value we want. If it does, print thestatement and then continue checking unitl last "then" is used. When a non match occurs the prompt to enter a new value is now displayed. Try your own conditional program in SCR # 39..... ( some chptr 4 samples/ problems bdk011987) ( here it is for you to change or use ) : ckansw ( check the answer and promt accordingly ) DUP 1 = IF ." WRONG" CR 12 TUTOR ELSE DUP 2 = IF ." CLOSE BUT REREAD QUESTION " ELSE DUP 3 = IF ." GOOD CHOICE " ELSE DUP 4 = IF ." BETTER LUCK NEXT TIME.. " ELSE ." ENTER VALUE OF 1 2 3 or 4 ONLY " THEN THEN THEN THEN DROP ; ( $$ ) ( chapter 5 glossary and interger math bdk011987) CHAPTER 5 GLOSSARY ( INTERGER MATH ) 1+ (n - n+1) Adds one to n 1- (n - n-1) Subtracts one from n 2+ (n - n+2) Adds two to n 2- (n - n-2) Subtracts two from n 2* (n - n*2) Multiplies n by two (shift left ) 2/ (n - n/2) Divides n by two ( shift right ) ABS (n - |n|) Returns absolute value of n NEGATE (n - -n) Changes the sign of n MIN (n1 n2 - n-min) Returns the minimum n (either n1 or n2) MAX (n1 n2 - n-max) Returns the maximum n (either n1 or n2) >R (n - ) Place stack top item on return stack top R> ( - n) Load top of stack with top of return stack R@ ( - n) Make a copy of return stack, put on top of stack ( More chapter 5 glossary and terms bdk012887)*/ (n1 n2 n3 - n) Multiplies then divides (n1*n2/n3) */MOD (n1 n2 n3 - n-rem n-result) Get remainder, quotient on top CHAPTER 5 TERMS ( INTERGER MATH ) Double length intermediate result Steps within an operation in which the number size has twice the normal digits, inorder to minimize errors. Fractional arithmetic The handling of numbers without the decimal point, using whole numbers, and later returning the decimal point to its proper place. FIXED POINT can be used inplace of fractional, they mean the same. Floating point math Number containing the decimal point and requiring adjustments before use by a computer. ( chapter 5 terms and some text bdk011487)Parameter stack The main data stack which is used to pass data between operations of the forth machine. Generally referred to simply as STACK or data stack. Return stack The stack used by forth for keeping return addresses on during operations. Can be used for holding data from stack (parameter) only WITHIN a definition. Always referred to as RETURN STACK, never stack! Scaling The adjustment of floating-point numbers such that all number are represent as intergers and with the same relevant relationship in respect to the decimal point. ( chapter 5 text INTERGER MATH math bdk012887) CHAPTER 5 INTERGER MATH Forth has a number of words that help perform math operationsquickly and easily. All of these operations work on INTERGER MATH concepts, or interger numbers. Typically these are signed numbers between +32768 and -32767. To add numbers that have a decimal point we mentally multiply the number by a power of ten enter those numbers and then replace the decimal point after theoperation. Some versions of Forth contain routines that will do this for you, they are called floating point utilities. They canslow down Forth considerably and waste memory. Most Forth users prefer to use interger math for the speed and memory savings. There are two words that help make interger math easier */ (star slash) and */MOD (star slash MOD). These words perform a multiply and then a divide (MOD produces ( chapter 5 text fixed point bdk011987)a remainder). Scaling is the method used in forth to change a value so that it can be used in interger math. To use numbers we scale them before use, then rescale the results back into thesame ratio. We can use PI not as 3.1416 but 31416 10000 / and when used in a formula like PI * Dia for area we use */ as in 4 31416 10000 */ . and we get the area of a 4 foot circle. We have made the results of 4 * 31416 be 10000 time larger than in you would using PI as 3.1416, but by dividing our results by 10000 we return it to proper scale. PI however has more places than four shown and will produce some error. There are fractionswhich can represent a more accurate means of expressing this andother numbers, they are called rational approximations, here area few: PI 355/ 113, SQRT of 2 19601/13860, SQRT of 3 18817/ 10864, .001Deg./22-bit rev. 18118/21109. To find our answer to the area of a 4 foot circle use the ( chapter 5 more fixed point text bdk012887)values of PI: 4 355 113 */ . this will be more accurate than before. */ does not produce a remainder and the area of the lastproblem is more than 12 square feet. Using */MOD will provide the remainder as the second item on the stack. When using the remainder we can then see the difference between dividing by 10000 and using 355/113, which is .0736. For a more detailed andillustrated review of this topic check chapter 5 in STARTING FORTH. The return stack is used by Forth to store return addressesof definitions (semicolons). It can be used within a definition to help shuffle values around. A good example of that would be aproblem that uses a constant several times. Instead of dupping the number and a ROT or SWAP it may be faster to copy it to the return stack and make copies of it each time you need it. You must remember to clear the return stack by the end or ; . ( chpt 5 some quickies to help out bdk011987) To help moving between the return stack and parameter stack use >R to push on R< to get off and back onto the stack. R@ makes a copy of top of return stack and places it on top of data stack. In most programs there are several operations that occur frequently and Forth has words to help out with them. Many a time we need to add or subtract by 1 or 2, and thus the words 1+ 1- 2+ 2- 2* 2/ . Filtering of values is also important, so wehave ABS for absolute value, NEGATE for changing signs, MIN and MAX to find the relationship between 2 values. Try these problems or write a new word in screen 47 for eachof these inputs,0 degrees F and 45 degrees C. Use these formulas C= (f-32)/1.8 and F= (C*1.8)+32 . Try and find the radius of a circle with a circumferance of 23 feet. ( problem room.... bdk011987) What is the area of circle 12.5 feet in diameter? ( $$ ) ( chapter 6 glossary of loop words bdk012887) GLOSSARY CHAPTER 6 ( LOOPS ) DO ... LOOP DO: (limit start -- ) LOOP: ( -- ) This word sets up a finite loop, with a starting value and a ending or limit value ( loop does no action accept return to begining of DO). DO ... +LOOP DO: (limit start -- ) +LOOP: (n -- ) Same as plain loop, but adds n to value each time it loops. LEAVE ( - ) Terminates loop at next LOOP or +LOOP. BEGIN .. UNTIL UNTIL: (f - ) Loops until f becomes true. BEGIN xxx WHILE yyy REPEAT WHILE: (f - ) Loop doing xxx while yyy remainds true, leave when f is false. .R (n width -- ) Prints unsigned value right justified within specified field width. PAGE ( - ) Send a form feed to the terminal or printer ( chapter 6 glos and terms..loops... bdk011487)QUIT ( - ) Kills current execution and returns to terminal. CHAPTER 6 TERMS ( LOOPS ) DEFINITE LOOP A looping routine which will execute as many times as needed to reach a fixed value after starting from some preset value. INFINITE LOOP More often called a LOCKED UP COMPUTER, one that will never reach a determined value. INDEFINITE LOOP Not to be confused with a infinite loop, this loop ends when some predetermined value is reached. Changes in flags or values will end these loops. This loop starts with BEGIN, while definite loops use DO. ( chapter 6 text on loops..... bdk011487) CHAPTER 6 LOOPS Loops are an extension of branching, it's just that they willbranch back to the begining of the word DO or BEGIN. A DO loop takes values off the stack, the starting value on top and the ending value below. The staring value is increased by one each time through the loop until it equals the ending value. The operations contained within the DO and LOOP are performed until the items are equal. These items are not kept on the data stack but stored on the return stack, which you can copy and print by using the word I (see last chapter for more info). This value is called the index and can be used within the loop to create new values or pointers. +LOOP takes the value off the stack and increments the loop counter by this amount. +LOOPs can then count by steps to the ( chapter 6 loops and more loops... bdk012887)limit value, which is the second value on the return stack (use I' to copy to data stack). Be careful of using 0 in loops, becuse you could end up multiplying by 0 and never reach your ending value, this is an infinite loops, never ends. The other form of looping is the indefinite loop which starts with BEGIN and ends with UNTIL. This loop will repeat what is between the BEGIN and UNTIL, as long as the flag remainstrue. This means you must perform some test within the loop that will change the flag. A modified version of this loop is BEGIN WHILE REPEAT loop. This loop works just the opposite of the BEGIN UNTIL loop, it works only while the flag is true. When the flag goes false this loop ends. A regular DO LOOP can be ended early by LEAVEing it. Using LEAVE within the loop will terminate the loop, so to prevent an unwanted leave, enclose the term LEAVE within an IF THEN ( chapter 6 last page of loops.. bdk012887)statement. The IF is checked and as long as the condition is nottrue, the loop will not be terminated by LEAVE but continue on with THEN. The text has several good examples of DO LOOPs and how to use them. The text omits any BEGIN UNTIL loop problems, so lets see if we can create a word using this loop. If printing stars on the screen remember to clear it first with PAGE. Now lets see if you can create a christmas tree using stars when the stack contains the height or width as a value. Should you want to see a sample of printing a tree with the lowest branch value used as width, displayed at begining, then enter 25 TREE for a tree with 25 stars accross the bottom. If you want you can try and make the value enterd equal the number of branches ( not stars ) by editing screen 53. Try it first before looking at screen 53, it is more fun..... $$ ( tree width begin until bdk012887) : STAR 42 EMIT ; ( print star ) : STARS 0 DO STAR LOOP ; ( print many stars ) : TREE ( n -- ) ( expects width to be on top of stack ) 2/ 2* 1 + ( guarantee it is odd ) PAGE CR CR ( clear screen and move down ) 1 39 DUP SPACES STAR ( get set and do a star ) BEGIN CR 1 - DUP SPACES ( start and move across ) SWAP 2 + DUP STARS ( set star count do it ) ROT SWAP >R DUP R> SWAP >R DUP >R ROT R> R> = UNTIL ( shuffle and check star to count ) CR 39 SPACES STAR CR 39 SPACES STAR CR CR ; ( the last line draws the tree stock and moves ok down ) ( $$ ) ( chapter 7 glossary ..numbers bdk011987) CHAPTER 7 GLOSSARY ( NUMBERS ) ASCII ( - c) Translate character into ASCII equivalent U. (u - ) Prints unsigned number and one space U.R (u wdth -) Display right justified unsigned number U< (u1 u2 - f) Flag true if u1 < u2, single length unsigned HEX ( - ) Set number base to sixteen OCTAL ( - ) Set number base to eight ( not on all systems ) DECIMAL ( - ) Set number base to ten <# Begins number conversion, unsigned double length # Converts digit to output character string #S Convert number until result is zero c HOLD Insert an ASCII character in string at HOLD point n SIGN Inserts minus if n is negative in string #> Leaves number string and stack ready for TYPE ( more number glossary chpt 7 bdk011987)D+ (d1 d2 - d-sum) Adds two 32 bit numbers D- (d1 d2 - d-diff) Subtract two 32 bit numbers DNEGATE (d - -d) Change sign of 32 bit number DABS (d - |d|) Returns absolute 32 bit value DMAX (d1 d2 - dmax) Returns maximum of two 32 bit numbers DMIN (d1 d2 - dmin) Returns minimum of two 32 bit numbers D= (d1 d2 - f) Flags true if d1 and d2 are equal D0= (d - f) Flag true if d equal zero D< (d1 d2 - f) Flag true if d1 less than d2 DU< (ud1 ud2 - f) Flag true if unsigned d1 < unsigned d2 D. ( d - ) Prints signed 32 bit number D.R ( d width - ) Prints signed 32 bit right justified UM* (u1 u2 - ud) Multiply two 16 bit, gets 32 bit unsigned UM/MOD (ud u1-u2 u3) Divides 32b by 16b, gets 16b rem and quot. M* (n1 n2 -d-prod) Multiplies two 16b gets 32 bit result ( last of glossary chapter 7 numbers... bdk011987)M+ (d n - d-sum) Adds a 32b to 16b, returns 32bit number M/ (d n - n-quot) Divides 32b by 16b, get 16b signed results M*/ (d n u - d ) Multiplies then divides 32 by 16 get 32 bit CHAPTER 7 TERMS ( NUMBERS ) ARITHMETIC SHIFTS Process of moving bit left or right, which is same as multiplying or dividing by two. ASCII The standard system of representing characters with numbers, eight bits in length. BINARY Number base of two, either on or off BYTE Term for 8 bit value CELL A Forth term for 16 bit value DECIMAL The number base of 10 ( chpt 7 more terms.... bdk012887)HEXADECIMAL Number base of 16 LITERAL A number that appears inside a definition MASK A means of filtering out unwanted bits NUMBER FORMATTING Changing binary number to display characters OCTAL Number base of 8 SIGN BIT A bit used to indicate sign in signed numbers TWO'S COMPLIMENT The binary method used to add negative valuesUNSIGNED NUMBER A positive number UNSIGNED SINGLE LENGTH NUMBER An interger between 0 and 65535 WORD In Forth the defined dictionary entry that will perform some function or command ( chapter 7 text.. numbers.. bdk012887) CHAPTER 7 NUMBERS Computers have only one way to handle numbers, that is the BINARY method. Everything inside computers is either a one or zero, a on or off, or combinations of these two states. Binary is the term for this type of handling data. Humans however have considerable trouble understanding these on and offs values, so we have created number systems for the different ways we want torepresent data. In a previous screen I indicated that ASCII characters is what a computer uses to display information. A number has been asigned for each character we wish to display. These and any number can be represented in a binary form. To send a carriage return to your screen we send a value of 13 decimal. The binary representation of 13 is 00001101 and is what the computer ( chapter 7 numbers more text... bdk012887)actually sent to the display. Several shorthand methods are usedto indicate binary values. Some older computers use OCTAL or base 8. Most new machines use HEXADECIMAL or base 16. Four bits of binary 1 or 0s is used to get the hexadecimal value. Four HEX(short for hexadeciaml) values will represent the sixteen bits used in most of Forths single numbers. Double numbers are based on using 32 bits or eight hex values. Remember the hex values are just easy ways to express the 4 places of on and off data. In forth we use normally 16 bits to represent an unsigned number, 15 bits for a signed number with the 16th bit being the sign. When counting in binary that is 65535 for unsigned and a range of +32768 to - 32767 for signed numbers, all 16 bits. For binary arithmetic check the book, it has some good samples There are a number of Forth words which binary understandinghelps in knowing what they do. ASCII numbers are used by the ( more chapter 7 text..numbers bdk012987)EMIT word. This command emits an number to the display system. F83 can take a character and automatically convert it to a ASCIIvalue. Using ASCII * EMIT will send a star to the display. The same technique is used when changing base number systems. HEX 0A 12 + . will produce 1C as the answer. To get a decimal value do HEX 0A 12 + DECIMAL . and it will print 28. There are many ways to display numbers in Forth. To print unsigned (16bit) numbers U. will print what is on the stack plusa space after it. If you want numbers in a column use U.R where stack top has the width of the column, and the second down has the number that will be right justified. For DO LOOP compares onunsigned numbers use U< to flag true if U1 is less than U2. We can do the same functions with double length numbers (32bits). D. prints signed numbers, UD. prints unsigned numbers, D.R like U.R for signed 32 bit numbers, and DU< is 32 bit U<. ( chapter 7 number formatting... bdk012187) To display numbers it is necessary to format their output. This formatting inserts . or / to indicate money or dates. The method in Forth is to asign positions in a string, relative to digits in the number being printed. The format words are <# # #>and HOLD TYPE #S ASCII all can be used within the string. To start a layout use <# then number of numbers used, your period as a number (45) HOLD to hold a place by inserting a . there and then #S to fill in any remainding numbers. The real problem is the left most #, will be the right most number, or if we have4 #s before the hold, it will have four values after the HOLD. We also need to end the string with a #>, followed by TYPE whichwill display the formatted number. No space is printed after TYPE so you may need to follow it with a SPACE or n SPACES. You should try some of the samples in the book to get a better grasp of number formatting. ( chapter 7 double and mixed numbers bdk012887) There are a few double length operators that help handle relationship between numbers. These are, DNEGATE which changes the sign of a 32 bit number, DABS that returns the absolute value, DMAX and DMIN for minimum and maximum of two numbers, D= set flag true if two doublelength numbers ar equal, D0= if the number is zero, D< true if d1 is less than d2. Remember these operate the same as their single length number, but work on 32 bits of data, not 16. As with single length number, some operations will require intermediate answers that are longer than 32 bits. In */ the 16 bit values used a 32 bit intermediate value to maintain the accuracy. M*/ takes a 32 bit number and multiplies it by a 16 bit getting a triple length results (48 bits), and then dividingby a 16 bit number, return the answer as a 32 bit value. There are several other MIXED LENGTH OPERATORS, they are UM* ( last of chapter 7, mixed..definitions.. bdk012187)mulitplies two 16 bits for a 32 bit answer, UM/MOD divides a 32 bit by a 16 bit, getting 16 bit answers all unsigned, M* takes two 16 bits and multiplies for a signed 32 bit value, M+ adds a 32 and a 16 bit number for a 32 bit answer, M/ a 32 by 16 for a 16 bit answer. One must remember that the number base you are in is used whencompiling a word. Inserting a HEX will not have the values in the word compiled as hex values if you are in decimal at the time. When words are executed, if they contain a number base, the base will change at that time and interpret the numbers thatwere stored literally into the equivalent base value. The book has more details and some interesting problems. A good problem is creating a BIT mask using a DO LOOP. A good and useful word would be one that display bit patterns for values entered, in both 16 and 32 bit lengths. ( chapter 7 problem area and expansion... bdk012187) Try some large size math problems using the new words from this chapter. ( $$ ) ( chapter 8 glossary for variables... bdk012187) CHAPTER 8 GLOSSARY ( VARIABLES ) CONSTANT xxx ( n -) Creates a constant xxx with a value of n VARIABLE xxx ( - ) Creates a variable xxx, xxx gets address CREATE xxx ( - ) Creates dictionary header xxx ! ( n a -) Stores single length number into address @ ( a - n) Fetches contents of address to stack ? ( a - ) Prints contents of address and a space +! (n a - ) Adds n to contents of address (single length) ALLOT ( n - ) Adds n bytes to the PFA of recently defined word, ( n - ) Compiles n into next available cell in dict. C, ( b - ) Compiles b ( byte) into available cell of dict. C! (b a - ) Store a 8 bit value into address C@ ( a - b) Fetch an 8 bit value ( byte) from address FILL (a u b -) Fill memory u bytes long, starting a, with b ( chapter 8 more glossary..variables... bdk012187)ERASE (a u -) Stores u zeros starting at address a BASE ( - a) Variable containing value of number base DUMP (a u - ) Display u bytes of memory from a address 2VARIABLE xxx Creates double length variable @CONSTANT xxx Creates double length constant 2! ( d a - ) Stores double length number into a address 2@ ( a - d ) Fetches double length double from a address 0. ( - 0 0 ) Puts a double length zero on stack FALSE ( - 0 ) Returns a zero or false condition TRUE ( - -1) Returns a -1 or all 16 bits set to one CHAPTER 8 TERMS ( VARIABLES ) ( chapter 8 terms.. variables .. bdk012787)ARRAY A series of memory locations referenced by one name CONSTANT A fixed value referenced by a single name FACTORING Pulling out common steps of a program into own words FETCH To retrieve a value from a memory location INDEX A number indicating a location within an array INITIALIZE The setting of an array to known values OFFSET An value added to address, pointing into an array STORE Placing a value into memory location VARIABLE Memory location for storing changing values CHAPTER 8 VARIABLES AND ARRAYS ( CHAPTER 8 TEXT .. VARIABLES bdk012187) Most programs, including tutor.blk, need to use variables and constants. Variables are pointers, temporary sums, or any values that can be changed. Constants are values that are used by programs and generally are not changed. Forth requires these locations to be declared before use, using either VARIABLE or CONSTANT inplace of the : . This tells the compiler to define a word and allocate memory for it. Constants take a value off the stack and place it in the allocated memory location. When these words are used they return their address to the stack for use by ! @ ? or +! . ! means to store a value in location of address on stack withvalue below it. @ gets or fetches value from address on stack. ? is a combination of @ and . to get and print a value. +! adds the number below the address on the stack, to the location of address. ( chapter 8 variable doubled..arrays..text bdk012187) There are double words for variables: 2VARIABLE, constants: 2CONSTANT, as well as 2! to store a double length variable, and 2@ to fetch double length variables or constants. Many programs use arrays, or a number of memory locations that can contain values. Arrays can have fixed values, as in a table of phone numbers, or variables which can keep count of a number of events. To create an array in Forth use the word CREATE and the name assigned to it. The compiler will set as many memory locations aside as you ALLOT to it. An array of two will be defined, unless you allot more. Placing values in or outof an array is the same as any variable, it is just the address provided will be for the first entry in the array. If you want the seventh item, you must increment the address by 14 as each location is 2 addresses in length. The same is true for ALLOT you must double the value (10 ALLOT creates 5 16bit locations). ( chapter 8 arrays and bytes.... bdk012187) An example of an array is your programs memory. Forth has a word for looking at this large array, it is DUMP. Place the starting address on the stack, next push the count or how far you want displayed, then DUMP and watch what is there. As we said before a byte is 8 bits and is the smallest way some machines handle information. You can get data from or into an array in 8 bits at a time. Arrays of characters are all 8 bitentries. C! stores 8 bits, while C@ fetch 8 bits, just remember to set the address one step for each location in the array. The , is used to create a constant with values entered at time of compilation. Use values and a , for each entry instead allotting space (do not forget the last , ). Variables, constants, and arrays are easy to create in Forthand just as easy to use. For a problem we can use the topic of last chapter and this to create a telephone listing or array. ( chapter 8 problems..telco array bdk012187)This array should contain numbers and when queried with an index produce formatted output. Lets give it a try... ( $$ ) ( chapter 9..glossary and engines.... bdk012287) CHAPTER 9 GLOSSARY ( FORTH ENGINE ) ' xxx ( - a ) Returns dictionary address of xxx ['] ( - a ) Generates literal number used inside the words definition of the next word used in definition EXECUTE (a -) Executes the dictionary entry at address a @EXECUTE (a -) Executes entry pointed to at address a >BODY (cfa -pfa) Returns parameter field from compilation addrEXIT ( -- ) Terminates or returns from definition QUIT ( -- ) Clears stack, gets control, no ok prompt ABORT ( -- ) Clears data stack then does QUIT DP ( - a) Returns address of dictionary pointer HERE ( -- a) Next available dictionary location PAD ( -- a) Beginning address of character string buffer SP@ ( -- a) Pointer to top of data stack ( chapter 9 glossary of engine... bdk012187)S0 ( -- a) Returns address of bottom of data stack TIB ( -- a) Returns address of text input buffer FORTH ( -- ) Makes FORTH context vocabulary EDITOR ( -- ) Makes EDITOR context vocabulary CONTEXT ( - a) Returns address of search order variable CURRENT ( - a) Returns address of new word vocabulary ( vocs) DEFINITIONS Sets the current vocs to context vocs CHAPTER 9 TERMS ( FORTH ENGINE ) ADDRESS INTERPRETER Interprets the address from the colon definitions and executes them ( chapter 9 terms engines... bdk012187)BODY The code and parameter of a dictionary entry BOOT The basic starting portion of Forth, precompiled ForthCFA Address of code field in a dictionary entry CONTROL TASK A task that does not converse with Forth CODE POINTER FIELD The entry in the dictionary that points to the run time code DEFINING WORD A Forth word that creates a dictionary entry ELECTIVES Optional blocks of words like floating point mathFORWARD REFERENCE Refering to undefined words HEAD Name and link field of dictionary entry LINK FIELD Pointer to next entry of vocabulary, search orderNAME FIELD Location of name of word, includes word length PAD Area of memory for intermediate data storage PARAMETER FIELD The area of the definition in which the actual code or values are contained ( chapter 9 terms...forth engine... bdk012187)PFA The address of the first entry of parmeter field PRECOMPILED PORTION The Forth system loaded at boot time with all dictionary words and terms ready to use RUN-TIME CODE Usually the actual code that is the word SYSTEM VARIABLES Variables usuable by all users in system TASK A area of memory set aside for a given activity TERMINAL TASK A task that has a user talking to Forth TEXT INPUT BUFFER Memory area containing terminal input data USER VARIABLE Variable accessible by one user only VECTORED EXECUTION Executing words by going to a pointer VOCABULARY An independent linked list of words. In F83 SHADOW EDITOR HIDDEN BUG ROOT USER ASSEMBLER DOS FORTH are vocabularies. Use VOCS to see this list of vocabularies. ( chapter 9 forth engines text... bdk012187) CHAPTER 9 FORTH ENGINE Forth is a THREADED programing language. This means that a action amounts to performing one instruction contained within an instruction. Words which perform the actions are made up of lists of addresses of words that together will perform the desired action. These words within words can also have words within them. If you follow the actual actions it is like a thread linking all the actions together. In comparing Forth to assembly language it would be like a routine calling a subroutine which calls a subroutine and can call more till it finally does something and then returns back through each of the called routines. That final actual code performing actions makes up the KERNAL of the system. ( chapter 9 forth engine text..... bdk012787) The kernal is written in native code of the machine it is on. The kernal creates the stack and basic operations of Forth. Utilities are then written using Forth words, building blocks until a full system is created. To move the system to another type of processor requires rewritting only the native code of the inner most kernal, not the utilities. Most computers are made up of CPU or central processor unitswhich have a number of registers and instructions to move data between registers and the outside world. What Forth does is to create an artificial processor in software that can be moved to different machines. This created processor can give the user near assembly language performance, while being transportable. In F83 we have the normal kernal using the Forth-83 word setas well as many utilities, which create a full system. All theseabilities are contained in the dictionary. When Forth words are ( chapter 9 forth engine..... bdk012787)interpreted, FIND searches the dictionary for a match, and then EXECUTES the instructions. What is passed is not actual words but their address. An word contains addresses or machine code. The kernal items are mostly code, while utilities are mostly addresses pointing to code containing words. Forth has several ways to handle words by the user, one way is ' which returns the address of the word, use U. to see the actual address of a word ( ' SEE U. ). What interpret does is ' the word then does EXECUTE on the address on the stack. This is not the address of the first address of a dictionary entry, but the third. Lets look at how words are arranged. When you create or define a word, several entries in memory are completed. The word name is stored, up to 32 characters in F83, after a count of the length of the name. Next is the link to the next item in the current vocabulary. This link tells the ( chapter 9 forth engine..... bdk012787)interpreter where next to look if the current word is not a match. After the link is the CODE FIELD ADDRESS or CFA. This is what is returned by ' and points to the code or code intrepter. The interpreter can be one of three types, variable, constant orcode. The variable and constant return address or values on to the stack respectively. The code points to either actual machinecode if it is a kernal item, or more CFA's. What it points to iscalled PARAMETER FIELD or PFA, and given the CFA >BODY will put the PFA on the stack. There are other actions that occur while the interpreter is going through the PFA, mainly pushing the next PFA onto the return stack. This is why use of the return stack must be done within the : definition, not doing so destroys the pointer to the next word. You can carefully handle this stack and cause wanted results by dropping off pointers, use caution though! ( chapter 9 engine exiting and map... bdk012787) You can officially leave a diffinition, using QUIT ABORT or ABORT" any of these three end the operation. Generally these ways are used inside of IF THEN or DO LOOPs checking for flags or problems. When the last PFA is found the word EXIT is left. This word removes the pointer from the return stack and this is interpreted next. EXIT can not be used inside of DO LOOP as it will return loop counters and not addresses. There are some ideas and words that you should know which relate to the memory map of a Forth system. Normally from low memory up is the kernal, system variables, utilities, users dictionary space, the PAD, DATA STACK, TIB, RETURN STACK, users variables, and block buffers. The users dictionary grows toward the PAD, while the DATA and RETURN stacks grow down toward low memory. The stack is actually a pointer to memory locations and is lowered each time an entry is made. ( chapter 9 system words..the engine.. bdk012787) To find these locations in memory, use DP to find the last or highest memory location free for new dictionary word entries.DP is the pointer while HERE will place the pointer value on thestack ( same as DP @ ). To find the true location of the stack use SP@ and it will fetch the pointers value, while S0 will get the starting address of the stack. In higher memory above the data stack is the TIB or Text Input Buffer and it grows up toward higher memory. TIB fetches the starting address of the buffer. The input line interpreter reads this buffer to find outwhat you have entered. To improve speed of interpretation, the dictionary is sortedinto different lists or vocabularies. When in these vocabulariesForth will only search those words through use of the linked address value. Typing the name of a vocabulary puts you into that linked list. These lists can be scanned consectatively if ( chapter 9 last screen...vocs... bdk012287)the word is not found in the first list. VOCS will display the list of current vocabualries, while CONTXET shows the search order. CURRENT will print which VOCS you are now in. To see the words contained in one of these list, enter DOS WORDS and you will see all the dictionary entries that relate to the DOS ( andare used by Forth when talking to the operating system). Take the time now and do some exploring in F83. Reading the file README will explain some of the system terms and show a memory map of a typical 8080 Forth system. Try reading all the VOCS and check CONTEXT before and after changing vocabularies. $$ ( chapter 10 glossary...I/O... bdk012787) CHAPTER 10 GLOSSARY ( I/O ) UPDATE ( - ) Marks most recently used block as modified SAVE-BUFFERS Writes all updated buffers to disk FLUSH Does save-buffers then frees all buffers EMPTY-BUFFERS Marks buffers as empty, all data is lost BLOCK ( u - a) Put starting address of block u on stack BUFFER ( u - a) Like block but does not load block from disk TYPE ( a # -) Send # characters at addr a to output device -TRAILING (a #1 - a #2) Changes byte count to reflect blanks >TYPE ( a # -) TYPE for multiusers, puts string in PAD first MOVE (a1 a2 # -) Moves # of cells from a1 to a2 (low > hi) CMOVE (a1 a2 # -) Moves # of bytes from a1 to a2 (low > hi) CMOVE> (a1 a2 #-) Moves # of bytes from a1 to a2 (hi > low) BLANK ( a # -) Fill a with # of blank ASCII bytes ( chapter 10 glossary I/O bdk012387)KEY ( - c) Put next available INPUTED ASCII char on stack EXPECT (a # -) Awaits # chars or CR from KEY storing at a SPAN ( - a) Addrs of number of chars stored by EXPECT WORD (c - a) Puts one word from input stream into addrs a COUNT (a -a+1 #) Changes stack values of string a for TYPE >IN ( - a ) Variable with pointer to next free input space BLK ( - a ) Variable pointing to active block, 0= TIB CONVERT (ud1 a1 -ud2 a2) Convert ASCII string a1 to binary ud2 NUMBER ( a -d ) Convert ASCII string a to binary values d -TEXT (a1 # a2-f) Flag true if no match in strings # long -MATCH (d # s # -a f) Find match in stings s/d return addrs flag" ( - a ) Returns address of compiled string ( chapter 10 terms ..I/O bdk012387) CHAPTER 10 TERMS ( I/O ) EXPECTING Stop computing and wait for keyboard input RELATIVE POINTER An index into an array used with address to find true location of data SCANNING Searching ahead for given characters SUPERSTRING A string within an array of strings VIRTUAL STRING Use of disk storage as if it were real memory ( chapter 10 text of I/O.... bdk012787) CHAPTER 10 I/O Forth handles data in blocks or groups of data 1024 bytes long. These can be in blocks of data on the disk or blocks of data contained in buffers within Forths memory map. These blockscan have data, screens of source code, text, or grabage. F83 hasa number of ways of handling these blocks of data. When we list a screen, F83 checks to see if the block has been load from disk, if not it loads it into a free buffer. Thenit returns a pointer to this block and LIST then displays it. Ifwe have edited a block or changed it, it will be UPDATEd and marked for storage to disk. This storage is not done until the buffer is needed. You can force the storage two ways. FLUSH willempty all updated buffers and clear all pointers, while the wordSAVE-BUFFERS writes to disk, but does not clear the pointers. ( chapter 10 I/O block and stuff.... bdk012787) EMPTY-BUFFERS will clear all pointers without writting to disk. Any data contained within the buffers is lost at the sake of freeing all buffers for more data. Accessing these buffers you use BLOCK to return the address of the first byte in the numbered block. If the block is not already in memory, BLOCK will force it to be read. BUFFER returns a blocks address but will not force a read ( used within BLOCK). We can get data into the system, either from the blocks or from the input string (keyboard). As indicated before to output characters to the terminal you use EMIT. To send strings you useTYPE, with the count on top and string address below. TYPE will print the characters including blanks, -TRAILING will return without the blanks by changing the stack count, then use TYPE. To get these strings into buffers or locations accessible toour programs we can MOVE them around. MOVE copies 16 bit cells ( chapter 10 I/O moves... bdk012787)from locations pointed to by the third stack item to the second stack address, and will move the count value(top stack). CMOVE does the same, but count is now byte moves or 8 bits at a time. These move the data from low memory to higher memory and could over write data yet to be moved. CMOVE> starts from the top or high memory and moves data down, preventing garbage generation. Forth has several ways of getting input from the keyboard into the system. KEY is the basic single character input word. KEY? flags if the keyboard has been used. EXPECT will wait and then store a string of characters from the keyboard. Once we have the data in the TIB, we now need to be able to process it. WORD will scan a string until it finds a given character and then moves this string to a new buffer with the count (length of string) as the first address. We use COUNT to add one to the address and push the count on the stack. ( chapter 10 I/O string working... bdk012787) When performing your own control over Forth, you will want more control than most programming languages provide. Many of the string commands help you understand how Forth works, and there are more pointers that may be of interest to you. >IN tells where in the input string the interpreter is at, while BLKindicates wether the system is taking input from the TIB or the block buffers. If BLK is zero, input is from TIB, non zero is block buffers. There are two ways to compare strings looking for matches. The-TEXT word compares two strings with a given length and will setthe flag false if they match. -MATCH searches for a match of onestring and its length within a second string of some length, if a match is found the stack will contain the starting address of the match and the flag set false (in that order). The handling of strings is not difficult in Forth and in fact( chapter 10 last of I/O text... bdk012387)you have more control over how to handle strings than any other programming language. If Forth doesn't do what you want, just write some word that does. As a problem, try writing some words that find matches in a block buffer and then change them to random words selected from a second buffer, should be fun and produce some intersting statements. ( $$ ) ( chapter 11 extending....glossary bdk012787) CHAPTER 11 GLOSSARY ( EXTENDING ) DOES> ( -- a) Separates compile data from run-time portion IMMEDIATE To be executed not compiled into the word COMPILE xxx Compile word xxx address into definition LITERAL A value pushed on stack by a word (binary) [ Leaves compile mode ] Starts compile mode [COMPILE] xxx Makes a immediate be treated as non-immediate STATE ( -- a) True if compiling, false if interpreting INTERPRET Perform text interpretation of input stream ( chapter 11 extending..terms.. bdk012787) CHAPTER 11 TERMS ( EXTENDING ) COMPILE-TIME The action of compiling or generating a new dictionary entry, for later run-time use. COMPILING WORD A word that has action only during the compilation stage, to generate proper run-time action. DEFINING WORD When executed defines a new dictionary entry that may have compile-time and run-time parts. IMMEDIATE WORD A word that gets executed during compilation and not compiled into dictionary. PRECEDENCE BIT The 16th bit, indicates wether a word should be executed (immediadte) or compiled. RUN-TIME The normal action which a word will take, which is what the word DOES>, it's definition. ( chapter 11 extending the dictionary..text.. bdk012787) CHAPTER 11 EXTENDING It is at this point that we find out how Forth works. More important it is where we find out how to change Forth to meet our needs. All of this is done by extending the dictionary or when compared to other languages it would be like re-writtingthe compiler so that it has new ways of handling the input. You can never NOT do something in Forth, it may not at present have a way of handling your desires, but learn its insides and you can make it do anything. We should remember that Forth has two states or actions possible. The first is interpreting, the other compiling. In theinterpretive mode we take data from a source and perform actionsmuch like basic reads lines of code and acts on them. The other mode creates new words for the interpreter to use. It would be ( chapter 11 extending... bdk012787)like creating a new print command in basic (something you can't do). The words we use in the interpret mode have all been definedand compiled in the kernal of Forth. The UTILITY.BLK and CPU8088.BLK have most of the source code words for you to look over. Inlooking these words over we will see two possible actions that can take place in creating the dictionary words. These two are compile-time and run-time activities. . When compiling if we used Forth words that act on the input data immediately, we would get garbage. That is it would output data as the word was being created, not when we are invoking it. Therefore we need to have words that control when words do their thing. CREATE is the word that creates the dicitonary entry and puts in link and code addresses. This word is used to define ( chapter 11 extending.. bdk012787)words like CONSTANT and VARIABLE. These words when we use them will CREATE a dictionary input using the name we pass at that time. CREATE doesn't do anything at the time it is used in the defined word, only when we invoke it as part of a new defined word. Now if we want the new defined word that was created by using a word with CREATE in it, we use DOES>. DOES> separates the creation from the activity when it is invoked. This is the difference between compile-time and run-time actions. Compile-time actions occur when the word is being created, while run-time actions occur when the word is being interpreted.It is important to understand the two different states of Forth activities. You compile words into the dictionary which when they get invoked will perform certain activities. To compile these words may require some actions which are different from the actions that occur at run-time (interpretation). ( chapter 11 extending.. bdk012787) Interpretation occurs at all times, it just that some of theinterpreting is used to make new dictionary entries and some is used to handle screen output. You don't want the two actions to become confussed. F83 has defined two words which can help show the differencebetween these two states ." and .( The ." will store a string that is printed when the word is invoke as in error messages. The .( will print the string only while the word is being compiled, or as I have used in the load screen to TUTOR it tellsyou to wait while it is loading new words. If we want to compute some values that later will be part ofthe new defined word as LITERAL values we would use [ and ] . The [ means interpret now, while ] means to stop interpreting and resume compiling the word. If you are compiling directly from the keyboard ] will continue compilation after a carriage ( chapter 11 extending and last text screen bdk012787)return. The word IMMEDIATE means that this word is used within a compilation to do its action immediately. The opposite of this is [COMPILE] which delays compiling of the word till used in an other words compilation. Keeping track of when and what is being compiled and interpreted takes some time and practice. Use the book for most of this discussion. The samples and charts of when and how the dictionary is changed is too complex for this simple tutorial. To really understand Forth, you must use it and play with itunderstanding how to adapt it to your style of programming. F83 and Forth together should be able to solve programming problems with ease once you understand it. ENJOY. ( $$ )