Programming Forth

Transcription

Programming ForthRevised May 2011Stephen Pelc

Programming ForthCopyrightCopyright (c) 2005, 2006, 2007, 2011 MicroProcessor Engineering LimitedFor further informationMicroProcessor Engineering Limited133 Hill Lane, SouthamptonSO15 5AF, UKTel: 44 (0)23 8063 1441Fax: 44 (0)23 8033 9691e-mail: peforth.comi

AcknowledgementsAcknowledgementsI would like to thank the following people in particular for their involvement in thecontent of this book:Peter Knaggs, Chris E. Bailey, Bill Stoddart, Bob Marchbanks, Hans BezemerThese people have influenced “Programming Forth” and contributed to it, and theirinput is valued. All faults are my own. Much criticism and proof-reading wasprovided by the readers of the comp.lang.forth newsgroup, especially:Stefan Schmiedl, William Cook, Anton ErtlOther people have influenced my programming style and general attitude to life.Fokko van Duin, Willem Botha, Chuck MooreProgramming ForthCopyright 2005, 2006, 2007, 2011MicroProcessor Engineering LimitedISBN 978-0-9525310-5-0

ii

ContentsTable of ContentsCopyright.iFor further out this book.11What Forth is.11Key concepts .12Interactivity, Development and Testing.13How to Debug.13Writing programs in Forth.15Editors.16Forth Implementation.16MPEisms.162Architecture of Forth.18Forth Virtual Machine.18Stacks and postfix notation.19Data types.20Words and Numbers.21Interpreting and compiling.21Defining Words and Immediate words.21Factoring.223How Forth is documented.23Comments.23Stack comments.23Notation.234First words in Forth.255Components of Forth.29Data stack operations.29Return Stack operations.30Maths operations.30Comparisons.31Widely available.32Bitwise logic.32Memory operations.33Widely available.33Constants and ol structures .35IF . THEN.35IF.ELSE.THEN.36EXIT.36DO . LOOP and DO . n LOOP.36?DO . LOOP and ?DO . n LOOP .38i

BEGIN . AGAIN.38BEGIN . UNTIL.38BEGIN . WHILE . REPEAT.39CASE . OF . ENDOF . ENDCASE.39MPEisms: CASE extensions.40Restarts and errors.41Text and strings.41Counted strings.41Character Strings.42Character Literals.42Text and String input.42Print Formatting.43Vocabularies.44Wordlists.466Example: Date validation.49Date Validation: the requirement.49Designing the solution.49Coding the solution.50Putting it all together.51Lessons from this example.527Simple character I/O.53Output.53Input.53String Output.54String input and the input stream.55Number output.56Number input.56Redirecting KEY and EMIT.578Defining with CREATE . DOES .59Arrays.60Structures.619Diary and Phone Book 63An Internal Phone Book.67Specification.67Some design notes.68Implementation.6910Execution Tokens and Vectors.75Execution vectors.75Execution arrays.7711Extending the compiler.79Immediate words.79Cautionary notes.81Accessing the compiler.81Structures revisited.83Cautionary notes.84v

Contents12Errors and exception handling.87ABORT, QUIT and ABORT”.87CATCH and THROW.87Description.87Sample implementation.88Features.89Stack rules for CATCH and THROW.89Some more features.90Error codes and return results.90Always clean up.9113Files.93ANS File Access Wordset.93Simple file tools.9514Common extensions.97Multitasking.97Cooperative and Preemptive taskers.97USER variables.97Simple Forth tasks.98I/O and PAUSE.99Error checking.99Floating point.100Local variables.101Cautionary notes.101Object oriented programming.103Integrated assembly.103Source location.103Mixed language programming.104Parameter passing.104DLLs and shared libraries.105Static linking.105Jump tables.10515Embedded Systems.107Defining and using memory.107Harvard targets.108Compiler and Interpreter extensions.109Defining words.110Compiler macros.111I/O ports.112Interrupt handlers.113Assembler interrupt.113High level interrupts.114Interlocks.116Umbilical Systems.117Debugging Embedded Systems.118Basic rules.119Make faults visible.119Check tasks.120Recover well.121Talk to the hardware people.121Block I/O.121Source in blocks.123v

16Forth Internals.125Anatomy of a Forth system.125Navigating the dictionary structure.127Structure of compiled code.127Native Code Compilation (NCC).128Subroutine Threaded Code (STC).128Direct Threaded Code (DTC).129Indirect Threaded Code (ITC).129Token Threaded Code (TTC).130Other forms.131Forth engines and stack machines.131Commercial devices.132Prototype and research machines.132Notes on embedded real-time.13317Using the Forth interpreter.135Configuration example.135Application and design.135Implementation.136Phone book s, issues and lessons.14218Code Layout.145Why a standard?.145Implications of editors.146Tabs.146Horizontal and Vertical layouts.147Comments.148File layout.148Header Section.149Code sections.150Test Section.151Base and numbers.151Vocabularies and wordlists.151Layout of a definition.151Header comments.152Name and stack comment.152Indenting and phrasing.153End of definition.153Comments.154Defining words.155Control Structure layout.155Flags and limits.155Indenting.156Short Structures.156I’ve changed my mind.157Layout of code definitions.157Constants, Values and Variables.158Buffers.158Data Tables.159Case questions.159v

Contents19Exercises.161Stack operations.161Arithmetic.161Input, output and loops.167Memory.169Defining words.172Miscellaneous.17320Solutions to Exercises.175Stack operations.175Arithmetic.175Input, output and loops.182Memory.185Defining words.187Miscellaneous.18921Adopting and managing Forth.191Interactivity and exploration.191Extensibility and notation.192Limited memory.192Why not the common language?.193We used Forth 15 years ago, but .194Managing Forth 7Portability.197Lifecycle.19822Legacy issues.199Forth Standards.199Native Code Compilers.199Converting from Forth-83.199Screen files.200Files.20023Other Books and Resources.203Starting Forth – Leo Brodie.203Thinking Forth – Leo Brodie.203Forth Programmer’s Handbook – Conklin & Rather.203Forth Application Techniques – Rather.204Other Resources.204Forth Interest Group.204Usenet news groups.204Conferences.204Amazon.20424Index.205v

List of TablesTable 1: File access data types.93Table 2: Cross Compiler search orders.109Table 3: Generic Forth registers.127Table 4: Native code register usage.128Table 5: Subroutine Threaded Code register usage.128Table 6: Direct Threaded Code register usage.129Table 7: Indirect Threaded Code register usage.130List of FiguresFigure 1: Debugging.14Figure 2: Forth and C Virtual Machines.18Figure 3: SENDIT VM and registers.19Figure 4: Umbilical Forth model.118Figure 5: Block buffers.122Figure 6: Source in blocks.124Figure 7: Typical Forth memory model.125Figure 8: Dictionary entry.126i

Introduction1IntroductionAbout this bookProgramming Forth introduces you to modern Forth systems. In 1994 the ANS Forthstandard was released and unleashed a wave of creativity among Forth compiler writers.Because the ANS standard, unlike the previous informal Forth-83 standard, avoidsspecifying implementation details, implementers took full advantage. The result hasbeen what I choose to call modern Forths, which are available from a range of sourcesboth commercial and open-source.This book concentrates on introducing people who already know some programming toANS Forth systems. It is not a treatise on ANS Forth itself – if you need the gorydetails, the last public (freely distributable) draft of the ANS standard is included on theCD supplied with purchased copies of the book. Copies in PDF format are available bydownload from http://www.mpeforth.com/arena at no cost. If you are a noviceprogrammer (or indeed at all interested in the craft of programming) read this bookalongside “Starting Forth” and “Thinking Forth” by Leo Brodie. How to get them is inthe chapter on other books and resources.Apart from the introduction of ANS Forth itself, Programming Forth includes examplesof varying sizes, exercises, some advanced topics, how to take best advantage of Forthand project management.The material is derived from course material from MicroProcessor Engineering andteaching work at Teesside University by Bill Stoddart and Peter Knaggs, plus newmaterial. Both the printed and the PDF versions are updated from time to time toincorporate changes requested by readers. If you want to comment on the book pleasesend feedback to programforth@mpeforth.com - I appreciate all your comments andcontributions.What Forth isForth is a member of the class of extensible interactive languages, which includesclassical implementations of Smalltalk. Extensible means that there is no disti

This book concentrates on introducing people who already know some programming to ANS Forth systems. It is not a treatise on ANS Forth itself - if you need the gory details, the last public (freely distributable) draft of the ANS standard is included on the CD supplied with purchased copies of the book. Copies in PDF format are available by