Annotation of gforth/doc/gforth.ds, revision 1.25

1.1       anton       1: \input texinfo   @c -*-texinfo-*-
                      2: @comment The source is gforth.ds, from which gforth.texi is generated
1.21      crook       3: @comment TODO: nac29jan99 - a list of things to add in the next edit:
                      4: @comment 1. x-ref all ambiguous or implementation-defined features
                      5: @comment 2. refer to all environment strings
                      6: @comment 3. gloss and info in blocks section
                      7: @comment 4. move file and blocks to common sub-section?
                      8: @comment 5. command-line editing, command completion etc.
                      9: @comment 6. document more of the words in require.fs
                     10: @comment 7. document the include files process (Describe the list,
                     11: @comment    including its scope)
                     12: @comment 8. Describe the use of Auser Avariable etc.
                     13: @comment 9. cross-compiler
                     14: @comment 10.words in miscellaneous section need a home.
                     15: @comment 11.Move structures and oof into their own chapters.
                     16: @comment 12.search for TODO for other minor works
1.1       anton      17: @comment %**start of header (This is for running Texinfo on a region.)
                     18: @setfilename gforth.info
                     19: @settitle Gforth Manual
                     20: @dircategory GNU programming tools
                     21: @direntry
                     22: * Gforth: (gforth).             A fast interpreter for the Forth language.
                     23: @end direntry
                     24: @comment @setchapternewpage odd
1.12      anton      25: @macro progstyle {}
                     26: Programming style note:
1.3       anton      27: @end macro
1.1       anton      28: @comment %**end of header (This is for running Texinfo on a region.)
                     29: 
1.10      anton      30: @include version.texi
                     31: 
1.1       anton      32: @ifinfo
1.11      anton      33: This file documents Gforth @value{VERSION}
1.1       anton      34: 
1.13      pazsan     35: Copyright @copyright{} 1995-1998 Free Software Foundation, Inc.
1.1       anton      36: 
                     37:      Permission is granted to make and distribute verbatim copies of
                     38:      this manual provided the copyright notice and this permission notice
                     39:      are preserved on all copies.
                     40:      
                     41: @ignore
                     42:      Permission is granted to process this file through TeX and print the
                     43:      results, provided the printed document carries a copying permission
                     44:      notice identical to this one except for the removal of this paragraph
                     45:      (this paragraph not being relevant to the printed manual).
                     46:      
                     47: @end ignore
                     48:      Permission is granted to copy and distribute modified versions of this
                     49:      manual under the conditions for verbatim copying, provided also that the
                     50:      sections entitled "Distribution" and "General Public License" are
                     51:      included exactly as in the original, and provided that the entire
                     52:      resulting derived work is distributed under the terms of a permission
                     53:      notice identical to this one.
                     54:      
                     55:      Permission is granted to copy and distribute translations of this manual
                     56:      into another language, under the above conditions for modified versions,
                     57:      except that the sections entitled "Distribution" and "General Public
                     58:      License" may be included in a translation approved by the author instead
                     59:      of in the original English.
                     60: @end ifinfo
                     61: 
                     62: @finalout
                     63: @titlepage
                     64: @sp 10
                     65: @center @titlefont{Gforth Manual}
                     66: @sp 2
1.11      anton      67: @center for version @value{VERSION}
1.1       anton      68: @sp 2
                     69: @center Anton Ertl
1.6       pazsan     70: @center Bernd Paysan
1.5       anton      71: @center Jens Wilke
1.23      crook      72: @center Neal Crook
1.1       anton      73: @sp 3
1.23      crook      74: @center This manual is permanently under construction and was last updated on 16-Feb-1999
1.1       anton      75: 
                     76: @comment  The following two commands start the copyright page.
                     77: @page
                     78: @vskip 0pt plus 1filll
1.13      pazsan     79: Copyright @copyright{} 1995--1998 Free Software Foundation, Inc.
1.1       anton      80: 
                     81: @comment !! Published by ... or You can get a copy of this manual ...
                     82: 
                     83:      Permission is granted to make and distribute verbatim copies of
                     84:      this manual provided the copyright notice and this permission notice
                     85:      are preserved on all copies.
                     86:      
                     87:      Permission is granted to copy and distribute modified versions of this
                     88:      manual under the conditions for verbatim copying, provided also that the
                     89:      sections entitled "Distribution" and "General Public License" are
                     90:      included exactly as in the original, and provided that the entire
                     91:      resulting derived work is distributed under the terms of a permission
                     92:      notice identical to this one.
                     93:      
                     94:      Permission is granted to copy and distribute translations of this manual
                     95:      into another language, under the above conditions for modified versions,
                     96:      except that the sections entitled "Distribution" and "General Public
                     97:      License" may be included in a translation approved by the author instead
                     98:      of in the original English.
                     99: @end titlepage
                    100: 
                    101: 
                    102: @node Top, License, (dir), (dir)
                    103: @ifinfo
                    104: Gforth is a free implementation of ANS Forth available on many
1.11      anton     105: personal machines. This manual corresponds to version @value{VERSION}.
1.1       anton     106: @end ifinfo
                    107: 
                    108: @menu
1.21      crook     109: * License::                     The GPL
                    110: * Introduction::                An introduction to ANS Forth
1.1       anton     111: * Goals::                       About the Gforth Project
1.21      crook     112: * Invoking Gforth::             Starting (and exiting) Gforth
1.1       anton     113: * Words::                       Forth words available in Gforth
1.24      anton     114: * Error messages::              How to interpret them
1.1       anton     115: * Tools::                       Programming tools
                    116: * ANS conformance::             Implementation-defined options etc.
                    117: * Model::                       The abstract machine of Gforth
                    118: * Integrating Gforth::          Forth as scripting language for applications
                    119: * Emacs and Gforth::            The Gforth Mode
                    120: * Image Files::                 @code{.fi} files contain compiled code
                    121: * Engine::                      The inner interpreter and the primitives
1.24      anton     122: * Binding to System Library::   
1.13      pazsan    123: * Cross Compiler::              The Cross Compiler
1.1       anton     124: * Bugs::                        How to report them
                    125: * Origin::                      Authors and ancestors of Gforth
1.21      crook     126: * Forth-related information::   Books and places to look on the WWW
1.1       anton     127: * Word Index::                  An item for each Forth word
                    128: * Concept Index::               A menu covering many topics
1.12      anton     129: 
1.24      anton     130: @detailmenu --- The Detailed Node Listing ---
1.12      anton     131: 
1.24      anton     132: An Introduction to ANS Forth
                    133: 
                    134: * Introducing the Text Interpreter::
                    135: * Stacks and Postfix notation::
                    136: * Your first definition::
                    137: * How does that work?::
                    138: * Forth is written in Forth::
                    139: * Review - elements of a Forth system::
                    140: * Exercises::
                    141: 
                    142: Goals of Gforth
1.21      crook     143: 
                    144: * Gforth Extensions Sinful?::
                    145: 
1.12      anton     146: Forth Words
                    147: 
                    148: * Notation::                    
1.21      crook     149: * Comments::
                    150: * Boolean Flags::
1.12      anton     151: * Arithmetic::                  
                    152: * Stack Manipulation::          
                    153: * Memory::                      
                    154: * Control Structures::          
                    155: * Locals::                      
                    156: * Defining Words::              
1.21      crook     157: * The Text Interpreter::
1.12      anton     158: * Structures::                  
                    159: * Object-oriented Forth::       
                    160: * Tokens for Words::            
1.21      crook     161: * Word Lists::                   
                    162: * Environmental Queries::
1.12      anton     163: * Files::                       
                    164: * Including Files::             
                    165: * Blocks::                      
                    166: * Other I/O::                   
                    167: * Programming Tools::           
                    168: * Assembler and Code Words::    
                    169: * Threading Words::             
1.21      crook     170: * Passing Commands to the OS::
                    171: * Miscellaneous Words::
1.12      anton     172: 
                    173: Arithmetic
                    174: 
                    175: * Single precision::            
                    176: * Bitwise operations::          
1.21      crook     177: * Double precision::            Double-cell integer arithmetic
                    178: * Numeric comparison::
1.12      anton     179: * Mixed precision::             operations with single and double-cell integers
                    180: * Floating Point::              
                    181: 
                    182: Stack Manipulation
                    183: 
                    184: * Data stack::                  
                    185: * Floating point stack::        
                    186: * Return stack::                
                    187: * Locals stack::                
                    188: * Stack pointer manipulation::  
                    189: 
                    190: Memory
                    191: 
                    192: * Memory Access::      
                    193: * Address arithmetic::          
                    194: * Memory Blocks::         
                    195: 
                    196: Control Structures
                    197: 
                    198: * Selection::                   
                    199: * Simple Loops::                
                    200: * Counted Loops::               
                    201: * Arbitrary control structures::  
                    202: * Calls and returns::           
                    203: * Exception Handling::          
                    204: 
                    205: Locals
                    206: 
                    207: * Gforth locals::               
                    208: * ANS Forth locals::            
                    209: 
                    210: Gforth locals
                    211: 
                    212: * Where are locals visible by name?::  
                    213: * How long do locals live?::    
                    214: * Programming Style::           
                    215: * Implementation::              
                    216: 
                    217: Defining Words
                    218: 
                    219: * Simple Defining Words::       
                    220: * Colon Definitions::           
                    221: * User-defined Defining Words::  
                    222: * Supplying names::             
                    223: * Interpretation and Compilation Semantics::  
                    224: 
1.21      crook     225: The Text Interpreter
                    226: 
                    227: * Number Conversion::
                    228: * Interpret/Compile states::
                    229: * Literals::
                    230: * Interpreter Directives::
                    231: 
1.12      anton     232: Structures
                    233: 
                    234: * Why explicit structure support?::  
                    235: * Structure Usage::             
                    236: * Structure Naming Convention::  
                    237: * Structure Implementation::    
                    238: * Structure Glossary::          
                    239: 
                    240: Object-oriented Forth
                    241: 
1.24      anton     242: * Why object-oriented programming?::
                    243: * Object-Oriented Terminology::
                    244: * Objects::
                    245: * OOF::
                    246: * Mini-OOF::
1.23      crook     247: * Comparison with other object models::  
1.12      anton     248: 
1.24      anton     249: The @file{objects.fs} model
1.12      anton     250: 
                    251: * Properties of the Objects model::  
                    252: * Basic Objects Usage::         
1.23      crook     253: * The Objects base class::            
1.12      anton     254: * Creating objects::            
                    255: * Object-Oriented Programming Style::  
                    256: * Class Binding::               
                    257: * Method conveniences::         
                    258: * Classes and Scoping::         
                    259: * Object Interfaces::           
                    260: * Objects Implementation::      
                    261: * Objects Glossary::            
                    262: 
1.24      anton     263: The @file{oof.fs} model
1.12      anton     264: 
                    265: * Properties of the OOF model::
                    266: * Basic OOF Usage::
1.23      crook     267: * The OOF base class::
1.12      anton     268: * Class Declaration::
                    269: * Class Implementation::
                    270: 
1.24      anton     271: The @file{mini-oof.fs} model
1.23      crook     272: 
                    273: * Basic Mini-OOF Usage::
                    274: * Mini-OOF Example::
                    275: * Mini-OOF Implementation::
                    276: 
1.21      crook     277: Word Lists
                    278: 
                    279: * Why use word lists?::
                    280: * Word list examples::
                    281: 
1.12      anton     282: Including Files
                    283: 
                    284: * Words for Including::         
                    285: * Search Path::                 
1.21      crook     286: * Forth Search Paths::    
1.12      anton     287: * General Search Paths::        
                    288: 
1.21      crook     289: Other I/O
                    290: 
1.24      anton     291: * Simple numeric output::       Predefined formats
                    292: * Formatted numeric output::    Formatted (pictured) output
                    293: * String Formats::              How Forth stores strings in memory
                    294: * Displaying characters and strings:: Other stuff
                    295: * Input::                       Input
1.21      crook     296: 
1.12      anton     297: Programming Tools
                    298: 
                    299: * Debugging::                   Simple and quick.
                    300: * Assertions::                  Making your programs self-checking.
                    301: * Singlestep Debugger::                Executing your program word by word.
                    302: 
                    303: Tools
                    304: 
                    305: * ANS Report::                  Report the words used, sorted by wordset.
                    306: 
                    307: ANS conformance
                    308: 
                    309: * The Core Words::              
                    310: * The optional Block word set::  
                    311: * The optional Double Number word set::  
                    312: * The optional Exception word set::  
                    313: * The optional Facility word set::  
                    314: * The optional File-Access word set::  
                    315: * The optional Floating-Point word set::  
                    316: * The optional Locals word set::  
                    317: * The optional Memory-Allocation word set::  
                    318: * The optional Programming-Tools word set::  
                    319: * The optional Search-Order word set::  
                    320: 
                    321: The Core Words
                    322: 
                    323: * core-idef::                   Implementation Defined Options                   
                    324: * core-ambcond::                Ambiguous Conditions                
                    325: * core-other::                  Other System Documentation                  
                    326: 
                    327: The optional Block word set
                    328: 
                    329: * block-idef::                  Implementation Defined Options
                    330: * block-ambcond::               Ambiguous Conditions               
                    331: * block-other::                 Other System Documentation                 
                    332: 
                    333: The optional Double Number word set
                    334: 
                    335: * double-ambcond::              Ambiguous Conditions              
                    336: 
                    337: The optional Exception word set
                    338: 
                    339: * exception-idef::              Implementation Defined Options              
                    340: 
                    341: The optional Facility word set
                    342: 
                    343: * facility-idef::               Implementation Defined Options               
                    344: * facility-ambcond::            Ambiguous Conditions            
                    345: 
                    346: The optional File-Access word set
                    347: 
                    348: * file-idef::                   Implementation Defined Options
                    349: * file-ambcond::                Ambiguous Conditions                
                    350: 
                    351: The optional Floating-Point word set
                    352: 
                    353: * floating-idef::               Implementation Defined Options
                    354: * floating-ambcond::            Ambiguous Conditions            
                    355: 
                    356: The optional Locals word set
                    357: 
                    358: * locals-idef::                 Implementation Defined Options                 
                    359: * locals-ambcond::              Ambiguous Conditions              
                    360: 
                    361: The optional Memory-Allocation word set
                    362: 
                    363: * memory-idef::                 Implementation Defined Options                 
                    364: 
                    365: The optional Programming-Tools word set
                    366: 
                    367: * programming-idef::            Implementation Defined Options            
                    368: * programming-ambcond::         Ambiguous Conditions         
                    369: 
                    370: The optional Search-Order word set
                    371: 
                    372: * search-idef::                 Implementation Defined Options                 
                    373: * search-ambcond::              Ambiguous Conditions              
                    374: 
                    375: Image Files
                    376: 
1.24      anton     377: * Image Licensing Issues::      Distribution terms for images.
                    378: * Image File Background::       Why have image files?
                    379: * Non-Relocatable Image Files::  don't always work.
                    380: * Data-Relocatable Image Files::  are better.
1.12      anton     381: * Fully Relocatable Image Files::  better yet.
1.24      anton     382: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
                    383: * Running Image Files::         @code{gforth -i @var{file}} or @var{file}.
                    384: * Modifying the Startup Sequence::  and turnkey applications.
1.12      anton     385: 
                    386: Fully Relocatable Image Files
                    387: 
1.24      anton     388: * gforthmi::            The normal way
1.12      anton     389: * cross.fs::                    The hard way
                    390: 
                    391: Engine
                    392: 
                    393: * Portability::                 
                    394: * Threading::                   
                    395: * Primitives::                  
                    396: * Performance::                 
                    397: 
                    398: Threading
                    399: 
                    400: * Scheduling::                  
                    401: * Direct or Indirect Threaded?::  
                    402: * DOES>::                       
                    403: 
                    404: Primitives
                    405: 
                    406: * Automatic Generation::        
                    407: * TOS Optimization::            
                    408: * Produced code::               
1.13      pazsan    409: 
                    410: Cross Compiler
                    411: 
                    412: * Using the Cross Compiler::
                    413: * How the Cross Compiler Works::
                    414: 
1.24      anton     415: Other Forth-related information
1.21      crook     416: 
                    417: * Internet resources::
                    418: * Books::
                    419: * The Forth Interest Group::
                    420: * Conferences::
                    421: 
1.24      anton     422: @end detailmenu
1.1       anton     423: @end menu
                    424: 
1.21      crook     425: @node License, Introduction, Top, Top
1.1       anton     426: @unnumbered GNU GENERAL PUBLIC LICENSE
                    427: @center Version 2, June 1991
                    428: 
                    429: @display
                    430: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
                    431: 675 Mass Ave, Cambridge, MA 02139, USA
                    432: 
                    433: Everyone is permitted to copy and distribute verbatim copies
                    434: of this license document, but changing it is not allowed.
                    435: @end display
                    436: 
                    437: @unnumberedsec Preamble
                    438: 
                    439:   The licenses for most software are designed to take away your
                    440: freedom to share and change it.  By contrast, the GNU General Public
                    441: License is intended to guarantee your freedom to share and change free
                    442: software---to make sure the software is free for all its users.  This
                    443: General Public License applies to most of the Free Software
                    444: Foundation's software and to any other program whose authors commit to
                    445: using it.  (Some other Free Software Foundation software is covered by
                    446: the GNU Library General Public License instead.)  You can apply it to
                    447: your programs, too.
                    448: 
                    449:   When we speak of free software, we are referring to freedom, not
                    450: price.  Our General Public Licenses are designed to make sure that you
                    451: have the freedom to distribute copies of free software (and charge for
                    452: this service if you wish), that you receive source code or can get it
                    453: if you want it, that you can change the software or use pieces of it
                    454: in new free programs; and that you know you can do these things.
                    455: 
                    456:   To protect your rights, we need to make restrictions that forbid
                    457: anyone to deny you these rights or to ask you to surrender the rights.
                    458: These restrictions translate to certain responsibilities for you if you
                    459: distribute copies of the software, or if you modify it.
                    460: 
                    461:   For example, if you distribute copies of such a program, whether
                    462: gratis or for a fee, you must give the recipients all the rights that
                    463: you have.  You must make sure that they, too, receive or can get the
                    464: source code.  And you must show them these terms so they know their
                    465: rights.
                    466: 
                    467:   We protect your rights with two steps: (1) copyright the software, and
                    468: (2) offer you this license which gives you legal permission to copy,
                    469: distribute and/or modify the software.
                    470: 
                    471:   Also, for each author's protection and ours, we want to make certain
                    472: that everyone understands that there is no warranty for this free
                    473: software.  If the software is modified by someone else and passed on, we
                    474: want its recipients to know that what they have is not the original, so
                    475: that any problems introduced by others will not reflect on the original
                    476: authors' reputations.
                    477: 
                    478:   Finally, any free program is threatened constantly by software
                    479: patents.  We wish to avoid the danger that redistributors of a free
                    480: program will individually obtain patent licenses, in effect making the
                    481: program proprietary.  To prevent this, we have made it clear that any
                    482: patent must be licensed for everyone's free use or not licensed at all.
                    483: 
                    484:   The precise terms and conditions for copying, distribution and
                    485: modification follow.
                    486: 
                    487: @iftex
                    488: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
                    489: @end iftex
                    490: @ifinfo
                    491: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
                    492: @end ifinfo
                    493: 
                    494: @enumerate 0
                    495: @item
                    496: This License applies to any program or other work which contains
                    497: a notice placed by the copyright holder saying it may be distributed
                    498: under the terms of this General Public License.  The ``Program'', below,
                    499: refers to any such program or work, and a ``work based on the Program''
                    500: means either the Program or any derivative work under copyright law:
                    501: that is to say, a work containing the Program or a portion of it,
                    502: either verbatim or with modifications and/or translated into another
                    503: language.  (Hereinafter, translation is included without limitation in
                    504: the term ``modification''.)  Each licensee is addressed as ``you''.
                    505: 
                    506: Activities other than copying, distribution and modification are not
                    507: covered by this License; they are outside its scope.  The act of
                    508: running the Program is not restricted, and the output from the Program
                    509: is covered only if its contents constitute a work based on the
                    510: Program (independent of having been made by running the Program).
                    511: Whether that is true depends on what the Program does.
                    512: 
                    513: @item
                    514: You may copy and distribute verbatim copies of the Program's
                    515: source code as you receive it, in any medium, provided that you
                    516: conspicuously and appropriately publish on each copy an appropriate
                    517: copyright notice and disclaimer of warranty; keep intact all the
                    518: notices that refer to this License and to the absence of any warranty;
                    519: and give any other recipients of the Program a copy of this License
                    520: along with the Program.
                    521: 
                    522: You may charge a fee for the physical act of transferring a copy, and
                    523: you may at your option offer warranty protection in exchange for a fee.
                    524: 
                    525: @item
                    526: You may modify your copy or copies of the Program or any portion
                    527: of it, thus forming a work based on the Program, and copy and
                    528: distribute such modifications or work under the terms of Section 1
                    529: above, provided that you also meet all of these conditions:
                    530: 
                    531: @enumerate a
                    532: @item
                    533: You must cause the modified files to carry prominent notices
                    534: stating that you changed the files and the date of any change.
                    535: 
                    536: @item
                    537: You must cause any work that you distribute or publish, that in
                    538: whole or in part contains or is derived from the Program or any
                    539: part thereof, to be licensed as a whole at no charge to all third
                    540: parties under the terms of this License.
                    541: 
                    542: @item
                    543: If the modified program normally reads commands interactively
                    544: when run, you must cause it, when started running for such
                    545: interactive use in the most ordinary way, to print or display an
                    546: announcement including an appropriate copyright notice and a
                    547: notice that there is no warranty (or else, saying that you provide
                    548: a warranty) and that users may redistribute the program under
                    549: these conditions, and telling the user how to view a copy of this
                    550: License.  (Exception: if the Program itself is interactive but
                    551: does not normally print such an announcement, your work based on
                    552: the Program is not required to print an announcement.)
                    553: @end enumerate
                    554: 
                    555: These requirements apply to the modified work as a whole.  If
                    556: identifiable sections of that work are not derived from the Program,
                    557: and can be reasonably considered independent and separate works in
                    558: themselves, then this License, and its terms, do not apply to those
                    559: sections when you distribute them as separate works.  But when you
                    560: distribute the same sections as part of a whole which is a work based
                    561: on the Program, the distribution of the whole must be on the terms of
                    562: this License, whose permissions for other licensees extend to the
                    563: entire whole, and thus to each and every part regardless of who wrote it.
                    564: 
                    565: Thus, it is not the intent of this section to claim rights or contest
                    566: your rights to work written entirely by you; rather, the intent is to
                    567: exercise the right to control the distribution of derivative or
                    568: collective works based on the Program.
                    569: 
                    570: In addition, mere aggregation of another work not based on the Program
                    571: with the Program (or with a work based on the Program) on a volume of
                    572: a storage or distribution medium does not bring the other work under
                    573: the scope of this License.
                    574: 
                    575: @item
                    576: You may copy and distribute the Program (or a work based on it,
                    577: under Section 2) in object code or executable form under the terms of
                    578: Sections 1 and 2 above provided that you also do one of the following:
                    579: 
                    580: @enumerate a
                    581: @item
                    582: Accompany it with the complete corresponding machine-readable
                    583: source code, which must be distributed under the terms of Sections
                    584: 1 and 2 above on a medium customarily used for software interchange; or,
                    585: 
                    586: @item
                    587: Accompany it with a written offer, valid for at least three
                    588: years, to give any third party, for a charge no more than your
                    589: cost of physically performing source distribution, a complete
                    590: machine-readable copy of the corresponding source code, to be
                    591: distributed under the terms of Sections 1 and 2 above on a medium
                    592: customarily used for software interchange; or,
                    593: 
                    594: @item
                    595: Accompany it with the information you received as to the offer
                    596: to distribute corresponding source code.  (This alternative is
                    597: allowed only for noncommercial distribution and only if you
                    598: received the program in object code or executable form with such
                    599: an offer, in accord with Subsection b above.)
                    600: @end enumerate
                    601: 
                    602: The source code for a work means the preferred form of the work for
                    603: making modifications to it.  For an executable work, complete source
                    604: code means all the source code for all modules it contains, plus any
                    605: associated interface definition files, plus the scripts used to
                    606: control compilation and installation of the executable.  However, as a
                    607: special exception, the source code distributed need not include
                    608: anything that is normally distributed (in either source or binary
                    609: form) with the major components (compiler, kernel, and so on) of the
                    610: operating system on which the executable runs, unless that component
                    611: itself accompanies the executable.
                    612: 
                    613: If distribution of executable or object code is made by offering
                    614: access to copy from a designated place, then offering equivalent
                    615: access to copy the source code from the same place counts as
                    616: distribution of the source code, even though third parties are not
                    617: compelled to copy the source along with the object code.
                    618: 
                    619: @item
                    620: You may not copy, modify, sublicense, or distribute the Program
                    621: except as expressly provided under this License.  Any attempt
                    622: otherwise to copy, modify, sublicense or distribute the Program is
                    623: void, and will automatically terminate your rights under this License.
                    624: However, parties who have received copies, or rights, from you under
                    625: this License will not have their licenses terminated so long as such
                    626: parties remain in full compliance.
                    627: 
                    628: @item
                    629: You are not required to accept this License, since you have not
                    630: signed it.  However, nothing else grants you permission to modify or
                    631: distribute the Program or its derivative works.  These actions are
                    632: prohibited by law if you do not accept this License.  Therefore, by
                    633: modifying or distributing the Program (or any work based on the
                    634: Program), you indicate your acceptance of this License to do so, and
                    635: all its terms and conditions for copying, distributing or modifying
                    636: the Program or works based on it.
                    637: 
                    638: @item
                    639: Each time you redistribute the Program (or any work based on the
                    640: Program), the recipient automatically receives a license from the
                    641: original licensor to copy, distribute or modify the Program subject to
                    642: these terms and conditions.  You may not impose any further
                    643: restrictions on the recipients' exercise of the rights granted herein.
                    644: You are not responsible for enforcing compliance by third parties to
                    645: this License.
                    646: 
                    647: @item
                    648: If, as a consequence of a court judgment or allegation of patent
                    649: infringement or for any other reason (not limited to patent issues),
                    650: conditions are imposed on you (whether by court order, agreement or
                    651: otherwise) that contradict the conditions of this License, they do not
                    652: excuse you from the conditions of this License.  If you cannot
                    653: distribute so as to satisfy simultaneously your obligations under this
                    654: License and any other pertinent obligations, then as a consequence you
                    655: may not distribute the Program at all.  For example, if a patent
                    656: license would not permit royalty-free redistribution of the Program by
                    657: all those who receive copies directly or indirectly through you, then
                    658: the only way you could satisfy both it and this License would be to
                    659: refrain entirely from distribution of the Program.
                    660: 
                    661: If any portion of this section is held invalid or unenforceable under
                    662: any particular circumstance, the balance of the section is intended to
                    663: apply and the section as a whole is intended to apply in other
                    664: circumstances.
                    665: 
                    666: It is not the purpose of this section to induce you to infringe any
                    667: patents or other property right claims or to contest validity of any
                    668: such claims; this section has the sole purpose of protecting the
                    669: integrity of the free software distribution system, which is
                    670: implemented by public license practices.  Many people have made
                    671: generous contributions to the wide range of software distributed
                    672: through that system in reliance on consistent application of that
                    673: system; it is up to the author/donor to decide if he or she is willing
                    674: to distribute software through any other system and a licensee cannot
                    675: impose that choice.
                    676: 
                    677: This section is intended to make thoroughly clear what is believed to
                    678: be a consequence of the rest of this License.
                    679: 
                    680: @item
                    681: If the distribution and/or use of the Program is restricted in
                    682: certain countries either by patents or by copyrighted interfaces, the
                    683: original copyright holder who places the Program under this License
                    684: may add an explicit geographical distribution limitation excluding
                    685: those countries, so that distribution is permitted only in or among
                    686: countries not thus excluded.  In such case, this License incorporates
                    687: the limitation as if written in the body of this License.
                    688: 
                    689: @item
                    690: The Free Software Foundation may publish revised and/or new versions
                    691: of the General Public License from time to time.  Such new versions will
                    692: be similar in spirit to the present version, but may differ in detail to
                    693: address new problems or concerns.
                    694: 
                    695: Each version is given a distinguishing version number.  If the Program
                    696: specifies a version number of this License which applies to it and ``any
                    697: later version'', you have the option of following the terms and conditions
                    698: either of that version or of any later version published by the Free
                    699: Software Foundation.  If the Program does not specify a version number of
                    700: this License, you may choose any version ever published by the Free Software
                    701: Foundation.
                    702: 
                    703: @item
                    704: If you wish to incorporate parts of the Program into other free
                    705: programs whose distribution conditions are different, write to the author
                    706: to ask for permission.  For software which is copyrighted by the Free
                    707: Software Foundation, write to the Free Software Foundation; we sometimes
                    708: make exceptions for this.  Our decision will be guided by the two goals
                    709: of preserving the free status of all derivatives of our free software and
                    710: of promoting the sharing and reuse of software generally.
                    711: 
                    712: @iftex
                    713: @heading NO WARRANTY
                    714: @end iftex
                    715: @ifinfo
                    716: @center NO WARRANTY
                    717: @end ifinfo
                    718: 
                    719: @item
                    720: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
                    721: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
                    722: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
                    723: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
                    724: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
                    725: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
                    726: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
                    727: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
                    728: REPAIR OR CORRECTION.
                    729: 
                    730: @item
                    731: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
                    732: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
                    733: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
                    734: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
                    735: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
                    736: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
                    737: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
                    738: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
                    739: POSSIBILITY OF SUCH DAMAGES.
                    740: @end enumerate
                    741: 
                    742: @iftex
                    743: @heading END OF TERMS AND CONDITIONS
                    744: @end iftex
                    745: @ifinfo
                    746: @center END OF TERMS AND CONDITIONS
                    747: @end ifinfo
                    748: 
                    749: @page
                    750: @unnumberedsec How to Apply These Terms to Your New Programs
                    751: 
                    752:   If you develop a new program, and you want it to be of the greatest
                    753: possible use to the public, the best way to achieve this is to make it
                    754: free software which everyone can redistribute and change under these terms.
                    755: 
                    756:   To do so, attach the following notices to the program.  It is safest
                    757: to attach them to the start of each source file to most effectively
                    758: convey the exclusion of warranty; and each file should have at least
                    759: the ``copyright'' line and a pointer to where the full notice is found.
                    760: 
                    761: @smallexample
                    762: @var{one line to give the program's name and a brief idea of what it does.}
                    763: Copyright (C) 19@var{yy}  @var{name of author}
                    764: 
                    765: This program is free software; you can redistribute it and/or modify 
                    766: it under the terms of the GNU General Public License as published by 
                    767: the Free Software Foundation; either version 2 of the License, or 
                    768: (at your option) any later version.
                    769: 
                    770: This program is distributed in the hope that it will be useful,
                    771: but WITHOUT ANY WARRANTY; without even the implied warranty of
                    772: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                    773: GNU General Public License for more details.
                    774: 
                    775: You should have received a copy of the GNU General Public License
                    776: along with this program; if not, write to the Free Software
                    777: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
                    778: @end smallexample
                    779: 
                    780: Also add information on how to contact you by electronic and paper mail.
                    781: 
                    782: If the program is interactive, make it output a short notice like this
                    783: when it starts in an interactive mode:
                    784: 
                    785: @smallexample
                    786: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
                    787: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
                    788: type `show w'.  
                    789: This is free software, and you are welcome to redistribute it 
                    790: under certain conditions; type `show c' for details.
                    791: @end smallexample
                    792: 
                    793: The hypothetical commands @samp{show w} and @samp{show c} should show
                    794: the appropriate parts of the General Public License.  Of course, the
                    795: commands you use may be called something other than @samp{show w} and
                    796: @samp{show c}; they could even be mouse-clicks or menu items---whatever
                    797: suits your program.
                    798: 
                    799: You should also get your employer (if you work as a programmer) or your
                    800: school, if any, to sign a ``copyright disclaimer'' for the program, if
                    801: necessary.  Here is a sample; alter the names:
                    802: 
                    803: @smallexample
                    804: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
                    805: `Gnomovision' (which makes passes at compilers) written by James Hacker.
                    806: 
                    807: @var{signature of Ty Coon}, 1 April 1989
                    808: Ty Coon, President of Vice
                    809: @end smallexample
                    810: 
                    811: This General Public License does not permit incorporating your program into
                    812: proprietary programs.  If your program is a subroutine library, you may
                    813: consider it more useful to permit linking proprietary applications with the
                    814: library.  If this is what you want to do, use the GNU Library General
                    815: Public License instead of this License.
                    816: 
                    817: @iftex
                    818: @unnumbered Preface
                    819: @cindex Preface
1.21      crook     820: This manual documents Gforth. Some introductory material is provided for
                    821: readers who are unfamiliar with Forth or who are migrating to Gforth
                    822: from other Forth compilers. However, this manual is primarily a
                    823: reference manual.
1.1       anton     824: @end iftex
                    825: 
1.21      crook     826: @c ----------------------------------------------------------
                    827: @node    Introduction, Goals, License, Top
                    828: @comment node-name,     next,           previous, up
                    829: @chapter An Introduction to ANS Forth
                    830: @cindex Forth - an introduction
                    831: 
                    832: The primary purpose of this manual is to document Gforth. However, since
                    833: Forth is not a widely-known language and there is a lack of up-to-date
                    834: teaching material, it seems worthwhile to provide some introductory
                    835: material. @xref{Forth-related information} for other sources of Forth-related
                    836: information.
                    837: 
                    838: The examples in this section should work on any ANS Standard Forth, the
                    839: output shown was produced using Gforth. In each example, I have tried to
                    840: reproduce the exact output that Gforth produces. If you try out the
                    841: examples (and you should), what you should type is shown @kbd{like this}
                    842: and Gforth's response is shown @code{like this}. The single exception is
                    843: that, where the example shows @kbd{<return>} it means that you should
                    844: press the "carriage return" key. Unfortunatley, some output formats for
                    845: this manual cannot show the difference between @kbd{this} and
                    846: @code{this} which will make trying out the examples harder (but not
                    847: impossible).
                    848: 
                    849: Forth is an unusual language. It provides an interactive development
                    850: environment which includes both an interpreter and compiler. Forth
                    851: programming style encourages you to break a problem down into many
                    852: @cindex factoring
                    853: small fragments (@var{factoring}), and then to develop and test each
                    854: fragment interactively. Forth advocates assert that breaking the
                    855: edit-compile-test cycle used by conventional programming languages can
                    856: lead to great productivity improvements.
                    857: 
                    858: @menu
                    859: * Introducing the Text Interpreter::
                    860: * Stacks and Postfix notation::
                    861: * Your first definition::
                    862: * How does that work?::
                    863: * Forth is written in Forth::
                    864: * Review - elements of a Forth system::
                    865: * Exercises::
                    866: @end menu
                    867: @comment TODO add these sections to the top xref lists
                    868: 
                    869: @comment ----------------------------------------------
                    870: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                    871: @section Introducing the Text Interpreter
                    872: @cindex text interpreter
                    873: @cindex outer interpreter
                    874: 
                    875: When you invoke the Forth image, you will see a startup banner printed
                    876: and nothing else (if you have Gforth installed on your system, try
                    877: invoking it now, by typing @kbd{gforth<return>}). Forth is now running
                    878: its command line interpreter, which is called the @var{Text Interpreter}
                    879: (also known as the @var{Outer Interpreter}).  (@pxref{The Text
                    880: Interpreter} describes it in more detail, but we will learn more about
                    881: its behaviour as we go through this chapter).
                    882: 
                    883: Although it may not be obvious, Forth is actually waiting for your
                    884: input. Type a number and press the <return> key:
                    885: 
                    886: @example
                    887: @kbd{45<return>}  ok
                    888: @end example
                    889: 
                    890: Rather than give you a prompt to invite you to input something, the text
                    891: interpreter prints a status message @var{after} it has processed a line
                    892: of input. The status message in this case (" ok" followed by
                    893: carriage-return) indicates that the text interpreter was able to process
                    894: all of your input successfully. Now type something illegal:
                    895: 
                    896: @example
                    897: @kbd{qwer341<return>}
                    898: ^^^^^^^
                    899: Error: Undefined word
                    900: @end example
                    901: 
                    902: When the text interpreter detects an error, it discards any remaining
                    903: text on a line, resets certain internal state and prints an error
                    904: message.
                    905: 
                    906: The text interpreter works on input one line at a time. Starting at
                    907: the beginning of the line, it breaks the line into groups of characters
                    908: separated by spaces. For each group of characters in turn, it makes two
                    909: attempts to do something:
                    910: 
                    911: @itemize @bullet
                    912: @item
                    913: It tries to treat it as a command. It does this by searching a @var{name
                    914: dictionary}. If the group of characters matches an entry in the name
                    915: dictionary, the name dictionary provides the text interpreter with
                    916: information that allows the text interpreter perform some actions. In
                    917: Forth jargon, we say that the group
                    918: @cindex word
                    919: @cindex definition
                    920: @cindex execution token
                    921: @cindex xt
                    922: of characters names a @var{word}, that the dictionary search returns an
                    923: @var{execution token (xt)} corresponding to the @var{definition} of the
                    924: word, and that the text interpreter executes the xt. Often, the terms
                    925: @var{word} and @var{definition} are used interchangeably.
                    926: @item
                    927: If the text interpreter fails to find a match in the name dictionary, it
                    928: tries to treat the group of characters as a number in the current number
                    929: base (when you start up Forth, the current number base is base 10). If
                    930: the group of characters legitimately represents a number, the text
                    931: interpreter pushes the number onto a stack (we'll learn more about that
                    932: in the next section).
                    933: @end itemize
                    934: 
                    935: If the text interpreter is unable to do either of these things with any
                    936: group of characters, it discards the rest of the line and print an error
                    937: message. If the text interpreter reaches the end of the line without
                    938: error, it prints the status message " ok" followed by carriage-return.
                    939: 
                    940: This is the simplest command we can give to the text interpreter:
                    941: 
                    942: @example
                    943: @kbd{<return>}  ok
                    944: @end example
                    945: 
                    946: The text interpreter did everything we asked it to do (nothing) without
                    947: an error, so it said that everything is "ok". Try a slightly longer
                    948: command:
                    949: 
                    950: @example
                    951: @kbd{12 dup fred dup<return>}
                    952:        ^^^^
                    953: Error: Undefined word
                    954: @end example
                    955: 
                    956: When you pres the <return> key, the text interpreter starts to work its
                    957: way along the line.
                    958: 
                    959: @itemize @bullet
                    960: @item
                    961: When it gets to the space after the @code{2}, it takes the group of
                    962: characters @code{12} and looks them up in the name
                    963: dictionary@footnote{We can't tell if it found them or not, but assume
                    964: for now that it did not}. There is no match for this group of characters
                    965: in the name dictionary, so it tries to treat them as a number. It is
                    966: able to do this successfully, so it puts the number, 12, "on the stack"
                    967: (whatever that means).
                    968: @item
                    969: The text interpreter resumes scanning the line and gets the next group
                    970: of characters, @code{dup}. It looks them up in the name dictionary and
                    971: (you'll have to take my word for this) finds them, and executes the word
                    972: @code{dup} (whatever that means).
                    973: @item
                    974: Once again, the text interpreter resumes scanning the line and gets the
                    975: group of characters @code{fred}. It looks them up in the name
                    976: dictionary, but can't find them. It tries to treat them as a number, but
                    977: they don't represent any legal number.
                    978: @end itemize
                    979: 
                    980: At this point, the text interpreter gives up and prints an error
                    981: message. The error message shows exactly how far the text interpreter
                    982: got in processing the line. In particular, it shows that the text
                    983: interpreter made no attempt to do anything with the final character
                    984: group, @code{dup}, even though we have good reason to believe that the
                    985: text interpreter would have had no problems with looking that word up
                    986: and executing it a second time.
                    987: 
                    988: 
                    989: @comment ----------------------------------------------
                    990: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                    991: @section Stacks, postfix notation and parameter passing
                    992: @cindex text interpreter
                    993: @cindex outer interpreter
                    994: 
                    995: In procedural programming languages (like C and Pascal), the
                    996: building-block of programs is the function or procedure. These
                    997: functions or procedures are called with explicit parameters. For
                    998: example, in C we might write:
                    999: 
                   1000: @example
                   1001: total = total + new_volume(length,height,depth);
                   1002: @end example
                   1003: 
                   1004: where total, length, height, depth are all variables and new_volume is
                   1005: a function-call to another piece of code.
                   1006: 
                   1007: In Forth, the equivalent to the function or procedure is the
                   1008: @var{definition} and parameters are implicitly passed between
                   1009: definitions using a shared stack that is visible to the
                   1010: programmer. Although Forth does support variables, the existence of the
                   1011: stack means that they are used far less often than in most other
                   1012: programming languages. When the text interpreter encounters a number, it
                   1013: will place (@var{push}) it on the stack. There are several stacks (the
                   1014: actual number is implementation-dependent ..) and the particular stack
                   1015: used for any operation is implied unambiguously by the operation being
                   1016: performed. The stack used for all integer operations is called the @var{data
                   1017: stack} and, since this is the stack used most commonly, references to
                   1018: "the data stack" are often abbreviated to "the stack".
                   1019: 
                   1020: The stacks have a last-in, first-out (LIFO) organisation. If you type:
                   1021: 
                   1022: @example
                   1023: @kbd{1 2 3<return>}  ok
                   1024: @end example
                   1025: 
                   1026: Then you (well, the text interpreter, really) have placed three numbers
                   1027: on the (data) stack. An analogy for the behaviour of the stack is to
                   1028: take a pack of playing cards and deal out the ace (1), 2 and 3 into a
                   1029: pile on the table. The 3 was the last card onto the pile ("last-in") and
                   1030: if you take a card off the pile then, unless you're prepared to fiddle a
                   1031: bit, the card that you take off will be the 3 ("first-out"). The number
                   1032: that will be first-out of the stack is called the "top of stack", which
                   1033: is often abbreviated to @var{TOS}.
                   1034: 
                   1035: To see how parameters are passed in Forth, we will consider the
                   1036: behaviour of the definition @code{+} (pronounced "plus"). You will not be
                   1037: surprised to learn that this definition performs addition. More
                   1038: precisely, it adds two number together and produces a result. Where does
                   1039: it get the two numbers from? It takes the first two numbers off the
                   1040: stack. Where does it place the result? On the stack. You can act-out the
                   1041: behaviour of @code{+} with your playing cards like this:
                   1042: 
                   1043: @itemize @bullet
                   1044: @item
                   1045: Pick up two cards from the stack
                   1046: @item
                   1047: Stare at them intently and ask yourself "what *is* the sum of these two
                   1048: numbers"
                   1049: @item
                   1050: Decide that the answer is 5
                   1051: @item
                   1052: Shuffle the two cards back into the pack and find a 5
                   1053: @item
                   1054: Put a 5 on the remaining ace that's on the table.
                   1055: @end itemize
                   1056: 
                   1057: If you don't have a pack of cards handy but you do have Forth running,
                   1058: you can use the definition .s to show the current state of the stack,
                   1059: without affecting the stack. Type:
                   1060: 
                   1061: @example
                   1062: @kbd{clearstack 1 2 3<return>} ok
                   1063: @kbd{.s<return> <3> 1 2 3 } ok
                   1064: @end example
                   1065: 
                   1066: The text interpreter looks up the word @code{clearstack} and executes
                   1067: it; it tidies up the stack and removes any entries that may have been
                   1068: left on it by earlier examples. The text interpreter pushes each of the
                   1069: three numbers in turn onto the stack. Finally, the text interpreter
                   1070: looks up the word @code{.s} and executes it. The effect of executing
                   1071: @code{.s} is to print the "<3>" (the total number of items on the stack)
                   1072: followed by a list of all the items and the item on the far right-hand
                   1073: side is the TOS.
                   1074: 
                   1075: You can now type:
                   1076: 
                   1077: + .s<return> <2> 1 5  ok
                   1078: 
                   1079: which is correct; there are now 2 items on the stack and the result of
                   1080: the addition is 5.
                   1081: 
                   1082: If you're playing with cards, try doing a second addition; pick up the
                   1083: two cards, work out that their sum is 6, shuffle them into the pack,
                   1084: look for a 6 and place that on the table. You now have just one item
                   1085: on the stack. What happens if you try to do a third addition? Pick up
                   1086: the first card, pick up the second card - ah. There is no second
                   1087: card. This is called a "stack underflow" and consitutes an error. If
                   1088: you try to do the same thing with Forth it will report an error
                   1089: (probably a Stack Underflow or an Invalid Memory Address error).
                   1090: 
                   1091: The opposite situation to a stack underflow is a stack overflow, which
                   1092: simply accepts that there is a finite amount of storage space reserved
                   1093: for the stack. To stretch the playing card analogy, if you had enough
                   1094: packs of cards and you piled the cards up on the table, you would
                   1095: eventually be unable to add another card; you'd hit the
                   1096: ceiling. Gforth allows you to set the maximum size of the stacks. In
                   1097: general, the only time that you will get a stack overflow is because a
                   1098: definition has a bug in it and is generating data on the stack
                   1099: uncontrollably.
                   1100: 
                   1101: There's one final use for the playing card analogy. If you model your
                   1102: stack using a pack of playing cards, the maximum number of items on
                   1103: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   1104: *value* of any item on the stack is 13 (the King). In fact, the only
                   1105: possible numbers are positive integer numbers 1 through 13; you can't
                   1106: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   1107: think about some of the cards, you can accommodate different
                   1108: numbers. For example, you could think of the Jack as representing 0,
                   1109: the Queen as representing -1 and the King as representing -2. Your
                   1110: *range* remains unchanged (you can still only represent a total of 13
                   1111: numbers) but the numbers that you can represent are -2 through 10.
                   1112: 
                   1113: In that analogy, the limit was the amount of information that a single
                   1114: stack entry could hold, and Forth has a similar limit. In Forth, the
                   1115: size of a stack entry is called a "cell". The actual size of a cell is
                   1116: implementation dependent and affects the maximum value that a stack
                   1117: entry can hold. A Standard Forth provides a cell size of at least
                   1118: 16-bits, and most desktop systems use a cell size of 32-bits.
                   1119: 
                   1120: Forth does not do any type checking for you, so you are free to
                   1121: manipulate and combine stack items in any way you wish. A convenient
                   1122: ways of treating stack items is as 2's complement signed integers, and
                   1123: that is what Standard words like "+" do. Therefore you can type:
                   1124: 
                   1125: -5 12 + .s<return> <1> 7  ok
                   1126: 
                   1127: If you use numbers and definitions like "+" in order to turn Forth
                   1128: into a great big pocket calculator, you will realise that it's rather
                   1129: different from a normal calculator. Rather than typing 2 + 3 = you had
                   1130: to type 2 3 + (ignore the fact that you had to use .s to see the
                   1131: result). The terminology used to describe this difference is to say
                   1132: that your calculator uses "Infix Notation" (parameters and operators
                   1133: are mixed) whilst Forth uses "Postfix Notation" (parameters and
                   1134: operators are separate), also called "Reverse Polish Notation".
                   1135: 
                   1136: Whilst postfix notation might look confusing to begin with, it has
                   1137: several important advantages:
                   1138: 
                   1139: - it is unambiguous
                   1140: - it is more concise
                   1141: - it fits naturally with a stack-based system
                   1142: 
                   1143: To examine these claims in more detail, consider these sums:
                   1144: 
                   1145: 6 + 5 * 4 =
                   1146: 4 * 5 + 6 =
                   1147: 
                   1148: If you're just learning maths or your maths is very rusty, you will
                   1149: probably come up with the answer 44 for the first and 26 for the
                   1150: second. If you are a bit of a whizz at maths you will remember the
                   1151: *convention* that multiplication takes precendence over addition, and
                   1152: you'd come up with the answer 26 both times. To explain the answer 26
                   1153: to someone who got the answer 44, you'd probably rewrite the first sum
                   1154: like this:
                   1155: 
                   1156: 6 + (5 * 4) =
                   1157: 
                   1158: If what you really wanted was to perform the addition before the
                   1159: multiplication, you would have to use parentheses to force it.
                   1160: 
                   1161: If you did the first two sums on a pocket calculator you would probably
                   1162: get the right answers, unless you were very cautious and entered them using
                   1163: these keystroke sequences:
                   1164: 
                   1165: 6 + 5 = * 4 =
                   1166: 4 * 5 = + 6 =
                   1167: 
                   1168: Postfix notation is unambiguous because the order that the operators
                   1169: are applied is always explicit; that also means that parentheses are
                   1170: never required. The operators are *active* (the act of quoting the
                   1171: operator makes the operation occur) which removes the need for "=".
                   1172: 
                   1173: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   1174: equivalent ways:
                   1175: 
                   1176: 6 5 4 * +      or:
                   1177: 5 4 * 6 +
                   1178: 
1.23      crook    1179: An important thing that you should notice about this notation is that
                   1180: the @var{order} of the numbers does not change; if you want to subtract
                   1181: 2 from 10 you type @code{10 2 -}.
                   1182: 
                   1183: The reason why Forth uses postfix notation is very simple to explain: it
                   1184: makes the implementation extremely simple, and it follows naturally from
                   1185: using the stack as a mechanism for passing parameters. Another way of
                   1186: thinking about this is to realise that all Forth definitions are
                   1187: @var{active}; they execute as they are encountered by the text
                   1188: interpreter. The result of this is that the syntax of Forth is almost
                   1189: trivially simple.
                   1190: 
                   1191: 
                   1192: 
                   1193: @comment ----------------------------------------------
                   1194: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   1195: @section Your first Forth definition
                   1196: @cindex first definition
1.21      crook    1197: 
1.23      crook    1198: Until now, the examples we've seen have been trivial; we've just been
                   1199: using Forth an a bigger-than-pocket calculator. Also, each calculation
                   1200: we've shown has been a "one-off" -- to repeat it we'd need to type it in
                   1201: again@footnote{That's not quite true. If you press the up-arrow key on
                   1202: your keyboard you should be able to scroll back to any earlier command,
                   1203: edit it and re-enter it.} In this section we'll see how to add new
                   1204: word to Forth's vocabulary.
                   1205: 
                   1206: The easiest way to create a new word is to use a "colon
                   1207: definition". We'll define a few and try them out before we worry too
                   1208: much about how they work. Try typing in these examples; be careful to
                   1209: copy the spaces accurately:
                   1210: 
                   1211: @example
                   1212: : add-two 2 + . ;
                   1213: : greet ." Hello and welcome" ;
                   1214: : demo 5 add-two ;
                   1215: @end example
1.21      crook    1216: 
1.23      crook    1217: @noindent
                   1218: Now try them out:
1.21      crook    1219: 
1.23      crook    1220: @example
                   1221: @kbd{greet<return>} Hello and welcome  ok
                   1222: @kbd{greet greet<return>} Hello and welcomeHello and welcome  ok
                   1223: @kbd{4 add-two<return>} 6  ok
                   1224: @kbd{demo<return>} 7  ok
                   1225: @kbd{9 greet demo add-two<return>} Hello and welcome7 11  ok
                   1226: @end example
1.21      crook    1227: 
1.23      crook    1228: The first new thing that we've introduced here is the pair of words
                   1229: @code{:} and @code{;}. These are used to start and terminate a new
                   1230: definition, respectively. The first word after the @code{:} is the name
                   1231: for the new definition.
1.21      crook    1232: 
1.23      crook    1233: As you can see from the examples, a definition is built up of words that
                   1234: have already been defined; Forth makes no distinction between
                   1235: definitions that existed when you started the system up, and those that
                   1236: you define yourself.
1.21      crook    1237: 
1.23      crook    1238: The examples also introduce the words @code{.} (dot), @code{."} (dot-quote)
                   1239: and @code{dup} (dewp). Dot takes the value from the top of the stack and
                   1240: displays it. It's like @code{.s} except that it only displays the top
                   1241: item of the stack and it is destructive; after it has executed the
                   1242: number is no longer on the top of the stack. There is always one space
                   1243: printed after the number, and no spaces before it. Dot-quote defines a
                   1244: string (a sequence of characters) that will be printed when the word is
                   1245: executed. The string can contain any printable characters except
                   1246: @code{"}. A @code{"} has a special function; it is not itself a Forth
                   1247: word but it acts as a delimiter. The way that it works is described in
                   1248: the next section. Finally, @code{dup} duplicates the value at the top of
                   1249: the stack. Try typing @code{5 dup .s} to see what it does.
1.21      crook    1250: 
1.23      crook    1251: We already know that the text interpreter searches through the
                   1252: dictionary to locate names. If you've followed the examples earlier, you
                   1253: will already have a definition called @code{add-two}. Lets try modifying
                   1254: it by typing in a new definition:
1.21      crook    1255: 
1.23      crook    1256: @example
                   1257: @kbd{: add-two dup . ." + 2 =" 2 + . ;<return>} redefined add-two  ok
                   1258: @end example
1.21      crook    1259: 
1.23      crook    1260: Forth recognised that we were defining a word that already exists, and
                   1261: printed a message to warn us of that fact. Let's try out the new
                   1262: definition:
1.21      crook    1263: 
1.23      crook    1264: @example
                   1265: @kbd{9 add-two<return>} 9 + 2 =11  ok
                   1266: @end example
1.21      crook    1267: 
1.23      crook    1268: @noindent
                   1269: All that we've actually done here, though, is to create a new
                   1270: definition, with a particular name. The fact that there was already a
                   1271: definition with the same name did not make any difference to the way
                   1272: that the new definition was created (except that Forth printed a warning
                   1273: message). The old definition of add-two still exists (try @code{demo}
                   1274: again to see that this is true). Any new definition will use the new
                   1275: definition of @code{add-two}, but old definitions continue to use the
                   1276: version that already existed at the time that they were @code{compiled}.
1.21      crook    1277: 
1.23      crook    1278: Before you go on to the next section, try defining and redefining some
                   1279: words of your own.
1.21      crook    1280: 
                   1281: @comment ----------------------------------------------
                   1282: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   1283: @section How does that work?
                   1284: @cindex parsing words
                   1285: 
1.23      crook    1286: Now we're going to take another look at the definition of @code{add-two}
                   1287: from the previous section. From our knowledge of the way that the text
                   1288: interpreter works, we would have expected this result when we tried to
                   1289: define @code{add-two}:
1.21      crook    1290: 
1.23      crook    1291: @example
                   1292: @kbd{: add-two 2 + . " ;<return>}
                   1293:   ^^^^^^^
                   1294: Error: Undefined word
                   1295: @end example
1.21      crook    1296: 
1.23      crook    1297: The reason that this didn't happen is bound up in the way that @code{:}
                   1298: works. The word @code{:} does two special things. The first special
                   1299: thing that it does prevents the text interpreter from ever seeing the
                   1300: characters @code{add-two}. The text interpreter uses a variable called
                   1301: @cindex modifying >IN
                   1302: @code{>IN} (pronounced ''to-in'') to keep track of where it is in the
                   1303: input line. When it encounters the word @code{:} it behaves in exactly
                   1304: the same way as it does for any other word; it looks it up in the name
                   1305: dictionary, finds its xt and executes it. When @code{:} executes, it
                   1306: looks at the input buffer, finds the word @code{add-two} and advances the
                   1307: value of @code{>IN} to point past it. It then does some other stuff
                   1308: associated with creating the new definition (including creating an entry
                   1309: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   1310: completes, control returns to the text interpreter, which is oblivious
                   1311: to the fact that it has been tricked into ignoring part of the input
                   1312: line.
1.21      crook    1313: 
1.23      crook    1314: @cindex parsing words
                   1315: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   1316: prevent the text interpreter from acting on the whole of the input line
                   1317: -- are called @var{parsing words}.
                   1318: 
                   1319: @cindex state - effect on the text interpreter
                   1320: @cindex text interpreter - effect of state
                   1321: The second special thing that @code{:} does is to change the value of a
                   1322: variable called @code{state}, which affects the way that the text
                   1323: interpreter behaves. When Gforth starts up, @code{state} has the value
                   1324: 0, and the text interpreter is said to be in @var{interpret}
                   1325: mode. During a colon definition (started with @code{:}), @code{state} is
                   1326: set to -1 and the text interpreter is said to be in @var{compile}
                   1327: mode. The word @code{;} ends the definition -- one of the things that it
                   1328: does is to change the value of @code{state} back to 0.
                   1329: 
                   1330: When the text interpreter is in @var{interpret} mode, we already know
                   1331: how it behaves; it looks for each character sequence in the dictionary,
                   1332: finds its xt and executes it, or it converts it to a number and pushes
                   1333: it onto the stack, or it fails to do either and generates an error.
                   1334: 
                   1335: When the text interpreter is in @var{compile} mode, its behaviour is
                   1336: slightly different; it still looks for each character sequence in the
                   1337: dictionary and finds its xt, or converts it to a number, or fails to do
                   1338: either and generates an error. However, instead of executing the xt or
                   1339: pushing the number onto the stack it lays down (@var{compiles}) some
                   1340: magic to make that xt or number get executed or pushed at a later time;
                   1341: at the time that @code{add-two} is @var{executed}. Therefore, when you
                   1342: execute @code{add-two} its @var{run-time effect} is exactly the same as
                   1343: if you had typed @code{2 + .} outside of a definition, and pressed
                   1344: <return>.
1.21      crook    1345: 
1.23      crook    1346: In Forth, every word or number can be described in terms of three
                   1347: properties:
1.21      crook    1348: 
                   1349: @itemize @bullet
                   1350: @item
1.23      crook    1351: Its behaviour at @var{compile} time
1.21      crook    1352: @item
1.23      crook    1353: Its behaviour at @var{interpret} time
1.21      crook    1354: @item
1.23      crook    1355: Its behaviour at @var{execution} time.
1.21      crook    1356: @end itemize
                   1357: 
1.23      crook    1358: These behaviours are called the @var{semantics} of the word or
                   1359: number. The value of @var{state} determines whether the text
                   1360: interpreter will use the compile or interpret semantics of a word or
                   1361: number that it encounters.
1.21      crook    1362: 
                   1363: @itemize @bullet
                   1364: @item
1.23      crook    1365: @cindex interpretation semantics
                   1366: When the text interpreter encounters a word or number in @var{interpret}
                   1367: state, it performs the @var{interpretation semantics} of the word or
                   1368: number.
1.21      crook    1369: @item
1.23      crook    1370: @cindex compilation semantics
                   1371: When the text interpreter encounters a word or number in @var{compile}
                   1372: state, it performs the @var{compilation semantics} of the word or
                   1373: number.
1.21      crook    1374: @end itemize
                   1375: 
1.23      crook    1376: The behaviour of numbers is always the same:
1.21      crook    1377: 
                   1378: @itemize @bullet
                   1379: @item
1.23      crook    1380: When the number is @var{compiled}, it is appended to the current
                   1381: definition so that its run-time behaviour is to execute. (In other
                   1382: words, the compilation semantics of a number are to postpone its
                   1383: execution semantics until the run-time of the definition that it is
                   1384: being compiled into.)
                   1385: @item
                   1386: When the number is @var{interpreted}, its behaviour is to execute. (In
                   1387: other words, the interpretation semantics of a number are to perform its
                   1388: execution semantics.)
1.21      crook    1389: @item
1.23      crook    1390: @cindex execution semantics
                   1391: When the number is @var{executed}, its behaviour is to push its value
                   1392: onto the stack. (In other words, the execution semantics of a number are
                   1393: to push its value onto the stack.)
1.21      crook    1394: @end itemize
                   1395: 
1.23      crook    1396: The behaviour of a word is not so regular, but the vast majority behave
                   1397: like this:
1.21      crook    1398: 
                   1399: @itemize @bullet
                   1400: @item
1.23      crook    1401: The @var{compilation semantics} of the word are to append its
                   1402: @var{execution semantics} to the current definition (so that its
                   1403: run-time behaviour is to execute).
1.21      crook    1404: @item
1.23      crook    1405: The @var{interpretation semantics} of the word are to execute.
                   1406: @item
                   1407: The @var{execution semantics} of the word are to do something useful.
1.21      crook    1408: @end itemize
                   1409: 
                   1410: 
1.23      crook    1411: The actual behaviour of any particular word depends upon the way in
                   1412: which it was defined. In all cases, the text interpreter decides what to
                   1413: do with the word; when it searches the name dictionary for a definition,
                   1414: it not only retrieves the xt for the word, it also retrieves a flag
                   1415: called the @var{immediate flag}. If the flag is set, the text
                   1416: interpreter will @var{execute} the word rather than @var{compiling}
                   1417: @cindex immediate words
                   1418: it. In other words, these so-called @var{immediate} words behave like
                   1419: this:
1.21      crook    1420: 
                   1421: @itemize @bullet
                   1422: @item
1.23      crook    1423: The @var{compilation semantics} of the word are to perform its
                   1424: @var{execution semantics} (so that its compile-time behaviour is to
                   1425: execute).
1.21      crook    1426: @item
1.23      crook    1427: The @var{interpretation semantics} of the word are to execute.
                   1428: @item
                   1429: The @var{execution semantics} of the word are to do something useful.
1.21      crook    1430: @end itemize
                   1431: 
1.23      crook    1432: This example shows the difference between an immediate and a
                   1433: non-immediate word:
1.21      crook    1434: 
                   1435: @example
1.23      crook    1436: : show-state state @ . ;
                   1437: : show-state-now show-state ; immediate
                   1438: : word1 show-state ;
                   1439: : word2 show-state-now ;
                   1440: @end example
                   1441: 
                   1442: The word @code{immediate} after the definition of @code{show-state-now}
                   1443: makes that word an immediate word. These definitions introduce a new
                   1444: word: @code{@@} (pronounced ''at''). This word fetches the value of a
                   1445: variable, and leaves it on the stack. Therefore, the behaviour of
                   1446: @code{show-state} is to print a number that represents the current value
                   1447: of @code{state}.
                   1448: 
                   1449: When you execute @code{word1}, it prints the number 0, indicating
                   1450: that the system is in interpret state. When the text interpreter
                   1451: compiled the definition of @code{word1}, it encountered
                   1452: @code{show-state} whose compilation semantics are to append its
                   1453: execution semantics to the current definition. When you execute
                   1454: @code{word1}, it performs the execution semantics of @code{show-state}.
                   1455: At the time that @code{word1} (and therefore @code{show-state}) are
                   1456: executed, the system is in interpret state.
                   1457: 
                   1458: When you pressed <return> after entering the definition of @code{word2},
                   1459: you should have seen the number -1 printed, followed by @code{ ok}. When
                   1460: the text interpreter compiled the definition of @code{word2}, it
                   1461: encountered @code{show-state-now}, an immediate word, whose compilation
                   1462: semantics are therefore to perform its execution semantics. It is
                   1463: executed straight away (even before the text interpreter has moved on
                   1464: to process another group of characters; the @code{;} in this
                   1465: example). The effect of executing it are to display the value of
                   1466: @code{state} @var{at the time that the definition of} @code{word2}
                   1467: @var{is being defined}. Printing -1 demonstrates that the system is in
                   1468: compilation state at this time. If you execute @code{word2} it does
                   1469: nothing at all.
                   1470: 
                   1471: @cindex ." -- how it works
                   1472: Before leaving the subject of immediate words, consider the behaviour of
                   1473: @code{."} in the definition of @code{greet}, in the previous
                   1474: section. This word is both a parsing word and an immediate word. Notice
                   1475: that there is a space between @code{."} and the start of the text
                   1476: @code{Hello and welcome}, but that there is no space between the last
                   1477: letter of @code{welcome} and the @code{"} character. The reason for this
                   1478: is that @code{."} is a Forth word; it must have a space after it so that
                   1479: the text interpreter can identify it. The @code{"} is not a Forth word;
                   1480: it is a @var{delimiter}. The examples earlier show that, when the string
                   1481: is displayed, there is neither a space before the @code{H} nor after the
                   1482: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   1483: that @code{greet is defined}. When it executes, it searches forward in
                   1484: the input line looking for the delimiter. When it finds the delimiter,
                   1485: it updates @code{>in} to point past the delimiter. It also compiles some
                   1486: magic code into the definition of @code{greet}; the xt of a run-time
                   1487: routine that prints a text string. It compiles the string @code{Hello
                   1488: and welcome} into memory so that it is available to be printed
                   1489: later. When the text interpreter gains control, the next word it finds
                   1490: in the input stream is @code{;} and so it terminates the definition of
                   1491: @code{greet}.
1.21      crook    1492: 
                   1493: 
1.23      crook    1494: @comment ----------------------------------------------
                   1495: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   1496: @section Forth is written in Forth
                   1497: @cindex structure of Forth programs
1.21      crook    1498: 
1.23      crook    1499: When you start up a Forth compiler, a large number of definitions
                   1500: already exist. In Forth, you develop a new application using bottom-up
                   1501: programming techniques to create new definitions that are defined in
                   1502: terms of existing definitions. As you create each definition you can
                   1503: test and debug it interactively.
                   1504: 
                   1505: If you have tried out the examples in this section, you will probably
                   1506: have typed them in by hand; when you leave Gforth, your definitions will
                   1507: be deleted. You can avoid this by using a text editor to enter Forth
                   1508: source code into a file, and then load all of the code from the file
                   1509: using @code{include} (@xref{Including Files}). A Forth source
                   1510: file is processed by the text interpreter, just as though you had typed
                   1511: it in by hand@footnote{Actually, there are some subtle differences, like
                   1512: the fact that it doesn't print @code{ ok} at the end of each line}. 
                   1513: 
                   1514: Gforth also supports the traditional Forth alternative to using text
                   1515: files for program entry (@xref{Blocks}).
                   1516: 
                   1517: In common with many, if not most, Forth compilers, most of Gforth is
                   1518: actually written in Forth. All of the @code{.fs} files in the
                   1519: installation directory are Forth source files, and you can look at them
                   1520: to see examples of Forth programming.
                   1521: 
                   1522: Gforth maintains a history file that records every line that you
                   1523: type to the text interpreter. This file is preserved between sessions,
                   1524: and is used to provide the command-line recall facility. If you enter
                   1525: long definitions by hand, you can use a text editor to paste them out of
                   1526: the history file into a Forth source file for reuse at a later time.
                   1527: 
                   1528: @cindex history file
                   1529: @cindex .gforth-history
                   1530: @cindex GFORTHHIST
                   1531: You can find out the name of your history file using @code{history-file
                   1532: type }. On non-Unix systems you can find the location of the file using
                   1533: @code{history-dir type }@footnote{The environment variable GFORTHHIST
                   1534: determines the location of the file.}
1.21      crook    1535: 
                   1536: 
                   1537: 
1.23      crook    1538: @comment ----------------------------------------------
                   1539: @node Review - elements of a Forth system, Exercises, Forth is written in Forth, Introduction
                   1540: @section Review - elements of a Forth system
                   1541: @cindex elements of a Forth system
1.21      crook    1542: 
1.23      crook    1543: To summarise this chapter:
1.21      crook    1544: 
                   1545: 
1.23      crook    1546: @itemize @bullet
                   1547: @item
                   1548: Forth programs use @var{factoring} to break a problem down into small
                   1549: fragments called @var{words} or @var{definitions}.
                   1550: @item
                   1551: Forth program development is an interactive process.
                   1552: @item
                   1553: The main command loop that accepts input, and controls both
                   1554: interpretation and compilation, is called the @var{text interpreter}
                   1555: (also known as the @var{outer interpreter}.
                   1556: @item
                   1557: Forth has a very simple syntax, consisting of words and numbers
                   1558: separated by spaces or carriage-return characters. Any additional syntax
                   1559: is imposed by @var{parsing words}.
                   1560: @item
                   1561: Forth uses a stack to pass parameters between words. As a result, it
                   1562: uses postfix notation.
                   1563: @item
                   1564: To use a word that has previously been defined, the text interpreter
                   1565: searches for the word in the @var{name dictionary}.
                   1566: @item
                   1567: Words have @var{interpretation semantics}, @var{compilation semantics}
                   1568: and @var{execution semantics}.
                   1569: @item
                   1570: The text interpreter uses the value of @code{state} to select between
                   1571: the use of the @var{interpretation semantics} and the  @var{compilation
                   1572: semantics} of a word that it encounters.
                   1573: @item
                   1574: The relationship between the @var{interpretation semantics}, @var{compilation semantics}
                   1575: and @var{execution semantics} for a word depend upon the way in which
                   1576: the word was defined (for example, whether it is an @var{immediate} word.
                   1577: @item
                   1578: Forth definitions can be implemented in Forth (called @var{high-level
                   1579: definitions}) or in some other way (usually a lower-level language and
                   1580: as a result often called @var{low-level definitions}, @var{code
                   1581: definitions} or @var{primitives}).
                   1582: @item
                   1583: Many Forth systems are implemented mainly in Forth.
                   1584: @item
                   1585: You now know enough to read and understand the rest of this manual and
                   1586: the ANS Forth Standard.
                   1587: @end itemize
1.21      crook    1588: 
                   1589: 
1.23      crook    1590: @comment TODO - other defining words
                   1591: @comment other parsing words
                   1592: @comment Your first loop
                   1593: @comment syntax and semantics
                   1594: @comment DOES>
                   1595: @comment taste of other elements of Forth
1.21      crook    1596: 
                   1597: 
                   1598: 
                   1599: @comment ----------------------------------------------
1.23      crook    1600: @node Exercises, ,Review - elements of a Forth system, Introduction
                   1601: @section Exercises
1.21      crook    1602: @cindex elements of a Forth system
                   1603: 
1.23      crook    1604: Amazing as it may seem, if you have read (and understood) this far, you
                   1605: know almost all the fundamentals about the inner workings of a Forth
                   1606: system. You certainly know enough to be able to read and understand the
                   1607: rest of this manual, to learn more about the facilities that Gforth
                   1608: provides. Even scarier, you know almost enough to implement your own Forth
                   1609: system. However, that's not a good idea just yet.. better to try writing
                   1610: some programs in Gforth.
                   1611: 
                   1612: The large number of Forth words available in ANS Standard Forth and
                   1613: Gforth make learning Forth somewhat daunting. To make the problem
                   1614: easier, use the index of this manual to learn more about these words:
1.21      crook    1615: 
1.23      crook    1616: ..levels of Forth words.
1.21      crook    1617: 
                   1618: 
                   1619: Ideally, provide a set of programming excercises linked into the stuff
                   1620: done already and into other sections of the manual. Provide solutions to
                   1621: all the exercises in a .fs file in the distribution. Get some
                   1622: inspiration from Starting Forth and Kelly&Spies.
                   1623: 
                   1624: 
1.23      crook    1625: 
1.21      crook    1626: @c ----------------------------------------------------------
                   1627: @node Goals, Invoking Gforth, Introduction, Top
1.1       anton    1628: @comment node-name,     next,           previous, up
                   1629: @chapter Goals of Gforth
                   1630: @cindex Goals
                   1631: The goal of the Gforth Project is to develop a standard model for
                   1632: ANS Forth. This can be split into several subgoals:
                   1633: 
                   1634: @itemize @bullet
                   1635: @item
1.21      crook    1636: Gforth should conform to the ANS Forth Standard.
1.1       anton    1637: @item
                   1638: It should be a model, i.e. it should define all the
                   1639: implementation-dependent things.
                   1640: @item
                   1641: It should become standard, i.e. widely accepted and used. This goal
                   1642: is the most difficult one.
                   1643: @end itemize
                   1644: 
                   1645: To achieve these goals Gforth should be
                   1646: @itemize @bullet
                   1647: @item
                   1648: Similar to previous models (fig-Forth, F83)
                   1649: @item
                   1650: Powerful. It should provide for all the things that are considered
                   1651: necessary today and even some that are not yet considered necessary.
                   1652: @item
                   1653: Efficient. It should not get the reputation of being exceptionally
                   1654: slow.
                   1655: @item
                   1656: Free.
                   1657: @item
                   1658: Available on many machines/easy to port.
                   1659: @end itemize
                   1660: 
                   1661: Have we achieved these goals? Gforth conforms to the ANS Forth
                   1662: standard. It may be considered a model, but we have not yet documented
                   1663: which parts of the model are stable and which parts we are likely to
1.12      anton    1664: change. It certainly has not yet become a de facto standard, but it
                   1665: appears to be quite popular. It has some similarities to and some
                   1666: differences from previous models. It has some powerful features, but not
                   1667: yet everything that we envisioned. We certainly have achieved our
                   1668: execution speed goals (@pxref{Performance}).  It is free and available
                   1669: on many machines.
1.1       anton    1670: 
1.21      crook    1671: @menu
                   1672: * Gforth Extensions Sinful?::
                   1673: @end menu
                   1674: 
                   1675: @node Gforth Extensions Sinful?, , Goals, Goals
                   1676: @comment node-name,     next,           previous, up
                   1677: @section Is it a Sin to use Gforth Extensions?
                   1678: @cindex Gforth extensions
                   1679: 
                   1680: If you've been paying attention, you will have realised that there is an
                   1681: ANS Standard for Forth. As you read through the rest of this manual, you
                   1682: will see documentation for @var{Standard} words, and documentation for
                   1683: some appealing Gforth @var{extensions}. You might ask yourself the
                   1684: question: @var{"Given that there is a standard, would I be committing a
                   1685: sin to use (non-Standard) Gforth extensions?"}
1.1       anton    1686: 
1.21      crook    1687: The answer to that question is somewhat pragmatic and somewhat
                   1688: philosophical. Consider these points:
1.1       anton    1689: 
1.21      crook    1690: @itemize @bullet
                   1691: @item
                   1692: A number of the Gforth extensions can be implemented in ANS Standard
                   1693: Forth using files provided in the @file{compat/} directory. These are
                   1694: mentioned in the text in passing.
                   1695: @item
                   1696: Forth has a rich historical precedent for programmers taking advantage
                   1697: of implementation-dependent features of their tools (for example,
                   1698: relying on a knowledge of the dictionary structure). Sometimes these
                   1699: techniques are necessary to extract every last bit of performance from
                   1700: the hardware, sometimes they are just a programming shorthand.
                   1701: @item
                   1702: The best way to break the rules is to know what the rules are. To learn
                   1703: the rules, there is no substitute for studying the text of the Standard
                   1704: itself. In particular, Appendix A of the Standard (@var{Rationale})
                   1705: provides a valuable insight into the thought processes of the technical
                   1706: committee.
                   1707: @item
                   1708: The best reason to break a rule is because you have to; because it's
                   1709: more productive to do that, because it makes your code run fast enough
                   1710: or because you can see no Standard way to achieve what you want to
                   1711: achieve.
                   1712: @end itemize
1.1       anton    1713: 
1.21      crook    1714: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
                   1715: analyse your program and determine what non-Standard definitions it
                   1716: relies upon.
1.1       anton    1717: 
                   1718: 
1.12      anton    1719: 
1.21      crook    1720: @c ----------------------------------------------------------
                   1721: @node Invoking Gforth, Words, Goals, Top
1.1       anton    1722: @chapter Invoking Gforth
1.21      crook    1723: @cindex Gforth - invoking
1.1       anton    1724: @cindex invoking Gforth
                   1725: @cindex running Gforth
                   1726: @cindex command-line options
                   1727: @cindex options on the command line
                   1728: @cindex flags on the command line
                   1729: 
                   1730: You will usually just say @code{gforth}. In many other cases the default
                   1731: Gforth image will be invoked like this:
                   1732: @example
                   1733: gforth [files] [-e forth-code]
                   1734: @end example
1.12      anton    1735: This interprets the contents of the files and the Forth code in the order they
1.1       anton    1736: are given.
                   1737: 
                   1738: In general, the command line looks like this:
                   1739: 
                   1740: @example
                   1741: gforth [initialization options] [image-specific options]
                   1742: @end example
                   1743: 
                   1744: The initialization options must come before the rest of the command
                   1745: line. They are:
                   1746: 
                   1747: @table @code
                   1748: @cindex -i, command-line option
                   1749: @cindex --image-file, command-line option
                   1750: @item --image-file @var{file}
                   1751: @itemx -i @var{file}
                   1752: Loads the Forth image @var{file} instead of the default
                   1753: @file{gforth.fi} (@pxref{Image Files}).
                   1754: 
                   1755: @cindex --path, command-line option
                   1756: @cindex -p, command-line option
                   1757: @item --path @var{path}
                   1758: @itemx -p @var{path}
                   1759: Uses @var{path} for searching the image file and Forth source code files
                   1760: instead of the default in the environment variable @code{GFORTHPATH} or
                   1761: the path specified at installation time (e.g.,
                   1762: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                   1763: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
                   1764: 
                   1765: @cindex --dictionary-size, command-line option
                   1766: @cindex -m, command-line option
                   1767: @cindex @var{size} parameters for command-line options
                   1768: @cindex size of the dictionary and the stacks
                   1769: @item --dictionary-size @var{size}
                   1770: @itemx -m @var{size}
                   1771: Allocate @var{size} space for the Forth dictionary space instead of
                   1772: using the default specified in the image (typically 256K). The
1.21      crook    1773: @var{size} specification for this and subsequent options consists of
                   1774: an integer and a unit (e.g.,
1.1       anton    1775: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
1.12      anton    1776: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                   1777: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                   1778: @code{e} is used.
1.1       anton    1779: 
                   1780: @cindex --data-stack-size, command-line option
                   1781: @cindex -d, command-line option
                   1782: @item --data-stack-size @var{size}
                   1783: @itemx -d @var{size}
                   1784: Allocate @var{size} space for the data stack instead of using the
                   1785: default specified in the image (typically 16K).
                   1786: 
                   1787: @cindex --return-stack-size, command-line option
                   1788: @cindex -r, command-line option
                   1789: @item --return-stack-size @var{size}
                   1790: @itemx -r @var{size}
                   1791: Allocate @var{size} space for the return stack instead of using the
                   1792: default specified in the image (typically 15K).
                   1793: 
                   1794: @cindex --fp-stack-size, command-line option
                   1795: @cindex -f, command-line option
                   1796: @item --fp-stack-size @var{size}
                   1797: @itemx -f @var{size}
                   1798: Allocate @var{size} space for the floating point stack instead of
                   1799: using the default specified in the image (typically 15.5K). In this case
                   1800: the unit specifier @code{e} refers to floating point numbers.
                   1801: 
                   1802: @cindex --locals-stack-size, command-line option
                   1803: @cindex -l, command-line option
                   1804: @item --locals-stack-size @var{size}
                   1805: @itemx -l @var{size}
                   1806: Allocate @var{size} space for the locals stack instead of using the
                   1807: default specified in the image (typically 14.5K).
                   1808: 
                   1809: @cindex -h, command-line option
                   1810: @cindex --help, command-line option
                   1811: @item --help
                   1812: @itemx -h
                   1813: Print a message about the command-line options
                   1814: 
                   1815: @cindex -v, command-line option
                   1816: @cindex --version, command-line option
                   1817: @item --version
                   1818: @itemx -v
                   1819: Print version and exit
                   1820: 
                   1821: @cindex --debug, command-line option
                   1822: @item --debug
                   1823: Print some information useful for debugging on startup.
                   1824: 
                   1825: @cindex --offset-image, command-line option
                   1826: @item --offset-image
                   1827: Start the dictionary at a slightly different position than would be used
                   1828: otherwise (useful for creating data-relocatable images,
                   1829: @pxref{Data-Relocatable Image Files}).
                   1830: 
1.5       anton    1831: @cindex --no-offset-im, command-line option
                   1832: @item --no-offset-im
                   1833: Start the dictionary at the normal position.
                   1834: 
1.1       anton    1835: @cindex --clear-dictionary, command-line option
                   1836: @item --clear-dictionary
                   1837: Initialize all bytes in the dictionary to 0 before loading the image
                   1838: (@pxref{Data-Relocatable Image Files}).
1.5       anton    1839: 
                   1840: @cindex --die-on-signal, command-line-option
                   1841: @item --die-on-signal
                   1842: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
                   1843: or the segmentation violation SIGSEGV) by translating it into a Forth
                   1844: @code{THROW}. With this option, Gforth exits if it receives such a
                   1845: signal. This option is useful when the engine and/or the image might be
                   1846: severely broken (such that it causes another signal before recovering
                   1847: from the first); this option avoids endless loops in such cases.
1.1       anton    1848: @end table
                   1849: 
                   1850: @cindex loading files at startup
                   1851: @cindex executing code on startup
                   1852: @cindex batch processing with Gforth
                   1853: As explained above, the image-specific command-line arguments for the
                   1854: default image @file{gforth.fi} consist of a sequence of filenames and
                   1855: @code{-e @var{forth-code}} options that are interpreted in the sequence
                   1856: in which they are given. The @code{-e @var{forth-code}} or
1.21      crook    1857: @code{--evaluate @var{forth-code}} option evaluates the Forth
1.1       anton    1858: code. This option takes only one argument; if you want to evaluate more
                   1859: Forth words, you have to quote them or use several @code{-e}s. To exit
                   1860: after processing the command line (instead of entering interactive mode)
                   1861: append @code{-e bye} to the command line.
                   1862: 
                   1863: @cindex versions, invoking other versions of Gforth
                   1864: If you have several versions of Gforth installed, @code{gforth} will
                   1865: invoke the version that was installed last. @code{gforth-@var{version}}
                   1866: invokes a specific version. You may want to use the option
                   1867: @code{--path}, if your environment contains the variable
                   1868: @code{GFORTHPATH}.
                   1869: 
                   1870: Not yet implemented:
                   1871: On startup the system first executes the system initialization file
                   1872: (unless the option @code{--no-init-file} is given; note that the system
                   1873: resulting from using this option may not be ANS Forth conformant). Then
                   1874: the user initialization file @file{.gforth.fs} is executed, unless the
                   1875: option @code{--no-rc} is given; this file is first searched in @file{.},
                   1876: then in @file{~}, then in the normal path (see above).
                   1877: 
1.21      crook    1878: 
                   1879: @cindex Gforth - leaving
                   1880: @cindex leaving Gforth
                   1881: 
                   1882: You can leave Gforth by typing @code{bye} or (if you invoked Gforth with
                   1883: the @code{--die-on-signal} option) Ctrl-C. When you leave Gforth, all of
                   1884: your definitions and data are discarded. @xref{Image Files} for ways
                   1885: of saving the state of the system before leaving Gforth.
                   1886: 
                   1887: doc-bye
                   1888: 
                   1889: 
1.23      crook    1890: @comment TODO add section on environment variables.. find them by
                   1891: @comment grep for "getenv" -- they are:
                   1892: @comment GFORTHHIST
                   1893: @comment POSIXELY_CORRECT
                   1894: @comment TMP TEMP
                   1895: @comment HOME
                   1896: @comment LINES
                   1897: @comment COLUMNS
                   1898: @comment GFORTHPATH
                   1899: @comment FORTHSIZES ?? in INSTALL but cannot find it in the source
                   1900: @comment some are in .c files.
                   1901: 
                   1902: 
1.24      anton    1903: @node Words, Error messages, Invoking Gforth, Top
1.1       anton    1904: @chapter Forth Words
                   1905: @cindex Words
                   1906: 
                   1907: @menu
                   1908: * Notation::                    
1.21      crook    1909: * Comments::
                   1910: * Boolean Flags::
1.1       anton    1911: * Arithmetic::                  
                   1912: * Stack Manipulation::          
1.5       anton    1913: * Memory::                      
1.1       anton    1914: * Control Structures::          
                   1915: * Locals::                      
                   1916: * Defining Words::              
1.21      crook    1917: * The Text Interpreter::
1.5       anton    1918: * Structures::                  
1.12      anton    1919: * Object-oriented Forth::       
                   1920: * Tokens for Words::            
1.21      crook    1921: * Word Lists::                   
                   1922: * Environmental Queries::
1.12      anton    1923: * Files::                       
                   1924: * Including Files::             
                   1925: * Blocks::                      
                   1926: * Other I/O::                   
                   1927: * Programming Tools::           
                   1928: * Assembler and Code Words::    
                   1929: * Threading Words::             
1.21      crook    1930: * Passing Commands to the OS::
                   1931: * Miscellaneous Words::
1.1       anton    1932: @end menu
                   1933: 
1.21      crook    1934: @node Notation, Comments, Words, Words
1.1       anton    1935: @section Notation
                   1936: @cindex notation of glossary entries
                   1937: @cindex format of glossary entries
                   1938: @cindex glossary notation format
                   1939: @cindex word glossary entry format
                   1940: 
                   1941: The Forth words are described in this section in the glossary notation
                   1942: that has become a de-facto standard for Forth texts, i.e.,
                   1943: 
                   1944: @format
                   1945: @var{word}     @var{Stack effect}   @var{wordset}   @var{pronunciation}
                   1946: @end format
                   1947: @var{Description}
                   1948: 
                   1949: @table @var
                   1950: @item word
                   1951: @cindex case insensitivity
                   1952: The name of the word. BTW, Gforth is case insensitive, so you can
                   1953: type the words in in lower case (However, @pxref{core-idef}).
                   1954: 
                   1955: @item Stack effect
                   1956: @cindex stack effect
                   1957: The stack effect is written in the notation @code{@var{before} --
                   1958: @var{after}}, where @var{before} and @var{after} describe the top of
                   1959: stack entries before and after the execution of the word. The rest of
                   1960: the stack is not touched by the word. The top of stack is rightmost,
                   1961: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   1962: uses a separate floating point stack, but a unified stack
                   1963: notation. Also, return stack effects are not shown in @var{stack
                   1964: effect}, but in @var{Description}. The name of a stack item describes
                   1965: the type and/or the function of the item. See below for a discussion of
                   1966: the types.
                   1967: 
                   1968: All words have two stack effects: A compile-time stack effect and a
                   1969: run-time stack effect. The compile-time stack-effect of most words is
                   1970: @var{ -- }. If the compile-time stack-effect of a word deviates from
                   1971: this standard behaviour, or the word does other unusual things at
                   1972: compile time, both stack effects are shown; otherwise only the run-time
                   1973: stack effect is shown.
                   1974: 
                   1975: @cindex pronounciation of words
                   1976: @item pronunciation
                   1977: How the word is pronounced.
                   1978: 
                   1979: @cindex wordset
                   1980: @item wordset
1.21      crook    1981: The ANS Forth standard is divided into several word sets. A standard
                   1982: system need not support all of them. Therefore, in theory, the fewer
                   1983: word sets your program uses the more portable it will be. However, we
                   1984: suspect that most ANS Forth systems on personal machines will feature
                   1985: all word sets. Words that are not defined in the ANS standard have
                   1986: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    1987: describes words that will work in future releases of Gforth;
                   1988: @code{gforth-internal} words are more volatile. Environmental query
                   1989: strings are also displayed like words; you can recognize them by the
1.21      crook    1990: @code{environment} in the word set field.
1.1       anton    1991: 
                   1992: @item Description
                   1993: A description of the behaviour of the word.
                   1994: @end table
                   1995: 
                   1996: @cindex types of stack items
                   1997: @cindex stack item types
                   1998: The type of a stack item is specified by the character(s) the name
                   1999: starts with:
                   2000: 
                   2001: @table @code
                   2002: @item f
                   2003: @cindex @code{f}, stack item type
                   2004: Boolean flags, i.e. @code{false} or @code{true}.
                   2005: @item c
                   2006: @cindex @code{c}, stack item type
                   2007: Char
                   2008: @item w
                   2009: @cindex @code{w}, stack item type
                   2010: Cell, can contain an integer or an address
                   2011: @item n
                   2012: @cindex @code{n}, stack item type
                   2013: signed integer
                   2014: @item u
                   2015: @cindex @code{u}, stack item type
                   2016: unsigned integer
                   2017: @item d
                   2018: @cindex @code{d}, stack item type
                   2019: double sized signed integer
                   2020: @item ud
                   2021: @cindex @code{ud}, stack item type
                   2022: double sized unsigned integer
                   2023: @item r
                   2024: @cindex @code{r}, stack item type
                   2025: Float (on the FP stack)
1.21      crook    2026: @item a-
1.1       anton    2027: @cindex @code{a_}, stack item type
                   2028: Cell-aligned address
1.21      crook    2029: @item c-
1.1       anton    2030: @cindex @code{c_}, stack item type
                   2031: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    2032: @item f-
1.1       anton    2033: @cindex @code{f_}, stack item type
                   2034: Float-aligned address
1.21      crook    2035: @item df-
1.1       anton    2036: @cindex @code{df_}, stack item type
                   2037: Address aligned for IEEE double precision float
1.21      crook    2038: @item sf-
1.1       anton    2039: @cindex @code{sf_}, stack item type
                   2040: Address aligned for IEEE single precision float
                   2041: @item xt
                   2042: @cindex @code{xt}, stack item type
                   2043: Execution token, same size as Cell
                   2044: @item wid
                   2045: @cindex @code{wid}, stack item type
1.21      crook    2046: Word list ID, same size as Cell
1.1       anton    2047: @item f83name
                   2048: @cindex @code{f83name}, stack item type
                   2049: Pointer to a name structure
                   2050: @item "
                   2051: @cindex @code{"}, stack item type
1.12      anton    2052: string in the input stream (not on the stack). The terminating character
                   2053: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    2054: quotes.
                   2055: @end table
                   2056: 
1.21      crook    2057: @node Comments, Boolean Flags, Notation, Words
                   2058: @section Comments
                   2059: @cindex Comments
                   2060: 
                   2061: Forth supports two styles of comment; the traditional "in-line" comment,
                   2062: @code{(} and its modern cousin, the "comment to end of line"; @code{\}.
                   2063: 
1.23      crook    2064: doc-(
1.21      crook    2065: doc-\
1.23      crook    2066: doc-\G
1.21      crook    2067: 
                   2068: @node Boolean Flags, Arithmetic, Comments, Words
                   2069: @section Boolean Flags
                   2070: @cindex Boolean Flags
                   2071: 
                   2072: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   2073: flag @code{false} and a flag with all bits set represents the flag
                   2074: @code{true}. Words that check a flag (for example, @var{IF}) will treat
                   2075: a cell that has @var{any} bit set as @code{true}.
                   2076: 
                   2077: doc-true
                   2078: doc-false
                   2079: 
                   2080: 
                   2081: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    2082: @section Arithmetic
                   2083: @cindex arithmetic words
                   2084: 
                   2085: @cindex division with potentially negative operands
                   2086: Forth arithmetic is not checked, i.e., you will not hear about integer
                   2087: overflow on addition or multiplication, you may hear about division by
                   2088: zero if you are lucky. The operator is written after the operands, but
                   2089: the operands are still in the original order. I.e., the infix @code{2-1}
                   2090: corresponds to @code{2 1 -}. Forth offers a variety of division
                   2091: operators. If you perform division with potentially negative operands,
                   2092: you do not want to use @code{/} or @code{/mod} with its undefined
                   2093: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   2094: former, @pxref{Mixed precision}).
                   2095: 
                   2096: @menu
                   2097: * Single precision::            
                   2098: * Bitwise operations::          
1.21      crook    2099: * Double precision::            Double-cell integer arithmetic
                   2100: * Numeric comparison::
1.1       anton    2101: * Mixed precision::             operations with single and double-cell integers
                   2102: * Floating Point::              
                   2103: @end menu
                   2104: 
                   2105: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
                   2106: @subsection Single precision
                   2107: @cindex single precision arithmetic words
                   2108: 
1.21      crook    2109: By default, numbers in Forth are single-precision integers that are 1
                   2110: CELL in size. They can be signed or unsigned, depending upon how you
                   2111: treat them. @xref{Number Conversion} for the rules used by the text
                   2112: interpreter for recognising single-precision integers.
                   2113: 
1.1       anton    2114: doc-+
1.21      crook    2115: doc-1+
1.1       anton    2116: doc--
1.21      crook    2117: doc-1-
1.1       anton    2118: doc-*
                   2119: doc-/
                   2120: doc-mod
                   2121: doc-/mod
                   2122: doc-negate
                   2123: doc-abs
                   2124: doc-min
                   2125: doc-max
1.21      crook    2126: doc-d>s
1.1       anton    2127: 
1.21      crook    2128: @node Bitwise operations, Double precision, Single precision, Arithmetic
1.1       anton    2129: @subsection Bitwise operations
                   2130: @cindex bitwise operation words
                   2131: 
                   2132: doc-and
                   2133: doc-or
                   2134: doc-xor
                   2135: doc-invert
1.21      crook    2136: doc-lshift
                   2137: doc-rshift
1.1       anton    2138: doc-2*
1.21      crook    2139: doc-d2*
1.1       anton    2140: doc-2/
1.21      crook    2141: doc-d2/
                   2142: 
                   2143: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
                   2144: @subsection Double precision
                   2145: @cindex double precision arithmetic words
                   2146: 
                   2147: @xref{Number Conversion} for the rules used by the text interpreter for
                   2148: recognising double-precision integers.
                   2149: 
                   2150: A double precision number is represented by a cell pair, with the most
                   2151: significant digit at the TOS. It is trivial to convert an unsigned single
                   2152: to an (unsigned) double; simply push a @code{0} onto the TOS. Since numbers
                   2153: are represented by Gforth using 2's complement arithmetic, converting
                   2154: a signed single to a (signed) double requires sign-extension across the
                   2155: most significant digit. This can be achieved using @code{s>d}. The moral
                   2156: of the story is that you cannot convert a number without knowing what that
                   2157: number represents.
                   2158: 
                   2159: doc-s>d
                   2160: doc-d+
                   2161: doc-d-
                   2162: doc-dnegate
                   2163: doc-dabs
                   2164: doc-dmin
                   2165: doc-dmax
                   2166: 
                   2167: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
                   2168: @subsection Numeric comparison
                   2169: @cindex numeric comparison words
                   2170: 
                   2171: doc-0<
1.23      crook    2172: doc-0<=
1.21      crook    2173: doc-0<>
                   2174: doc-0=
1.23      crook    2175: doc-0>
                   2176: doc-0>=
1.21      crook    2177: doc-<
1.23      crook    2178: doc-<=
1.21      crook    2179: doc-<>
                   2180: doc-=
                   2181: doc->
1.23      crook    2182: doc->=
                   2183: 
1.21      crook    2184: doc-d0<
1.23      crook    2185: doc-d0<=
                   2186: doc-d0<>
1.21      crook    2187: doc-d0=
1.23      crook    2188: doc-d0>
                   2189: doc-d0>=
1.21      crook    2190: doc-d<
1.23      crook    2191: doc-d<=
                   2192: doc-d<>
1.21      crook    2193: doc-d=
1.23      crook    2194: doc-d>
                   2195: doc-d>=
                   2196: 
1.21      crook    2197: doc-u<
                   2198: doc-du<
                   2199: doc-u>
1.23      crook    2200: doc-u<=
                   2201: @comment why u<> and u= .. they are the same as <> and =
                   2202: doc-u<>
                   2203: doc-u=
                   2204: doc-u>=
1.21      crook    2205: doc-within
1.1       anton    2206: 
1.21      crook    2207: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    2208: @subsection Mixed precision
                   2209: @cindex mixed precision arithmetic words
                   2210: 
                   2211: doc-m+
                   2212: doc-*/
                   2213: doc-*/mod
                   2214: doc-m*
                   2215: doc-um*
                   2216: doc-m*/
                   2217: doc-um/mod
                   2218: doc-fm/mod
                   2219: doc-sm/rem
                   2220: 
1.21      crook    2221: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    2222: @subsection Floating Point
                   2223: @cindex floating point arithmetic words
                   2224: 
1.21      crook    2225: @xref{Number Conversion} for the rules used by the text interpreter for
                   2226: recognising floating-point numbers.
1.1       anton    2227: 
                   2228: @cindex angles in trigonometric operations
                   2229: @cindex trigonometric operations
                   2230: Angles in floating point operations are given in radians (a full circle
                   2231: has 2 pi radians). Note, that Gforth has a separate floating point
                   2232: stack, but we use the unified notation.
                   2233: 
                   2234: @cindex floating-point arithmetic, pitfalls
                   2235: Floating point numbers have a number of unpleasant surprises for the
                   2236: unwary (e.g., floating point addition is not associative) and even a few
                   2237: for the wary. You should not use them unless you know what you are doing
                   2238: or you don't care that the results you get are totally bogus. If you
                   2239: want to learn about the problems of floating point numbers (and how to
                   2240: avoid them), you might start with @cite{David Goldberg, What Every
                   2241: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
1.17      anton    2242: Computing Surveys 23(1):5@minus{}48, March 1991}
                   2243: (@url{http://www.validgh.com/goldberg/paper.ps}).
1.1       anton    2244: 
1.21      crook    2245: doc-d>f
                   2246: doc-f>d
1.1       anton    2247: doc-f+
                   2248: doc-f-
                   2249: doc-f*
                   2250: doc-f/
                   2251: doc-fnegate
                   2252: doc-fabs
                   2253: doc-fmax
                   2254: doc-fmin
                   2255: doc-floor
                   2256: doc-fround
                   2257: doc-f**
                   2258: doc-fsqrt
                   2259: doc-fexp
                   2260: doc-fexpm1
                   2261: doc-fln
                   2262: doc-flnp1
                   2263: doc-flog
                   2264: doc-falog
                   2265: doc-fsin
                   2266: doc-fcos
                   2267: doc-fsincos
                   2268: doc-ftan
                   2269: doc-fasin
                   2270: doc-facos
                   2271: doc-fatan
                   2272: doc-fatan2
                   2273: doc-fsinh
                   2274: doc-fcosh
                   2275: doc-ftanh
                   2276: doc-fasinh
                   2277: doc-facosh
                   2278: doc-fatanh
1.21      crook    2279: doc-pi
                   2280: doc-f0<
                   2281: doc-f0=
                   2282: doc-f<
                   2283: doc-f<=
                   2284: doc-f<>
                   2285: doc-f=
                   2286: doc-f>
                   2287: doc-f>=
                   2288: doc-f2*
                   2289: doc-f2/
                   2290: doc-1/f
                   2291: doc-f~
                   2292: doc-precision
                   2293: doc-set-precision
1.1       anton    2294: 
                   2295: @node Stack Manipulation, Memory, Arithmetic, Words
                   2296: @section Stack Manipulation
                   2297: @cindex stack manipulation words
                   2298: 
                   2299: @cindex floating-point stack in the standard
1.21      crook    2300: Gforth maintains a number of separate stacks:
                   2301: 
                   2302: @itemize @bullet
                   2303: @item
                   2304: A data stack (aka parameter stack) -- for characters, cells,
                   2305: addresses, and double cells.
                   2306: 
                   2307: @item
                   2308: A floating point stack -- for floating point numbers.
                   2309: 
                   2310: @item
                   2311: A return stack -- for storing the return addresses of colon
                   2312: definitions and other data.
                   2313: 
                   2314: @item
                   2315: A locals stack for storing local variables.
                   2316: @end itemize
                   2317: 
                   2318: Whilst every sane Forth has a separate floating-point stack, it is not
                   2319: strictly required; an ANS Forth system could theoretically keep
                   2320: floating-point numbers on the data stack. As an additional difficulty,
                   2321: you don't know how many cells a floating-point number takes. It is
                   2322: reportedly possible to write words in a way that they work also for a
                   2323: unified stack model, but we do not recommend trying it. Instead, just
                   2324: say that your program has an environmental dependency on a separate
                   2325: floating-point stack.
                   2326: 
                   2327: doc-floating-stack
1.1       anton    2328: 
                   2329: @cindex return stack and locals
                   2330: @cindex locals and return stack
1.21      crook    2331: A Forth system is allowed to keep local variables on the
1.1       anton    2332: return stack. This is reasonable, as local variables usually eliminate
                   2333: the need to use the return stack explicitly. So, if you want to produce
1.21      crook    2334: a standard compliant program and you are using local variables in a
                   2335: word, forget about return stack manipulations in that word (refer to the
1.1       anton    2336: standard document for the exact rules).
                   2337: 
                   2338: @menu
                   2339: * Data stack::                  
                   2340: * Floating point stack::        
                   2341: * Return stack::                
                   2342: * Locals stack::                
                   2343: * Stack pointer manipulation::  
                   2344: @end menu
                   2345: 
                   2346: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   2347: @subsection Data stack
                   2348: @cindex data stack manipulation words
                   2349: @cindex stack manipulations words, data stack
                   2350: 
                   2351: doc-drop
                   2352: doc-nip
                   2353: doc-dup
                   2354: doc-over
                   2355: doc-tuck
                   2356: doc-swap
1.21      crook    2357: doc-pick
1.1       anton    2358: doc-rot
                   2359: doc--rot
                   2360: doc-?dup
                   2361: doc-roll
                   2362: doc-2drop
                   2363: doc-2nip
                   2364: doc-2dup
                   2365: doc-2over
                   2366: doc-2tuck
                   2367: doc-2swap
                   2368: doc-2rot
                   2369: 
                   2370: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   2371: @subsection Floating point stack
                   2372: @cindex floating-point stack manipulation words
                   2373: @cindex stack manipulation words, floating-point stack
                   2374: 
                   2375: doc-fdrop
                   2376: doc-fnip
                   2377: doc-fdup
                   2378: doc-fover
                   2379: doc-ftuck
                   2380: doc-fswap
1.21      crook    2381: doc-fpick
1.1       anton    2382: doc-frot
                   2383: 
                   2384: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   2385: @subsection Return stack
                   2386: @cindex return stack manipulation words
                   2387: @cindex stack manipulation words, return stack
                   2388: 
                   2389: doc->r
                   2390: doc-r>
                   2391: doc-r@
                   2392: doc-rdrop
                   2393: doc-2>r
                   2394: doc-2r>
                   2395: doc-2r@
                   2396: doc-2rdrop
                   2397: 
                   2398: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   2399: @subsection Locals stack
                   2400: 
1.21      crook    2401: 
1.1       anton    2402: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   2403: @subsection Stack pointer manipulation
                   2404: @cindex stack pointer manipulation words
                   2405: 
1.21      crook    2406: doc-sp0
                   2407: doc-s0
1.1       anton    2408: doc-sp@
                   2409: doc-sp!
1.21      crook    2410: doc-fp0
1.1       anton    2411: doc-fp@
                   2412: doc-fp!
1.21      crook    2413: doc-rp0
                   2414: doc-r0
1.1       anton    2415: doc-rp@
                   2416: doc-rp!
1.21      crook    2417: doc-lp0
                   2418: doc-l0
1.1       anton    2419: doc-lp@
                   2420: doc-lp!
                   2421: 
                   2422: @node Memory, Control Structures, Stack Manipulation, Words
                   2423: @section Memory
                   2424: @cindex Memory words
                   2425: 
                   2426: @menu
                   2427: * Memory Access::      
                   2428: * Address arithmetic::          
                   2429: * Memory Blocks::         
                   2430: @end menu
                   2431: 
                   2432: @node Memory Access, Address arithmetic, Memory, Memory
                   2433: @subsection Memory Access
                   2434: @cindex memory access words
                   2435: 
                   2436: doc-@
                   2437: doc-!
                   2438: doc-+!
                   2439: doc-c@
                   2440: doc-c!
                   2441: doc-2@
                   2442: doc-2!
                   2443: doc-f@
                   2444: doc-f!
                   2445: doc-sf@
                   2446: doc-sf!
                   2447: doc-df@
                   2448: doc-df!
                   2449: 
                   2450: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   2451: @subsection Address arithmetic
                   2452: @cindex address arithmetic words
                   2453: 
                   2454: ANS Forth does not specify the sizes of the data types. Instead, it
                   2455: offers a number of words for computing sizes and doing address
                   2456: arithmetic. Basically, address arithmetic is performed in terms of
                   2457: address units (aus); on most systems the address unit is one byte. Note
                   2458: that a character may have more than one au, so @code{chars} is no noop
                   2459: (on systems where it is a noop, it compiles to nothing).
                   2460: 
                   2461: @cindex alignment of addresses for types
                   2462: ANS Forth also defines words for aligning addresses for specific
                   2463: types. Many computers require that accesses to specific data types
                   2464: must only occur at specific addresses; e.g., that cells may only be
                   2465: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   2466: accesses, it can usually perform aligned accesses faster. 
                   2467: 
                   2468: For the performance-conscious: alignment operations are usually only
                   2469: necessary during the definition of a data structure, not during the
                   2470: (more frequent) accesses to it.
                   2471: 
                   2472: ANS Forth defines no words for character-aligning addresses. This is not
                   2473: an oversight, but reflects the fact that addresses that are not
                   2474: char-aligned have no use in the standard and therefore will not be
                   2475: created.
                   2476: 
                   2477: @cindex @code{CREATE} and alignment
                   2478: The standard guarantees that addresses returned by @code{CREATE}d words
                   2479: are cell-aligned; in addition, Gforth guarantees that these addresses
                   2480: are aligned for all purposes.
                   2481: 
                   2482: Note that the standard defines a word @code{char}, which has nothing to
                   2483: do with address arithmetic.
                   2484: 
                   2485: doc-chars
                   2486: doc-char+
                   2487: doc-cells
                   2488: doc-cell+
                   2489: doc-cell
                   2490: doc-align
                   2491: doc-aligned
                   2492: doc-floats
                   2493: doc-float+
                   2494: doc-float
                   2495: doc-falign
                   2496: doc-faligned
                   2497: doc-sfloats
                   2498: doc-sfloat+
                   2499: doc-sfalign
                   2500: doc-sfaligned
                   2501: doc-dfloats
                   2502: doc-dfloat+
                   2503: doc-dfalign
                   2504: doc-dfaligned
                   2505: doc-maxalign
                   2506: doc-maxaligned
                   2507: doc-cfalign
                   2508: doc-cfaligned
                   2509: doc-address-unit-bits
                   2510: 
                   2511: @node Memory Blocks,  , Address arithmetic, Memory
                   2512: @subsection Memory Blocks
                   2513: @cindex memory block words
                   2514: 
1.21      crook    2515: Some of these words work on address units (increments of @code{CELL}),
                   2516: and expect a @code{CELL}-aligned address. Others work on character units
                   2517: (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
                   2518: address. Choose the correct operation depending upon your data type. If
                   2519: you are moving a block of memory (for example, a region reserved by
                   2520: @code{allot}) it is safe to use @code{move}, and it should be faster
                   2521: than using @code{cmove}. If you are moving (for example) a string
                   2522: compiled using @code{S"}, it is not portable to use @code{move}; the
                   2523: alignment of the string in memory could change, and the relationship
                   2524: between @code{CELL} and @code{CHAR} could change.
                   2525: 
                   2526: When copying characters between overlapping memory regions, choose
                   2527: carefully between @code{cmove} and @code{cmove>}.
                   2528: 
                   2529: You can only use any of these words @var{portably} to access data space.
                   2530: 
                   2531: @comment - think the naming of the arguments is wrong for move
1.1       anton    2532: doc-move
                   2533: doc-erase
                   2534: 
1.21      crook    2535: @comment - think the naming of the arguments is wrong for cmove
1.1       anton    2536: doc-cmove
1.21      crook    2537: @comment - think the naming of the arguments is wrong for cmove>
1.1       anton    2538: doc-cmove>
                   2539: doc-fill
1.21      crook    2540: @comment - think the naming of the arguments is wrong for blank
1.1       anton    2541: doc-blank
1.21      crook    2542: doc-compare
                   2543: doc-search
1.1       anton    2544: 
                   2545: @node Control Structures, Locals, Memory, Words
                   2546: @section Control Structures
                   2547: @cindex control structures
                   2548: 
                   2549: Control structures in Forth cannot be used in interpret state, only in
                   2550: compile state@footnote{More precisely, they have no interpretation
                   2551: semantics (@pxref{Interpretation and Compilation Semantics})}, i.e., in
                   2552: a colon definition. We do not like this limitation, but have not seen a
                   2553: satisfying way around it yet, although many schemes have been proposed.
                   2554: 
                   2555: @menu
                   2556: * Selection::                   
                   2557: * Simple Loops::                
                   2558: * Counted Loops::               
                   2559: * Arbitrary control structures::  
                   2560: * Calls and returns::           
                   2561: * Exception Handling::          
                   2562: @end menu
                   2563: 
                   2564: @node Selection, Simple Loops, Control Structures, Control Structures
                   2565: @subsection Selection
                   2566: @cindex selection control structures
                   2567: @cindex control structures for selection
                   2568: 
                   2569: @cindex @code{IF} control structure
                   2570: @example
                   2571: @var{flag}
                   2572: IF
                   2573:   @var{code}
                   2574: ENDIF
                   2575: @end example
1.21      crook    2576: @noindent
1.1       anton    2577: or
                   2578: @example
                   2579: @var{flag}
                   2580: IF
                   2581:   @var{code1}
                   2582: ELSE
                   2583:   @var{code2}
                   2584: ENDIF
                   2585: @end example
                   2586: 
                   2587: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   2588: standard, and @code{ENDIF} is not, although it is quite popular. We
                   2589: recommend using @code{ENDIF}, because it is less confusing for people
                   2590: who also know other languages (and is not prone to reinforcing negative
                   2591: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   2592: system that only supplies @code{THEN} is simple:
                   2593: @example
1.21      crook    2594: : ENDIF   POSTPONE THEN ; immediate
1.1       anton    2595: @end example
                   2596: 
                   2597: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   2598: (adv.)}  has the following meanings:
                   2599: @quotation
                   2600: ... 2b: following next after in order ... 3d: as a necessary consequence
                   2601: (if you were there, then you saw them).
                   2602: @end quotation
                   2603: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   2604: and many other programming languages has the meaning 3d.]
                   2605: 
1.21      crook    2606: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    2607: you can avoid using @code{?dup}. Using these alternatives is also more
1.21      crook    2608: efficient than using @code{?dup}. Definitions in ANS Standard Forth
1.1       anton    2609: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   2610: @file{compat/control.fs}.
                   2611: 
                   2612: @cindex @code{CASE} control structure
                   2613: @example
                   2614: @var{n}
                   2615: CASE
                   2616:   @var{n1} OF @var{code1} ENDOF
                   2617:   @var{n2} OF @var{code2} ENDOF
                   2618:   @dots{}
                   2619: ENDCASE
                   2620: @end example
                   2621: 
                   2622: Executes the first @var{codei}, where the @var{ni} is equal to
                   2623: @var{n}. A default case can be added by simply writing the code after
                   2624: the last @code{ENDOF}. It may use @var{n}, which is on top of the stack,
                   2625: but must not consume it.
                   2626: 
                   2627: @node Simple Loops, Counted Loops, Selection, Control Structures
                   2628: @subsection Simple Loops
                   2629: @cindex simple loops
                   2630: @cindex loops without count 
                   2631: 
                   2632: @cindex @code{WHILE} loop
                   2633: @example
                   2634: BEGIN
                   2635:   @var{code1}
                   2636:   @var{flag}
                   2637: WHILE
                   2638:   @var{code2}
                   2639: REPEAT
                   2640: @end example
                   2641: 
                   2642: @var{code1} is executed and @var{flag} is computed. If it is true,
                   2643: @var{code2} is executed and the loop is restarted; If @var{flag} is
                   2644: false, execution continues after the @code{REPEAT}.
                   2645: 
                   2646: @cindex @code{UNTIL} loop
                   2647: @example
                   2648: BEGIN
                   2649:   @var{code}
                   2650:   @var{flag}
                   2651: UNTIL
                   2652: @end example
                   2653: 
                   2654: @var{code} is executed. The loop is restarted if @code{flag} is false.
                   2655: 
                   2656: @cindex endless loop
                   2657: @cindex loops, endless
                   2658: @example
                   2659: BEGIN
                   2660:   @var{code}
                   2661: AGAIN
                   2662: @end example
                   2663: 
                   2664: This is an endless loop.
                   2665: 
                   2666: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   2667: @subsection Counted Loops
                   2668: @cindex counted loops
                   2669: @cindex loops, counted
                   2670: @cindex @code{DO} loops
                   2671: 
                   2672: The basic counted loop is:
                   2673: @example
                   2674: @var{limit} @var{start}
                   2675: ?DO
                   2676:   @var{body}
                   2677: LOOP
                   2678: @end example
                   2679: 
                   2680: This performs one iteration for every integer, starting from @var{start}
1.21      crook    2681: and up to, but excluding @var{limit}. The counter, or @var{index}, can be
                   2682: accessed with @code{i}. For example, the loop:
1.1       anton    2683: @example
                   2684: 10 0 ?DO
                   2685:   i .
                   2686: LOOP
                   2687: @end example
1.21      crook    2688: @noindent
                   2689: prints @code{0 1 2 3 4 5 6 7 8 9}
                   2690: 
1.1       anton    2691: The index of the innermost loop can be accessed with @code{i}, the index
                   2692: of the next loop with @code{j}, and the index of the third loop with
                   2693: @code{k}.
                   2694: 
                   2695: doc-i
                   2696: doc-j
                   2697: doc-k
                   2698: 
                   2699: The loop control data are kept on the return stack, so there are some
1.21      crook    2700: restrictions on mixing return stack accesses and counted loop words. In
                   2701: particuler, if you put values on the return stack outside the loop, you
                   2702: cannot read them inside the loop@footnote{well, not in a way that is
                   2703: portable.}. If you put values on the return stack within a loop, you
                   2704: have to remove them before the end of the loop and before accessing the
                   2705: index of the loop.
1.1       anton    2706: 
                   2707: There are several variations on the counted loop:
                   2708: 
1.21      crook    2709: @itemize @bullet
                   2710: @item
                   2711: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   2712: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   2713: 
                   2714: @example
                   2715: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   2716: @end example
                   2717: prints @code{0 1 2 3}
                   2718: 
1.1       anton    2719: 
1.21      crook    2720: @item
                   2721: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   2722: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   2723: return stack so @code{EXIT} can get to its return address. For example:
                   2724: 
                   2725: @example
                   2726: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   2727: @end example
                   2728: prints @code{0 1 2 3}
                   2729: 
                   2730: 
                   2731: @item
1.1       anton    2732: If @var{start} is greater than @var{limit}, a @code{?DO} loop is entered
                   2733: (and @code{LOOP} iterates until they become equal by wrap-around
                   2734: arithmetic). This behaviour is usually not what you want. Therefore,
                   2735: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
                   2736: @code{?DO}), which do not enter the loop if @var{start} is greater than
                   2737: @var{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
                   2738: unsigned loop parameters.
                   2739: 
1.21      crook    2740: @item
                   2741: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   2742: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   2743: if you know that the loop is entered in any case. Such knowledge tends
                   2744: to become invalid during maintenance of a program, and then the
                   2745: @code{DO} will make trouble.
                   2746: 
                   2747: @item
1.1       anton    2748: @code{LOOP} can be replaced with @code{@var{n} +LOOP}; this updates the
                   2749: index by @var{n} instead of by 1. The loop is terminated when the border
                   2750: between @var{limit-1} and @var{limit} is crossed. E.g.:
                   2751: 
1.21      crook    2752: @example
                   2753: 4 0 +DO  i .  2 +LOOP
                   2754: @end example
                   2755: @noindent
                   2756: prints @code{0 2}
                   2757: 
                   2758: @example
                   2759: 4 1 +DO  i .  2 +LOOP
                   2760: @end example
                   2761: @noindent
                   2762: prints @code{1 3}
1.1       anton    2763: 
                   2764: 
                   2765: @cindex negative increment for counted loops
                   2766: @cindex counted loops with negative increment
                   2767: The behaviour of @code{@var{n} +LOOP} is peculiar when @var{n} is negative:
                   2768: 
1.21      crook    2769: @example
                   2770: -1 0 ?DO  i .  -1 +LOOP
                   2771: @end example
                   2772: @noindent
                   2773: prints @code{0 -1}
1.1       anton    2774: 
1.21      crook    2775: @example
                   2776: 0 0 ?DO  i .  -1 +LOOP
                   2777: @end example
                   2778: prints nothing.
1.1       anton    2779: 
                   2780: Therefore we recommend avoiding @code{@var{n} +LOOP} with negative
                   2781: @var{n}. One alternative is @code{@var{u} -LOOP}, which reduces the
                   2782: index by @var{u} each iteration. The loop is terminated when the border
                   2783: between @var{limit+1} and @var{limit} is crossed. Gforth also provides
                   2784: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   2785: 
1.21      crook    2786: @example
                   2787: -2 0 -DO  i .  1 -LOOP
                   2788: @end example
                   2789: @noindent
                   2790: prints @code{0 -1}
1.1       anton    2791: 
1.21      crook    2792: @example
                   2793: -1 0 -DO  i .  1 -LOOP
                   2794: @end example
                   2795: @noindent
                   2796: prints @code{0}
                   2797: 
                   2798: @example
                   2799: 0 0 -DO  i .  1 -LOOP
                   2800: @end example
                   2801: @noindent
                   2802: prints nothing.
1.1       anton    2803: 
1.21      crook    2804: @end itemize
1.1       anton    2805: 
                   2806: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
                   2807: @code{-LOOP} are not in the ANS Forth standard. However, an
                   2808: implementation for these words that uses only standard words is provided
                   2809: in @file{compat/loops.fs}.
                   2810: 
                   2811: 
                   2812: 
                   2813: @cindex @code{FOR} loops
                   2814: Another counted loop is
                   2815: @example
                   2816: @var{n}
                   2817: FOR
                   2818:   @var{body}
                   2819: NEXT
                   2820: @end example
                   2821: This is the preferred loop of native code compiler writers who are too
                   2822: lazy to optimize @code{?DO} loops properly. In Gforth, this loop
                   2823: iterates @var{n+1} times; @code{i} produces values starting with @var{n}
                   2824: and ending with 0. Other Forth systems may behave differently, even if
                   2825: they support @code{FOR} loops. To avoid problems, don't use @code{FOR}
                   2826: loops.
                   2827: 
                   2828: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   2829: @subsection Arbitrary control structures
                   2830: @cindex control structures, user-defined
                   2831: 
                   2832: @cindex control-flow stack
                   2833: ANS Forth permits and supports using control structures in a non-nested
                   2834: way. Information about incomplete control structures is stored on the
                   2835: control-flow stack. This stack may be implemented on the Forth data
                   2836: stack, and this is what we have done in Gforth.
                   2837: 
                   2838: @cindex @code{orig}, control-flow stack item
                   2839: @cindex @code{dest}, control-flow stack item
                   2840: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   2841: entry represents a backward branch target. A few words are the basis for
                   2842: building any control structure possible (except control structures that
                   2843: need storage, like calls, coroutines, and backtracking).
                   2844: 
                   2845: doc-if
                   2846: doc-ahead
                   2847: doc-then
                   2848: doc-begin
                   2849: doc-until
                   2850: doc-again
                   2851: doc-cs-pick
                   2852: doc-cs-roll
                   2853: 
1.21      crook    2854: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   2855: manipulate the control-flow stack in a portable way. Without them, you
                   2856: would need to know how many stack items are occupied by a control-flow
                   2857: entry (many systems use one cell. In Gforth they currently take three,
                   2858: but this may change in the future).
                   2859: 
1.1       anton    2860: 
                   2861: Some standard control structure words are built from these words:
                   2862: 
                   2863: doc-else
                   2864: doc-while
                   2865: doc-repeat
                   2866: 
                   2867: Gforth adds some more control-structure words:
                   2868: 
                   2869: doc-endif
                   2870: doc-?dup-if
                   2871: doc-?dup-0=-if
                   2872: 
                   2873: Counted loop words constitute a separate group of words:
                   2874: 
                   2875: doc-?do
                   2876: doc-+do
                   2877: doc-u+do
                   2878: doc--do
                   2879: doc-u-do
                   2880: doc-do
                   2881: doc-for
                   2882: doc-loop
                   2883: doc-+loop
                   2884: doc--loop
                   2885: doc-next
                   2886: doc-leave
                   2887: doc-?leave
                   2888: doc-unloop
                   2889: doc-done
                   2890: 
1.21      crook    2891: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   2892: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    2893: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   2894: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   2895: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   2896: resolved (by using one of the loop-ending words or @code{DONE}).
                   2897: 
                   2898: Another group of control structure words are
                   2899: 
                   2900: doc-case
                   2901: doc-endcase
                   2902: doc-of
                   2903: doc-endof
                   2904: 
1.21      crook    2905: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   2906: @code{CS-ROLL}.
1.1       anton    2907: 
                   2908: @subsubsection Programming Style
                   2909: 
                   2910: In order to ensure readability we recommend that you do not create
                   2911: arbitrary control structures directly, but define new control structure
                   2912: words for the control structure you want and use these words in your
                   2913: program.
                   2914: 
1.21      crook    2915: E.g., instead of writing:
1.1       anton    2916: 
                   2917: @example
                   2918: begin
                   2919:   ...
                   2920: if [ 1 cs-roll ]
                   2921:   ...
                   2922: again then
                   2923: @end example
                   2924: 
1.21      crook    2925: @noindent
1.1       anton    2926: we recommend defining control structure words, e.g.,
                   2927: 
                   2928: @example
                   2929: : while ( dest -- orig dest )
                   2930:  POSTPONE if
                   2931:  1 cs-roll ; immediate
                   2932: 
                   2933: : repeat ( orig dest -- )
                   2934:  POSTPONE again
                   2935:  POSTPONE then ; immediate
                   2936: @end example
                   2937: 
1.21      crook    2938: @noindent
1.1       anton    2939: and then using these to create the control structure:
                   2940: 
                   2941: @example
                   2942: begin
                   2943:   ...
                   2944: while
                   2945:   ...
                   2946: repeat
                   2947: @end example
                   2948: 
                   2949: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   2950: @code{WHILE} are predefined, so in this example it would not be
                   2951: necessary to define them.
                   2952: 
                   2953: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   2954: @subsection Calls and returns
                   2955: @cindex calling a definition
                   2956: @cindex returning from a definition
                   2957: 
1.3       anton    2958: @cindex recursive definitions
                   2959: A definition can be called simply be writing the name of the definition
                   2960: to be called. Note that normally a definition is invisible during its
                   2961: definition. If you want to write a directly recursive definition, you
                   2962: can use @code{recursive} to make the current definition visible.
                   2963: 
                   2964: doc-recursive
                   2965: 
                   2966: Another way to perform a recursive call is
                   2967: 
                   2968: doc-recurse
                   2969: 
1.21      crook    2970: @comment TODO add example of the two recursion methods
1.12      anton    2971: @quotation
                   2972: @progstyle
                   2973: I prefer using @code{recursive} to @code{recurse}, because calling the
                   2974: definition by name is more descriptive (if the name is well-chosen) than
                   2975: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   2976: implementation, it is much better to read (and think) ``now sort the
                   2977: partitions'' than to read ``now do a recursive call''.
                   2978: @end quotation
1.3       anton    2979: 
1.21      crook    2980: @comment TODO maybe move deferred words to Defining Words section and x-ref
                   2981: @comment from here.. that is where these two are glossed.
                   2982: 
1.3       anton    2983: For mutual recursion, use @code{defer}red words, like this:
                   2984: 
                   2985: @example
                   2986: defer foo
                   2987: 
                   2988: : bar ( ... -- ... )
                   2989:  ... foo ... ;
                   2990: 
                   2991: :noname ( ... -- ... )
                   2992:  ... bar ... ;
                   2993: IS foo
                   2994: @end example
                   2995: 
                   2996: When the end of the definition is reached, it returns. An earlier return
                   2997: can be forced using
1.1       anton    2998: 
                   2999: doc-exit
                   3000: 
                   3001: Don't forget to clean up the return stack and @code{UNLOOP} any
1.21      crook    3002: outstanding @code{?DO}...@code{LOOP}s before @code{EXIT}ing.
1.1       anton    3003: 
                   3004: doc-;s
                   3005: 
                   3006: @node Exception Handling,  , Calls and returns, Control Structures
                   3007: @subsection Exception Handling
                   3008: @cindex Exceptions
                   3009: 
1.21      crook    3010: @comment TODO examples and blurb
1.1       anton    3011: doc-catch
                   3012: doc-throw
1.21      crook    3013: @comment TODO -- think this will alllcate you a new THROW code?
                   3014: @comment for reserving new exception numbers. Note the existence of compat/exception.fs
                   3015: doc---exception-exception
                   3016: doc-quit
                   3017: doc-abort
                   3018: doc-abort"
                   3019: 
1.1       anton    3020: 
                   3021: @node Locals, Defining Words, Control Structures, Words
                   3022: @section Locals
                   3023: @cindex locals
                   3024: 
                   3025: Local variables can make Forth programming more enjoyable and Forth
                   3026: programs easier to read. Unfortunately, the locals of ANS Forth are
                   3027: laden with restrictions. Therefore, we provide not only the ANS Forth
                   3028: locals wordset, but also our own, more powerful locals wordset (we
                   3029: implemented the ANS Forth locals wordset through our locals wordset).
                   3030: 
                   3031: The ideas in this section have also been published in the paper
                   3032: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
                   3033: at EuroForth '94; it is available at
                   3034: @*@url{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
                   3035: 
                   3036: @menu
                   3037: * Gforth locals::               
                   3038: * ANS Forth locals::            
                   3039: @end menu
                   3040: 
                   3041: @node Gforth locals, ANS Forth locals, Locals, Locals
                   3042: @subsection Gforth locals
                   3043: @cindex Gforth locals
                   3044: @cindex locals, Gforth style
                   3045: 
                   3046: Locals can be defined with
                   3047: 
                   3048: @example
                   3049: @{ local1 local2 ... -- comment @}
                   3050: @end example
                   3051: or
                   3052: @example
                   3053: @{ local1 local2 ... @}
                   3054: @end example
                   3055: 
                   3056: E.g.,
                   3057: @example
                   3058: : max @{ n1 n2 -- n3 @}
                   3059:  n1 n2 > if
                   3060:    n1
                   3061:  else
                   3062:    n2
                   3063:  endif ;
                   3064: @end example
                   3065: 
                   3066: The similarity of locals definitions with stack comments is intended. A
                   3067: locals definition often replaces the stack comment of a word. The order
                   3068: of the locals corresponds to the order in a stack comment and everything
                   3069: after the @code{--} is really a comment.
                   3070: 
                   3071: This similarity has one disadvantage: It is too easy to confuse locals
                   3072: declarations with stack comments, causing bugs and making them hard to
                   3073: find. However, this problem can be avoided by appropriate coding
                   3074: conventions: Do not use both notations in the same program. If you do,
                   3075: they should be distinguished using additional means, e.g. by position.
                   3076: 
                   3077: @cindex types of locals
                   3078: @cindex locals types
                   3079: The name of the local may be preceded by a type specifier, e.g.,
                   3080: @code{F:} for a floating point value:
                   3081: 
                   3082: @example
                   3083: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   3084: \ complex multiplication
                   3085:  Ar Br f* Ai Bi f* f-
                   3086:  Ar Bi f* Ai Br f* f+ ;
                   3087: @end example
                   3088: 
                   3089: @cindex flavours of locals
                   3090: @cindex locals flavours
                   3091: @cindex value-flavoured locals
                   3092: @cindex variable-flavoured locals
                   3093: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   3094: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   3095: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   3096: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   3097: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   3098: produces its address (which becomes invalid when the variable's scope is
                   3099: left). E.g., the standard word @code{emit} can be defined in terms of
                   3100: @code{type} like this:
                   3101: 
                   3102: @example
                   3103: : emit @{ C^ char* -- @}
                   3104:     char* 1 type ;
                   3105: @end example
                   3106: 
                   3107: @cindex default type of locals
                   3108: @cindex locals, default type
                   3109: A local without type specifier is a @code{W:} local. Both flavours of
                   3110: locals are initialized with values from the data or FP stack.
                   3111: 
                   3112: Currently there is no way to define locals with user-defined data
                   3113: structures, but we are working on it.
                   3114: 
                   3115: Gforth allows defining locals everywhere in a colon definition. This
                   3116: poses the following questions:
                   3117: 
                   3118: @menu
                   3119: * Where are locals visible by name?::  
                   3120: * How long do locals live?::    
                   3121: * Programming Style::           
                   3122: * Implementation::              
                   3123: @end menu
                   3124: 
                   3125: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   3126: @subsubsection Where are locals visible by name?
                   3127: @cindex locals visibility
                   3128: @cindex visibility of locals
                   3129: @cindex scope of locals
                   3130: 
                   3131: Basically, the answer is that locals are visible where you would expect
                   3132: it in block-structured languages, and sometimes a little longer. If you
                   3133: want to restrict the scope of a local, enclose its definition in
                   3134: @code{SCOPE}...@code{ENDSCOPE}.
                   3135: 
                   3136: doc-scope
                   3137: doc-endscope
                   3138: 
                   3139: These words behave like control structure words, so you can use them
                   3140: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   3141: arbitrary ways.
                   3142: 
                   3143: If you want a more exact answer to the visibility question, here's the
                   3144: basic principle: A local is visible in all places that can only be
                   3145: reached through the definition of the local@footnote{In compiler
                   3146: construction terminology, all places dominated by the definition of the
                   3147: local.}. In other words, it is not visible in places that can be reached
                   3148: without going through the definition of the local. E.g., locals defined
                   3149: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   3150: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   3151: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
                   3152: 
                   3153: The reasoning behind this solution is: We want to have the locals
                   3154: visible as long as it is meaningful. The user can always make the
                   3155: visibility shorter by using explicit scoping. In a place that can
                   3156: only be reached through the definition of a local, the meaning of a
                   3157: local name is clear. In other places it is not: How is the local
                   3158: initialized at the control flow path that does not contain the
                   3159: definition? Which local is meant, if the same name is defined twice in
                   3160: two independent control flow paths?
                   3161: 
                   3162: This should be enough detail for nearly all users, so you can skip the
                   3163: rest of this section. If you really must know all the gory details and
                   3164: options, read on.
                   3165: 
                   3166: In order to implement this rule, the compiler has to know which places
                   3167: are unreachable. It knows this automatically after @code{AHEAD},
                   3168: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   3169: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   3170: compiler that the control flow never reaches that place. If
                   3171: @code{UNREACHABLE} is not used where it could, the only consequence is
                   3172: that the visibility of some locals is more limited than the rule above
                   3173: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   3174: lie to the compiler), buggy code will be produced.
                   3175: 
                   3176: doc-unreachable
                   3177: 
                   3178: Another problem with this rule is that at @code{BEGIN}, the compiler
                   3179: does not know which locals will be visible on the incoming
                   3180: back-edge. All problems discussed in the following are due to this
                   3181: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   3182: loops as examples; the discussion also applies to @code{?DO} and other
                   3183: loops). Perhaps the most insidious example is:
                   3184: @example
                   3185: AHEAD
                   3186: BEGIN
                   3187:   x
                   3188: [ 1 CS-ROLL ] THEN
                   3189:   @{ x @}
                   3190:   ...
                   3191: UNTIL
                   3192: @end example
                   3193: 
                   3194: This should be legal according to the visibility rule. The use of
                   3195: @code{x} can only be reached through the definition; but that appears
                   3196: textually below the use.
                   3197: 
                   3198: From this example it is clear that the visibility rules cannot be fully
                   3199: implemented without major headaches. Our implementation treats common
                   3200: cases as advertised and the exceptions are treated in a safe way: The
                   3201: compiler makes a reasonable guess about the locals visible after a
                   3202: @code{BEGIN}; if it is too pessimistic, the
                   3203: user will get a spurious error about the local not being defined; if the
                   3204: compiler is too optimistic, it will notice this later and issue a
                   3205: warning. In the case above the compiler would complain about @code{x}
                   3206: being undefined at its use. You can see from the obscure examples in
                   3207: this section that it takes quite unusual control structures to get the
                   3208: compiler into trouble, and even then it will often do fine.
                   3209: 
                   3210: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   3211: is that all locals visible before the @code{BEGIN} will also be
                   3212: visible after the @code{BEGIN}. This guess is valid for all loops that
                   3213: are entered only through the @code{BEGIN}, in particular, for normal
                   3214: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   3215: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   3216: compiler. When the branch to the @code{BEGIN} is finally generated by
                   3217: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   3218: warns the user if it was too optimistic:
                   3219: @example
                   3220: IF
                   3221:   @{ x @}
                   3222: BEGIN
                   3223:   \ x ? 
                   3224: [ 1 cs-roll ] THEN
                   3225:   ...
                   3226: UNTIL
                   3227: @end example
                   3228: 
                   3229: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   3230: optimistically assumes that it lives until the @code{THEN}. It notices
                   3231: this difference when it compiles the @code{UNTIL} and issues a
                   3232: warning. The user can avoid the warning, and make sure that @code{x}
                   3233: is not used in the wrong area by using explicit scoping:
                   3234: @example
                   3235: IF
                   3236:   SCOPE
                   3237:   @{ x @}
                   3238:   ENDSCOPE
                   3239: BEGIN
                   3240: [ 1 cs-roll ] THEN
                   3241:   ...
                   3242: UNTIL
                   3243: @end example
                   3244: 
                   3245: Since the guess is optimistic, there will be no spurious error messages
                   3246: about undefined locals.
                   3247: 
                   3248: If the @code{BEGIN} is not reachable from above (e.g., after
                   3249: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   3250: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   3251: defined later. Therefore, the compiler assumes that no locals are
                   3252: visible after the @code{BEGIN}. However, the user can use
                   3253: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   3254: visible at the BEGIN as at the point where the top control-flow stack
                   3255: item was created.
                   3256: 
                   3257: doc-assume-live
                   3258: 
                   3259: E.g.,
                   3260: @example
                   3261: @{ x @}
                   3262: AHEAD
                   3263: ASSUME-LIVE
                   3264: BEGIN
                   3265:   x
                   3266: [ 1 CS-ROLL ] THEN
                   3267:   ...
                   3268: UNTIL
                   3269: @end example
                   3270: 
                   3271: Other cases where the locals are defined before the @code{BEGIN} can be
                   3272: handled by inserting an appropriate @code{CS-ROLL} before the
                   3273: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   3274: behind the @code{ASSUME-LIVE}).
                   3275: 
                   3276: Cases where locals are defined after the @code{BEGIN} (but should be
                   3277: visible immediately after the @code{BEGIN}) can only be handled by
                   3278: rearranging the loop. E.g., the ``most insidious'' example above can be
                   3279: arranged into:
                   3280: @example
                   3281: BEGIN
                   3282:   @{ x @}
                   3283:   ... 0=
                   3284: WHILE
                   3285:   x
                   3286: REPEAT
                   3287: @end example
                   3288: 
                   3289: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
                   3290: @subsubsection How long do locals live?
                   3291: @cindex locals lifetime
                   3292: @cindex lifetime of locals
                   3293: 
                   3294: The right answer for the lifetime question would be: A local lives at
                   3295: least as long as it can be accessed. For a value-flavoured local this
                   3296: means: until the end of its visibility. However, a variable-flavoured
                   3297: local could be accessed through its address far beyond its visibility
                   3298: scope. Ultimately, this would mean that such locals would have to be
                   3299: garbage collected. Since this entails un-Forth-like implementation
                   3300: complexities, I adopted the same cowardly solution as some other
                   3301: languages (e.g., C): The local lives only as long as it is visible;
                   3302: afterwards its address is invalid (and programs that access it
                   3303: afterwards are erroneous).
                   3304: 
                   3305: @node Programming Style, Implementation, How long do locals live?, Gforth locals
                   3306: @subsubsection Programming Style
                   3307: @cindex locals programming style
                   3308: @cindex programming style, locals
                   3309: 
                   3310: The freedom to define locals anywhere has the potential to change
                   3311: programming styles dramatically. In particular, the need to use the
                   3312: return stack for intermediate storage vanishes. Moreover, all stack
                   3313: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   3314: determined arguments) can be eliminated: If the stack items are in the
                   3315: wrong order, just write a locals definition for all of them; then
                   3316: write the items in the order you want.
                   3317: 
                   3318: This seems a little far-fetched and eliminating stack manipulations is
                   3319: unlikely to become a conscious programming objective. Still, the number
                   3320: of stack manipulations will be reduced dramatically if local variables
                   3321: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
                   3322: a traditional implementation of @code{max}).
                   3323: 
                   3324: This shows one potential benefit of locals: making Forth programs more
                   3325: readable. Of course, this benefit will only be realized if the
                   3326: programmers continue to honour the principle of factoring instead of
                   3327: using the added latitude to make the words longer.
                   3328: 
                   3329: @cindex single-assignment style for locals
                   3330: Using @code{TO} can and should be avoided.  Without @code{TO},
                   3331: every value-flavoured local has only a single assignment and many
                   3332: advantages of functional languages apply to Forth. I.e., programs are
                   3333: easier to analyse, to optimize and to read: It is clear from the
                   3334: definition what the local stands for, it does not turn into something
                   3335: different later.
                   3336: 
                   3337: E.g., a definition using @code{TO} might look like this:
                   3338: @example
                   3339: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   3340:  u1 u2 min 0
                   3341:  ?do
                   3342:    addr1 c@@ addr2 c@@ -
                   3343:    ?dup-if
                   3344:      unloop exit
                   3345:    then
                   3346:    addr1 char+ TO addr1
                   3347:    addr2 char+ TO addr2
                   3348:  loop
                   3349:  u1 u2 - ;
                   3350: @end example
                   3351: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   3352: every loop iteration. @code{strcmp} is a typical example of the
                   3353: readability problems of using @code{TO}. When you start reading
                   3354: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   3355: string. Only near the end of the loop you realize that it is something
                   3356: else.
                   3357: 
                   3358: This can be avoided by defining two locals at the start of the loop that
                   3359: are initialized with the right value for the current iteration.
                   3360: @example
                   3361: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   3362:  addr1 addr2
                   3363:  u1 u2 min 0 
                   3364:  ?do @{ s1 s2 @}
                   3365:    s1 c@@ s2 c@@ -
                   3366:    ?dup-if
                   3367:      unloop exit
                   3368:    then
                   3369:    s1 char+ s2 char+
                   3370:  loop
                   3371:  2drop
                   3372:  u1 u2 - ;
                   3373: @end example
                   3374: Here it is clear from the start that @code{s1} has a different value
                   3375: in every loop iteration.
                   3376: 
                   3377: @node Implementation,  , Programming Style, Gforth locals
                   3378: @subsubsection Implementation
                   3379: @cindex locals implementation
                   3380: @cindex implementation of locals
                   3381: 
                   3382: @cindex locals stack
                   3383: Gforth uses an extra locals stack. The most compelling reason for
                   3384: this is that the return stack is not float-aligned; using an extra stack
                   3385: also eliminates the problems and restrictions of using the return stack
                   3386: as locals stack. Like the other stacks, the locals stack grows toward
                   3387: lower addresses. A few primitives allow an efficient implementation:
                   3388: 
                   3389: doc-@local#
                   3390: doc-f@local#
                   3391: doc-laddr#
                   3392: doc-lp+!#
                   3393: doc-lp!
                   3394: doc->l
                   3395: doc-f>l
                   3396: 
                   3397: In addition to these primitives, some specializations of these
                   3398: primitives for commonly occurring inline arguments are provided for
                   3399: efficiency reasons, e.g., @code{@@local0} as specialization of
                   3400: @code{@@local#} for the inline argument 0. The following compiling words
                   3401: compile the right specialized version, or the general version, as
                   3402: appropriate:
                   3403: 
                   3404: doc-compile-@local
                   3405: doc-compile-f@local
                   3406: doc-compile-lp+!
                   3407: 
                   3408: Combinations of conditional branches and @code{lp+!#} like
                   3409: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   3410: is taken) are provided for efficiency and correctness in loops.
                   3411: 
                   3412: A special area in the dictionary space is reserved for keeping the
                   3413: local variable names. @code{@{} switches the dictionary pointer to this
                   3414: area and @code{@}} switches it back and generates the locals
                   3415: initializing code. @code{W:} etc.@ are normal defining words. This
                   3416: special area is cleared at the start of every colon definition.
                   3417: 
1.21      crook    3418: @cindex word list for defining locals
1.1       anton    3419: A special feature of Gforth's dictionary is used to implement the
1.21      crook    3420: definition of locals without type specifiers: every word list (aka
1.1       anton    3421: vocabulary) has its own methods for searching
1.21      crook    3422: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
1.1       anton    3423: with a special search method: When it is searched for a word, it
                   3424: actually creates that word using @code{W:}. @code{@{} changes the search
1.21      crook    3425: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   3426: and then the word list for defining locals without type specifiers.
1.1       anton    3427: 
                   3428: The lifetime rules support a stack discipline within a colon
                   3429: definition: The lifetime of a local is either nested with other locals
                   3430: lifetimes or it does not overlap them.
                   3431: 
                   3432: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   3433: pointer manipulation is generated. Between control structure words
                   3434: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   3435: is the simplest of the other three control flow words. It has to
                   3436: restore the locals stack depth of the corresponding @code{BEGIN}
                   3437: before branching. The code looks like this:
                   3438: @format
                   3439: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   3440: @code{branch} <begin>
                   3441: @end format
                   3442: 
                   3443: @code{UNTIL} is a little more complicated: If it branches back, it
                   3444: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   3445: the locals stack must not be changed. The compiler generates the
                   3446: following code:
                   3447: @format
                   3448: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   3449: @end format
                   3450: The locals stack pointer is only adjusted if the branch is taken.
                   3451: 
                   3452: @code{THEN} can produce somewhat inefficient code:
                   3453: @format
                   3454: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   3455: <orig target>:
                   3456: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   3457: @end format
                   3458: The second @code{lp+!#} adjusts the locals stack pointer from the
                   3459: level at the @var{orig} point to the level after the @code{THEN}. The
                   3460: first @code{lp+!#} adjusts the locals stack pointer from the current
                   3461: level to the level at the orig point, so the complete effect is an
                   3462: adjustment from the current level to the right level after the
                   3463: @code{THEN}.
                   3464: 
                   3465: @cindex locals information on the control-flow stack
                   3466: @cindex control-flow stack items, locals information
                   3467: In a conventional Forth implementation a dest control-flow stack entry
                   3468: is just the target address and an orig entry is just the address to be
1.21      crook    3469: patched. Our locals implementation adds a word list to every orig or dest
1.1       anton    3470: item. It is the list of locals visible (or assumed visible) at the point
                   3471: described by the entry. Our implementation also adds a tag to identify
                   3472: the kind of entry, in particular to differentiate between live and dead
                   3473: (reachable and unreachable) orig entries.
                   3474: 
1.21      crook    3475: A few unusual operations have to be performed on locals word lists:
1.1       anton    3476: 
                   3477: doc-common-list
                   3478: doc-sub-list?
                   3479: doc-list-size
                   3480: 
1.21      crook    3481: Several features of our locals word list implementation make these
                   3482: operations easy to implement: The locals word lists are organised as
1.1       anton    3483: linked lists; the tails of these lists are shared, if the lists
                   3484: contain some of the same locals; and the address of a name is greater
                   3485: than the address of the names behind it in the list.
                   3486: 
                   3487: Another important implementation detail is the variable
                   3488: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   3489: determine if they can be reached directly or only through the branch
                   3490: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   3491: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   3492: definition, by @code{BEGIN} and usually by @code{THEN}.
                   3493: 
                   3494: Counted loops are similar to other loops in most respects, but
                   3495: @code{LEAVE} requires special attention: It performs basically the same
                   3496: service as @code{AHEAD}, but it does not create a control-flow stack
                   3497: entry. Therefore the information has to be stored elsewhere;
                   3498: traditionally, the information was stored in the target fields of the
                   3499: branches created by the @code{LEAVE}s, by organizing these fields into a
                   3500: linked list. Unfortunately, this clever trick does not provide enough
                   3501: space for storing our extended control flow information. Therefore, we
                   3502: introduce another stack, the leave stack. It contains the control-flow
                   3503: stack entries for all unresolved @code{LEAVE}s.
                   3504: 
                   3505: Local names are kept until the end of the colon definition, even if
                   3506: they are no longer visible in any control-flow path. In a few cases
                   3507: this may lead to increased space needs for the locals name area, but
                   3508: usually less than reclaiming this space would cost in code size.
                   3509: 
                   3510: 
                   3511: @node ANS Forth locals,  , Gforth locals, Locals
                   3512: @subsection ANS Forth locals
                   3513: @cindex locals, ANS Forth style
                   3514: 
                   3515: The ANS Forth locals wordset does not define a syntax for locals, but
                   3516: words that make it possible to define various syntaxes. One of the
                   3517: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   3518: wordset, i.e.:
                   3519: 
                   3520: @example
                   3521: @{ local1 local2 ... -- comment @}
                   3522: @end example
1.23      crook    3523: @noindent
1.1       anton    3524: or
                   3525: @example
                   3526: @{ local1 local2 ... @}
                   3527: @end example
                   3528: 
                   3529: The order of the locals corresponds to the order in a stack comment. The
                   3530: restrictions are:
                   3531: 
                   3532: @itemize @bullet
                   3533: @item
                   3534: Locals can only be cell-sized values (no type specifiers are allowed).
                   3535: @item
                   3536: Locals can be defined only outside control structures.
                   3537: @item
                   3538: Locals can interfere with explicit usage of the return stack. For the
                   3539: exact (and long) rules, see the standard. If you don't use return stack
                   3540: accessing words in a definition using locals, you will be all right. The
                   3541: purpose of this rule is to make locals implementation on the return
                   3542: stack easier.
                   3543: @item
                   3544: The whole definition must be in one line.
                   3545: @end itemize
                   3546: 
                   3547: Locals defined in this way behave like @code{VALUE}s (@xref{Simple
                   3548: Defining Words}). I.e., they are initialized from the stack. Using their
                   3549: name produces their value. Their value can be changed using @code{TO}.
                   3550: 
                   3551: Since this syntax is supported by Gforth directly, you need not do
                   3552: anything to use it. If you want to port a program using this syntax to
                   3553: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   3554: syntax on the other system.
                   3555: 
                   3556: Note that a syntax shown in the standard, section A.13 looks
                   3557: similar, but is quite different in having the order of locals
                   3558: reversed. Beware!
                   3559: 
1.23      crook    3560: The ANS Forth locals wordset itself consists of a word:
1.1       anton    3561: 
                   3562: doc-(local)
                   3563: 
1.23      crook    3564: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
1.1       anton    3565: awful that we strongly recommend not to use it. We have implemented this
                   3566: syntax to make porting to Gforth easy, but do not document it here. The
                   3567: problem with this syntax is that the locals are defined in an order
                   3568: reversed with respect to the standard stack comment notation, making
                   3569: programs harder to read, and easier to misread and miswrite. The only
                   3570: merit of this syntax is that it is easy to implement using the ANS Forth
                   3571: locals wordset.
                   3572: 
1.21      crook    3573: @node Defining Words, The Text Interpreter, Locals, Words
1.1       anton    3574: @section Defining Words
                   3575: @cindex defining words
                   3576: 
                   3577: @menu
                   3578: * Simple Defining Words::       
                   3579: * Colon Definitions::           
                   3580: * User-defined Defining Words::  
                   3581: * Supplying names::             
                   3582: * Interpretation and Compilation Semantics::  
                   3583: @end menu
                   3584: 
                   3585: @node Simple Defining Words, Colon Definitions, Defining Words, Defining Words
                   3586: @subsection Simple Defining Words
                   3587: @cindex simple defining words
                   3588: @cindex defining words, simple
                   3589: 
                   3590: doc-constant
                   3591: doc-2constant
                   3592: doc-fconstant
                   3593: doc-variable
                   3594: doc-2variable
                   3595: doc-fvariable
                   3596: doc-create
                   3597: doc-user
                   3598: doc-value
                   3599: doc-to
                   3600: doc-defer
                   3601: doc-is
                   3602: 
1.21      crook    3603: Definitions in ANS Standard Forth for @code{defer}, @code{<is>} and
                   3604: @code{[is]} are provided in @file{compat/defer.fs}. TODO - what do
                   3605: the two is words do?
                   3606: 
1.1       anton    3607: @node Colon Definitions, User-defined Defining Words, Simple Defining Words, Defining Words
                   3608: @subsection Colon Definitions
                   3609: @cindex colon definitions
                   3610: 
                   3611: @example
                   3612: : name ( ... -- ... )
                   3613:     word1 word2 word3 ;
                   3614: @end example
                   3615: 
                   3616: creates a word called @code{name}, that, upon execution, executes
                   3617: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
                   3618: 
                   3619: The explanation above is somewhat superficial. @xref{Interpretation and
                   3620: Compilation Semantics} for an in-depth discussion of some of the issues
                   3621: involved.
                   3622: 
                   3623: doc-:
                   3624: doc-;
                   3625: 
                   3626: @node User-defined Defining Words, Supplying names, Colon Definitions, Defining Words
                   3627: @subsection User-defined Defining Words
                   3628: @cindex user-defined defining words
                   3629: @cindex defining words, user-defined
                   3630: 
                   3631: You can create new defining words simply by wrapping defining-time code
                   3632: around existing defining words and putting the sequence in a colon
                   3633: definition.
                   3634: 
1.21      crook    3635: @comment TODO example
                   3636: 
1.1       anton    3637: @cindex @code{CREATE} ... @code{DOES>}
                   3638: If you want the words defined with your defining words to behave
                   3639: differently from words defined with standard defining words, you can
                   3640: write your defining word like this:
                   3641: 
                   3642: @example
                   3643: : def-word ( "name" -- )
                   3644:     Create @var{code1}
                   3645: DOES> ( ... -- ... )
                   3646:     @var{code2} ;
                   3647: 
                   3648: def-word name
                   3649: @end example
                   3650: 
                   3651: Technically, this fragment defines a defining word @code{def-word}, and
                   3652: a word @code{name}; when you execute @code{name}, the address of the
                   3653: body of @code{name} is put on the data stack and @var{code2} is executed
                   3654: (the address of the body of @code{name} is the address @code{HERE}
1.21      crook    3655: returns immediately after the @code{CREATE}). The word @code{name} is
                   3656: sometimes called a @var{child} of @code{def-word}.
1.1       anton    3657: 
                   3658: In other words, if you make the following definitions:
                   3659: 
                   3660: @example
                   3661: : def-word1 ( "name" -- )
                   3662:     Create @var{code1} ;
                   3663: 
                   3664: : action1 ( ... -- ... )
                   3665:     @var{code2} ;
                   3666: 
                   3667: def-word name1
                   3668: @end example
                   3669: 
                   3670: Using @code{name1 action1} is equivalent to using @code{name}.
                   3671: 
                   3672: E.g., you can implement @code{Constant} in this way:
                   3673: 
                   3674: @example
                   3675: : constant ( w "name" -- )
                   3676:     create ,
                   3677: DOES> ( -- w )
                   3678:     @@ ;
                   3679: @end example
                   3680: 
1.21      crook    3681: @comment that is the classic example.. maybe it should be earlier. There
                   3682: @comment is a beautiful description of how this works and what it does in
                   3683: @comment the Forthwrite 100th edition.
                   3684: 
1.1       anton    3685: When you create a constant with @code{5 constant five}, first a new word
                   3686: @code{five} is created, then the value 5 is laid down in the body of
                   3687: @code{five} with @code{,}. When @code{five} is invoked, the address of
                   3688: the body is put on the stack, and @code{@@} retrieves the value 5.
                   3689: 
                   3690: @cindex stack effect of @code{DOES>}-parts
                   3691: @cindex @code{DOES>}-parts, stack effect
                   3692: In the example above the stack comment after the @code{DOES>} specifies
                   3693: the stack effect of the defined words, not the stack effect of the
                   3694: following code (the following code expects the address of the body on
                   3695: the top of stack, which is not reflected in the stack comment). This is
                   3696: the convention that I use and recommend (it clashes a bit with using
                   3697: locals declarations for stack effect specification, though).
                   3698: 
                   3699: @subsubsection Applications of @code{CREATE..DOES>}
                   3700: @cindex @code{CREATE} ... @code{DOES>}, applications
                   3701: 
                   3702: You may wonder how to use this feature. Here are some usage patterns:
                   3703: 
                   3704: @cindex factoring similar colon definitions
                   3705: When you see a sequence of code occurring several times, and you can
                   3706: identify a meaning, you will factor it out as a colon definition. When
                   3707: you see similar colon definitions, you can factor them using
                   3708: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   3709: that look very similar:
                   3710: @example
                   3711: : ori, ( reg-target reg-source n -- )
                   3712:     0 asm-reg-reg-imm ;
                   3713: : andi, ( reg-target reg-source n -- )
                   3714:     1 asm-reg-reg-imm ;
                   3715: @end example
                   3716: 
1.21      crook    3717: @noindent
1.1       anton    3718: This could be factored with:
                   3719: @example
                   3720: : reg-reg-imm ( op-code -- )
1.21      crook    3721:     CREATE ,
1.1       anton    3722: DOES> ( reg-target reg-source n -- )
                   3723:     @@ asm-reg-reg-imm ;
                   3724: 
                   3725: 0 reg-reg-imm ori,
                   3726: 1 reg-reg-imm andi,
                   3727: @end example
                   3728: 
                   3729: @cindex currying
                   3730: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   3731: supply a part of the parameters for a word (known as @dfn{currying} in
                   3732: the functional language community). E.g., @code{+} needs two
                   3733: parameters. Creating versions of @code{+} with one parameter fixed can
                   3734: be done like this:
                   3735: @example
                   3736: : curry+ ( n1 -- )
1.21      crook    3737:     CREATE ,
1.1       anton    3738: DOES> ( n2 -- n1+n2 )
                   3739:     @@ + ;
                   3740: 
                   3741:  3 curry+ 3+
                   3742: -2 curry+ 2-
                   3743: @end example
                   3744: 
                   3745: @subsubsection The gory details of @code{CREATE..DOES>}
                   3746: @cindex @code{CREATE} ... @code{DOES>}, details
                   3747: 
                   3748: doc-does>
                   3749: 
                   3750: @cindex @code{DOES>} in a separate definition
                   3751: This means that you need not use @code{CREATE} and @code{DOES>} in the
1.21      crook    3752: same definition; you can put the @code{DOES>}-part in a separate
1.1       anton    3753: definition. This allows us to, e.g., select among different DOES>-parts:
                   3754: @example
                   3755: : does1 
                   3756: DOES> ( ... -- ... )
                   3757:     ... ;
                   3758: 
                   3759: : does2
                   3760: DOES> ( ... -- ... )
                   3761:     ... ;
                   3762: 
                   3763: : def-word ( ... -- ... )
                   3764:     create ...
                   3765:     IF
                   3766:        does1
                   3767:     ELSE
                   3768:        does2
                   3769:     ENDIF ;
                   3770: @end example
                   3771: 
1.21      crook    3772: In this example, the selection of whether to use @code{does1} or
                   3773: @code{does2} is made at compile-time; at the time that the child word is
                   3774: @code{Create}d.
                   3775: 
1.1       anton    3776: @cindex @code{DOES>} in interpretation state
                   3777: In a standard program you can apply a @code{DOES>}-part only if the last
                   3778: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   3779: will override the behaviour of the last word defined in any case. In a
                   3780: standard program, you can use @code{DOES>} only in a colon
                   3781: definition. In Gforth, you can also use it in interpretation state, in a
1.23      crook    3782: kind of one-shot mode; for example:
1.1       anton    3783: @example
                   3784: CREATE name ( ... -- ... )
                   3785:   @var{initialization}
                   3786: DOES>
                   3787:   @var{code} ;
                   3788: @end example
1.23      crook    3789: 
                   3790: @noindent
                   3791: is equivalent to the standard:
1.1       anton    3792: @example
                   3793: :noname
                   3794: DOES>
                   3795:     @var{code} ;
                   3796: CREATE name EXECUTE ( ... -- ... )
                   3797:     @var{initialization}
                   3798: @end example
                   3799: 
1.23      crook    3800: You can get the address of the body of a word with:
1.1       anton    3801: 
                   3802: doc->body
                   3803: 
                   3804: @node Supplying names, Interpretation and Compilation Semantics, User-defined Defining Words, Defining Words
                   3805: @subsection Supplying names for the defined words
                   3806: @cindex names for defined words
                   3807: @cindex defining words, name parameter
                   3808: 
                   3809: @cindex defining words, name given in a string
                   3810: By default, defining words take the names for the defined words from the
                   3811: input stream. Sometimes you want to supply the name from a string. You
1.21      crook    3812: can do this with:
1.1       anton    3813: 
                   3814: doc-nextname
                   3815: 
1.21      crook    3816: For example:
1.1       anton    3817: 
                   3818: @example
                   3819: s" foo" nextname create
                   3820: @end example
1.21      crook    3821: @noindent
                   3822: is equivalent to:
1.1       anton    3823: @example
                   3824: create foo
                   3825: @end example
                   3826: 
                   3827: @cindex defining words without name
1.21      crook    3828: Sometimes you want to define an @var{anonymous word}; a word without a
                   3829: name. You can do this with:
                   3830: 
                   3831: doc-:noname
                   3832: 
                   3833: This leaves the execution token for the word on the stack after the
                   3834: closing @code{;}. Here's an example in which a deferred word is
                   3835: initialised with an @code{xt} from an anonymous colon definition:
                   3836: @example
                   3837: Defer deferred
                   3838: :noname ( ... -- ... )
                   3839:   ... ;
                   3840: IS deferred
                   3841: @end example
                   3842: 
                   3843: Gforth provides an alternative way of doing this, using two separate
                   3844: words:
1.1       anton    3845: 
                   3846: doc-noname
                   3847: @cindex execution token of last defined word
1.21      crook    3848: doc-lastxt
1.1       anton    3849: 
1.21      crook    3850: The previous example can be rewritten using @code{noname} and
                   3851: @code{lastxt}:
1.1       anton    3852: 
                   3853: @example
                   3854: Defer deferred
                   3855: noname : ( ... -- ... )
                   3856:   ... ;
                   3857: lastxt IS deferred
                   3858: @end example
                   3859: 
                   3860: @code{lastxt} also works when the last word was not defined as
                   3861: @code{noname}. 
                   3862: 
                   3863: 
                   3864: @node Interpretation and Compilation Semantics,  , Supplying names, Defining Words
                   3865: @subsection Interpretation and Compilation Semantics
                   3866: @cindex semantics, interpretation and compilation
                   3867: 
                   3868: @cindex interpretation semantics
                   3869: The @dfn{interpretation semantics} of a word are what the text
                   3870: interpreter does when it encounters the word in interpret state. It also
                   3871: appears in some other contexts, e.g., the execution token returned by
                   3872: @code{' @var{word}} identifies the interpretation semantics of
                   3873: @var{word} (in other words, @code{' @var{word} execute} is equivalent to
                   3874: interpret-state text interpretation of @code{@var{word}}).
                   3875: 
                   3876: @cindex compilation semantics
                   3877: The @dfn{compilation semantics} of a word are what the text interpreter
                   3878: does when it encounters the word in compile state. It also appears in
                   3879: other contexts, e.g, @code{POSTPONE @var{word}} compiles@footnote{In
                   3880: standard terminology, ``appends to the current definition''.} the
                   3881: compilation semantics of @var{word}.
                   3882: 
                   3883: @cindex execution semantics
                   3884: The standard also talks about @dfn{execution semantics}. They are used
                   3885: only for defining the interpretation and compilation semantics of many
                   3886: words. By default, the interpretation semantics of a word are to
                   3887: @code{execute} its execution semantics, and the compilation semantics of
                   3888: a word are to @code{compile,} its execution semantics.@footnote{In
                   3889: standard terminology: The default interpretation semantics are its
                   3890: execution semantics; the default compilation semantics are to append its
                   3891: execution semantics to the execution semantics of the current
                   3892: definition.}
                   3893: 
1.21      crook    3894: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   3895: 
1.1       anton    3896: @cindex immediate words
                   3897: You can change the compilation semantics into @code{execute}ing the
                   3898: execution semantics with
                   3899: 
                   3900: doc-immediate
                   3901: 
                   3902: @cindex compile-only words
                   3903: You can remove the interpretation semantics of a word with
                   3904: 
                   3905: doc-compile-only
                   3906: doc-restrict
                   3907: 
                   3908: Note that ticking (@code{'}) compile-only words gives an error
                   3909: (``Interpreting a compile-only word'').
                   3910: 
                   3911: Gforth also allows you to define words with arbitrary combinations of
                   3912: interpretation and compilation semantics.
                   3913: 
                   3914: doc-interpret/compile:
                   3915: 
                   3916: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   3917: recommend that you do not define such words, as cute as they may be:
                   3918: they make it hard to get at both parts of the word in some contexts.
                   3919: E.g., assume you want to get an execution token for the compilation
                   3920: part. Instead, define two words, one that embodies the interpretation
1.15      anton    3921: part, and one that embodies the compilation part.  Once you have done
                   3922: that, you can define a combined word with @code{interpret/compile:} for
                   3923: the convenience of your users.
1.1       anton    3924: 
1.23      crook    3925: You also might try to  with this feature, like this:
1.1       anton    3926: 
1.23      crook    3927: You might try to use this feature to provide an optimizing
                   3928: implementation of the default compilation semantics of a word. For
                   3929: example, by defining:
1.1       anton    3930: @example
                   3931: :noname
                   3932:    foo bar ;
                   3933: :noname
                   3934:    POSTPONE foo POSTPONE bar ;
                   3935: interpret/compile: foobar
                   3936: @end example
                   3937: 
1.21      crook    3938: @noindent
                   3939: as an optimizing version of:
1.15      anton    3940: 
                   3941: @example
                   3942: : foobar
                   3943:     foo bar ;
                   3944: @end example
                   3945: 
                   3946: Unfortunately, this does not work correctly with @code{[compile]},
                   3947: because @code{[compile]} assumes that the compilation semantics of all
                   3948: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
                   3949: foobar} would compile the compilation semantics for the optimizing
                   3950: @code{foobar}, whereas it would compile the interpretation semantics for
                   3951: the non-optimizing @code{foobar}.
1.1       anton    3952: 
1.23      crook    3953: @cindex state-smart words (are a bad idea)
                   3954: Some people try to use @var{state-smart} words to emulate the feature provided
1.1       anton    3955: by @code{interpret/compile:} (words are state-smart if they check
                   3956: @code{STATE} during execution). E.g., they would try to code
                   3957: @code{foobar} like this:
                   3958: 
                   3959: @example
                   3960: : foobar
                   3961:   STATE @@
                   3962:   IF ( compilation state )
                   3963:     POSTPONE foo POSTPONE bar
                   3964:   ELSE
                   3965:     foo bar
                   3966:   ENDIF ; immediate
                   3967: @end example
                   3968: 
1.23      crook    3969: Although this works if @code{foobar} is only processed by the text
1.1       anton    3970: interpreter, it does not work in other contexts (like @code{'} or
                   3971: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   3972: for a state-smart word, not for the interpretation semantics of the
                   3973: original @code{foobar}; when you execute this execution token (directly
                   3974: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   3975: state, the result will not be what you expected (i.e., it will not
                   3976: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
1.21      crook    3977: write them@footnote{For a more detailed discussion of this topic, see
                   3978: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
                   3979: Ertl; presented at EuroForth '98 and available from
                   3980: @url{http://www.complang.tuwien.ac.at/papers/}}!
1.1       anton    3981: 
                   3982: @cindex defining words with arbitrary semantics combinations
                   3983: It is also possible to write defining words that define words with
1.15      anton    3984: arbitrary combinations of interpretation and compilation semantics. In
1.23      crook    3985: general, they look like this:
1.1       anton    3986: 
                   3987: @example
                   3988: : def-word
                   3989:     create-interpret/compile
                   3990:     @var{code1}
                   3991: interpretation>
                   3992:     @var{code2}
                   3993: <interpretation
                   3994: compilation>
                   3995:     @var{code3}
1.21      crook    3996: <compilation ;
                   3997: @end example
                   3998: 
                   3999: For a @var{word} defined with @code{def-word}, the interpretation
                   4000: semantics are to push the address of the body of @var{word} and perform
                   4001: @var{code2}, and the compilation semantics are to push the address of
                   4002: the body of @var{word} and perform @var{code3}. E.g., @code{constant}
                   4003: can also be defined like this (except that the defined constants don't
                   4004: behave correctly when @code{[compile]}d):
                   4005: 
                   4006: @example
                   4007: : constant ( n "name" -- )
                   4008:     create-interpret/compile
                   4009:     ,
                   4010: interpretation> ( -- n )
                   4011:     @@
                   4012: <interpretation
                   4013: compilation> ( compilation. -- ; run-time. -- n )
                   4014:     @@ postpone literal
                   4015: <compilation ;
                   4016: @end example
                   4017: 
                   4018: doc-create-interpret/compile
                   4019: doc-interpretation>
                   4020: doc-<interpretation
                   4021: doc-compilation>
                   4022: doc-<compilation
                   4023: 
                   4024: Note that words defined with @code{interpret/compile:} and
                   4025: @code{create-interpret/compile} have an extended header structure that
                   4026: differs from other words; however, unless you try to access them with
                   4027: plain address arithmetic, you should not notice this. Words for
                   4028: accessing the header structure usually know how to deal with this; e.g.,
                   4029: @code{' word >body} also gives you the body of a word created with
                   4030: @code{create-interpret/compile}.
                   4031: 
                   4032: @c ----------------------------------------------------------
                   4033: @node The Text Interpreter, Structures, Defining Words, Words
                   4034: @section  The Text Interpreter
                   4035: @cindex interpreter - outer
                   4036: @cindex text interpreter
                   4037: @cindex outer interpreter
                   4038: 
1.23      crook    4039: Intro blah.
                   4040: 
                   4041: @comment TODO
1.21      crook    4042: 
                   4043: doc->in
1.23      crook    4044: doc-tib
                   4045: doc-#tib
                   4046: doc-span
                   4047: doc-restore-input
                   4048: doc-save-input
                   4049: doc-source
                   4050: doc-source-id
1.21      crook    4051: 
                   4052: 
                   4053: @menu
                   4054: * Number Conversion::
                   4055: * Interpret/Compile states::
                   4056: * Literals::
                   4057: * Interpreter Directives::
                   4058: @end menu
                   4059: 
1.23      crook    4060: @comment TODO
1.21      crook    4061: 
                   4062: The text interpreter works on input one line at a time. Starting at
                   4063: the beginning of the line, it skips leading spaces (called
                   4064: "delimiters") then parses a string (a sequence of non-space
                   4065: characters) until it either reaches a space character or it
                   4066: reaches the end of the line. Having parsed a string, it then makes two
                   4067: attempts to do something with it:
                   4068: 
                   4069: * It looks the string up in a dictionary of definitions. If the string
                   4070:   is found in the dictionary, the string names a "definition" (also
                   4071:   known as a "word") and the dictionary search will return an
                   4072:   "Execution token" (xt) for the definition and some flags that show
                   4073:   when the definition can be used legally. If the definition can be
                   4074:   legally executed in "Interpret" mode then the text interpreter will
                   4075:   use the xt to execute it, otherwise it will issue an error
                   4076:   message. The dictionary is described in more detail in <blah>.
                   4077: 
                   4078: * If the string is not found in the dictionary, the text interpreter
                   4079:   attempts to treat it as a number in the current radix (base 10 after
                   4080:   initial startup). If the string represents a legal number in the
                   4081:   current radix, the number is pushed onto the appropriate parameter
                   4082:   stack. Stacks are discussed in more detail in <blah>. Number
                   4083:   conversion is described in more detail in <section about +, -
                   4084:   numbers and different number formats>.
                   4085: 
                   4086: If both of these attempts fail, the remainer of the input line is
                   4087: discarded and the text interpreter isses an error message. If one of
                   4088: these attempts succeeds, the text interpreter repeats the parsing
                   4089: process until the end of the line has been reached. At this point, 
                   4090: it prints the status message "  ok" and waits for more input.
                   4091: 
                   4092: There are two important things to note about the behaviour of the text
                   4093: interpreter:
                   4094: 
                   4095: * it processes each input string to completion before parsing
                   4096:   additional characters from the input line.
                   4097: 
                   4098: * it keeps track of its position in the input line using a variable
                   4099:   (called >IN, pronounced "to-in"). The value of >IN can be modified
                   4100:   by the execution of definitions in the input line. This means that
                   4101:   definitions can "trick" the text interpreter either into skipping
                   4102:   sections of the input line or into parsing a section of the
                   4103:   input line more than once.
                   4104: 
                   4105: 
1.23      crook    4106: @node Number Conversion, Interpret/Compile states, The Text Interpreter, The Text Interpreter
                   4107: @subsection Number Conversion
                   4108: @cindex Number conversion
                   4109: @cindex double-cell numbers, input format
                   4110: @cindex input format for double-cell numbers
                   4111: @cindex single-cell numbers, input format
                   4112: @cindex input format for single-cell numbers
                   4113: @cindex floating-point numbers, input format
                   4114: @cindex input format for floating-point numbers
1.21      crook    4115: 
1.23      crook    4116: If the text interpreter fails to find a particular string in the name
                   4117: dictionary, it attempts to convert it to a number using a set of rules.
1.21      crook    4118: 
1.23      crook    4119: Let <digit> represent any character that is a legal digit in the current
                   4120: number base (for example, 0-9 when the number base is decimal or 0-9, A-F
                   4121: when the number base is hexadecimal).
1.21      crook    4122: 
1.23      crook    4123: Let <decimal digit> represent any character in the range 0-9.
1.21      crook    4124: 
1.23      crook    4125: @comment TODO need to extend the next defn to support fp format
                   4126: Let @{+ | -@} represent the optional presence of either a @code{+} or
                   4127: @code{-} character.
1.21      crook    4128: 
1.23      crook    4129: Let * represent any number of instances of the previous character
                   4130: (including none).
1.21      crook    4131: 
1.23      crook    4132: Let any other character represent itself.
1.21      crook    4133: 
1.23      crook    4134: Now, the conversion rules are:
1.21      crook    4135: 
1.23      crook    4136: @itemize @bullet
                   4137: @item
                   4138: A string of the form <digit><digit>* is treated as a single-precision
                   4139: (CELL-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
                   4140: @item
                   4141: A string of the form -<digit><digit>* is treated as a single-precision
                   4142: (CELL-sized) negative integer, and is represented using 2's-complement
                   4143: arithmetic. Examples are -45 -5681 -0
                   4144: @item
                   4145: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
                   4146: (double-CELL-sized) positive integer. Examples are 3465. 3.465 34.65
                   4147: (and note that these all represent the same number).
                   4148: @item
                   4149: A string of the form -<digit><digit>*.<digit>* is treated as a
                   4150: double-precision (double-CELL-sized) negative integer, and is
                   4151: represented using 2's-complement arithmetic. Examples are -3465. -3.465
                   4152: -34.65 (and note that these all represent the same number).
                   4153: @item
                   4154: A string of the form @{+ | -@}<decimal digit>@{.@}<decimal digit>*@{e | E@}@{+
                   4155: | -@}<decimal digit><decimal digit>* is treated as floating-point
                   4156: number. Examples are 1e0 1.e 1.e0 +1e+0 (which all represent the same
                   4157: number) +12.E-4 
                   4158: @end itemize
1.21      crook    4159: 
1.23      crook    4160: By default, the number base used for integer number conversion is given
                   4161: by the contents of a variable named @code{BASE}. Base 10 (decimal) is
                   4162: always used for floating-point number conversion.
1.21      crook    4163: 
1.23      crook    4164: doc-base
                   4165: doc-hex
                   4166: doc-decimal
1.21      crook    4167: 
1.23      crook    4168: @cindex '-prefix for character strings
                   4169: @cindex &-prefix for decimal numbers
                   4170: @cindex %-prefix for binary numbers
                   4171: @cindex $-prefix for hexadecimal numbers
                   4172: Gforth allows you to override the value of @code{BASE} by using a prefix
                   4173: before the first digit of an (integer) number. Four prefixes are
                   4174: supported:
1.21      crook    4175: 
1.23      crook    4176: @itemize @bullet
                   4177: @item
                   4178: @code{&} -- decimal number
                   4179: @item
                   4180: @code{%} -- binary number
                   4181: @item
                   4182: @code{$} -- hexadecimal number
                   4183: @item
                   4184: @code{'} -- base 256 number
                   4185: @end itemize
1.21      crook    4186: 
1.23      crook    4187: Here are some examples, with the equivalent decimal number shown after
                   4188: in braces:
1.21      crook    4189: 
                   4190: -$41 (-65) %1001101 (205) %1001.0001 (145 - a double-precision number)
                   4191: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66)
                   4192: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98)
                   4193: &905 (905) $abc (2478) $ABC (2478)
                   4194: 
                   4195: @cindex Number conversion - traps for the unwary
                   4196: Number conversion has a number of traps for the unwary:
                   4197: 
                   4198: @itemize @bullet
                   4199: @item
                   4200: You cannot determine the current number base using the code sequence
                   4201: @code{BASE @@ .} -- the number base is always 10 in the current number
                   4202: base. Instead, use something like @code{BASE @@ DECIMAL DUP . BASE !}
                   4203: @item
                   4204: If the number base is set to a value greater than 14 (for example,
                   4205: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   4206: it to be intepreted as either a single-precision integer or a
                   4207: floating-point number (Gforth treats it as an integer). The ambiguity
                   4208: can be resolved by explicitly stating the sign of the mantissa and/or
                   4209: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   4210: ambiguity arises; either representation will be treated as a
                   4211: floating-point number.
                   4212: @item
                   4213: There is a word @code{bin} but it does @var{not} set the number base!
                   4214: It is used to specify file types.
                   4215: @item
                   4216: ANS Forth Standard requires the @code{.} of a double-precision number to
                   4217: be the final character in the string. Allowing the @code{.} to be
                   4218: anywhere after the first digit is a Gforth extension.
                   4219: @item
                   4220: The number conversion process does not check for overflow.
                   4221: @item
                   4222: In Gforth, number conversion to floating-point numbers always use base
                   4223: 10, irrespective of the value of @code{BASE}. For the ANS Forth
                   4224: Standard, conversion to floating-point numbers whilst the value of
                   4225: @code{BASE} is not 10 is an ambiguous condition.
                   4226: @end itemize
                   4227: 
                   4228: 
                   4229: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
                   4230: @subsection Interpret/Compile states
                   4231: @cindex Interpret/Compile states
                   4232: 
1.23      crook    4233: @comment TODO
                   4234: Intro blah.
1.21      crook    4235: 
                   4236: doc-state
                   4237: doc-[
                   4238: doc-]
1.1       anton    4239: 
                   4240: 
1.21      crook    4241: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
                   4242: @subsection Literals
                   4243: @cindex Literals
                   4244: 
1.23      crook    4245: @comment TODO
                   4246: Intro blah.
1.21      crook    4247: 
                   4248: doc-literal
1.23      crook    4249: doc-]L
1.21      crook    4250: doc-2literal
                   4251: doc-fliteral
                   4252: 
                   4253: @node Interpreter Directives, ,Literals, The Text Interpreter
                   4254: @subsection Interpreter Directives
                   4255: @cindex Interpreter Directives
                   4256: 
                   4257: These words are usually used outside of definitions; for example, to
                   4258: control which parts of a source file are processed by the text
                   4259: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   4260: supplements these with a rich set of immediate control structure words
                   4261: to compensate for the fact that the non-immediate versions can only be
                   4262: used in compile state (@pxref{Control Structures}).
                   4263: 
                   4264: doc-[IF]
                   4265: doc-[ELSE]
                   4266: doc-[THEN]
                   4267: doc-[ENDIF]
                   4268: 
                   4269: doc-[IFDEF]
                   4270: doc-[IFUNDEF]
                   4271: 
                   4272: doc-[?DO]
                   4273: doc-[DO]
                   4274: doc-[FOR]
                   4275: doc-[LOOP]
                   4276: doc-[+LOOP]
                   4277: doc-[NEXT]
                   4278: 
                   4279: doc-[BEGIN]
                   4280: doc-[UNTIL]
                   4281: doc-[AGAIN]
                   4282: doc-[WHILE]
                   4283: doc-[REPEAT]
1.1       anton    4284: 
                   4285: 
1.5       anton    4286: @c ----------------------------------------------------------
1.21      crook    4287: @node Structures, Object-oriented Forth, The Text Interpreter, Words
1.5       anton    4288: @section  Structures
                   4289: @cindex structures
                   4290: @cindex records
                   4291: 
                   4292: This section presents the structure package that comes with Gforth. A
1.21      crook    4293: version of the package implemented in ANS Standard Forth is available in
1.5       anton    4294: @file{compat/struct.fs}. This package was inspired by a posting on
                   4295: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   4296: possibly John Hayes). A version of this section has been published in
                   4297: ???. Marcel Hendrix provided helpful comments.
                   4298: 
                   4299: @menu
                   4300: * Why explicit structure support?::  
                   4301: * Structure Usage::             
                   4302: * Structure Naming Convention::  
                   4303: * Structure Implementation::    
                   4304: * Structure Glossary::          
                   4305: @end menu
                   4306: 
                   4307: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   4308: @subsection Why explicit structure support?
                   4309: 
                   4310: @cindex address arithmetic for structures
                   4311: @cindex structures using address arithmetic
                   4312: If we want to use a structure containing several fields, we could simply
                   4313: reserve memory for it, and access the fields using address arithmetic
                   4314: (@pxref{Address arithmetic}). As an example, consider a structure with
                   4315: the following fields
                   4316: 
                   4317: @table @code
                   4318: @item a
                   4319: is a float
                   4320: @item b
                   4321: is a cell
                   4322: @item c
                   4323: is a float
                   4324: @end table
                   4325: 
                   4326: Given the (float-aligned) base address of the structure we get the
                   4327: address of the field
                   4328: 
                   4329: @table @code
                   4330: @item a
                   4331: without doing anything further.
                   4332: @item b
                   4333: with @code{float+}
                   4334: @item c
                   4335: with @code{float+ cell+ faligned}
                   4336: @end table
                   4337: 
                   4338: It is easy to see that this can become quite tiring. 
                   4339: 
                   4340: Moreover, it is not very readable, because seeing a
                   4341: @code{cell+} tells us neither which kind of structure is
                   4342: accessed nor what field is accessed; we have to somehow infer the kind
                   4343: of structure, and then look up in the documentation, which field of
                   4344: that structure corresponds to that offset.
                   4345: 
                   4346: Finally, this kind of address arithmetic also causes maintenance
                   4347: troubles: If you add or delete a field somewhere in the middle of the
                   4348: structure, you have to find and change all computations for the fields
                   4349: afterwards.
                   4350: 
                   4351: So, instead of using @code{cell+} and friends directly, how
                   4352: about storing the offsets in constants:
                   4353: 
                   4354: @example
                   4355: 0 constant a-offset
                   4356: 0 float+ constant b-offset
                   4357: 0 float+ cell+ faligned c-offset
                   4358: @end example
                   4359: 
                   4360: Now we can get the address of field @code{x} with @code{x-offset
                   4361: +}. This is much better in all respects. Of course, you still
                   4362: have to change all later offset definitions if you add a field. You can
                   4363: fix this by declaring the offsets in the following way:
                   4364: 
                   4365: @example
                   4366: 0 constant a-offset
                   4367: a-offset float+ constant b-offset
                   4368: b-offset cell+ faligned constant c-offset
                   4369: @end example
                   4370: 
1.23      crook    4371: Since we always use the offsets with @code{+}, we could use a defining
                   4372: word @code{cfield} that includes the @code{+} in the action of the
                   4373: defined word:
1.5       anton    4374: 
                   4375: @example
                   4376: : cfield ( n "name" -- )
                   4377:     create ,
                   4378: does> ( name execution: addr1 -- addr2 )
                   4379:     @@ + ;
                   4380: 
                   4381: 0 cfield a
                   4382: 0 a float+ cfield b
                   4383: 0 b cell+ faligned cfield c
                   4384: @end example
                   4385: 
                   4386: Instead of @code{x-offset +}, we now simply write @code{x}.
                   4387: 
                   4388: The structure field words now can be used quite nicely. However,
                   4389: their definition is still a bit cumbersome: We have to repeat the
                   4390: name, the information about size and alignment is distributed before
                   4391: and after the field definitions etc.  The structure package presented
                   4392: here addresses these problems.
                   4393: 
                   4394: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   4395: @subsection Structure Usage
                   4396: @cindex structure usage
                   4397: 
                   4398: @cindex @code{field} usage
                   4399: @cindex @code{struct} usage
                   4400: @cindex @code{end-struct} usage
1.23      crook    4401: You can define a structure for a (data-less) linked list with:
1.5       anton    4402: @example
                   4403: struct
                   4404:     cell% field list-next
                   4405: end-struct list%
                   4406: @end example
                   4407: 
                   4408: With the address of the list node on the stack, you can compute the
                   4409: address of the field that contains the address of the next node with
                   4410: @code{list-next}. E.g., you can determine the length of a list
                   4411: with:
                   4412: 
                   4413: @example
                   4414: : list-length ( list -- n )
                   4415: \ "list" is a pointer to the first element of a linked list
                   4416: \ "n" is the length of the list
                   4417:     0 begin ( list1 n1 )
                   4418:         over
                   4419:     while ( list1 n1 )
                   4420:         1+ swap list-next @@ swap
                   4421:     repeat
                   4422:     nip ;
                   4423: @end example
                   4424: 
                   4425: You can reserve memory for a list node in the dictionary with
                   4426: @code{list% %allot}, which leaves the address of the list node on the
                   4427: stack. For the equivalent allocation on the heap you can use @code{list%
                   4428: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
1.23      crook    4429: use @code{list% %allocate}). You can get the the size of a list
                   4430: node with @code{list% %size} and its alignment with @code{list%
1.5       anton    4431: %alignment}.
                   4432: 
                   4433: Note that in ANS Forth the body of a @code{create}d word is
                   4434: @code{aligned} but not necessarily @code{faligned};
1.23      crook    4435: therefore, if you do a:
1.5       anton    4436: @example
                   4437: create @emph{name} foo% %allot
                   4438: @end example
                   4439: 
1.23      crook    4440: @noindent
1.5       anton    4441: then the memory alloted for @code{foo%} is
                   4442: guaranteed to start at the body of @code{@emph{name}} only if
                   4443: @code{foo%} contains only character, cell and double fields.
                   4444: 
                   4445: @cindex strcutures containing structures
1.23      crook    4446: You can include a structure @code{foo%} as a field of
                   4447: another structure, like this:
1.5       anton    4448: @example
                   4449: struct
                   4450: ...
                   4451:     foo% field ...
                   4452: ...
                   4453: end-struct ...
                   4454: @end example
                   4455: 
                   4456: @cindex structure extension
                   4457: @cindex extended records
1.23      crook    4458: Instead of starting with an empty structure, you can extend an
1.5       anton    4459: existing structure. E.g., a plain linked list without data, as defined
                   4460: above, is hardly useful; You can extend it to a linked list of integers,
                   4461: like this:@footnote{This feature is also known as @emph{extended
                   4462: records}. It is the main innovation in the Oberon language; in other
                   4463: words, adding this feature to Modula-2 led Wirth to create a new
                   4464: language, write a new compiler etc.  Adding this feature to Forth just
1.23      crook    4465: required a few lines of code.}
1.5       anton    4466: 
                   4467: @example
                   4468: list%
                   4469:     cell% field intlist-int
                   4470: end-struct intlist%
                   4471: @end example
                   4472: 
                   4473: @code{intlist%} is a structure with two fields:
                   4474: @code{list-next} and @code{intlist-int}.
                   4475: 
                   4476: @cindex structures containing arrays
                   4477: You can specify an array type containing @emph{n} elements of
                   4478: type @code{foo%} like this:
                   4479: 
                   4480: @example
                   4481: foo% @emph{n} *
                   4482: @end example
                   4483: 
                   4484: You can use this array type in any place where you can use a normal
                   4485: type, e.g., when defining a @code{field}, or with
                   4486: @code{%allot}.
                   4487: 
                   4488: @cindex first field optimization
                   4489: The first field is at the base address of a structure and the word
                   4490: for this field (e.g., @code{list-next}) actually does not change
                   4491: the address on the stack. You may be tempted to leave it away in the
                   4492: interest of run-time and space efficiency. This is not necessary,
                   4493: because the structure package optimizes this case and compiling such
                   4494: words does not generate any code. So, in the interest of readability
                   4495: and maintainability you should include the word for the field when
                   4496: accessing the field.
                   4497: 
                   4498: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   4499: @subsection Structure Naming Convention
                   4500: @cindex structure naming conventions
                   4501: 
                   4502: The field names that come to (my) mind are often quite generic, and,
                   4503: if used, would cause frequent name clashes. E.g., many structures
                   4504: probably contain a @code{counter} field. The structure names
                   4505: that come to (my) mind are often also the logical choice for the names
                   4506: of words that create such a structure.
                   4507: 
                   4508: Therefore, I have adopted the following naming conventions: 
                   4509: 
                   4510: @itemize @bullet
                   4511: @cindex field naming convention
                   4512: @item
                   4513: The names of fields are of the form
                   4514: @code{@emph{struct}-@emph{field}}, where
                   4515: @code{@emph{struct}} is the basic name of the structure, and
                   4516: @code{@emph{field}} is the basic name of the field. You can
1.23      crook    4517: think of field words as converting the (address of the)
1.5       anton    4518: structure into the (address of the) field.
                   4519: 
                   4520: @cindex structure naming convention
                   4521: @item
                   4522: The names of structures are of the form
                   4523: @code{@emph{struct}%}, where
                   4524: @code{@emph{struct}} is the basic name of the structure.
                   4525: @end itemize
                   4526: 
                   4527: This naming convention does not work that well for fields of extended
                   4528: structures; e.g., the integer list structure has a field
                   4529: @code{intlist-int}, but has @code{list-next}, not
                   4530: @code{intlist-next}.
                   4531: 
                   4532: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   4533: @subsection Structure Implementation
                   4534: @cindex structure implementation
                   4535: @cindex implementation of structures
                   4536: 
                   4537: The central idea in the implementation is to pass the data about the
                   4538: structure being built on the stack, not in some global
                   4539: variable. Everything else falls into place naturally once this design
                   4540: decision is made.
                   4541: 
                   4542: The type description on the stack is of the form @emph{align
                   4543: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   4544: very simple.
                   4545: 
1.21      crook    4546: @code{field} is a defining word that uses @code{Create}
                   4547: and @code{DOES>}. The body of the field contains the offset
1.23      crook    4548: of the field, and the normal @code{DOES>} action is simply:
1.5       anton    4549: 
                   4550: @example
                   4551: @ +
                   4552: @end example
                   4553: 
1.21      crook    4554: @noindent
1.5       anton    4555: i.e., add the offset to the address, giving the stack effect
1.23      crook    4556: @var{addr1 -- addr2} for a field.
1.5       anton    4557: 
                   4558: @cindex first field optimization, implementation
                   4559: This simple structure is slightly complicated by the optimization
                   4560: for fields with offset 0, which requires a different
1.21      crook    4561: @code{DOES>}-part (because we cannot rely on there being
1.5       anton    4562: something on the stack if such a field is invoked during
1.21      crook    4563: compilation). Therefore, we put the different @code{DOES>}-parts
1.5       anton    4564: in separate words, and decide which one to invoke based on the
                   4565: offset. For a zero offset, the field is basically a noop; it is
                   4566: immediate, and therefore no code is generated when it is compiled.
                   4567: 
                   4568: @node Structure Glossary,  , Structure Implementation, Structures
                   4569: @subsection Structure Glossary
                   4570: @cindex structure glossary
                   4571: 
                   4572: doc-%align
                   4573: doc-%alignment
                   4574: doc-%alloc
                   4575: doc-%allocate
                   4576: doc-%allot
                   4577: doc-cell%
                   4578: doc-char%
                   4579: doc-dfloat%
                   4580: doc-double%
                   4581: doc-end-struct
                   4582: doc-field
                   4583: doc-float%
                   4584: doc-nalign
                   4585: doc-sfloat%
                   4586: doc-%size
                   4587: doc-struct
                   4588: 
                   4589: @c -------------------------------------------------------------
1.12      anton    4590: @node Object-oriented Forth, Tokens for Words, Structures, Words
                   4591: @section Object-oriented Forth
                   4592: 
1.23      crook    4593: Gforth comes with three packets for object-oriented programming:
1.12      anton    4594: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   4595: is preloaded, so you have to @code{include} them before use. The most
                   4596: important differences between these packets (and others) are discussed
                   4597: in @ref{Comparison with other object models}. All packets are written
                   4598: in ANS Forth and can be used with any other ANS Forth.
                   4599: 
                   4600: @menu
1.23      crook    4601: * Why object-oriented programming?::
                   4602: * Object-Oriented Terminology::
                   4603: * Objects::
                   4604: * OOF::
                   4605: * Mini-OOF::
1.5       anton    4606: * Comparison with other object models::  
                   4607: @end menu
                   4608: 
                   4609: 
1.23      crook    4610: @node Why object-oriented programming?, Object-Oriented Terminology, , Object-oriented Forth
1.12      anton    4611: @subsubsection Why object-oriented programming?
1.5       anton    4612: @cindex object-oriented programming motivation
                   4613: @cindex motivation for object-oriented programming
                   4614: 
                   4615: Often we have to deal with several data structures (@emph{objects}),
1.23      crook    4616: that have to be treated similarly in some respects, but differently in
                   4617: others. Graphical objects are the textbook example: circles, triangles,
                   4618: dinosaurs, icons, and others, and we may want to add more during program
                   4619: development. We want to apply some operations to any graphical object,
                   4620: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   4621: has to do something different for every kind of object.
                   4622: @comment TODO add some other operations eg perimeter, area
                   4623: @comment and tie in to concrete examples later..
1.5       anton    4624: 
                   4625: We could implement @code{draw} as a big @code{CASE}
                   4626: control structure that executes the appropriate code depending on the
                   4627: kind of object to be drawn. This would be not be very elegant, and,
                   4628: moreover, we would have to change @code{draw} every time we add
                   4629: a new kind of graphical object (say, a spaceship).
                   4630: 
                   4631: What we would rather do is: When defining spaceships, we would tell
                   4632: the system: "Here's how you @code{draw} a spaceship; you figure
                   4633: out the rest."
                   4634: 
                   4635: This is the problem that all systems solve that (rightfully) call
1.23      crook    4636: themselves object-oriented; the object-oriented packages presented here
                   4637: solve this problem (and not much else).
                   4638: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.5       anton    4639: 
1.23      crook    4640: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
1.12      anton    4641: @subsubsection Object-Oriented Terminology
1.5       anton    4642: @cindex object-oriented terminology
                   4643: @cindex terminology for object-oriented programming
                   4644: 
                   4645: This section is mainly for reference, so you don't have to understand
                   4646: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   4647: short:
                   4648: 
                   4649: @table @emph
                   4650: @cindex class
                   4651: @item class
                   4652: a data structure definition with some extras.
                   4653: 
                   4654: @cindex object
                   4655: @item object
                   4656: an instance of the data structure described by the class definition.
                   4657: 
                   4658: @cindex instance variables
                   4659: @item instance variables
                   4660: fields of the data structure.
                   4661: 
                   4662: @cindex selector
                   4663: @cindex method selector
                   4664: @cindex virtual function
                   4665: @item selector
                   4666: (or @emph{method selector}) a word (e.g.,
1.23      crook    4667: @code{draw}) that performs an operation on a variety of data
1.5       anton    4668: structures (classes). A selector describes @emph{what} operation to
                   4669: perform. In C++ terminology: a (pure) virtual function.
                   4670: 
                   4671: @cindex method
                   4672: @item method
                   4673: the concrete definition that performs the operation
                   4674: described by the selector for a specific class. A method specifies
                   4675: @emph{how} the operation is performed for a specific class.
                   4676: 
                   4677: @cindex selector invocation
                   4678: @cindex message send
                   4679: @cindex invoking a selector
                   4680: @item selector invocation
                   4681: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   4682: is used for determining which method is used. In Smalltalk terminology:
                   4683: a message (consisting of the selector and the other arguments) is sent
                   4684: to the object.
                   4685: 
                   4686: @cindex receiving object
                   4687: @item receiving object
                   4688: the object used for determining the method executed by a selector
1.23      crook    4689: invocation. In the @file{objects.fs} model, it is the object that is on
                   4690: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   4691: the Smalltalk @emph{message} terminology.)
1.5       anton    4692: 
                   4693: @cindex child class
                   4694: @cindex parent class
                   4695: @cindex inheritance
                   4696: @item child class
                   4697: a class that has (@emph{inherits}) all properties (instance variables,
                   4698: selectors, methods) from a @emph{parent class}. In Smalltalk
                   4699: terminology: The subclass inherits from the superclass. In C++
                   4700: terminology: The derived class inherits from the base class.
                   4701: 
                   4702: @end table
                   4703: 
                   4704: @c If you wonder about the message sending terminology, it comes from
                   4705: @c a time when each object had it's own task and objects communicated via
                   4706: @c message passing; eventually the Smalltalk developers realized that
                   4707: @c they can do most things through simple (indirect) calls. They kept the
                   4708: @c terminology.
                   4709: 
1.23      crook    4710: 
                   4711: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   4712: @subsection The @file{objects.fs} model
                   4713: @cindex objects
                   4714: @cindex object-oriented programming
                   4715: 
                   4716: @cindex @file{objects.fs}
                   4717: @cindex @file{oof.fs}
                   4718: 
                   4719: This section describes the @file{objects.fs} packet. This material also has been published in @cite{Yet Another Forth Objects Package} by Anton Ertl and appeared in Forth Dimensions 19(2), pages 37--43 (@url{http://www.complang.tuwien.ac.at/forth/objects/objects.html}).
                   4720: @c McKewan's and Zsoter's packages
                   4721: 
                   4722: This section assumes that you have read @ref{Structures}.
                   4723: 
                   4724: The techniques on which this model is based have been used to implement
                   4725: the parser generator, Gray, and have also been used in Gforth for
                   4726: implementing the various flavours of word lists (hashed or not,
                   4727: case-sensitive or not, special-purpose word lists for locals etc.).
                   4728: 
                   4729: 
                   4730: @menu
                   4731: * Properties of the Objects model::  
                   4732: * Basic Objects Usage::         
                   4733: * The Objects base class::            
                   4734: * Creating objects::            
                   4735: * Object-Oriented Programming Style::  
                   4736: * Class Binding::               
                   4737: * Method conveniences::         
                   4738: * Classes and Scoping::         
                   4739: * Object Interfaces::           
                   4740: * Objects Implementation::      
                   4741: * Objects Glossary::            
                   4742: @end menu
                   4743: 
                   4744: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
                   4745: and Bernd Paysan helped me with the related works section.
                   4746: 
                   4747: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   4748: @subsubsection Properties of the @file{objects.fs} model
                   4749: @cindex @file{objects.fs} properties
                   4750: 
                   4751: @itemize @bullet
                   4752: @item
                   4753: It is straightforward to pass objects on the stack. Passing
                   4754: selectors on the stack is a little less convenient, but possible.
                   4755: 
                   4756: @item
                   4757: Objects are just data structures in memory, and are referenced by their
                   4758: address. You can create words for objects with normal defining words
                   4759: like @code{constant}. Likewise, there is no difference between instance
                   4760: variables that contain objects and those that contain other data.
                   4761: 
                   4762: @item
                   4763: Late binding is efficient and easy to use.
                   4764: 
                   4765: @item
                   4766: It avoids parsing, and thus avoids problems with state-smartness
                   4767: and reduced extensibility; for convenience there are a few parsing
                   4768: words, but they have non-parsing counterparts. There are also a few
                   4769: defining words that parse. This is hard to avoid, because all standard
                   4770: defining words parse (except @code{:noname}); however, such
                   4771: words are not as bad as many other parsing words, because they are not
                   4772: state-smart.
                   4773: 
                   4774: @item
                   4775: It does not try to incorporate everything. It does a few things and does
                   4776: them well (IMO). In particular, this model was not designed to support
                   4777: information hiding (although it has features that may help); you can use
                   4778: a separate package for achieving this.
                   4779: 
                   4780: @item
                   4781: It is layered; you don't have to learn and use all features to use this
                   4782: model. Only a few features are necessary (@xref{Basic Objects Usage},
                   4783: @xref{The Objects base class}, @xref{Creating objects}.), the others
                   4784: are optional and independent of each other.
                   4785: 
                   4786: @item
                   4787: An implementation in ANS Forth is available.
                   4788: 
                   4789: @end itemize
                   4790: 
                   4791: 
                   4792: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   4793: @subsubsection Basic @file{objects.fs} Usage
1.5       anton    4794: @cindex basic objects usage
                   4795: @cindex objects, basic usage
                   4796: 
                   4797: You can define a class for graphical objects like this:
                   4798: 
                   4799: @cindex @code{class} usage
                   4800: @cindex @code{end-class} usage
                   4801: @cindex @code{selector} usage
                   4802: @example
                   4803: object class \ "object" is the parent class
                   4804:   selector draw ( x y graphical -- )
                   4805: end-class graphical
                   4806: @end example
                   4807: 
                   4808: This code defines a class @code{graphical} with an
                   4809: operation @code{draw}.  We can perform the operation
                   4810: @code{draw} on any @code{graphical} object, e.g.:
                   4811: 
                   4812: @example
                   4813: 100 100 t-rex draw
                   4814: @end example
                   4815: 
1.23      crook    4816: @noindent
1.5       anton    4817: where @code{t-rex} is a word (say, a constant) that produces a
                   4818: graphical object.
                   4819: 
1.23      crook    4820: @comment nac TODO add a 2nd operation eg perimeter.. and use for
                   4821: @comment a concrete example
                   4822: 
1.5       anton    4823: @cindex abstract class
                   4824: How do we create a graphical object? With the present definitions,
                   4825: we cannot create a useful graphical object. The class
                   4826: @code{graphical} describes graphical objects in general, but not
                   4827: any concrete graphical object type (C++ users would call it an
                   4828: @emph{abstract class}); e.g., there is no method for the selector
                   4829: @code{draw} in the class @code{graphical}.
                   4830: 
                   4831: For concrete graphical objects, we define child classes of the
                   4832: class @code{graphical}, e.g.:
                   4833: 
                   4834: @cindex @code{overrides} usage
                   4835: @cindex @code{field} usage in class definition
                   4836: @example
                   4837: graphical class \ "graphical" is the parent class
                   4838:   cell% field circle-radius
                   4839: 
                   4840: :noname ( x y circle -- )
                   4841:   circle-radius @@ draw-circle ;
                   4842: overrides draw
                   4843: 
                   4844: :noname ( n-radius circle -- )
                   4845:   circle-radius ! ;
                   4846: overrides construct
                   4847: 
                   4848: end-class circle
                   4849: @end example
                   4850: 
                   4851: Here we define a class @code{circle} as a child of @code{graphical},
1.23      crook    4852: with field @code{circle-radius} (which behaves just like a field
                   4853: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   4854: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   4855: defined in @code{object}, the parent class of @code{graphical}).
1.5       anton    4856: 
                   4857: Now we can create a circle on the heap (i.e.,
1.23      crook    4858: @code{allocate}d memory) with:
1.5       anton    4859: 
                   4860: @cindex @code{heap-new} usage
                   4861: @example
                   4862: 50 circle heap-new constant my-circle
                   4863: @end example
                   4864: 
1.23      crook    4865: @noindent
1.5       anton    4866: @code{heap-new} invokes @code{construct}, thus
                   4867: initializing the field @code{circle-radius} with 50. We can draw
1.23      crook    4868: this new circle at (100,100) with:
1.5       anton    4869: 
                   4870: @example
                   4871: 100 100 my-circle draw
                   4872: @end example
                   4873: 
                   4874: @cindex selector invocation, restrictions
                   4875: @cindex class definition, restrictions
1.23      crook    4876: Note: You can only invoke a selector if the object on the TOS
1.5       anton    4877: (the receiving object) belongs to the class where the selector was
                   4878: defined or one of its descendents; e.g., you can invoke
                   4879: @code{draw} only for objects belonging to @code{graphical}
                   4880: or its descendents (e.g., @code{circle}).  Immediately before
                   4881: @code{end-class}, the search order has to be the same as
                   4882: immediately after @code{class}.
                   4883: 
1.23      crook    4884: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   4885: @subsubsection The @file{object.fs} base class
1.5       anton    4886: @cindex @code{object} class
                   4887: 
                   4888: When you define a class, you have to specify a parent class.  So how do
                   4889: you start defining classes? There is one class available from the start:
1.23      crook    4890: @code{object}. It is ancestor for all classes and so is the
1.5       anton    4891: only class that has no parent. It has two selectors: @code{construct}
                   4892: and @code{print}.
                   4893: 
1.23      crook    4894: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
1.12      anton    4895: @subsubsection Creating objects
1.5       anton    4896: @cindex creating objects
                   4897: @cindex object creation
                   4898: @cindex object allocation options
                   4899: 
                   4900: @cindex @code{heap-new} discussion
                   4901: @cindex @code{dict-new} discussion
                   4902: @cindex @code{construct} discussion
                   4903: You can create and initialize an object of a class on the heap with
                   4904: @code{heap-new} ( ... class -- object ) and in the dictionary
                   4905: (allocation with @code{allot}) with @code{dict-new} (
                   4906: ... class -- object ). Both words invoke @code{construct}, which
                   4907: consumes the stack items indicated by "..." above.
                   4908: 
                   4909: @cindex @code{init-object} discussion
                   4910: @cindex @code{class-inst-size} discussion
                   4911: If you want to allocate memory for an object yourself, you can get its
                   4912: alignment and size with @code{class-inst-size 2@@} ( class --
                   4913: align size ). Once you have memory for an object, you can initialize
                   4914: it with @code{init-object} ( ... class object -- );
                   4915: @code{construct} does only a part of the necessary work.
                   4916: 
                   4917: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
1.12      anton    4918: @subsubsection Object-Oriented Programming Style
1.5       anton    4919: @cindex object-oriented programming style
                   4920: 
                   4921: This section is not exhaustive.
                   4922: 
                   4923: @cindex stack effects of selectors
                   4924: @cindex selectors and stack effects
                   4925: In general, it is a good idea to ensure that all methods for the
                   4926: same selector have the same stack effect: when you invoke a selector,
                   4927: you often have no idea which method will be invoked, so, unless all
                   4928: methods have the same stack effect, you will not know the stack effect
                   4929: of the selector invocation.
                   4930: 
                   4931: One exception to this rule is methods for the selector
                   4932: @code{construct}. We know which method is invoked, because we
                   4933: specify the class to be constructed at the same place. Actually, I
                   4934: defined @code{construct} as a selector only to give the users a
                   4935: convenient way to specify initialization. The way it is used, a
                   4936: mechanism different from selector invocation would be more natural
                   4937: (but probably would take more code and more space to explain).
                   4938: 
                   4939: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
1.12      anton    4940: @subsubsection Class Binding
1.5       anton    4941: @cindex class binding
                   4942: @cindex early binding
                   4943: 
                   4944: @cindex late binding
                   4945: Normal selector invocations determine the method at run-time depending
1.23      crook    4946: on the class of the receiving object. This run-time selection is called
                   4947: @var{late binding}.
1.5       anton    4948: 
1.23      crook    4949: Sometimes it's preferable to invoke a different method. For example,
                   4950: you might want to use the simple method for @code{print}ing
                   4951: @code{object}s instead of the possibly long-winded @code{print} method
                   4952: of the receiver class. You can achieve this by replacing the invocation
                   4953: of @code{print} with:
1.5       anton    4954: 
                   4955: @cindex @code{[bind]} usage
                   4956: @example
                   4957: [bind] object print
                   4958: @end example
                   4959: 
1.23      crook    4960: @noindent
                   4961: in compiled code or:
1.5       anton    4962: 
                   4963: @cindex @code{bind} usage
                   4964: @example
                   4965: bind object print
                   4966: @end example
                   4967: 
                   4968: @cindex class binding, alternative to
1.23      crook    4969: @noindent
1.5       anton    4970: in interpreted code. Alternatively, you can define the method with a
                   4971: name (e.g., @code{print-object}), and then invoke it through the
                   4972: name. Class binding is just a (often more convenient) way to achieve
                   4973: the same effect; it avoids name clutter and allows you to invoke
                   4974: methods directly without naming them first.
                   4975: 
                   4976: @cindex superclass binding
                   4977: @cindex parent class binding
                   4978: A frequent use of class binding is this: When we define a method
                   4979: for a selector, we often want the method to do what the selector does
                   4980: in the parent class, and a little more. There is a special word for
                   4981: this purpose: @code{[parent]}; @code{[parent]
                   4982: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   4983: selector}}, where @code{@emph{parent}} is the parent
                   4984: class of the current class. E.g., a method definition might look like:
                   4985: 
                   4986: @cindex @code{[parent]} usage
                   4987: @example
                   4988: :noname
                   4989:   dup [parent] foo \ do parent's foo on the receiving object
                   4990:   ... \ do some more
                   4991: ; overrides foo
                   4992: @end example
                   4993: 
                   4994: @cindex class binding as optimization
                   4995: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   4996: March 1997), Andrew McKewan presents class binding as an optimization
                   4997: technique. I recommend not using it for this purpose unless you are in
                   4998: an emergency. Late binding is pretty fast with this model anyway, so the
                   4999: benefit of using class binding is small; the cost of using class binding
                   5000: where it is not appropriate is reduced maintainability.
                   5001: 
                   5002: While we are at programming style questions: You should bind
                   5003: selectors only to ancestor classes of the receiving object. E.g., say,
                   5004: you know that the receiving object is of class @code{foo} or its
                   5005: descendents; then you should bind only to @code{foo} and its
                   5006: ancestors.
                   5007: 
                   5008: @node Method conveniences, Classes and Scoping, Class Binding, Objects
1.12      anton    5009: @subsubsection Method conveniences
1.5       anton    5010: @cindex method conveniences
                   5011: 
                   5012: In a method you usually access the receiving object pretty often.  If
                   5013: you define the method as a plain colon definition (e.g., with
                   5014: @code{:noname}), you may have to do a lot of stack
                   5015: gymnastics. To avoid this, you can define the method with @code{m:
                   5016: ... ;m}. E.g., you could define the method for
                   5017: @code{draw}ing a @code{circle} with
                   5018: 
                   5019: @cindex @code{this} usage
                   5020: @cindex @code{m:} usage
                   5021: @cindex @code{;m} usage
                   5022: @example
                   5023: m: ( x y circle -- )
                   5024:   ( x y ) this circle-radius @@ draw-circle ;m
                   5025: @end example
                   5026: 
                   5027: @cindex @code{exit} in @code{m: ... ;m}
                   5028: @cindex @code{exitm} discussion
                   5029: @cindex @code{catch} in @code{m: ... ;m}
                   5030: When this method is executed, the receiver object is removed from the
                   5031: stack; you can access it with @code{this} (admittedly, in this
                   5032: example the use of @code{m: ... ;m} offers no advantage). Note
                   5033: that I specify the stack effect for the whole method (i.e. including
                   5034: the receiver object), not just for the code between @code{m:}
                   5035: and @code{;m}. You cannot use @code{exit} in
                   5036: @code{m:...;m}; instead, use
                   5037: @code{exitm}.@footnote{Moreover, for any word that calls
                   5038: @code{catch} and was defined before loading
                   5039: @code{objects.fs}, you have to redefine it like I redefined
                   5040: @code{catch}: @code{: catch this >r catch r> to-this ;}}
                   5041: 
                   5042: @cindex @code{inst-var} usage
                   5043: You will frequently use sequences of the form @code{this
                   5044: @emph{field}} (in the example above: @code{this
                   5045: circle-radius}). If you use the field only in this way, you can
                   5046: define it with @code{inst-var} and eliminate the
                   5047: @code{this} before the field name. E.g., the @code{circle}
                   5048: class above could also be defined with:
                   5049: 
                   5050: @example
                   5051: graphical class
                   5052:   cell% inst-var radius
                   5053: 
                   5054: m: ( x y circle -- )
                   5055:   radius @@ draw-circle ;m
                   5056: overrides draw
                   5057: 
                   5058: m: ( n-radius circle -- )
                   5059:   radius ! ;m
                   5060: overrides construct
                   5061: 
                   5062: end-class circle
                   5063: @end example
                   5064: 
                   5065: @code{radius} can only be used in @code{circle} and its
                   5066: descendent classes and inside @code{m:...;m}.
                   5067: 
                   5068: @cindex @code{inst-value} usage
                   5069: You can also define fields with @code{inst-value}, which is
                   5070: to @code{inst-var} what @code{value} is to
                   5071: @code{variable}.  You can change the value of such a field with
                   5072: @code{[to-inst]}.  E.g., we could also define the class
                   5073: @code{circle} like this:
                   5074: 
                   5075: @example
                   5076: graphical class
                   5077:   inst-value radius
                   5078: 
                   5079: m: ( x y circle -- )
                   5080:   radius draw-circle ;m
                   5081: overrides draw
                   5082: 
                   5083: m: ( n-radius circle -- )
                   5084:   [to-inst] radius ;m
                   5085: overrides construct
                   5086: 
                   5087: end-class circle
                   5088: @end example
                   5089: 
                   5090: 
                   5091: @node Classes and Scoping, Object Interfaces, Method conveniences, Objects
1.12      anton    5092: @subsubsection Classes and Scoping
1.5       anton    5093: @cindex classes and scoping
                   5094: @cindex scoping and classes
                   5095: 
                   5096: Inheritance is frequent, unlike structure extension. This exacerbates
                   5097: the problem with the field name convention (@pxref{Structure Naming
                   5098: Convention}): One always has to remember in which class the field was
                   5099: originally defined; changing a part of the class structure would require
                   5100: changes for renaming in otherwise unaffected code.
                   5101: 
                   5102: @cindex @code{inst-var} visibility
                   5103: @cindex @code{inst-value} visibility
                   5104: To solve this problem, I added a scoping mechanism (which was not in my
                   5105: original charter): A field defined with @code{inst-var} (or
                   5106: @code{inst-value}) is visible only in the class where it is defined and in
                   5107: the descendent classes of this class.  Using such fields only makes
                   5108: sense in @code{m:}-defined methods in these classes anyway.
                   5109: 
                   5110: This scoping mechanism allows us to use the unadorned field name,
                   5111: because name clashes with unrelated words become much less likely.
                   5112: 
                   5113: @cindex @code{protected} discussion
                   5114: @cindex @code{private} discussion
                   5115: Once we have this mechanism, we can also use it for controlling the
                   5116: visibility of other words: All words defined after
                   5117: @code{protected} are visible only in the current class and its
                   5118: descendents. @code{public} restores the compilation
1.21      crook    5119: (i.e. @code{current}) word list that was in effect before. If you
1.5       anton    5120: have several @code{protected}s without an intervening
                   5121: @code{public} or @code{set-current}, @code{public}
1.21      crook    5122: will restore the compilation word list in effect before the first of
1.5       anton    5123: these @code{protected}s.
                   5124: 
                   5125: @node Object Interfaces, Objects Implementation, Classes and Scoping, Objects
1.12      anton    5126: @subsubsection Object Interfaces
1.5       anton    5127: @cindex object interfaces
                   5128: @cindex interfaces for objects
                   5129: 
                   5130: In this model you can only call selectors defined in the class of the
                   5131: receiving objects or in one of its ancestors. If you call a selector
                   5132: with a receiving object that is not in one of these classes, the
                   5133: result is undefined; if you are lucky, the program crashes
                   5134: immediately.
                   5135: 
                   5136: @cindex selectors common to hardly-related classes
                   5137: Now consider the case when you want to have a selector (or several)
                   5138: available in two classes: You would have to add the selector to a
                   5139: common ancestor class, in the worst case to @code{object}. You
                   5140: may not want to do this, e.g., because someone else is responsible for
                   5141: this ancestor class.
                   5142: 
                   5143: The solution for this problem is interfaces. An interface is a
                   5144: collection of selectors. If a class implements an interface, the
                   5145: selectors become available to the class and its descendents. A class
                   5146: can implement an unlimited number of interfaces. For the problem
                   5147: discussed above, we would define an interface for the selector(s), and
                   5148: both classes would implement the interface.
                   5149: 
                   5150: As an example, consider an interface @code{storage} for
                   5151: writing objects to disk and getting them back, and a class
1.23      crook    5152: @code{foo} that implements it. The code would look like this:
1.5       anton    5153: 
                   5154: @cindex @code{interface} usage
                   5155: @cindex @code{end-interface} usage
                   5156: @cindex @code{implementation} usage
                   5157: @example
                   5158: interface
                   5159:   selector write ( file object -- )
                   5160:   selector read1 ( file object -- )
                   5161: end-interface storage
                   5162: 
                   5163: bar class
                   5164:   storage implementation
                   5165: 
                   5166: ... overrides write
                   5167: ... overrides read
                   5168: ...
                   5169: end-class foo
                   5170: @end example
                   5171: 
1.23      crook    5172: @noindent
                   5173: (I would add a word @code{read} @var{( file -- object )} that uses
1.5       anton    5174: @code{read1} internally, but that's beyond the point illustrated
                   5175: here.)
                   5176: 
                   5177: Note that you cannot use @code{protected} in an interface; and
                   5178: of course you cannot define fields.
                   5179: 
                   5180: In the Neon model, all selectors are available for all classes;
                   5181: therefore it does not need interfaces. The price you pay in this model
                   5182: is slower late binding, and therefore, added complexity to avoid late
                   5183: binding.
                   5184: 
1.23      crook    5185: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
1.12      anton    5186: @subsubsection @file{objects.fs} Implementation
1.5       anton    5187: @cindex @file{objects.fs} implementation
                   5188: 
                   5189: @cindex @code{object-map} discussion
                   5190: An object is a piece of memory, like one of the data structures
                   5191: described with @code{struct...end-struct}. It has a field
                   5192: @code{object-map} that points to the method map for the object's
                   5193: class.
                   5194: 
                   5195: @cindex method map
                   5196: @cindex virtual function table
                   5197: The @emph{method map}@footnote{This is Self terminology; in C++
                   5198: terminology: virtual function table.} is an array that contains the
1.23      crook    5199: execution tokens (@var{xt}s) of the methods for the object's class. Each
                   5200: selector contains an offset into a method map.
1.5       anton    5201: 
                   5202: @cindex @code{selector} implementation, class
                   5203: @code{selector} is a defining word that uses
1.23      crook    5204: @code{CREATE} and @code{DOES>}. The body of the
1.5       anton    5205: selector contains the offset; the @code{does>} action for a
                   5206: class selector is, basically:
                   5207: 
                   5208: @example
                   5209: ( object addr ) @@ over object-map @@ + @@ execute
                   5210: @end example
                   5211: 
                   5212: Since @code{object-map} is the first field of the object, it
                   5213: does not generate any code. As you can see, calling a selector has a
                   5214: small, constant cost.
                   5215: 
                   5216: @cindex @code{current-interface} discussion
                   5217: @cindex class implementation and representation
                   5218: A class is basically a @code{struct} combined with a method
                   5219: map. During the class definition the alignment and size of the class
                   5220: are passed on the stack, just as with @code{struct}s, so
                   5221: @code{field} can also be used for defining class
                   5222: fields. However, passing more items on the stack would be
                   5223: inconvenient, so @code{class} builds a data structure in memory,
                   5224: which is accessed through the variable
                   5225: @code{current-interface}. After its definition is complete, the
                   5226: class is represented on the stack by a pointer (e.g., as parameter for
                   5227: a child class definition).
                   5228: 
1.23      crook    5229: A new class starts off with the alignment and size of its parent,
1.5       anton    5230: and a copy of the parent's method map. Defining new fields extends the
                   5231: size and alignment; likewise, defining new selectors extends the
1.23      crook    5232: method map. @code{overrides} just stores a new @var{xt} in the method
1.5       anton    5233: map at the offset given by the selector.
                   5234: 
                   5235: @cindex class binding, implementation
1.23      crook    5236: Class binding just gets the @var{xt} at the offset given by the selector
1.5       anton    5237: from the class's method map and @code{compile,}s (in the case of
                   5238: @code{[bind]}) it.
                   5239: 
                   5240: @cindex @code{this} implementation
                   5241: @cindex @code{catch} and @code{this}
                   5242: @cindex @code{this} and @code{catch}
                   5243: I implemented @code{this} as a @code{value}. At the
                   5244: start of an @code{m:...;m} method the old @code{this} is
                   5245: stored to the return stack and restored at the end; and the object on
                   5246: the TOS is stored @code{TO this}. This technique has one
                   5247: disadvantage: If the user does not leave the method via
                   5248: @code{;m}, but via @code{throw} or @code{exit},
                   5249: @code{this} is not restored (and @code{exit} may
                   5250: crash). To deal with the @code{throw} problem, I have redefined
                   5251: @code{catch} to save and restore @code{this}; the same
                   5252: should be done with any word that can catch an exception. As for
                   5253: @code{exit}, I simply forbid it (as a replacement, there is
                   5254: @code{exitm}).
                   5255: 
                   5256: @cindex @code{inst-var} implementation
                   5257: @code{inst-var} is just the same as @code{field}, with
                   5258: a different @code{does>} action:
                   5259: @example
                   5260: @@ this +
                   5261: @end example
                   5262: Similar for @code{inst-value}.
                   5263: 
                   5264: @cindex class scoping implementation
1.21      crook    5265: Each class also has a word list that contains the words defined with
1.5       anton    5266: @code{inst-var} and @code{inst-value}, and its protected
                   5267: words. It also has a pointer to its parent. @code{class} pushes
1.23      crook    5268: the word lists of the class and all its ancestors onto the search order stack,
1.5       anton    5269: and @code{end-class} drops them.
                   5270: 
                   5271: @cindex interface implementation
                   5272: An interface is like a class without fields, parent and protected
                   5273: words; i.e., it just has a method map. If a class implements an
                   5274: interface, its method map contains a pointer to the method map of the
                   5275: interface. The positive offsets in the map are reserved for class
                   5276: methods, therefore interface map pointers have negative
                   5277: offsets. Interfaces have offsets that are unique throughout the
                   5278: system, unlike class selectors, whose offsets are only unique for the
                   5279: classes where the selector is available (invokable).
                   5280: 
                   5281: This structure means that interface selectors have to perform one
                   5282: indirection more than class selectors to find their method. Their body
                   5283: contains the interface map pointer offset in the class method map, and
                   5284: the method offset in the interface method map. The
                   5285: @code{does>} action for an interface selector is, basically:
                   5286: 
                   5287: @example
                   5288: ( object selector-body )
                   5289: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   5290: swap object-map @@ + @@ ( object selector-body map )
                   5291: swap selector-offset @@ + @@ execute
                   5292: @end example
                   5293: 
                   5294: where @code{object-map} and @code{selector-offset} are
                   5295: first fields and generate no code.
                   5296: 
                   5297: As a concrete example, consider the following code:
                   5298: 
                   5299: @example
                   5300: interface
                   5301:   selector if1sel1
                   5302:   selector if1sel2
                   5303: end-interface if1
                   5304: 
                   5305: object class
                   5306:   if1 implementation
                   5307:   selector cl1sel1
                   5308:   cell% inst-var cl1iv1
                   5309: 
                   5310: ' m1 overrides construct
                   5311: ' m2 overrides if1sel1
                   5312: ' m3 overrides if1sel2
                   5313: ' m4 overrides cl1sel2
                   5314: end-class cl1
                   5315: 
                   5316: create obj1 object dict-new drop
                   5317: create obj2 cl1    dict-new drop
                   5318: @end example
                   5319: 
                   5320: The data structure created by this code (including the data structure
                   5321: for @code{object}) is shown in the <a
                   5322: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
1.23      crook    5323: @comment nac TODO add this diagram..
1.5       anton    5324: 
1.23      crook    5325: @node Objects Glossary,  , Objects Implementation, Objects
1.12      anton    5326: @subsubsection @file{objects.fs} Glossary
1.5       anton    5327: @cindex @file{objects.fs} Glossary
                   5328: 
1.19      anton    5329: doc---objects-bind
                   5330: doc---objects-<bind>
                   5331: doc---objects-bind'
                   5332: doc---objects-[bind]
                   5333: doc---objects-class
                   5334: doc---objects-class->map
                   5335: doc---objects-class-inst-size
                   5336: doc---objects-class-override!
                   5337: doc---objects-construct
                   5338: doc---objects-current'
                   5339: doc---objects-[current]
                   5340: doc---objects-current-interface
                   5341: doc---objects-dict-new
                   5342: doc---objects-drop-order
                   5343: doc---objects-end-class
                   5344: doc---objects-end-class-noname
                   5345: doc---objects-end-interface
                   5346: doc---objects-end-interface-noname
                   5347: doc---objects-exitm
                   5348: doc---objects-heap-new
                   5349: doc---objects-implementation
                   5350: doc---objects-init-object
                   5351: doc---objects-inst-value
                   5352: doc---objects-inst-var
                   5353: doc---objects-interface
                   5354: doc---objects-;m
                   5355: doc---objects-m:
                   5356: doc---objects-method
                   5357: doc---objects-object
                   5358: doc---objects-overrides
                   5359: doc---objects-[parent]
                   5360: doc---objects-print
                   5361: doc---objects-protected
                   5362: doc---objects-public
                   5363: doc---objects-push-order
                   5364: doc---objects-selector
                   5365: doc---objects-this
                   5366: doc---objects-<to-inst>
                   5367: doc---objects-[to-inst]
                   5368: doc---objects-to-this
                   5369: doc---objects-xt-new
1.5       anton    5370: 
                   5371: @c -------------------------------------------------------------
1.12      anton    5372: @node OOF, Mini-OOF, Objects, Object-oriented Forth
1.23      crook    5373: @subsection The @file{oof.fs} model
1.6       pazsan   5374: @cindex oof
                   5375: @cindex object-oriented programming
                   5376: 
                   5377: @cindex @file{objects.fs}
                   5378: @cindex @file{oof.fs}
1.12      anton    5379: 
1.23      crook    5380: This section describes the @file{oof.fs} packet.
1.6       pazsan   5381: 
1.23      crook    5382: The packet described in this section has been used in bigFORTH since 1991, and
1.6       pazsan   5383: used for two large applications: a chromatographic system used to
                   5384: create new medicaments, and a graphic user interface library (MINOS).
                   5385: 
1.12      anton    5386: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   5387: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   5388: 10(2), 1994.
                   5389: 
1.6       pazsan   5390: @menu
                   5391: * Properties of the OOF model::
                   5392: * Basic OOF Usage::
1.23      crook    5393: * The OOF base class::
1.7       pazsan   5394: * Class Declaration::
                   5395: * Class Implementation::
1.6       pazsan   5396: @end menu
                   5397: 
1.12      anton    5398: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
1.23      crook    5399: @subsubsection Properties of the @file{oof.fs} model
1.6       pazsan   5400: @cindex @file{oof.fs} properties
                   5401: 
                   5402: @itemize @bullet
                   5403: @item
                   5404: This model combines object oriented programming with information
                   5405: hiding. It helps you writing large application, where scoping is
                   5406: necessary, because it provides class-oriented scoping.
                   5407: 
                   5408: @item
                   5409: Named objects, object pointers, and object arrays can be created,
                   5410: selector invocation uses the "object selector" syntax. Selector invocation
                   5411: to objects and/or selectors on the stack is a bit less convenient, but
                   5412: possible.
                   5413: 
                   5414: @item
                   5415: Selector invocation and instance variable usage of the active object is
1.23      crook    5416: straightforward, since both make use of the active object.
1.6       pazsan   5417: 
                   5418: @item
                   5419: Late binding is efficient and easy to use.
                   5420: 
                   5421: @item
                   5422: State-smart objects parse selectors. However, extensibility is provided
                   5423: using a (parsing) selector @code{postpone} and a selector @code{'}.
                   5424: 
                   5425: @item
                   5426: An implementation in ANS Forth is available.
                   5427: 
                   5428: @end itemize
                   5429: 
                   5430: 
1.23      crook    5431: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   5432: @subsubsection Basic @file{oof.fs} Usage
1.6       pazsan   5433: @cindex @file{oof.fs} usage
                   5434: 
1.23      crook    5435: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.6       pazsan   5436: 
                   5437: You can define a class for graphical objects like this:
                   5438: 
                   5439: @cindex @code{class} usage
                   5440: @cindex @code{class;} usage
                   5441: @cindex @code{method} usage
                   5442: @example
                   5443: object class graphical \ "object" is the parent class
                   5444:   method draw ( x y graphical -- )
                   5445: class;
                   5446: @end example
                   5447: 
                   5448: This code defines a class @code{graphical} with an
                   5449: operation @code{draw}.  We can perform the operation
                   5450: @code{draw} on any @code{graphical} object, e.g.:
                   5451: 
                   5452: @example
                   5453: 100 100 t-rex draw
                   5454: @end example
                   5455: 
1.23      crook    5456: @noindent
1.6       pazsan   5457: where @code{t-rex} is an object or object pointer, created with e.g.
1.13      pazsan   5458: @code{graphical : t-rex}.
1.6       pazsan   5459: 
                   5460: @cindex abstract class
                   5461: How do we create a graphical object? With the present definitions,
                   5462: we cannot create a useful graphical object. The class
                   5463: @code{graphical} describes graphical objects in general, but not
                   5464: any concrete graphical object type (C++ users would call it an
                   5465: @emph{abstract class}); e.g., there is no method for the selector
                   5466: @code{draw} in the class @code{graphical}.
                   5467: 
                   5468: For concrete graphical objects, we define child classes of the
                   5469: class @code{graphical}, e.g.:
                   5470: 
                   5471: @example
                   5472: graphical class circle \ "graphical" is the parent class
                   5473:   cell var circle-radius
                   5474: how:
                   5475:   : draw ( x y -- )
                   5476:     circle-radius @@ draw-circle ;
                   5477: 
                   5478:   : init ( n-radius -- (
                   5479:     circle-radius ! ;
                   5480: class;
                   5481: @end example
                   5482: 
                   5483: Here we define a class @code{circle} as a child of @code{graphical},
                   5484: with a field @code{circle-radius}; it defines new methods for the
                   5485: selectors @code{draw} and @code{init} (@code{init} is defined in
                   5486: @code{object}, the parent class of @code{graphical}).
                   5487: 
                   5488: Now we can create a circle in the dictionary with
                   5489: 
                   5490: @example
                   5491: 50 circle : my-circle
                   5492: @end example
                   5493: 
1.23      crook    5494: @noindent
1.6       pazsan   5495: @code{:} invokes @code{init}, thus initializing the field
                   5496: @code{circle-radius} with 50. We can draw this new circle at (100,100)
1.23      crook    5497: with:
1.6       pazsan   5498: 
                   5499: @example
                   5500: 100 100 my-circle draw
                   5501: @end example
                   5502: 
                   5503: @cindex selector invocation, restrictions
                   5504: @cindex class definition, restrictions
1.23      crook    5505: Note: You can only invoke a selector if the receiving object belongs to
1.6       pazsan   5506: the class where the selector was defined or one of its descendents;
                   5507: e.g., you can invoke @code{draw} only for objects belonging to
                   5508: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
1.7       pazsan   5509: mechanism will check if you try to invoke a selector that is not
1.6       pazsan   5510: defined in this class hierarchy, so you'll get an error at compilation
                   5511: time.
                   5512: 
                   5513: 
1.23      crook    5514: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   5515: @subsubsection The @file{oof.fs} base class
1.6       pazsan   5516: @cindex @file{oof.fs} base class
                   5517: 
                   5518: When you define a class, you have to specify a parent class.  So how do
                   5519: you start defining classes? There is one class available from the start:
                   5520: @code{object}. You have to use it as ancestor for all classes. It is the
                   5521: only class that has no parent. Classes are also objects, except that
                   5522: they don't have instance variables; class manipulation such as
                   5523: inheritance or changing definitions of a class is handled through
                   5524: selectors of the class @code{object}.
                   5525: 
                   5526: @code{object} provides a number of selectors:
                   5527: 
                   5528: @itemize @bullet
                   5529: @item
                   5530: @code{class} for subclassing, @code{definitions} to add definitions
                   5531: later on, and @code{class?} to get type informations (is the class a
                   5532: subclass of the class passed on the stack?).
1.7       pazsan   5533: doc---object-class
                   5534: doc---object-definitions
                   5535: doc---object-class?
1.6       pazsan   5536: 
                   5537: @item
1.23      crook    5538: @code{init} and @code{dispose} as constructor and destructor of the
1.6       pazsan   5539: object. @code{init} is invocated after the object's memory is allocated,
                   5540: while @code{dispose} also handles deallocation. Thus if you redefine
                   5541: @code{dispose}, you have to call the parent's dispose with @code{super
                   5542: dispose}, too.
1.7       pazsan   5543: doc---object-init
                   5544: doc---object-dispose
1.6       pazsan   5545: 
                   5546: @item
1.7       pazsan   5547: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   5548: @code{[]} to create named and unnamed objects and object arrays or
                   5549: object pointers.
                   5550: doc---object-new
                   5551: doc---object-new[]
                   5552: doc---object-:
                   5553: doc---object-ptr
                   5554: doc---object-asptr
                   5555: doc---object-[]
1.6       pazsan   5556: 
                   5557: @item
1.23      crook    5558: @code{::} and @code{super} for explicit scoping. You should use explicit
1.6       pazsan   5559: scoping only for super classes or classes with the same set of instance
1.23      crook    5560: variables. Explicitly-scoped selectors use early binding.
1.7       pazsan   5561: doc---object-::
                   5562: doc---object-super
1.6       pazsan   5563: 
                   5564: @item
                   5565: @code{self} to get the address of the object
1.7       pazsan   5566: doc---object-self
1.6       pazsan   5567: 
                   5568: @item
                   5569: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   5570: pointers and instance defers.
1.7       pazsan   5571: doc---object-bind
                   5572: doc---object-bound
                   5573: doc---object-link
                   5574: doc---object-is
1.6       pazsan   5575: 
                   5576: @item
                   5577: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   5578: form the stack, and @code{postpone} to generate selector invocation code.
1.7       pazsan   5579: doc---object-'
                   5580: doc---object-postpone
1.6       pazsan   5581: 
                   5582: @item
                   5583: @code{with} and @code{endwith} to select the active object from the
1.23      crook    5584: stack, and enable its scope. Using @code{with} and @code{endwith}
                   5585: also allows you to create code using selector @code{postpone} without being
                   5586: trapped by the state-smart objects.
1.7       pazsan   5587: doc---object-with
                   5588: doc---object-endwith
1.6       pazsan   5589: 
                   5590: @end itemize
                   5591: 
1.23      crook    5592: @node Class Declaration, Class Implementation, The OOF base class, OOF
1.12      anton    5593: @subsubsection Class Declaration
1.7       pazsan   5594: @cindex class declaration
                   5595: 
                   5596: @itemize @bullet
                   5597: @item
                   5598: Instance variables
                   5599: doc---oof-var
                   5600: 
                   5601: @item
                   5602: Object pointers
                   5603: doc---oof-ptr
                   5604: doc---oof-asptr
                   5605: 
                   5606: @item
                   5607: Instance defers
                   5608: doc---oof-defer
                   5609: 
                   5610: @item
                   5611: Method selectors
                   5612: doc---oof-early
                   5613: doc---oof-method
                   5614: 
                   5615: @item
1.23      crook    5616: Class-wide variables
1.7       pazsan   5617: doc---oof-static
                   5618: 
                   5619: @item
                   5620: End declaration
                   5621: doc---oof-how:
                   5622: doc---oof-class;
                   5623: 
                   5624: @end itemize
                   5625: 
1.13      pazsan   5626: @c -------------------------------------------------------------
1.12      anton    5627: @node Class Implementation,  , Class Declaration, OOF
                   5628: @subsubsection Class Implementation
1.7       pazsan   5629: @cindex class implementation
                   5630: 
1.13      pazsan   5631: @c -------------------------------------------------------------
1.23      crook    5632: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   5633: @subsection The @file{mini-oof.fs} model
1.8       pazsan   5634: @cindex mini-oof
                   5635: 
                   5636: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.23      crook    5637: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
1.13      pazsan   5638: and reduces to the bare minimum of features. This is based on a posting
                   5639: of Bernd Paysan in comp.arch.
                   5640: 
                   5641: @menu
1.23      crook    5642: * Basic Mini-OOF Usage::
1.13      pazsan   5643: * Mini-OOF Example::
1.20      pazsan   5644: * Mini-OOF Implementation::
1.13      pazsan   5645: @end menu
                   5646: 
                   5647: @c -------------------------------------------------------------
1.23      crook    5648: @node Basic Mini-OOF Usage, Mini-OOF Example, , Mini-OOF
                   5649: @subsubsection Basic @file{mini-oof.fs} Usage
1.13      pazsan   5650: @cindex mini-oof usage
                   5651: 
1.23      crook    5652: There is a base class (@code{class}, which allocates one cell
                   5653: for the object pointer) plus seven other words: to define a method, a
                   5654: variable, a class; to end a class, to resolve binding, to allocate an
                   5655: object and to compile a class method.
                   5656: @comment TODO better description of the last one
1.13      pazsan   5657: 
1.23      crook    5658: doc-object
1.13      pazsan   5659: doc-method
                   5660: doc-var
                   5661: doc-class
                   5662: doc-end-class
                   5663: doc-defines
                   5664: doc-new
                   5665: doc-::
                   5666: 
                   5667: 
                   5668: @c -------------------------------------------------------------
1.23      crook    5669: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
1.13      pazsan   5670: @subsubsection Mini-OOF Example
                   5671: @cindex mini-oof example
                   5672: 
                   5673: A short example shows how to use this package.
1.23      crook    5674: @comment nac TODO could flesh this out with some comments from the Forthwrite article
1.13      pazsan   5675: 
                   5676: @example
                   5677: object class
                   5678:   method init
                   5679:   method draw
                   5680: end-class graphical
                   5681: @end example
                   5682: 
                   5683: This code defines a class @code{graphical} with an
                   5684: operation @code{draw}.  We can perform the operation
                   5685: @code{draw} on any @code{graphical} object, e.g.:
                   5686: 
                   5687: @example
                   5688: 100 100 t-rex draw
                   5689: @end example
                   5690: 
                   5691: where @code{t-rex} is an object or object pointer, created with e.g.
                   5692: @code{graphical new Constant t-rex}.
                   5693: 
                   5694: For concrete graphical objects, we define child classes of the
                   5695: class @code{graphical}, e.g.:
1.8       pazsan   5696: 
                   5697: @example
1.13      pazsan   5698: graphical class
                   5699:   cell var circle-radius
                   5700: end-class circle \ "graphical" is the parent class
                   5701: 
                   5702: :noname ( x y -- )
                   5703:   circle-radius @@ draw-circle ; circle defines draw
                   5704: :noname ( r -- )
                   5705:   circle-radius ! ; circle defines init
                   5706: @end example
                   5707: 
                   5708: There is no implicit init method, so we have to define one. The creation
                   5709: code of the object now has to call init explicitely.
                   5710: 
                   5711: @example
                   5712: circle new Constant my-circle
                   5713: 50 my-circle init
                   5714: @end example
                   5715: 
                   5716: It is also possible to add a function to create named objects with
                   5717: automatic call of @code{init}, given that all objects have @code{init}
1.23      crook    5718: on the same place:
1.13      pazsan   5719: 
                   5720: @example
                   5721: : new: ( .. o "name" -- )
                   5722:     new dup Constant init ;
                   5723: 80 circle new: large-circle
                   5724: @end example
                   5725: 
1.23      crook    5726: We can draw this new circle at (100,100) with:
1.13      pazsan   5727: 
                   5728: @example
                   5729: 100 100 my-circle draw
1.8       pazsan   5730: @end example
                   5731: 
1.20      pazsan   5732: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
1.23      crook    5733: @subsubsection @file{mini-oof.fs} Implementation
1.20      pazsan   5734: 
1.23      crook    5735: Object-oriented systems with late binding typically use a
1.20      pazsan   5736: "vtable"-approach: the first variable in each object is a pointer to a
1.23      crook    5737: table, which contains the methods as function pointers. The vtable
                   5738: may also contain other information.
1.20      pazsan   5739: 
                   5740: So first, let's declare methods:
                   5741: 
                   5742: @example
                   5743: : method ( m v -- m' v ) Create  over , swap cell+ swap
                   5744:   DOES> ( ... o -- ... ) @ over @ + @ execute ;
                   5745: @end example
                   5746: 
                   5747: During method declaration, the number of methods and instance
                   5748: variables is on the stack (in address units). @code{method} creates
                   5749: one method and increments the method number. To execute a method, it
                   5750: takes the object, fetches the vtable pointer, adds the offset, and
1.23      crook    5751: executes the @var{xt} stored there. Each method takes the object it is
1.20      pazsan   5752: invoked from as top of stack parameter. The method itself should
                   5753: consume that object.
                   5754: 
                   5755: Now, we also have to declare instance variables
                   5756: 
                   5757: @example
                   5758: : var ( m v size -- m v' ) Create  over , +
                   5759:   DOES> ( o -- addr ) @ + ;
                   5760: @end example
                   5761: 
1.23      crook    5762: As before, a word is created with the current offset. Instance
1.20      pazsan   5763: variables can have different sizes (cells, floats, doubles, chars), so
                   5764: all we do is take the size and add it to the offset. If your machine
                   5765: has alignment restrictions, put the proper @code{aligned} or
1.23      crook    5766: @code{faligned} before the variable, to adjust the variable
1.20      pazsan   5767: offset. That's why it is on the top of stack.
                   5768: 
1.23      crook    5769: We need a starting point (the base object) and some syntactic sugar:
1.20      pazsan   5770: 
                   5771: @example
                   5772: Create object  1 cells , 2 cells ,
                   5773: : class ( class -- class methods vars ) dup 2@ ;
                   5774: @end example
                   5775: 
1.23      crook    5776: For inheritance, the vtable of the parent object has to be
                   5777: copied when a new, derived class is declared. This gives all the
1.20      pazsan   5778: methods of the parent class, which can be overridden, though.
                   5779: 
                   5780: @example
                   5781: : end-class  ( class methods vars -- )
                   5782:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   5783:   cell+ dup cell+ r> rot @ 2 cells /string move ;
                   5784: @end example
                   5785: 
                   5786: The first line creates the vtable, initialized with
                   5787: @code{noop}s. The second line is the inheritance mechanism, it
                   5788: copies the xts from the parent vtable.
                   5789: 
                   5790: We still have no way to define new methods, let's do that now:
                   5791: 
                   5792: @example
                   5793: : defines ( xt class -- ) ' >body @ + ! ;
                   5794: @end example
                   5795: 
                   5796: To allocate a new object, we need a word, too:
                   5797: 
                   5798: @example
                   5799: : new ( class -- o )  here over @ allot swap over ! ;
                   5800: @end example
                   5801: 
1.23      crook    5802: Sometimes derived classes want to access the method of the
                   5803: parent object. There are two ways to achieve this with Mini-OOF:
1.20      pazsan   5804: first, you could use named words, and second, you could look up the
                   5805: vtable of the parent object.
                   5806: 
                   5807: @example
                   5808: : :: ( class "name" -- ) ' >body @ + @ compile, ;
                   5809: @end example
                   5810: 
                   5811: 
                   5812: Nothing can be more confusing than a good example, so here is
1.23      crook    5813: one. First let's declare a text object (called
1.20      pazsan   5814: @code{button}), that stores text and position:
                   5815: 
                   5816: @example
                   5817: object class
                   5818:   cell var text
                   5819:   cell var len
                   5820:   cell var x
                   5821:   cell var y
                   5822:   method init
                   5823:   method draw
                   5824: end-class button
                   5825: @end example
                   5826: 
1.23      crook    5827: @noindent
1.20      pazsan   5828: Now, implement the two methods, @code{draw} and @code{init}:
                   5829: 
                   5830: @example
1.23      crook    5831: :noname ( o -- )
                   5832:  >r r@ x @ r@ y @ at-xy  r@ text @ r> len @ type ;
1.20      pazsan   5833:  button defines draw
1.23      crook    5834: :noname ( addr u o -- )
                   5835:  >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
1.20      pazsan   5836:  button defines init
                   5837: @end example
                   5838: 
1.23      crook    5839: @noindent
                   5840: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.20      pazsan   5841: new data and no new methods.
                   5842: 
                   5843: @example
                   5844: button class
                   5845: end-class bold-button
                   5846: 
                   5847: : bold   27 emit ." [1m" ;
                   5848: : normal 27 emit ." [0m" ;
                   5849: 
1.23      crook    5850: @noindent
                   5851: The class @code{bold-button} has a different draw method to
                   5852: @code{button}, but the new method is defined in terms of the draw method
                   5853: for @code{button}:
                   5854: 
1.20      pazsan   5855: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   5856: @end example
                   5857: 
1.23      crook    5858: @noindent
                   5859: Finally, create two objects and apply methods:
1.20      pazsan   5860: 
                   5861: @example
                   5862: button new Constant foo
                   5863: s" thin foo" foo init
                   5864: page
                   5865: foo draw
                   5866: bold-button new Constant bar
                   5867: s" fat bar" bar init
                   5868: 1 bar y !
                   5869: bar draw
                   5870: @end example
                   5871: 
1.23      crook    5872: 
                   5873: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
                   5874: @subsubsection Comparison with other object models
                   5875: @cindex comparison of object models
                   5876: @cindex object models, comparison
                   5877: 
                   5878: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   5879: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   5880: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   5881: relation of the object models described here to two well-known and two
                   5882: closely-related (by the use of method maps) models.
                   5883: 
                   5884: @cindex Neon model
                   5885: The most popular model currently seems to be the Neon model (see
                   5886: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   5887: 1997) by Andrew McKewan) but this model has a number of limitations
                   5888: @footnote{A longer version of this critique can be
                   5889: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   5890: Dimensions, May 1997) by Anton Ertl.}:
                   5891: 
                   5892: @itemize @bullet
                   5893: @item
                   5894: It uses a @code{@emph{selector
                   5895: object}} syntax, which makes it unnatural to pass objects on the
                   5896: stack.
                   5897: 
                   5898: @item
                   5899: It requires that the selector parses the input stream (at
                   5900: compile time); this leads to reduced extensibility and to bugs that are+
                   5901: hard to find.
                   5902: 
                   5903: @item
                   5904: It allows using every selector to every object;
                   5905: this eliminates the need for classes, but makes it harder to create
                   5906: efficient implementations. 
                   5907: @end itemize
                   5908: 
                   5909: @cindex Pountain's object-oriented model
                   5910: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   5911: Press, London, 1987) by Dick Pountain. However, it is not really about
                   5912: object-oriented programming, because it hardly deals with late
                   5913: binding. Instead, it focuses on features like information hiding and
                   5914: overloading that are characteristic of modular languages like Ada (83).
                   5915: 
                   5916: @cindex Zsoter's object-oriented model
                   5917: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1) 1996, pages 31-35)
                   5918: Andras Zsoter describes a model that makes heavy use of an active object
                   5919: (like @code{this} in @file{objects.fs}): The active object is not only
                   5920: used for accessing all fields, but also specifies the receiving object
                   5921: of every selector invocation; you have to change the active object
                   5922: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
                   5923: changes more or less implicitly at @code{m: ... ;m}. Such a change at
                   5924: the method entry point is unnecessary with the Zsoter's model, because
                   5925: the receiving object is the active object already. On the other hand, the explicit
                   5926: change is absolutely necessary in that model, because otherwise no one
                   5927: could ever change the active object. An ANS Forth implementation of this
                   5928: model is available at @url{http://www.forth.org/fig/oopf.html}.
                   5929: 
                   5930: @cindex @file{oof.fs}, differences to other models
                   5931: The @file{oof.fs} model combines information hiding and overloading
                   5932: resolution (by keeping names in various word lists) with object-oriented
                   5933: programming. It sets the active object implicitly on method entry, but
                   5934: also allows explicit changing (with @code{>o...o>} or with
                   5935: @code{with...endwith}). It uses parsing and state-smart objects and
                   5936: classes for resolving overloading and for early binding: the object or
                   5937: class parses the selector and determines the method from this. If the
                   5938: selector is not parsed by an object or class, it performs a call to the
                   5939: selector for the active object (late binding), like Zsoter's model.
                   5940: Fields are always accessed through the active object. The big
                   5941: disadvantage of this model is the parsing and the state-smartness, which
                   5942: reduces extensibility and increases the opportunities for subtle bugs;
                   5943: essentially, you are only safe if you never tick or @code{postpone} an
                   5944: object or class (Bernd disagrees, but I (Anton) am not convinced).
                   5945: 
                   5946: @cindex @file{mini-oof.fs}, differences to other models
                   5947: The @file{mini-oof.fs} model is quite similar to a very stripped-down version of
                   5948: the @file{objects.fs} model, but syntactically it is a mixture of the @file{objects.fs} and
                   5949: @file{oof.fs} models.
                   5950: 
                   5951: 
                   5952: 
1.6       pazsan   5953: @c -------------------------------------------------------------
1.21      crook    5954: @node Tokens for Words, Word Lists, Object-oriented Forth, Words
1.1       anton    5955: @section Tokens for Words
                   5956: @cindex tokens for words
                   5957: 
                   5958: This chapter describes the creation and use of tokens that represent
                   5959: words on the stack (and in data space).
                   5960: 
                   5961: Named words have interpretation and compilation semantics. Unnamed words
                   5962: just have execution semantics.
                   5963: 
1.21      crook    5964: @comment TODO ?normally interpretation semantics are the execution semantics.
                   5965: @comment this should all be covered in earlier ss
                   5966: 
1.1       anton    5967: @cindex execution token
                   5968: An @dfn{execution token} represents the execution semantics of an
                   5969: unnamed word. An execution token occupies one cell. As explained in
1.21      crook    5970: @ref{Supplying names}, the execution token of the last word
                   5971: defined can be produced with @code{lastxt}.
1.1       anton    5972: 
1.21      crook    5973: You can perform the semantics represented by an execution token with:
1.1       anton    5974: doc-execute
1.21      crook    5975: You can compile the word with:
1.1       anton    5976: doc-compile,
                   5977: 
                   5978: @cindex code field address
                   5979: @cindex CFA
                   5980: In Gforth, the abstract data type @emph{execution token} is implemented
                   5981: as CFA (code field address).
1.21      crook    5982: @comment TODO note that the standard does not say what it represents..
                   5983: @comment and you cannot necessarily compile it in all Forths (eg native
                   5984: @comment compilers?).
1.1       anton    5985: 
                   5986: The interpretation semantics of a named word are also represented by an
                   5987: execution token. You can get it with
                   5988: 
                   5989: doc-[']
                   5990: doc-'
                   5991: 
                   5992: For literals, you use @code{'} in interpreted code and @code{[']} in
                   5993: compiled code. Gforth's @code{'} and @code{[']} behave somewhat unusual
                   5994: by complaining about compile-only words. To get an execution token for a
                   5995: compiling word @var{X}, use @code{COMP' @var{X} drop} or @code{[COMP']
                   5996: @var{X} drop}.
                   5997: 
                   5998: @cindex compilation token
                   5999: The compilation semantics are represented by a @dfn{compilation token}
                   6000: consisting of two cells: @var{w xt}. The top cell @var{xt} is an
                   6001: execution token. The compilation semantics represented by the
                   6002: compilation token can be performed with @code{execute}, which consumes
                   6003: the whole compilation token, with an additional stack effect determined
                   6004: by the represented compilation semantics.
                   6005: 
                   6006: doc-[comp']
                   6007: doc-comp'
                   6008: 
                   6009: You can compile the compilation semantics with @code{postpone,}. I.e.,
                   6010: @code{COMP' @var{word} POSTPONE,} is equivalent to @code{POSTPONE
                   6011: @var{word}}.
                   6012: 
                   6013: doc-postpone,
                   6014: 
                   6015: At present, the @var{w} part of a compilation token is an execution
                   6016: token, and the @var{xt} part represents either @code{execute} or
                   6017: @code{compile,}. However, don't rely on that knowledge, unless necessary;
                   6018: we may introduce unusual compilation tokens in the future (e.g.,
                   6019: compilation tokens representing the compilation semantics of literals).
                   6020: 
                   6021: @cindex name token
                   6022: @cindex name field address
                   6023: @cindex NFA
                   6024: Named words are also represented by the @dfn{name token}. The abstract
                   6025: data type @emph{name token} is implemented as NFA (name field address).
                   6026: 
                   6027: doc-find-name
                   6028: doc-name>int
                   6029: doc-name?int
                   6030: doc-name>comp
                   6031: doc-name>string
                   6032: 
1.21      crook    6033: @node Word Lists, Environmental Queries, Tokens for Words, Words
                   6034: @section Word Lists
                   6035: @cindex word lists
                   6036: @cindex name dictionary
                   6037: 
                   6038: @cindex wid
                   6039: All definitions other than those created by @code{:noname} have an entry
                   6040: in the name dictionary. The name dictionary is fragmented into a number
                   6041: of parts, called @var{word lists}. A word list is identified by a
                   6042: cell-sized word list identifier (@var{wid}) in much the same way as a
                   6043: file is identified by a file handle. The numerical value of the wid has
                   6044: no (portable) meaning, and might change from session to session.
                   6045: 
                   6046: @cindex compilation word list
                   6047: At any one time, a single word list is defined as the word list to which
                   6048: all new definitions will be added -- this is called the @var{compilation
                   6049: word list}. When Gforth is started, the compilation word list is the
                   6050: word list called @code{FORTH-WORDLIST}.
                   6051: 
                   6052: @cindex search order stack
                   6053: Forth maintains a stack of word lists, representing the @var{search
                   6054: order}.  When the name dictionary is searched (for example, when
                   6055: attempting to find a word's execution token during compilation), only
                   6056: those word lists that are currently in the search order are
                   6057: searched. The most recently-defined word in the word list at the top of
                   6058: the word list stack is searched first, and the search proceeds until
                   6059: either the word is located or the oldest definition in the word list at
                   6060: the bottom of the stack is reached. Definitions of the word may exist in
                   6061: more than one word lists; the search order determines which version will
                   6062: be found.
                   6063: 
                   6064: The ANS Forth Standard "Search order" word set is intended to provide a
                   6065: set of low-level tools that allow various different schemes to be
                   6066: implemented. Gforth provides @code{vocabulary}, a traditional Forth
                   6067: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
                   6068: Standard Forth.
                   6069: 
                   6070: TODO: locals section refers to here, saying that every word list (aka
                   6071: vocabulary) has its own methods for searching etc. Need to document that.
                   6072: 
                   6073: doc-forth-wordlist
                   6074: doc-definitions
                   6075: doc-get-current
                   6076: doc-set-current
                   6077: 
                   6078: @comment TODO when a defn (like set-order) is instanced twice, the second instance gets documented.
                   6079: @comment In general that might be fine, but in this example (search.fs) the second instance is an
                   6080: @comment alias, so it would not naturally have documentation
                   6081: 
                   6082: doc-get-order
                   6083: doc-set-order
                   6084: doc-wordlist
                   6085: doc-also
                   6086: doc-forth
                   6087: doc-only
                   6088: doc-order
                   6089: doc-previous
                   6090: 
                   6091: doc-find
                   6092: doc-search-wordlist
                   6093: 
                   6094: doc-words
                   6095: doc-vlist
                   6096: 
                   6097: doc-mappedwordlist
                   6098: doc-root
                   6099: doc-vocabulary
                   6100: doc-seal
                   6101: doc-vocs
                   6102: doc-current
                   6103: doc-context
                   6104: 
                   6105: @menu
                   6106: * Why use word lists?::
                   6107: * Word list examples::
                   6108: @end menu
                   6109: 
                   6110: @node Why use word lists?, Word list examples, Word Lists, Word Lists
                   6111: @subsection Why use word lists?
                   6112: @cindex word lists - why use them?
                   6113: 
                   6114: There are several reasons for using multiple word lists:
                   6115: 
                   6116: @itemize @bullet
                   6117: @item
                   6118: To improve compilation speed by reducing the number of name dictionary
                   6119: entries that must be searched. This is achieved by creating a new
                   6120: word list that contains all of the definitions that are used in the
                   6121: definition of a Forth system but which would not usually be used by
                   6122: programs running on that system. That word list would be on the search
                   6123: list when the Forth system was compiled but would be removed from the
                   6124: search list for normal operation. This can be a useful technique for
                   6125: low-performance systems (for example, 8-bit processors in embedded
                   6126: systems) but is unlikely to be necessary in high-performance desktop
                   6127: systems.
                   6128: @item
                   6129: To prevent a set of words from being used outside the context in which
                   6130: they are valid. Two classic examples of this are an integrated editor
                   6131: (all of the edit commands are defined in a separate word list; the
                   6132: search order is set to the editor word list when the editor is invoked;
                   6133: the old search order is restored when the editor is terminated) and an
                   6134: integrated assembler (the op-codes for the machine are defined in a
                   6135: separate word list which is used when a @code{CODE} word is defined).
                   6136: @item
                   6137: To prevent a name-space clash between multiple definitions with the same
                   6138: name. For example, when building a cross-compiler you might have a word
                   6139: @code{IF} that generates conditional code for your target system. By
                   6140: placing this definition in a different word list you can control whether
                   6141: the host system's @code{IF} or the target system's @code{IF} get used in
                   6142: any particular context by controlling the order of the word lists on the
                   6143: search order stack.
                   6144: @end itemize
                   6145: 
                   6146: @node Word list examples, ,Why use word lists?, Word Lists
                   6147: @subsection Word list examples
                   6148: @cindex word lists - examples
                   6149: 
                   6150: Here is an example of creating and using a new wordlist using ANS
                   6151: Standard words:
                   6152: 
                   6153: @example
                   6154: wordlist constant my-new-words-wordlist
                   6155: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
                   6156: 
                   6157: \ add it to the search order
                   6158: also my-new-words
                   6159: 
                   6160: \ alternatively, add it to the search order and make it
                   6161: \ the compilation word list
                   6162: also my-new-words definitions
                   6163: \ type "order" to see the problem
                   6164: @end example
                   6165: 
                   6166: The problem with this example is that @code{order} has no way to
                   6167: associate the name @code{my-new-words} with the wid of the word list (in
                   6168: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   6169: that has no associated name). There is no Standard way of associating a
                   6170: name with a wid.
                   6171: 
                   6172: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   6173: associates a name with a wid:
                   6174: 
                   6175: @example
                   6176: vocabulary my-new-words
                   6177: 
                   6178: \ add it to the search order
                   6179: my-new-words
                   6180: 
                   6181: \ alternatively, add it to the search order and make it
                   6182: \ the compilation word list
                   6183: my-new-words definitions
                   6184: \ type "order" to see that the problem is solved
                   6185: @end example
                   6186: 
                   6187: 
                   6188: @node Environmental Queries, Files, Word Lists, Words
                   6189: @section Environmental Queries
                   6190: @cindex environmental queries
                   6191: @comment TODO more index entries
                   6192: 
                   6193: The ANS Standard introduced the idea of "environmental queries" as a way
                   6194: for a program running on a system to determine certain characteristics of the system.
                   6195: The Standard specifies a number of strings that might be recognised by a system.
                   6196: 
                   6197: The Standard requires that the name space used for environmental queries
                   6198: be distinct from the name space used for definitions.
                   6199: 
                   6200: Typically, environmental queries are supported by creating a set of
                   6201: definitions in a word set that is @var{only} used during environmental
                   6202: queries; that is what Gforth does. There is no Standard way of adding
                   6203: definitions to the set of recognised environmental queries, but any
                   6204: implementation that supports the loading of optional word sets must have
                   6205: some mechanism for doing this (after loading the word set, the
                   6206: associated environmental query string must return @code{true}). In
                   6207: Gforth, the word set used to honour environmental queries can be
                   6208: manipulated just like any other word set.
                   6209: 
                   6210: doc-environment?
                   6211: doc-environment-wordlist
                   6212: 
                   6213: doc-gforth
                   6214: doc-os-class
                   6215: 
                   6216: Note that, whilst the documentation for (eg) @code{gforth} shows it
                   6217: returning two items on the stack, querying it using @code{environment?}
                   6218: will return an additional item; the @code{true} flag that shows that the
                   6219: string was recognised.
1.1       anton    6220: 
1.21      crook    6221: TODO Document the standard strings or note where they are documented herein
                   6222: 
                   6223: Here are some examples of using environmental queries:
                   6224: 
                   6225: @example
                   6226: s" address-unit-bits" environment? 0=
                   6227: [IF]
                   6228:      cr .( environmental attribute address-units-bits unknown... ) cr
                   6229: [THEN]
                   6230: 
                   6231: s" block" environment? [IF] DROP include block.fs [THEN]
                   6232: 
                   6233: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
                   6234: 
                   6235: s" gforth" environment? [IF] .( Gforth version ) TYPE [ELSE] .( Not Gforth..) [THEN]
                   6236: 
                   6237: @end example
                   6238: 
                   6239: 
                   6240: Here is an example of adding a definition to the environment word list:
                   6241: 
                   6242: @example
                   6243: get-current environment-wordlist set-current
                   6244: true constant block
                   6245: true constant block-ext
                   6246: set-current
                   6247: @end example
                   6248: 
                   6249: You can see what definitions are in the environment word list like this:
                   6250: 
                   6251: @example
                   6252: get-order 1+ environment-wordlist swap set-order words previous
                   6253: @end example
                   6254: 
                   6255: 
                   6256: 
                   6257: @node Files, Including Files, Environmental Queries, Words
1.1       anton    6258: @section Files
                   6259: 
1.20      pazsan   6260: This chapter describes how to operate on files from Forth.
                   6261: 
1.21      crook    6262: Files are opened/created by name and type. The following types are
                   6263: recognised:
1.20      pazsan   6264: 
                   6265: doc-r/o
                   6266: doc-r/w
                   6267: doc-w/o
                   6268: doc-bin
                   6269: 
1.21      crook    6270: When a file is opened/created, it returns a file identifier,
                   6271: @var{wfileid} that is used for all other file commands. All file
                   6272: commands also return a status value, @var{wior}, that is 0 for a
                   6273: successful operation and an implementation-defined non-zero value in the
                   6274: case of an error.
1.20      pazsan   6275: 
                   6276: doc-open-file
                   6277: doc-create-file
                   6278: 
                   6279: doc-close-file
                   6280: doc-delete-file
                   6281: doc-rename-file
                   6282: doc-read-file
                   6283: doc-read-line
                   6284: doc-write-file
1.21      crook    6285: doc-write-line
1.20      pazsan   6286: doc-emit-file
                   6287: doc-flush-file
                   6288: 
                   6289: doc-file-status
                   6290: doc-file-position
                   6291: doc-reposition-file
                   6292: doc-file-size
                   6293: doc-resize-file
                   6294: 
1.12      anton    6295: @node Including Files, Blocks, Files, Words
                   6296: @section Including Files
                   6297: @cindex including files
                   6298: 
                   6299: @menu
                   6300: * Words for Including::         
                   6301: * Search Path::                 
1.21      crook    6302: * Forth Search Paths::    
1.12      anton    6303: * General Search Paths::        
                   6304: @end menu
                   6305: 
                   6306: @node Words for Including, Search Path, Including Files, Including Files
                   6307: @subsection Words for Including
                   6308: 
                   6309: doc-include-file
                   6310: doc-included
                   6311: doc-include
                   6312: 
                   6313: Usually you want to include a file only if it is not included already
                   6314: (by, say, another source file):
1.21      crook    6315: @comment TODO describe what happens on error. Describes how the require
                   6316: @comment stuff works and describe how to clear/reset the history (eg
                   6317: @comment for debug). Might want to include that in the MARKER example.
1.12      anton    6318: 
                   6319: doc-required
                   6320: doc-require
                   6321: doc-needs
                   6322: 
1.21      crook    6323: A definition in ANS Standard Forth for @code{required} is provided in
                   6324: @file{compat/required.fs}.
                   6325: 
1.12      anton    6326: @cindex stack effect of included files
                   6327: @cindex including files, stack effect
                   6328: I recommend that you write your source files such that interpreting them
                   6329: does not change the stack. This allows using these files with
                   6330: @code{required} and friends without complications. E.g.,
                   6331: 
                   6332: @example
                   6333: 1 require foo.fs drop
                   6334: @end example
                   6335: 
1.21      crook    6336: @node Search Path, Forth Search Paths, Words for Including, Including Files
1.12      anton    6337: @subsection Search Path
                   6338: @cindex path for @code{included}
                   6339: @cindex file search path
                   6340: @cindex include search path
                   6341: @cindex search path for files
                   6342: 
1.21      crook    6343: @comment what uses these search paths.. just inc;lude and friends?
1.12      anton    6344: If you specify an absolute filename (i.e., a filename starting with
                   6345: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   6346: @samp{C:...})) for @code{included} and friends, that file is included
                   6347: just as you would expect.
                   6348: 
                   6349: For relative filenames, Gforth uses a search path similar to Forth's
1.21      crook    6350: search order (@pxref{Word Lists}). It tries to find the given filename in
1.12      anton    6351: the directories present in the path, and includes the first one it
                   6352: finds.
                   6353: 
                   6354: If the search path contains the directory @file{.} (as it should), this
                   6355: refers to the directory that the present file was @code{included}
                   6356: from. This allows files to include other files relative to their own
                   6357: position (irrespective of the current working directory or the absolute
                   6358: position).  This feature is essential for libraries consisting of
                   6359: several files, where a file may include other files from the library.
                   6360: It corresponds to @code{#include "..."} in C. If the current input
                   6361: source is not a file, @file{.} refers to the directory of the innermost
                   6362: file being included, or, if there is no file being included, to the
                   6363: current working directory.
                   6364: 
                   6365: Use @file{~+} to refer to the current working directory (as in the
                   6366: @code{bash}).
                   6367: 
                   6368: If the filename starts with @file{./}, the search path is not searched
                   6369: (just as with absolute filenames), and the @file{.} has the same meaning
                   6370: as described above.
                   6371: 
1.21      crook    6372: @node Forth Search Paths, General Search Paths, Search Path, Including Files
                   6373: @subsection Forth Search Paths
                   6374: @cindex search path control - forth
1.12      anton    6375: 
                   6376: The search path is initialized when you start Gforth (@pxref{Invoking
                   6377: Gforth}). You can display it with
                   6378: 
                   6379: doc-.fpath
                   6380: 
                   6381: You can change it later with the following words:
                   6382: 
                   6383: doc-fpath+
                   6384: doc-fpath=
                   6385: 
                   6386: Using fpath and require would look like:
                   6387: 
                   6388: @example
                   6389: fpath= /usr/lib/forth/|./
                   6390: 
                   6391: require timer.fs
                   6392: @end example
                   6393: 
                   6394: If you have the need to look for a file in the Forth search path, you could
1.21      crook    6395: use this Gforth feature in your application:
1.12      anton    6396: 
                   6397: doc-open-fpath-file
                   6398: 
1.21      crook    6399: @node General Search Paths,  , Forth Search Paths, Including Files
1.12      anton    6400: @subsection General Search Paths
1.21      crook    6401: @cindex search path control - for user applications
1.12      anton    6402: 
                   6403: Your application may need to search files in sevaral directories, like
                   6404: @code{included} does. For this purpose you can define and use your own
                   6405: search paths. Create a search path like this:
                   6406: 
                   6407: @example
1.21      crook    6408: \ Make a buffer for the path:
1.12      anton    6409: create mypath   100 chars ,     \ maximum length (is checked)
                   6410:                 0 ,             \ real len
                   6411:                 100 chars allot \ space for path
                   6412: @end example
                   6413: 
                   6414: You have the same functions for the forth search path in a generic version
                   6415: for different paths.
                   6416: 
1.21      crook    6417: Gforth also provides generic equivalents of the Forth search path words:
                   6418: 
                   6419: doc-.path
1.12      anton    6420: doc-path+
                   6421: doc-path=
                   6422: doc-open-path-file
                   6423: 
                   6424: 
                   6425: @node Blocks, Other I/O, Including Files, Words
1.1       anton    6426: @section Blocks
                   6427: 
1.20      pazsan   6428: This chapter describes how to use block files within Gforth.
                   6429: 
                   6430: Block files are traditionally means of data and source storage in
                   6431: Forth. They have been very important in resource-starved computers
                   6432: without OS in the past. Gforth doesn't encourage to use blocks as
                   6433: source, and provides blocks only for backward compatibility. The ANS
                   6434: standard requires blocks to be available when files are.
                   6435: 
1.21      crook    6436: @comment TODO what about errors on open-blocks?
1.20      pazsan   6437: doc-open-blocks
                   6438: doc-use
1.21      crook    6439: doc-scr
                   6440: doc-blk
1.20      pazsan   6441: doc-get-block-fid
                   6442: doc-block-position
                   6443: doc-update
1.21      crook    6444: doc-save-buffers
1.20      pazsan   6445: doc-save-buffer
1.21      crook    6446: doc-empty-buffers
1.20      pazsan   6447: doc-empty-buffer
                   6448: doc-flush
                   6449: doc-get-buffer
1.21      crook    6450: doc---block-block
1.20      pazsan   6451: doc-buffer
                   6452: doc-updated?
                   6453: doc-list
                   6454: doc-load
                   6455: doc-thru
                   6456: doc-+load
                   6457: doc-+thru
                   6458: doc---block--->
                   6459: doc-block-included
                   6460: 
1.1       anton    6461: @node Other I/O, Programming Tools, Blocks, Words
                   6462: @section Other I/O
1.21      crook    6463: @comment TODO more index entries
                   6464: 
                   6465: @menu
                   6466: * Simple numeric output::       Predefined formats
                   6467: * Formatted numeric output::    Formatted (pictured) output
                   6468: * String Formats::              How Forth stores strings in memory
                   6469: * Displaying characters and strings:: Other stuff
                   6470: * Input::                       Input
                   6471: @end menu
                   6472: 
                   6473: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   6474: @subsection Simple numeric output
                   6475: @cindex Simple numeric output
                   6476: @comment TODO more index entries
                   6477: 
                   6478: The simplest output functions are those that display numbers from the
                   6479: data or floating-point stacks. Floating-point output is always displayed
                   6480: using base 10. Numbers displayed from the data stack use the value stored
                   6481: in @code{base}.
                   6482: 
                   6483: doc-.
                   6484: doc-dec.
                   6485: doc-hex.
                   6486: doc-u.
                   6487: doc-.r
                   6488: doc-u.r
                   6489: doc-d.
                   6490: doc-ud.
                   6491: doc-d.r
                   6492: doc-ud.r
                   6493: doc-f.
                   6494: doc-fe.
                   6495: doc-fs.
                   6496: 
                   6497: Examples of printing the number 1234.5678E23 in the different floating-point output
                   6498: formats are shown below:
                   6499: 
                   6500: @example
                   6501: f. 123456779999999000000000000.
                   6502: fe. 123.456779999999E24
                   6503: fs. 1.23456779999999E26
                   6504: @end example
                   6505: 
                   6506: 
                   6507: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   6508: @subsection Formatted numeric output
                   6509: @cindex Formatted numeric output
                   6510: @cindex pictured numeric output
                   6511: @comment TODO more index entries
                   6512: 
                   6513: Forth traditionally uses a technique called @var{pictured numeric
                   6514: output} for formatted printing of integers.  In this technique,
                   6515: digits are extracted from the number (using the current output radix
                   6516: defined by @code{base}), converted to ASCII codes and appended to a
                   6517: string that is built in a scratch-pad area of memory
                   6518: (@pxref{core-idef,Implementation-defined options}). During the extraction
                   6519: sequence, other arbitrary characters can be appended to the string. The
                   6520: completed string is specified by an address and length and can
                   6521: be manipulated (@code{TYPE}ed, copied, modified) under program control.
                   6522: 
                   6523: All of the words described in the previous section for simple numeric
                   6524: output are implemented in Gforth using pictured numeric output.
                   6525: 
                   6526: Three important things to remember about Pictured Numeric Output:
                   6527: 
                   6528: @itemize @bullet
                   6529: @item
                   6530: It always operates on double-precision numbers; to display a single-precision number,
                   6531: convert it first (@pxref{Double precision} for ways of doing this).
                   6532: @item
                   6533: It always treats the double-precision number as though it were unsigned. Refer to
                   6534: the examples below for ways of printing signed numbers.
                   6535: @item
                   6536: The string is built up from right to left; least significant digit first.
                   6537: @end itemize
                   6538: 
                   6539: doc-<#
                   6540: doc-#
                   6541: doc-#s
                   6542: doc-hold
                   6543: doc-sign
                   6544: doc-#>
                   6545: 
                   6546: doc-represent
                   6547: 
                   6548: Here are some examples of using pictured numeric output:
                   6549: 
                   6550: @example
                   6551: : my-u. ( u -- )
                   6552:   \ Simplest use of pns.. behaves like Standard u. 
                   6553:   0              \ convert to unsigned double
                   6554:   <#             \ start conversion
                   6555:   #s             \ convert all digits
                   6556:   #>             \ complete conversion
                   6557:   TYPE SPACE ;   \ display, with trailing space
                   6558: 
                   6559: : cents-only ( u -- )
                   6560:   0              \ convert to unsigned double
                   6561:   <#             \ start conversion
                   6562:   # #            \ convert two least-significant digits
                   6563:   #>             \ complete conversion, discard other digits
                   6564:   TYPE SPACE ;   \ display, with trailing space
                   6565: 
                   6566: : dollars-and-cents ( u -- )
                   6567:   0              \ convert to unsigned double
                   6568:   <#             \ start conversion
                   6569:   # #            \ convert two least-significant digits
                   6570:   [char] . hold  \ insert decimal point
                   6571:   #s             \ convert remaining digits
                   6572:   [char] $ hold  \ append currency symbol
                   6573:   #>             \ complete conversion
                   6574:   TYPE SPACE ;   \ display, with trailing space
                   6575: 
                   6576: : my-. ( n -- )
                   6577:   \ handling negatives.. behaves like Standard .
                   6578:   s>d            \ convert to signed double
                   6579:   swap over dabs \ leave sign byte followed by unsigned double
                   6580:   <#             \ start conversion
                   6581:   #s             \ convert all digits
                   6582:   rot sign       \ get at sign byte, append "-" if needed
                   6583:   #>             \ complete conversion
                   6584:   TYPE SPACE ;   \ display, with trailing space
                   6585: 
                   6586: : account. ( n -- )
                   6587:   \ accountants don't like minus signs, they use braces
                   6588:   \ for negative numbers
                   6589:   s>d            \ convert to signed double
                   6590:   swap over dabs \ leave sign byte followed by unsigned double
                   6591:   <#             \ start conversion
                   6592:   2 pick         \ get copy of sign byte
                   6593:   0< IF [char] ) hold THEN \ right-most character of output
                   6594:   #s             \ convert all digits
                   6595:   rot            \ get at sign byte
                   6596:   0< IF [char] ( hold THEN
                   6597:   #>             \ complete conversion
                   6598:   TYPE SPACE ;   \ display, with trailing space
                   6599: @end example
                   6600: 
                   6601: Here are some examples of using these words:
                   6602: 
                   6603: @example
                   6604: 1 my-u. 1
                   6605: hex -1 my-u. decimal FFFFFFFF
                   6606: 1 cents-only 01
                   6607: 1234 cents-only 34
                   6608: 2 dollars-and-cents $0.02
                   6609: 1234 dollars-and-cents $12.34
                   6610: 123 my-. 123
                   6611: -123 my. -123
                   6612: 123 account. 123
                   6613: -456 account. (456)
                   6614: @end example
                   6615: 
                   6616: 
                   6617: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   6618: @subsection String Formats
                   6619: @cindex string formats
                   6620: 
                   6621: @comment TODO more index entries
                   6622: 
                   6623: Forth commonly uses two different methods for representing a string:
                   6624: 
                   6625: @itemize @bullet
                   6626: @item
                   6627: @cindex address of counted string
                   6628: As a @var{counted string}, represented by a c-addr. The char addressed
                   6629: by c-addr contains a character-count, n,  of the string and the string
                   6630: occupies the subsequent n char addresses in memory.
                   6631: @item
                   6632: As cell pair on the stack; c-addr u, where u is the length of the string
                   6633: in characters, and c-addr is the address of the first byte of the string.
                   6634: @end itemize
                   6635: 
                   6636: The ANS Forth Standard encourages the use of the second format when
                   6637: representing strings on the stack, whilst conceeding that the counted
                   6638: string format remains useful as a way of storing strings in memory.
                   6639: 
                   6640: doc-count
                   6641: 
                   6642: @xref{Memory Blocks} for words that move, copy and search
                   6643: for strings. @xref{Displaying characters and strings,} for words that
                   6644: display characters and strings.
                   6645: 
                   6646: 
                   6647: @node Displaying characters and strings, Input, String Formats, Other I/O
                   6648: @subsection Displaying characters and strings
                   6649: @cindex displaying characters and strings
                   6650: @cindex compiling characters and strings
                   6651: @cindex cursor control
                   6652: 
                   6653: @comment TODO more index entries
                   6654: 
                   6655: This section starts with a glossary of Forth words and ends with a set
                   6656: of examples.
                   6657: 
                   6658: doc-bl
                   6659: doc-space
                   6660: doc-spaces
                   6661: doc-emit
1.23      crook    6662: doc-toupper
1.21      crook    6663: doc-."
                   6664: doc-.(
                   6665: doc-type
                   6666: doc-cr
                   6667: doc-at-xy
                   6668: doc-page
                   6669: doc-s"
                   6670: doc-c"
                   6671: doc-char
                   6672: doc-[char]
                   6673: doc-sliteral
                   6674: 
                   6675: As an example, consider the following text, stored in a file @file{test.fs}:
                   6676: 
                   6677: @example
                   6678: .( text-1)
                   6679: : my-word
                   6680:   ." text-2" cr
                   6681:   .( text-3)
                   6682: ;
                   6683: 
                   6684: ." text-4"
                   6685: 
                   6686: : my-char
                   6687:   [char] ALPHABET emit
                   6688:   char emit
                   6689: ;
                   6690: @end example
                   6691: 
                   6692: When you load this code into Gforth, the following output is generated:
                   6693: 
                   6694: @example
                   6695: @kbd{include test.fs} text-1text-3text-4 ok
                   6696: @end example
                   6697: 
                   6698: @itemize @bullet
                   6699: @item
                   6700: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   6701: is an immediate word; it behaves in the same way whether it is used inside
                   6702: or outside a colon definition.
                   6703: @item
                   6704: Message @code{text-4} is displayed because of Gforth's added interpretation
                   6705: semantics for @code{."}.
                   6706: @item
                   6707: Message @code{text-2} is @var{not} displayed, because the text interpreter
                   6708: performs the compilation semantics for @code{."} within the definition of
                   6709: @code{my-word}.
                   6710: @end itemize
                   6711: 
                   6712: Here are some examples of executing @code{my-word} and @code{my-char}:
                   6713: 
                   6714: @example
                   6715: my-word text-2
                   6716:  ok
                   6717: @kbd{my-char fred} Af ok
                   6718: @kbd{my-char jim} Aj ok
                   6719: @end example
                   6720: 
                   6721: @itemize @bullet
                   6722: @item
                   6723: Message @code{text-2} is displayed because of the run-time behaviour of
                   6724: @code{."}.
                   6725: @item
                   6726: @code{[char]} compiles the "A" from "ALPHABET" and puts its display code
                   6727: on the stack at run-time. @code{emit} always displays the character
                   6728: when @code{my-char} is executed.
                   6729: @item
                   6730: @code{char} parses a string at run-time and the second @code{emit} displays
                   6731: the first character of the string.
                   6732: @item
                   6733: If you type @code{see my-char} you can see that @code{[char]} discarded
                   6734: the text "LPHABET" and only compiled the display code for "A" into the
                   6735: definition of @code{my-char}.
                   6736: @end itemize
                   6737: 
                   6738: 
                   6739: 
                   6740: @node Input, , Displaying characters and strings, Other I/O
                   6741: @subsection Input
                   6742: @cindex Input
                   6743: @comment TODO more index entries
                   6744: 
                   6745: Blah on traditional and recommended string formats.
                   6746: 
                   6747: doc--trailing
                   6748: doc-/string
                   6749: doc-convert
                   6750: doc->number
                   6751: doc->float
                   6752: doc-accept
                   6753: doc-query
                   6754: doc-expect
                   6755: doc-evaluate
                   6756: doc-key
                   6757: doc-key?
                   6758: 
                   6759: TODO reference the block move stuff elsewhere
                   6760: 
                   6761: TODO convert and >number might be better in the numeric input section.
                   6762: 
                   6763: TODO maybe some of these shouldn't be here but should be in a "parsing" section
                   6764: 
1.1       anton    6765: 
1.7       pazsan   6766: @node Programming Tools, Assembler and Code Words, Other I/O, Words
1.1       anton    6767: @section Programming Tools
                   6768: @cindex programming tools
                   6769: 
                   6770: @menu
                   6771: * Debugging::                   Simple and quick.
                   6772: * Assertions::                  Making your programs self-checking.
1.6       pazsan   6773: * Singlestep Debugger::                Executing your program word by word.
1.1       anton    6774: @end menu
                   6775: 
                   6776: @node Debugging, Assertions, Programming Tools, Programming Tools
                   6777: @subsection Debugging
                   6778: @cindex debugging
                   6779: 
1.21      crook    6780: Languages with a slow edit/compile/link/test development loop tend to
                   6781: require sophisticated tracing/stepping debuggers to facilate
                   6782: productive debugging.
1.1       anton    6783: 
                   6784: A much better (faster) way in fast-compiling languages is to add
                   6785: printing code at well-selected places, let the program run, look at
                   6786: the output, see where things went wrong, add more printing code, etc.,
                   6787: until the bug is found.
                   6788: 
1.21      crook    6789: The simple debugging aids provided in @file{debugs.fs}
                   6790: are meant to support this style of debugging. In addition, there are
                   6791: words for non-destructively inspecting the stack and memory:
                   6792: 
                   6793: doc-.s
                   6794: doc-f.s
                   6795: 
                   6796: There is a word @code{.r} but it does @var{not} display the return
                   6797: stack! It is used for formatted numeric output.
                   6798: 
                   6799: doc-depth
                   6800: doc-fdepth
                   6801: doc-clearstack
                   6802: doc-?
                   6803: doc-dump
                   6804: 
                   6805: The word @code{~~} prints debugging information (by default the source
                   6806: location and the stack contents). It is easy to insert. If you use Emacs
                   6807: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
1.1       anton    6808: query-replace them with nothing). The deferred words
                   6809: @code{printdebugdata} and @code{printdebugline} control the output of
                   6810: @code{~~}. The default source location output format works well with
                   6811: Emacs' compilation mode, so you can step through the program at the
                   6812: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   6813: is that you can step in any direction and you know where the crash has
                   6814: happened or where the strange data has occurred).
                   6815: 
                   6816: Note that the default actions clobber the contents of the pictured
                   6817: numeric output string, so you should not use @code{~~}, e.g., between
                   6818: @code{<#} and @code{#>}.
                   6819: 
                   6820: doc-~~
                   6821: doc-printdebugdata
                   6822: doc-printdebugline
                   6823: 
1.21      crook    6824: doc-see
                   6825: doc-marker
                   6826: 
                   6827: Here's an example of using @code{marker} at the start of a source file
                   6828: that you are debugging; it ensures that you only ever have one copy of
                   6829: the file's definitions compiled at any time:
                   6830: 
                   6831: @example
                   6832: [IFDEF] my-code
                   6833:     my-code
                   6834: [ENDIF]
                   6835: 
                   6836: marker my-code
                   6837: 
                   6838: \ .. definitions start here
                   6839: \ .
                   6840: \ .
                   6841: \ end
                   6842: @end example
                   6843: 
                   6844: 
                   6845: 
1.2       jwilke   6846: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
1.1       anton    6847: @subsection Assertions
                   6848: @cindex assertions
                   6849: 
                   6850: It is a good idea to make your programs self-checking, in particular, if
                   6851: you use an assumption (e.g., that a certain field of a data structure is
                   6852: never zero) that may become wrong during maintenance. Gforth supports
                   6853: assertions for this purpose. They are used like this:
                   6854: 
                   6855: @example
                   6856: assert( @var{flag} )
                   6857: @end example
                   6858: 
                   6859: The code between @code{assert(} and @code{)} should compute a flag, that
                   6860: should be true if everything is alright and false otherwise. It should
                   6861: not change anything else on the stack. The overall stack effect of the
                   6862: assertion is @code{( -- )}. E.g.
                   6863: 
                   6864: @example
                   6865: assert( 1 1 + 2 = ) \ what we learn in school
                   6866: assert( dup 0<> ) \ assert that the top of stack is not zero
                   6867: assert( false ) \ this code should not be reached
                   6868: @end example
                   6869: 
                   6870: The need for assertions is different at different times. During
                   6871: debugging, we want more checking, in production we sometimes care more
                   6872: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   6873: becomes a comment. Depending on the importance of an assertion and the
                   6874: time it takes to check it, you may want to turn off some assertions and
                   6875: keep others turned on. Gforth provides several levels of assertions for
                   6876: this purpose:
                   6877: 
                   6878: doc-assert0(
                   6879: doc-assert1(
                   6880: doc-assert2(
                   6881: doc-assert3(
                   6882: doc-assert(
                   6883: doc-)
                   6884: 
                   6885: @code{Assert(} is the same as @code{assert1(}. The variable
                   6886: @code{assert-level} specifies the highest assertions that are turned
                   6887: on. I.e., at the default @code{assert-level} of one, @code{assert0(} and
                   6888: @code{assert1(} assertions perform checking, while @code{assert2(} and
                   6889: @code{assert3(} assertions are treated as comments.
                   6890: 
                   6891: Note that the @code{assert-level} is evaluated at compile-time, not at
                   6892: run-time. I.e., you cannot turn assertions on or off at run-time, you
                   6893: have to set the @code{assert-level} appropriately before compiling a
                   6894: piece of code. You can compile several pieces of code at several
                   6895: @code{assert-level}s (e.g., a trusted library at level 1 and newly
                   6896: written code at level 3).
                   6897: 
                   6898: doc-assert-level
                   6899: 
                   6900: If an assertion fails, a message compatible with Emacs' compilation mode
                   6901: is produced and the execution is aborted (currently with @code{ABORT"}.
                   6902: If there is interest, we will introduce a special throw code. But if you
                   6903: intend to @code{catch} a specific condition, using @code{throw} is
                   6904: probably more appropriate than an assertion).
                   6905: 
1.21      crook    6906: Definitions in ANS Standard Forth for these assertion words are provided
                   6907: in @file{compat/assert.fs}.
                   6908: 
                   6909: 
1.2       jwilke   6910: @node Singlestep Debugger, , Assertions, Programming Tools
                   6911: @subsection Singlestep Debugger
                   6912: @cindex singlestep Debugger
                   6913: @cindex debugging Singlestep
                   6914: @cindex @code{dbg}
                   6915: @cindex @code{BREAK:}
                   6916: @cindex @code{BREAK"}
                   6917: 
                   6918: When a new word is created there's often the need to check whether it behaves
1.21      crook    6919: correctly or not. You can do this by typing @code{dbg badword}.
                   6920: 
                   6921: doc-dbg
                   6922: 
                   6923: This might look like:
                   6924: 
1.2       jwilke   6925: @example
                   6926: : badword 0 DO i . LOOP ;  ok
                   6927: 2 dbg badword 
                   6928: : badword  
                   6929: Scanning code...
                   6930: 
                   6931: Nesting debugger ready!
                   6932: 
                   6933: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   6934: 400D4740  8049F68 DO             -> [ 0 ] 
                   6935: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   6936: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   6937: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   6938: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   6939: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   6940: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   6941: 400D4758  804B384 ;              ->  ok
                   6942: @end example
                   6943: 
1.5       anton    6944: Each line displayed is one step. You always have to hit return to
                   6945: execute the next word that is displayed. If you don't want to execute
                   6946: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   6947: an overview what keys are available:
1.2       jwilke   6948: 
                   6949: @table @i
                   6950: 
1.4       anton    6951: @item <return>
1.5       anton    6952: Next; Execute the next word.
1.2       jwilke   6953: 
                   6954: @item n
1.5       anton    6955: Nest; Single step through next word.
1.2       jwilke   6956: 
                   6957: @item u
1.5       anton    6958: Unnest; Stop debugging and execute rest of word. If we got to this word
                   6959: with nest, continue debugging with the calling word.
1.2       jwilke   6960: 
                   6961: @item d
1.5       anton    6962: Done; Stop debugging and execute rest.
1.2       jwilke   6963: 
                   6964: @item s
1.5       anton    6965: Stopp; Abort immediately.
1.2       jwilke   6966: 
                   6967: @end table
                   6968: 
                   6969: Debugging large application with this mechanism is very difficult, because
                   6970: you have to nest very deep into the program before the interesting part
                   6971: begins. This takes a lot of time. 
                   6972: 
                   6973: To do it more directly put a @code{BREAK:} command into your source code.
                   6974: When program execution reaches @code{BREAK:} the single step debugger is
                   6975: invoked and you have all the features described above.
                   6976: 
                   6977: If you have more than one part to debug it is useful to know where the
                   6978: program has stopped at the moment. You can do this by the 
                   6979: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   6980: string is typed out when the ``breakpoint'' is reached.
                   6981: 
1.7       pazsan   6982: @node Assembler and Code Words, Threading Words, Programming Tools, Words
                   6983: @section Assembler and Code Words
1.1       anton    6984: @cindex assembler
                   6985: @cindex code words
                   6986: 
                   6987: Gforth provides some words for defining primitives (words written in
                   6988: machine code), and for defining the the machine-code equivalent of
                   6989: @code{DOES>}-based defining words. However, the machine-independent
                   6990: nature of Gforth poses a few problems: First of all, Gforth runs on
                   6991: several architectures, so it can provide no standard assembler. What's
                   6992: worse is that the register allocation not only depends on the processor,
                   6993: but also on the @code{gcc} version and options used.
                   6994: 
                   6995: The words that Gforth offers encapsulate some system dependences (e.g., the
                   6996: header structure), so a system-independent assembler may be used in
                   6997: Gforth. If you do not have an assembler, you can compile machine code
                   6998: directly with @code{,} and @code{c,}.
                   6999: 
                   7000: doc-assembler
                   7001: doc-code
                   7002: doc-end-code
                   7003: doc-;code
                   7004: doc-flush-icache
                   7005: 
                   7006: If @code{flush-icache} does not work correctly, @code{code} words
                   7007: etc. will not work (reliably), either.
                   7008: 
                   7009: These words are rarely used. Therefore they reside in @code{code.fs},
                   7010: which is usually not loaded (except @code{flush-icache}, which is always
                   7011: present). You can load them with @code{require code.fs}.
                   7012: 
                   7013: @cindex registers of the inner interpreter
                   7014: In the assembly code you will want to refer to the inner interpreter's
                   7015: registers (e.g., the data stack pointer) and you may want to use other
                   7016: registers for temporary storage. Unfortunately, the register allocation
                   7017: is installation-dependent.
                   7018: 
                   7019: The easiest solution is to use explicit register declarations
                   7020: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
                   7021: GNU C Manual}) for all of the inner interpreter's registers: You have to
                   7022: compile Gforth with @code{-DFORCE_REG} (configure option
                   7023: @code{--enable-force-reg}) and the appropriate declarations must be
                   7024: present in the @code{machine.h} file (see @code{mips.h} for an example;
                   7025: you can find a full list of all declarable register symbols with
                   7026: @code{grep register engine.c}). If you give explicit registers to all
                   7027: variables that are declared at the beginning of @code{engine()}, you
                   7028: should be able to use the other caller-saved registers for temporary
                   7029: storage. Alternatively, you can use the @code{gcc} option
                   7030: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
                   7031: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
                   7032: (however, this restriction on register allocation may slow Gforth
                   7033: significantly).
                   7034: 
                   7035: If this solution is not viable (e.g., because @code{gcc} does not allow
                   7036: you to explicitly declare all the registers you need), you have to find
                   7037: out by looking at the code where the inner interpreter's registers
                   7038: reside and which registers can be used for temporary storage. You can
                   7039: get an assembly listing of the engine's code with @code{make engine.s}.
                   7040: 
                   7041: In any case, it is good practice to abstract your assembly code from the
                   7042: actual register allocation. E.g., if the data stack pointer resides in
                   7043: register @code{$17}, create an alias for this register called @code{sp},
                   7044: and use that in your assembly code.
                   7045: 
                   7046: @cindex code words, portable
                   7047: Another option for implementing normal and defining words efficiently
                   7048: is: adding the wanted functionality to the source of Gforth. For normal
                   7049: words you just have to edit @file{primitives} (@pxref{Automatic
                   7050: Generation}), defining words (equivalent to @code{;CODE} words, for fast
1.21      crook    7051: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
1.1       anton    7052: @file{prims2x.fs}, and possibly @file{cross.fs}.
                   7053: 
                   7054: 
1.21      crook    7055: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
1.1       anton    7056: @section Threading Words
                   7057: @cindex threading words
                   7058: 
                   7059: @cindex code address
                   7060: These words provide access to code addresses and other threading stuff
                   7061: in Gforth (and, possibly, other interpretive Forths). It more or less
                   7062: abstracts away the differences between direct and indirect threading
                   7063: (and, for direct threading, the machine dependences). However, at
                   7064: present this wordset is still incomplete. It is also pretty low-level;
                   7065: some day it will hopefully be made unnecessary by an internals wordset
                   7066: that abstracts implementation details away completely.
                   7067: 
1.21      crook    7068: doc-threading-method
1.1       anton    7069: doc->code-address
                   7070: doc->does-code
                   7071: doc-code-address!
                   7072: doc-does-code!
                   7073: doc-does-handler!
                   7074: doc-/does-handler
                   7075: 
                   7076: The code addresses produced by various defining words are produced by
                   7077: the following words:
                   7078: 
                   7079: doc-docol:
                   7080: doc-docon:
                   7081: doc-dovar:
                   7082: doc-douser:
                   7083: doc-dodefer:
                   7084: doc-dofield:
                   7085: 
                   7086: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
                   7087: with @code{>DOES-CODE}. If the word was defined in that way, the value
                   7088: returned is different from 0 and identifies the @code{DOES>} used by the
                   7089: defining word.
1.21      crook    7090: @comment TODO should that be "identifies the xt of the DOES> ??
                   7091: 
                   7092: @node Passing Commands to the OS, Miscellaneous Words, Threading Words, Words
                   7093: @section Passing Commands to the Operating System
                   7094: @cindex operating system - passing commands
                   7095: @cindex shell commands
                   7096: 
                   7097: Gforth allows you to pass an arbitrary string to the host operating
                   7098: system shell (if such a thing exists) for execution.
                   7099: 
                   7100: doc-sh
                   7101: doc-system
                   7102: doc-$?
1.23      crook    7103: doc-getenv
1.21      crook    7104: 
                   7105: 
                   7106: @node Miscellaneous Words,  , Passing Commands to the OS, Words
                   7107: @section Miscellaneous Words
                   7108: @cindex miscellaneous words
                   7109: 
                   7110: These section lists the ANS Standard Forth words that are not documented
                   7111: elsewhere in this manual. Ultimately, they all need proper homes.
                   7112: 
                   7113: doc-,
                   7114: doc-allocate
                   7115: doc-allot
                   7116: doc-c,
                   7117: doc-here
                   7118: doc-ms
                   7119: doc-pad
                   7120: doc-parse
                   7121: doc-postpone
                   7122: doc-resize
                   7123: doc-time&date
                   7124: doc-unused
                   7125: doc-word
                   7126: doc-[compile]
1.23      crook    7127: doc-refill
1.21      crook    7128: 
                   7129: These ANS Standard Forth words are not currently implemented in Gforth
                   7130: (see TODO section on dependencies)
                   7131: 
                   7132: The following ANS Standard Forth words are not currently supported by Gforth 
                   7133: (@pxref{ANS conformance})
                   7134: 
                   7135: @code{EDITOR} 
                   7136: @code{EKEY} 
                   7137: @code{EKEY>CHAR} 
                   7138: @code{EKEY?} 
                   7139: @code{EMIT?} 
                   7140: @code{FORGET} 
                   7141: 
1.24      anton    7142: @c ******************************************************************
                   7143: @node Error messages, Tools, Words, Top
                   7144: @chapter Error messages
                   7145: @cindex error messages
                   7146: @cindex backtrace
                   7147: 
                   7148: A typical Gforth error message looks like this:
                   7149: 
                   7150: @example
                   7151: in file included from :-1
                   7152: in file included from ./yyy.fs:1
                   7153: ./xxx.fs:4: Invalid memory address
                   7154: bar
                   7155: ^^^
1.25    ! anton    7156: $400E664C @@
        !          7157: $400E6664 foo
1.24      anton    7158: @end example
                   7159: 
                   7160: The message identifying the error is @code{Invalid memory address}.  The
                   7161: error happened when text-interpreting line 4 of the file
                   7162: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
                   7163: word on the line where the error happened, is pointed out (with
                   7164: @code{^^^}).
                   7165: 
                   7166: The file containing the error was included in line 1 of @file{./yyy.fs},
                   7167: and @file{yyy.fs} was included from a non-file (in this case, by giving
                   7168: @file{yyy.fs} as command-line parameter to Gforth).
                   7169: 
                   7170: At the end of the error message you find a return stack dump that can be
                   7171: interpreted as a backtrace (possibly empty). On top you find the top of
                   7172: the return stack when the @code{throw} happened, and at the bottom you
                   7173: find the return stack entry just above the return stack of the topmost
                   7174: text interpreter.
                   7175: 
                   7176: To the right of most return stack entries you see a guess for the word
                   7177: that pushed that return stack entry as its return address. This gives a
                   7178: backtrace. In our case we see that @code{bar} called @code{foo}, and
                   7179: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
                   7180: address} exception).
                   7181: 
                   7182: Note that the backtrace is not perfect: We don't know which return stack
                   7183: entries are return addresses (so we may get false positives); and in
                   7184: some cases (e.g., for @code{abort"}) we cannot determine from the return
                   7185: address the word that pushed the return address, so for some return
                   7186: addresses you see no names in the return stack dump.
1.25    ! anton    7187: 
        !          7188: @cindex @code{catch} and backtraces
        !          7189: The return stack dump represents the return stack at the time when a
        !          7190: specific @code{throw} was executed.  In programs that make use of
        !          7191: @code{catch}, it is not necessarily clear which @code{throw} should be
        !          7192: used for the return stack dump (e.g., consider one @code{throw} that
        !          7193: indicates an error, which is caught, and during recovery another error
        !          7194: happens; which @code{throw} should be used for the stack dump).  Gforth
        !          7195: presents the return stack dump for the first @code{throw} after the last
        !          7196: executed (not returned-to) @code{catch}; this works well in the usual
        !          7197: case.
        !          7198: 
        !          7199: @cindex @code{gforth-fast} and backtraces
        !          7200: @cindex @code{gforth-fast}, difference from @code{gforth}
        !          7201: @cindex backtraces with @code{gforth-fast}
        !          7202: @cindex return stack dump with @code{gforth-fast}
        !          7203: @code{gforth} is able to do a return stack dump for throws generated
        !          7204: from primitives (e.g., invalid memory address, stack empty etc.);
        !          7205: @code{gforth-fast} is only able to do a return stack dump from a
        !          7206: directly called @code{throw} (including @code{abort} etc.).  This is the
        !          7207: only difference (apart from a speed difference of about 30%) between
        !          7208: @code{gforth} and @code{gforth-fast}.  Given an exception caused by a
        !          7209: primitive in @code{gforth-fast}, you will typically see no return stack
        !          7210: dump at all; however, if the exception is caught by @code{catch} (e.g.,
        !          7211: for restoring some state), and then @code{throw}n again, the return
        !          7212: stack dump will be for the first such @code{throw}.
1.2       jwilke   7213: 
1.5       anton    7214: @c ******************************************************************
1.24      anton    7215: @node Tools, ANS conformance, Error messages, Top
1.1       anton    7216: @chapter Tools
                   7217: 
                   7218: @menu
                   7219: * ANS Report::                  Report the words used, sorted by wordset.
                   7220: @end menu
                   7221: 
                   7222: See also @ref{Emacs and Gforth}.
                   7223: 
                   7224: @node ANS Report,  , Tools, Tools
                   7225: @section @file{ans-report.fs}: Report the words used, sorted by wordset
                   7226: @cindex @file{ans-report.fs}
                   7227: @cindex report the words used in your program
                   7228: @cindex words used in your program
                   7229: 
                   7230: If you want to label a Forth program as ANS Forth Program, you must
                   7231: document which wordsets the program uses; for extension wordsets, it is
                   7232: helpful to list the words the program requires from these wordsets
                   7233: (because Forth systems are allowed to provide only some words of them).
                   7234: 
                   7235: The @file{ans-report.fs} tool makes it easy for you to determine which
                   7236: words from which wordset and which non-ANS words your application
                   7237: uses. You simply have to include @file{ans-report.fs} before loading the
                   7238: program you want to check. After loading your program, you can get the
                   7239: report with @code{print-ans-report}. A typical use is to run this as
                   7240: batch job like this:
                   7241: @example
                   7242: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
                   7243: @end example
                   7244: 
                   7245: The output looks like this (for @file{compat/control.fs}):
                   7246: @example
                   7247: The program uses the following words
                   7248: from CORE :
                   7249: : POSTPONE THEN ; immediate ?dup IF 0= 
                   7250: from BLOCK-EXT :
                   7251: \ 
                   7252: from FILE :
                   7253: ( 
                   7254: @end example
                   7255: 
                   7256: @subsection Caveats
                   7257: 
                   7258: Note that @file{ans-report.fs} just checks which words are used, not whether
                   7259: they are used in an ANS Forth conforming way!
                   7260: 
                   7261: Some words are defined in several wordsets in the
                   7262: standard. @file{ans-report.fs} reports them for only one of the
                   7263: wordsets, and not necessarily the one you expect. It depends on usage
                   7264: which wordset is the right one to specify. E.g., if you only use the
                   7265: compilation semantics of @code{S"}, it is a Core word; if you also use
                   7266: its interpretation semantics, it is a File word.
                   7267: 
                   7268: @c ******************************************************************
                   7269: @node ANS conformance, Model, Tools, Top
                   7270: @chapter ANS conformance
                   7271: @cindex ANS conformance of Gforth
                   7272: 
                   7273: To the best of our knowledge, Gforth is an
                   7274: 
                   7275: ANS Forth System
                   7276: @itemize @bullet
                   7277: @item providing the Core Extensions word set
                   7278: @item providing the Block word set
                   7279: @item providing the Block Extensions word set
                   7280: @item providing the Double-Number word set
                   7281: @item providing the Double-Number Extensions word set
                   7282: @item providing the Exception word set
                   7283: @item providing the Exception Extensions word set
                   7284: @item providing the Facility word set
                   7285: @item providing @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
                   7286: @item providing the File Access word set
                   7287: @item providing the File Access Extensions word set
                   7288: @item providing the Floating-Point word set
                   7289: @item providing the Floating-Point Extensions word set
                   7290: @item providing the Locals word set
                   7291: @item providing the Locals Extensions word set
                   7292: @item providing the Memory-Allocation word set
                   7293: @item providing the Memory-Allocation Extensions word set (that one's easy)
                   7294: @item providing the Programming-Tools word set
                   7295: @item providing @code{;CODE}, @code{AHEAD}, @code{ASSEMBLER}, @code{BYE}, @code{CODE}, @code{CS-PICK}, @code{CS-ROLL}, @code{STATE}, @code{[ELSE]}, @code{[IF]}, @code{[THEN]} from the Programming-Tools Extensions word set
                   7296: @item providing the Search-Order word set
                   7297: @item providing the Search-Order Extensions word set
                   7298: @item providing the String word set
                   7299: @item providing the String Extensions word set (another easy one)
                   7300: @end itemize
                   7301: 
                   7302: @cindex system documentation
                   7303: In addition, ANS Forth systems are required to document certain
                   7304: implementation choices. This chapter tries to meet these
                   7305: requirements. In many cases it gives a way to ask the system for the
                   7306: information instead of providing the information directly, in
                   7307: particular, if the information depends on the processor, the operating
                   7308: system or the installation options chosen, or if they are likely to
                   7309: change during the maintenance of Gforth.
                   7310: 
                   7311: @comment The framework for the rest has been taken from pfe.
                   7312: 
                   7313: @menu
                   7314: * The Core Words::              
                   7315: * The optional Block word set::  
                   7316: * The optional Double Number word set::  
                   7317: * The optional Exception word set::  
                   7318: * The optional Facility word set::  
                   7319: * The optional File-Access word set::  
                   7320: * The optional Floating-Point word set::  
                   7321: * The optional Locals word set::  
                   7322: * The optional Memory-Allocation word set::  
                   7323: * The optional Programming-Tools word set::  
                   7324: * The optional Search-Order word set::  
                   7325: @end menu
                   7326: 
                   7327: 
                   7328: @c =====================================================================
                   7329: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
                   7330: @comment  node-name,  next,  previous,  up
                   7331: @section The Core Words
                   7332: @c =====================================================================
                   7333: @cindex core words, system documentation
                   7334: @cindex system documentation, core words
                   7335: 
                   7336: @menu
                   7337: * core-idef::                   Implementation Defined Options                   
                   7338: * core-ambcond::                Ambiguous Conditions                
                   7339: * core-other::                  Other System Documentation                  
                   7340: @end menu
                   7341: 
                   7342: @c ---------------------------------------------------------------------
                   7343: @node core-idef, core-ambcond, The Core Words, The Core Words
                   7344: @subsection Implementation Defined Options
                   7345: @c ---------------------------------------------------------------------
                   7346: @cindex core words, implementation-defined options
                   7347: @cindex implementation-defined options, core words
                   7348: 
                   7349: 
                   7350: @table @i
                   7351: @item (Cell) aligned addresses:
                   7352: @cindex cell-aligned addresses
                   7353: @cindex aligned addresses
                   7354: processor-dependent. Gforth's alignment words perform natural alignment
                   7355: (e.g., an address aligned for a datum of size 8 is divisible by
                   7356: 8). Unaligned accesses usually result in a @code{-23 THROW}.
                   7357: 
                   7358: @item @code{EMIT} and non-graphic characters:
                   7359: @cindex @code{EMIT} and non-graphic characters
                   7360: @cindex non-graphic characters and @code{EMIT}
                   7361: The character is output using the C library function (actually, macro)
                   7362: @code{putc}.
                   7363: 
                   7364: @item character editing of @code{ACCEPT} and @code{EXPECT}:
                   7365: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
                   7366: @cindex editing in @code{ACCEPT} and @code{EXPECT}
                   7367: @cindex @code{ACCEPT}, editing
                   7368: @cindex @code{EXPECT}, editing
                   7369: This is modeled on the GNU readline library (@pxref{Readline
                   7370: Interaction, , Command Line Editing, readline, The GNU Readline
                   7371: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
                   7372: producing a full word completion every time you type it (instead of
                   7373: producing the common prefix of all completions).
                   7374: 
                   7375: @item character set:
                   7376: @cindex character set
                   7377: The character set of your computer and display device. Gforth is
                   7378: 8-bit-clean (but some other component in your system may make trouble).
                   7379: 
                   7380: @item Character-aligned address requirements:
                   7381: @cindex character-aligned address requirements
                   7382: installation-dependent. Currently a character is represented by a C
                   7383: @code{unsigned char}; in the future we might switch to @code{wchar_t}
                   7384: (Comments on that requested).
                   7385: 
                   7386: @item character-set extensions and matching of names:
                   7387: @cindex character-set extensions and matching of names
                   7388: @cindex case sensitivity for name lookup
                   7389: @cindex name lookup, case sensitivity
                   7390: @cindex locale and case sensitivity
1.21      crook    7391: Any character except the ASCII NUL character can be used in a
1.1       anton    7392: name. Matching is case-insensitive (except in @code{TABLE}s). The
                   7393: matching is performed using the C function @code{strncasecmp}, whose
                   7394: function is probably influenced by the locale. E.g., the @code{C} locale
                   7395: does not know about accents and umlauts, so they are matched
                   7396: case-sensitively in that locale. For portability reasons it is best to
                   7397: write programs such that they work in the @code{C} locale. Then one can
                   7398: use libraries written by a Polish programmer (who might use words
                   7399: containing ISO Latin-2 encoded characters) and by a French programmer
                   7400: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
                   7401: funny results for some of the words (which ones, depends on the font you
                   7402: are using)). Also, the locale you prefer may not be available in other
                   7403: operating systems. Hopefully, Unicode will solve these problems one day.
                   7404: 
                   7405: @item conditions under which control characters match a space delimiter:
                   7406: @cindex space delimiters
                   7407: @cindex control characters as delimiters
                   7408: If @code{WORD} is called with the space character as a delimiter, all
                   7409: white-space characters (as identified by the C macro @code{isspace()})
                   7410: are delimiters. @code{PARSE}, on the other hand, treats space like other
                   7411: delimiters. @code{PARSE-WORD} treats space like @code{WORD}, but behaves
                   7412: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
                   7413: interpreter (aka text interpreter) by default, treats all white-space
                   7414: characters as delimiters.
                   7415: 
                   7416: @item format of the control flow stack:
                   7417: @cindex control flow stack, format
                   7418: The data stack is used as control flow stack. The size of a control flow
                   7419: stack item in cells is given by the constant @code{cs-item-size}. At the
                   7420: time of this writing, an item consists of a (pointer to a) locals list
                   7421: (third), an address in the code (second), and a tag for identifying the
                   7422: item (TOS). The following tags are used: @code{defstart},
                   7423: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
                   7424: @code{scopestart}.
                   7425: 
                   7426: @item conversion of digits > 35
                   7427: @cindex digits > 35
                   7428: The characters @code{[\]^_'} are the digits with the decimal value
                   7429: 36@minus{}41. There is no way to input many of the larger digits.
                   7430: 
                   7431: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
                   7432: @cindex @code{EXPECT}, display after end of input
                   7433: @cindex @code{ACCEPT}, display after end of input
                   7434: The cursor is moved to the end of the entered string. If the input is
                   7435: terminated using the @kbd{Return} key, a space is typed.
                   7436: 
                   7437: @item exception abort sequence of @code{ABORT"}:
                   7438: @cindex exception abort sequence of @code{ABORT"}
                   7439: @cindex @code{ABORT"}, exception abort sequence
                   7440: The error string is stored into the variable @code{"error} and a
                   7441: @code{-2 throw} is performed.
                   7442: 
                   7443: @item input line terminator:
                   7444: @cindex input line terminator
                   7445: @cindex line terminator on input
                   7446: @cindex newline charcter on input
                   7447: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
                   7448: lines. One of these characters is typically produced when you type the
                   7449: @kbd{Enter} or @kbd{Return} key.
                   7450: 
                   7451: @item maximum size of a counted string:
                   7452: @cindex maximum size of a counted string
                   7453: @cindex counted string, maximum size
                   7454: @code{s" /counted-string" environment? drop .}. Currently 255 characters
                   7455: on all ports, but this may change.
                   7456: 
                   7457: @item maximum size of a parsed string:
                   7458: @cindex maximum size of a parsed string
                   7459: @cindex parsed string, maximum size
                   7460: Given by the constant @code{/line}. Currently 255 characters.
                   7461: 
                   7462: @item maximum size of a definition name, in characters:
                   7463: @cindex maximum size of a definition name, in characters
                   7464: @cindex name, maximum length
                   7465: 31
                   7466: 
                   7467: @item maximum string length for @code{ENVIRONMENT?}, in characters:
                   7468: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
                   7469: @cindex @code{ENVIRONMENT?} string length, maximum
                   7470: 31
                   7471: 
                   7472: @item method of selecting the user input device:
                   7473: @cindex user input device, method of selecting
                   7474: The user input device is the standard input. There is currently no way to
                   7475: change it from within Gforth. However, the input can typically be
                   7476: redirected in the command line that starts Gforth.
                   7477: 
                   7478: @item method of selecting the user output device:
                   7479: @cindex user output device, method of selecting
                   7480: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10      anton    7481: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
                   7482: output when the user output device is a terminal, otherwise the output
                   7483: is buffered.
1.1       anton    7484: 
                   7485: @item methods of dictionary compilation:
                   7486: What are we expected to document here?
                   7487: 
                   7488: @item number of bits in one address unit:
                   7489: @cindex number of bits in one address unit
                   7490: @cindex address unit, size in bits
                   7491: @code{s" address-units-bits" environment? drop .}. 8 in all current
                   7492: ports.
                   7493: 
                   7494: @item number representation and arithmetic:
                   7495: @cindex number representation and arithmetic
                   7496: Processor-dependent. Binary two's complement on all current ports.
                   7497: 
                   7498: @item ranges for integer types:
                   7499: @cindex ranges for integer types
                   7500: @cindex integer types, ranges
                   7501: Installation-dependent. Make environmental queries for @code{MAX-N},
                   7502: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
                   7503: unsigned (and positive) types is 0. The lower bound for signed types on
                   7504: two's complement and one's complement machines machines can be computed
                   7505: by adding 1 to the upper bound.
                   7506: 
                   7507: @item read-only data space regions:
                   7508: @cindex read-only data space regions
                   7509: @cindex data-space, read-only regions
                   7510: The whole Forth data space is writable.
                   7511: 
                   7512: @item size of buffer at @code{WORD}:
                   7513: @cindex size of buffer at @code{WORD}
                   7514: @cindex @code{WORD} buffer size
                   7515: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   7516: shared with the pictured numeric output string. If overwriting
                   7517: @code{PAD} is acceptable, it is as large as the remaining dictionary
                   7518: space, although only as much can be sensibly used as fits in a counted
                   7519: string.
                   7520: 
                   7521: @item size of one cell in address units:
                   7522: @cindex cell size
                   7523: @code{1 cells .}.
                   7524: 
                   7525: @item size of one character in address units:
                   7526: @cindex char size
                   7527: @code{1 chars .}. 1 on all current ports.
                   7528: 
                   7529: @item size of the keyboard terminal buffer:
                   7530: @cindex size of the keyboard terminal buffer
                   7531: @cindex terminal buffer, size
                   7532: Varies. You can determine the size at a specific time using @code{lp@@
                   7533: tib - .}. It is shared with the locals stack and TIBs of files that
                   7534: include the current file. You can change the amount of space for TIBs
                   7535: and locals stack at Gforth startup with the command line option
                   7536: @code{-l}.
                   7537: 
                   7538: @item size of the pictured numeric output buffer:
                   7539: @cindex size of the pictured numeric output buffer
                   7540: @cindex pictured numeric output buffer, size
                   7541: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   7542: shared with @code{WORD}.
                   7543: 
                   7544: @item size of the scratch area returned by @code{PAD}:
                   7545: @cindex size of the scratch area returned by @code{PAD}
                   7546: @cindex @code{PAD} size
                   7547: The remainder of dictionary space. @code{unused pad here - - .}.
                   7548: 
                   7549: @item system case-sensitivity characteristics:
                   7550: @cindex case-sensitivity characteristics
                   7551: Dictionary searches are case insensitive (except in
                   7552: @code{TABLE}s). However, as explained above under @i{character-set
                   7553: extensions}, the matching for non-ASCII characters is determined by the
                   7554: locale you are using. In the default @code{C} locale all non-ASCII
                   7555: characters are matched case-sensitively.
                   7556: 
                   7557: @item system prompt:
                   7558: @cindex system prompt
                   7559: @cindex prompt
                   7560: @code{ ok} in interpret state, @code{ compiled} in compile state.
                   7561: 
                   7562: @item division rounding:
                   7563: @cindex division rounding
                   7564: installation dependent. @code{s" floored" environment? drop .}. We leave
                   7565: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
                   7566: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
                   7567: 
                   7568: @item values of @code{STATE} when true:
                   7569: @cindex @code{STATE} values
                   7570: -1.
                   7571: 
                   7572: @item values returned after arithmetic overflow:
                   7573: On two's complement machines, arithmetic is performed modulo
                   7574: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   7575: arithmetic (with appropriate mapping for signed types). Division by zero
                   7576: typically results in a @code{-55 throw} (Floating-point unidentified
                   7577: fault), although a @code{-10 throw} (divide by zero) would be more
                   7578: appropriate.
                   7579: 
                   7580: @item whether the current definition can be found after @t{DOES>}:
                   7581: @cindex @t{DOES>}, visibility of current definition
                   7582: No.
                   7583: 
                   7584: @end table
                   7585: 
                   7586: @c ---------------------------------------------------------------------
                   7587: @node core-ambcond, core-other, core-idef, The Core Words
                   7588: @subsection Ambiguous conditions
                   7589: @c ---------------------------------------------------------------------
                   7590: @cindex core words, ambiguous conditions
                   7591: @cindex ambiguous conditions, core words
                   7592: 
                   7593: @table @i
                   7594: 
                   7595: @item a name is neither a word nor a number:
                   7596: @cindex name not found
                   7597: @cindex Undefined word
                   7598: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
                   7599: preserves the data and FP stack, so you don't lose more work than
                   7600: necessary.
                   7601: 
                   7602: @item a definition name exceeds the maximum length allowed:
                   7603: @cindex Word name too long
                   7604: @code{-19 throw} (Word name too long)
                   7605: 
                   7606: @item addressing a region not inside the various data spaces of the forth system:
                   7607: @cindex Invalid memory address
                   7608: The stacks, code space and name space are accessible. Machine code space is
                   7609: typically readable. Accessing other addresses gives results dependent on
                   7610: the operating system. On decent systems: @code{-9 throw} (Invalid memory
                   7611: address).
                   7612: 
                   7613: @item argument type incompatible with parameter:
                   7614: @cindex Argument type mismatch
                   7615: This is usually not caught. Some words perform checks, e.g., the control
                   7616: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
                   7617: mismatch).
                   7618: 
                   7619: @item attempting to obtain the execution token of a word with undefined execution semantics:
                   7620: @cindex Interpreting a compile-only word, for @code{'} etc.
                   7621: @cindex execution token of words with undefined execution semantics
                   7622: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
                   7623: get an execution token for @code{compile-only-error} (which performs a
                   7624: @code{-14 throw} when executed).
                   7625: 
                   7626: @item dividing by zero:
                   7627: @cindex dividing by zero
                   7628: @cindex floating point unidentified fault, integer division
                   7629: @cindex divide by zero
1.24      anton    7630: On better platforms, this produces a @code{-10 throw} (Division by
                   7631: zero); on other systems, this typically results in a @code{-55 throw}
                   7632: (Floating-point unidentified fault).
1.1       anton    7633: 
                   7634: @item insufficient data stack or return stack space:
                   7635: @cindex insufficient data stack or return stack space
                   7636: @cindex stack overflow
                   7637: @cindex Address alignment exception, stack overflow
                   7638: @cindex Invalid memory address, stack overflow
                   7639: Depending on the operating system, the installation, and the invocation
                   7640: of Gforth, this is either checked by the memory management hardware, or
1.24      anton    7641: it is not checked. If it is checked, you typically get a @code{-3 throw}
                   7642: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
                   7643: throw} (Invalid memory address) (depending on the platform and how you
                   7644: achieved the overflow) as soon as the overflow happens. If it is not
                   7645: checked, overflows typically result in mysterious illegal memory
                   7646: accesses, producing @code{-9 throw} (Invalid memory address) or
                   7647: @code{-23 throw} (Address alignment exception); they might also destroy
                   7648: the internal data structure of @code{ALLOCATE} and friends, resulting in
                   7649: various errors in these words.
1.1       anton    7650: 
                   7651: @item insufficient space for loop control parameters:
                   7652: @cindex insufficient space for loop control parameters
                   7653: like other return stack overflows.
                   7654: 
                   7655: @item insufficient space in the dictionary:
                   7656: @cindex insufficient space in the dictionary
                   7657: @cindex dictionary overflow
1.12      anton    7658: If you try to allot (either directly with @code{allot}, or indirectly
                   7659: with @code{,}, @code{create} etc.) more memory than available in the
                   7660: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
                   7661: to access memory beyond the end of the dictionary, the results are
                   7662: similar to stack overflows.
1.1       anton    7663: 
                   7664: @item interpreting a word with undefined interpretation semantics:
                   7665: @cindex interpreting a word with undefined interpretation semantics
                   7666: @cindex Interpreting a compile-only word
                   7667: For some words, we have defined interpretation semantics. For the
                   7668: others: @code{-14 throw} (Interpreting a compile-only word).
                   7669: 
                   7670: @item modifying the contents of the input buffer or a string literal:
                   7671: @cindex modifying the contents of the input buffer or a string literal
                   7672: These are located in writable memory and can be modified.
                   7673: 
                   7674: @item overflow of the pictured numeric output string:
                   7675: @cindex overflow of the pictured numeric output string
                   7676: @cindex pictured numeric output string, overflow
1.24      anton    7677: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1       anton    7678: 
                   7679: @item parsed string overflow:
                   7680: @cindex parsed string overflow
                   7681: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
                   7682: 
                   7683: @item producing a result out of range:
                   7684: @cindex result out of range
                   7685: On two's complement machines, arithmetic is performed modulo
                   7686: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   7687: arithmetic (with appropriate mapping for signed types). Division by zero
1.24      anton    7688: typically results in a @code{-10 throw} (divide by zero) or @code{-55
                   7689: throw} (floating point unidentified fault). @code{convert} and
                   7690: @code{>number} currently overflow silently.
1.1       anton    7691: 
                   7692: @item reading from an empty data or return stack:
                   7693: @cindex stack empty
                   7694: @cindex stack underflow
1.24      anton    7695: @cindex return stack underflow
1.1       anton    7696: The data stack is checked by the outer (aka text) interpreter after
                   7697: every word executed. If it has underflowed, a @code{-4 throw} (Stack
                   7698: underflow) is performed. Apart from that, stacks may be checked or not,
1.24      anton    7699: depending on operating system, installation, and invocation. If they are
                   7700: caught by a check, they typically result in @code{-4 throw} (Stack
                   7701: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
                   7702: (Invalid memory address), depending on the platform and which stack
                   7703: underflows and by how much. Note that even if the system uses checking
                   7704: (through the MMU), your program may have to underflow by a significant
                   7705: number of stack items to trigger the reaction (the reason for this is
                   7706: that the MMU, and therefore the checking, works with a page-size
                   7707: granularity).  If there is no checking, the symptoms resulting from an
                   7708: underflow are similar to those from an overflow.  Unbalanced return
                   7709: stack errors result in a variaty of symptoms, including @code{-9 throw}
                   7710: (Invalid memory address) and Illegal Instruction (typically @code{-260
                   7711: throw}).
1.1       anton    7712: 
                   7713: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
                   7714: @cindex unexpected end of the input buffer
                   7715: @cindex zero-length string as a name
                   7716: @cindex Attempt to use zero-length string as a name
                   7717: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
                   7718: use zero-length string as a name). Words like @code{'} probably will not
                   7719: find what they search. Note that it is possible to create zero-length
                   7720: names with @code{nextname} (should it not?).
                   7721: 
                   7722: @item @code{>IN} greater than input buffer:
                   7723: @cindex @code{>IN} greater than input buffer
                   7724: The next invocation of a parsing word returns a string with length 0.
                   7725: 
                   7726: @item @code{RECURSE} appears after @code{DOES>}:
                   7727: @cindex @code{RECURSE} appears after @code{DOES>}
                   7728: Compiles a recursive call to the defining word, not to the defined word.
                   7729: 
                   7730: @item argument input source different than current input source for @code{RESTORE-INPUT}:
                   7731: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
                   7732: @cindex Argument type mismatch, @code{RESTORE-INPUT}
                   7733: @cindex @code{RESTORE-INPUT}, Argument type mismatch
                   7734: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
                   7735: the end of the file was reached), its source-id may be
                   7736: reused. Therefore, restoring an input source specification referencing a
                   7737: closed file may lead to unpredictable results instead of a @code{-12
                   7738: THROW}.
                   7739: 
                   7740: In the future, Gforth may be able to restore input source specifications
                   7741: from other than the current input source.
                   7742: 
                   7743: @item data space containing definitions gets de-allocated:
                   7744: @cindex data space containing definitions gets de-allocated
                   7745: Deallocation with @code{allot} is not checked. This typically results in
                   7746: memory access faults or execution of illegal instructions.
                   7747: 
                   7748: @item data space read/write with incorrect alignment:
                   7749: @cindex data space read/write with incorrect alignment
                   7750: @cindex alignment faults
                   7751: @cindex Address alignment exception
                   7752: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12      anton    7753: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1       anton    7754: alignment turned on, incorrect alignment results in a @code{-9 throw}
                   7755: (Invalid memory address). There are reportedly some processors with
1.12      anton    7756: alignment restrictions that do not report violations.
1.1       anton    7757: 
                   7758: @item data space pointer not properly aligned, @code{,}, @code{C,}:
                   7759: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
                   7760: Like other alignment errors.
                   7761: 
                   7762: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
                   7763: Like other stack underflows.
                   7764: 
                   7765: @item loop control parameters not available:
                   7766: @cindex loop control parameters not available
                   7767: Not checked. The counted loop words simply assume that the top of return
                   7768: stack items are loop control parameters and behave accordingly.
                   7769: 
                   7770: @item most recent definition does not have a name (@code{IMMEDIATE}):
                   7771: @cindex most recent definition does not have a name (@code{IMMEDIATE})
                   7772: @cindex last word was headerless
                   7773: @code{abort" last word was headerless"}.
                   7774: 
                   7775: @item name not defined by @code{VALUE} used by @code{TO}:
                   7776: @cindex name not defined by @code{VALUE} used by @code{TO}
                   7777: @cindex @code{TO} on non-@code{VALUE}s
                   7778: @cindex Invalid name argument, @code{TO}
                   7779: @code{-32 throw} (Invalid name argument) (unless name is a local or was
                   7780: defined by @code{CONSTANT}; in the latter case it just changes the constant).
                   7781: 
                   7782: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
                   7783: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
                   7784: @cindex Undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
                   7785: @code{-13 throw} (Undefined word)
                   7786: 
                   7787: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
                   7788: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
                   7789: Gforth behaves as if they were of the same type. I.e., you can predict
                   7790: the behaviour by interpreting all parameters as, e.g., signed.
                   7791: 
                   7792: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
                   7793: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
                   7794: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
                   7795: compilation semantics of @code{TO}.
                   7796: 
                   7797: @item String longer than a counted string returned by @code{WORD}:
                   7798: @cindex String longer than a counted string returned by @code{WORD}
                   7799: @cindex @code{WORD}, string overflow
                   7800: Not checked. The string will be ok, but the count will, of course,
                   7801: contain only the least significant bits of the length.
                   7802: 
                   7803: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
                   7804: @cindex @code{LSHIFT}, large shift counts
                   7805: @cindex @code{RSHIFT}, large shift counts
                   7806: Processor-dependent. Typical behaviours are returning 0 and using only
                   7807: the low bits of the shift count.
                   7808: 
                   7809: @item word not defined via @code{CREATE}:
                   7810: @cindex @code{>BODY} of non-@code{CREATE}d words
                   7811: @code{>BODY} produces the PFA of the word no matter how it was defined.
                   7812: 
                   7813: @cindex @code{DOES>} of non-@code{CREATE}d words
                   7814: @code{DOES>} changes the execution semantics of the last defined word no
                   7815: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
                   7816: @code{CREATE , DOES>}.
                   7817: 
                   7818: @item words improperly used outside @code{<#} and @code{#>}:
                   7819: Not checked. As usual, you can expect memory faults.
                   7820: 
                   7821: @end table
                   7822: 
                   7823: 
                   7824: @c ---------------------------------------------------------------------
                   7825: @node core-other,  , core-ambcond, The Core Words
                   7826: @subsection Other system documentation
                   7827: @c ---------------------------------------------------------------------
                   7828: @cindex other system documentation, core words
                   7829: @cindex core words, other system documentation
                   7830: 
                   7831: @table @i
                   7832: @item nonstandard words using @code{PAD}:
                   7833: @cindex @code{PAD} use by nonstandard words
                   7834: None.
                   7835: 
                   7836: @item operator's terminal facilities available:
                   7837: @cindex operator's terminal facilities available
                   7838: After processing the command line, Gforth goes into interactive mode,
                   7839: and you can give commands to Gforth interactively. The actual facilities
                   7840: available depend on how you invoke Gforth.
                   7841: 
                   7842: @item program data space available:
                   7843: @cindex program data space available
                   7844: @cindex data space available
                   7845: @code{UNUSED .} gives the remaining dictionary space. The total
                   7846: dictionary space can be specified with the @code{-m} switch
                   7847: (@pxref{Invoking Gforth}) when Gforth starts up.
                   7848: 
                   7849: @item return stack space available:
                   7850: @cindex return stack space available
                   7851: You can compute the total return stack space in cells with
                   7852: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
                   7853: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
                   7854: 
                   7855: @item stack space available:
                   7856: @cindex stack space available
                   7857: You can compute the total data stack space in cells with
                   7858: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
                   7859: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
                   7860: 
                   7861: @item system dictionary space required, in address units:
                   7862: @cindex system dictionary space required, in address units
                   7863: Type @code{here forthstart - .} after startup. At the time of this
                   7864: writing, this gives 80080 (bytes) on a 32-bit system.
                   7865: @end table
                   7866: 
                   7867: 
                   7868: @c =====================================================================
                   7869: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
                   7870: @section The optional Block word set
                   7871: @c =====================================================================
                   7872: @cindex system documentation, block words
                   7873: @cindex block words, system documentation
                   7874: 
                   7875: @menu
                   7876: * block-idef::                  Implementation Defined Options
                   7877: * block-ambcond::               Ambiguous Conditions               
                   7878: * block-other::                 Other System Documentation                 
                   7879: @end menu
                   7880: 
                   7881: 
                   7882: @c ---------------------------------------------------------------------
                   7883: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
                   7884: @subsection Implementation Defined Options
                   7885: @c ---------------------------------------------------------------------
                   7886: @cindex implementation-defined options, block words
                   7887: @cindex block words, implementation-defined options
                   7888: 
                   7889: @table @i
                   7890: @item the format for display by @code{LIST}:
                   7891: @cindex @code{LIST} display format
                   7892: First the screen number is displayed, then 16 lines of 64 characters,
                   7893: each line preceded by the line number.
                   7894: 
                   7895: @item the length of a line affected by @code{\}:
                   7896: @cindex length of a line affected by @code{\}
                   7897: @cindex @code{\}, line length in blocks
                   7898: 64 characters.
                   7899: @end table
                   7900: 
                   7901: 
                   7902: @c ---------------------------------------------------------------------
                   7903: @node block-ambcond, block-other, block-idef, The optional Block word set
                   7904: @subsection Ambiguous conditions
                   7905: @c ---------------------------------------------------------------------
                   7906: @cindex block words, ambiguous conditions
                   7907: @cindex ambiguous conditions, block words
                   7908: 
                   7909: @table @i
                   7910: @item correct block read was not possible:
                   7911: @cindex block read not possible
                   7912: Typically results in a @code{throw} of some OS-derived value (between
                   7913: -512 and -2048). If the blocks file was just not long enough, blanks are
                   7914: supplied for the missing portion.
                   7915: 
                   7916: @item I/O exception in block transfer:
                   7917: @cindex I/O exception in block transfer
                   7918: @cindex block transfer, I/O exception
                   7919: Typically results in a @code{throw} of some OS-derived value (between
                   7920: -512 and -2048).
                   7921: 
                   7922: @item invalid block number:
                   7923: @cindex invalid block number
                   7924: @cindex block number invalid
                   7925: @code{-35 throw} (Invalid block number)
                   7926: 
                   7927: @item a program directly alters the contents of @code{BLK}:
                   7928: @cindex @code{BLK}, altering @code{BLK}
                   7929: The input stream is switched to that other block, at the same
                   7930: position. If the storing to @code{BLK} happens when interpreting
                   7931: non-block input, the system will get quite confused when the block ends.
                   7932: 
                   7933: @item no current block buffer for @code{UPDATE}:
                   7934: @cindex @code{UPDATE}, no current block buffer
                   7935: @code{UPDATE} has no effect.
                   7936: 
                   7937: @end table
                   7938: 
                   7939: @c ---------------------------------------------------------------------
                   7940: @node block-other,  , block-ambcond, The optional Block word set
                   7941: @subsection Other system documentation
                   7942: @c ---------------------------------------------------------------------
                   7943: @cindex other system documentation, block words
                   7944: @cindex block words, other system documentation
                   7945: 
                   7946: @table @i
                   7947: @item any restrictions a multiprogramming system places on the use of buffer addresses:
                   7948: No restrictions (yet).
                   7949: 
                   7950: @item the number of blocks available for source and data:
                   7951: depends on your disk space.
                   7952: 
                   7953: @end table
                   7954: 
                   7955: 
                   7956: @c =====================================================================
                   7957: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
                   7958: @section The optional Double Number word set
                   7959: @c =====================================================================
                   7960: @cindex system documentation, double words
                   7961: @cindex double words, system documentation
                   7962: 
                   7963: @menu
                   7964: * double-ambcond::              Ambiguous Conditions              
                   7965: @end menu
                   7966: 
                   7967: 
                   7968: @c ---------------------------------------------------------------------
                   7969: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
                   7970: @subsection Ambiguous conditions
                   7971: @c ---------------------------------------------------------------------
                   7972: @cindex double words, ambiguous conditions
                   7973: @cindex ambiguous conditions, double words
                   7974: 
                   7975: @table @i
                   7976: @item @var{d} outside of range of @var{n} in @code{D>S}:
                   7977: @cindex @code{D>S}, @var{d} out of range of @var{n} 
                   7978: The least significant cell of @var{d} is produced.
                   7979: 
                   7980: @end table
                   7981: 
                   7982: 
                   7983: @c =====================================================================
                   7984: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
                   7985: @section The optional Exception word set
                   7986: @c =====================================================================
                   7987: @cindex system documentation, exception words
                   7988: @cindex exception words, system documentation
                   7989: 
                   7990: @menu
                   7991: * exception-idef::              Implementation Defined Options              
                   7992: @end menu
                   7993: 
                   7994: 
                   7995: @c ---------------------------------------------------------------------
                   7996: @node exception-idef,  , The optional Exception word set, The optional Exception word set
                   7997: @subsection Implementation Defined Options
                   7998: @c ---------------------------------------------------------------------
                   7999: @cindex implementation-defined options, exception words
                   8000: @cindex exception words, implementation-defined options
                   8001: 
                   8002: @table @i
                   8003: @item @code{THROW}-codes used in the system:
                   8004: @cindex @code{THROW}-codes used in the system
                   8005: The codes -256@minus{}-511 are used for reporting signals. The mapping
                   8006: from OS signal numbers to throw codes is -256@minus{}@var{signal}. The
                   8007: codes -512@minus{}-2047 are used for OS errors (for file and memory
                   8008: allocation operations). The mapping from OS error numbers to throw codes
                   8009: is -512@minus{}@code{errno}. One side effect of this mapping is that
                   8010: undefined OS errors produce a message with a strange number; e.g.,
                   8011: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
                   8012: @end table
                   8013: 
                   8014: @c =====================================================================
                   8015: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
                   8016: @section The optional Facility word set
                   8017: @c =====================================================================
                   8018: @cindex system documentation, facility words
                   8019: @cindex facility words, system documentation
                   8020: 
                   8021: @menu
                   8022: * facility-idef::               Implementation Defined Options               
                   8023: * facility-ambcond::            Ambiguous Conditions            
                   8024: @end menu
                   8025: 
                   8026: 
                   8027: @c ---------------------------------------------------------------------
                   8028: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
                   8029: @subsection Implementation Defined Options
                   8030: @c ---------------------------------------------------------------------
                   8031: @cindex implementation-defined options, facility words
                   8032: @cindex facility words, implementation-defined options
                   8033: 
                   8034: @table @i
                   8035: @item encoding of keyboard events (@code{EKEY}):
                   8036: @cindex keyboard events, encoding in @code{EKEY}
                   8037: @cindex @code{EKEY}, encoding of keyboard events
                   8038: Not yet implemented.
                   8039: 
                   8040: @item duration of a system clock tick:
                   8041: @cindex duration of a system clock tick
                   8042: @cindex clock tick duration
                   8043: System dependent. With respect to @code{MS}, the time is specified in
                   8044: microseconds. How well the OS and the hardware implement this, is
                   8045: another question.
                   8046: 
                   8047: @item repeatability to be expected from the execution of @code{MS}:
                   8048: @cindex repeatability to be expected from the execution of @code{MS}
                   8049: @cindex @code{MS}, repeatability to be expected
                   8050: System dependent. On Unix, a lot depends on load. If the system is
                   8051: lightly loaded, and the delay is short enough that Gforth does not get
                   8052: swapped out, the performance should be acceptable. Under MS-DOS and
                   8053: other single-tasking systems, it should be good.
                   8054: 
                   8055: @end table
                   8056: 
                   8057: 
                   8058: @c ---------------------------------------------------------------------
                   8059: @node facility-ambcond,  , facility-idef, The optional Facility word set
                   8060: @subsection Ambiguous conditions
                   8061: @c ---------------------------------------------------------------------
                   8062: @cindex facility words, ambiguous conditions
                   8063: @cindex ambiguous conditions, facility words
                   8064: 
                   8065: @table @i
                   8066: @item @code{AT-XY} can't be performed on user output device:
                   8067: @cindex @code{AT-XY} can't be performed on user output device
                   8068: Largely terminal dependent. No range checks are done on the arguments.
                   8069: No errors are reported. You may see some garbage appearing, you may see
                   8070: simply nothing happen.
                   8071: 
                   8072: @end table
                   8073: 
                   8074: 
                   8075: @c =====================================================================
                   8076: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
                   8077: @section The optional File-Access word set
                   8078: @c =====================================================================
                   8079: @cindex system documentation, file words
                   8080: @cindex file words, system documentation
                   8081: 
                   8082: @menu
                   8083: * file-idef::                   Implementation Defined Options
                   8084: * file-ambcond::                Ambiguous Conditions                
                   8085: @end menu
                   8086: 
                   8087: @c ---------------------------------------------------------------------
                   8088: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
                   8089: @subsection Implementation Defined Options
                   8090: @c ---------------------------------------------------------------------
                   8091: @cindex implementation-defined options, file words
                   8092: @cindex file words, implementation-defined options
                   8093: 
                   8094: @table @i
                   8095: @item file access methods used:
                   8096: @cindex file access methods used
                   8097: @code{R/O}, @code{R/W} and @code{BIN} work as you would
                   8098: expect. @code{W/O} translates into the C file opening mode @code{w} (or
                   8099: @code{wb}): The file is cleared, if it exists, and created, if it does
                   8100: not (with both @code{open-file} and @code{create-file}).  Under Unix
                   8101: @code{create-file} creates a file with 666 permissions modified by your
                   8102: umask.
                   8103: 
                   8104: @item file exceptions:
                   8105: @cindex file exceptions
                   8106: The file words do not raise exceptions (except, perhaps, memory access
                   8107: faults when you pass illegal addresses or file-ids).
                   8108: 
                   8109: @item file line terminator:
                   8110: @cindex file line terminator
                   8111: System-dependent. Gforth uses C's newline character as line
                   8112: terminator. What the actual character code(s) of this are is
                   8113: system-dependent.
                   8114: 
                   8115: @item file name format:
                   8116: @cindex file name format
                   8117: System dependent. Gforth just uses the file name format of your OS.
                   8118: 
                   8119: @item information returned by @code{FILE-STATUS}:
                   8120: @cindex @code{FILE-STATUS}, returned information
                   8121: @code{FILE-STATUS} returns the most powerful file access mode allowed
                   8122: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
                   8123: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
                   8124: along with the returned mode.
                   8125: 
                   8126: @item input file state after an exception when including source:
                   8127: @cindex exception when including source
                   8128: All files that are left via the exception are closed.
                   8129: 
                   8130: @item @var{ior} values and meaning:
                   8131: @cindex @var{ior} values and meaning
                   8132: The @var{ior}s returned by the file and memory allocation words are
                   8133: intended as throw codes. They typically are in the range
                   8134: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
                   8135: @var{ior}s is -512@minus{}@var{errno}.
                   8136: 
                   8137: @item maximum depth of file input nesting:
                   8138: @cindex maximum depth of file input nesting
                   8139: @cindex file input nesting, maximum depth
                   8140: limited by the amount of return stack, locals/TIB stack, and the number
                   8141: of open files available. This should not give you troubles.
                   8142: 
                   8143: @item maximum size of input line:
                   8144: @cindex maximum size of input line
                   8145: @cindex input line size, maximum
                   8146: @code{/line}. Currently 255.
                   8147: 
                   8148: @item methods of mapping block ranges to files:
                   8149: @cindex mapping block ranges to files
                   8150: @cindex files containing blocks
                   8151: @cindex blocks in files
                   8152: By default, blocks are accessed in the file @file{blocks.fb} in the
                   8153: current working directory. The file can be switched with @code{USE}.
                   8154: 
                   8155: @item number of string buffers provided by @code{S"}:
                   8156: @cindex @code{S"}, number of string buffers
                   8157: 1
                   8158: 
                   8159: @item size of string buffer used by @code{S"}:
                   8160: @cindex @code{S"}, size of string buffer
                   8161: @code{/line}. currently 255.
                   8162: 
                   8163: @end table
                   8164: 
                   8165: @c ---------------------------------------------------------------------
                   8166: @node file-ambcond,  , file-idef, The optional File-Access word set
                   8167: @subsection Ambiguous conditions
                   8168: @c ---------------------------------------------------------------------
                   8169: @cindex file words, ambiguous conditions
                   8170: @cindex ambiguous conditions, file words
                   8171: 
                   8172: @table @i
                   8173: @item attempting to position a file outside its boundaries:
                   8174: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
                   8175: @code{REPOSITION-FILE} is performed as usual: Afterwards,
                   8176: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
                   8177: 
                   8178: @item attempting to read from file positions not yet written:
                   8179: @cindex reading from file positions not yet written
                   8180: End-of-file, i.e., zero characters are read and no error is reported.
                   8181: 
                   8182: @item @var{file-id} is invalid (@code{INCLUDE-FILE}):
                   8183: @cindex @code{INCLUDE-FILE}, @var{file-id} is invalid 
                   8184: An appropriate exception may be thrown, but a memory fault or other
                   8185: problem is more probable.
                   8186: 
                   8187: @item I/O exception reading or closing @var{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
                   8188: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @var{file-id}
                   8189: @cindex @code{INCLUDED}, I/O exception reading or closing @var{file-id}
                   8190: The @var{ior} produced by the operation, that discovered the problem, is
                   8191: thrown.
                   8192: 
                   8193: @item named file cannot be opened (@code{INCLUDED}):
                   8194: @cindex @code{INCLUDED}, named file cannot be opened
                   8195: The @var{ior} produced by @code{open-file} is thrown.
                   8196: 
                   8197: @item requesting an unmapped block number:
                   8198: @cindex unmapped block numbers
                   8199: There are no unmapped legal block numbers. On some operating systems,
                   8200: writing a block with a large number may overflow the file system and
                   8201: have an error message as consequence.
                   8202: 
                   8203: @item using @code{source-id} when @code{blk} is non-zero:
                   8204: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
                   8205: @code{source-id} performs its function. Typically it will give the id of
                   8206: the source which loaded the block. (Better ideas?)
                   8207: 
                   8208: @end table
                   8209: 
                   8210: 
                   8211: @c =====================================================================
                   8212: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
                   8213: @section The optional Floating-Point word set
                   8214: @c =====================================================================
                   8215: @cindex system documentation, floating-point words
                   8216: @cindex floating-point words, system documentation
                   8217: 
                   8218: @menu
                   8219: * floating-idef::               Implementation Defined Options
                   8220: * floating-ambcond::            Ambiguous Conditions            
                   8221: @end menu
                   8222: 
                   8223: 
                   8224: @c ---------------------------------------------------------------------
                   8225: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
                   8226: @subsection Implementation Defined Options
                   8227: @c ---------------------------------------------------------------------
                   8228: @cindex implementation-defined options, floating-point words
                   8229: @cindex floating-point words, implementation-defined options
                   8230: 
                   8231: @table @i
                   8232: @item format and range of floating point numbers:
                   8233: @cindex format and range of floating point numbers
                   8234: @cindex floating point numbers, format and range
                   8235: System-dependent; the @code{double} type of C.
                   8236: 
                   8237: @item results of @code{REPRESENT} when @var{float} is out of range:
                   8238: @cindex  @code{REPRESENT}, results when @var{float} is out of range
                   8239: System dependent; @code{REPRESENT} is implemented using the C library
                   8240: function @code{ecvt()} and inherits its behaviour in this respect.
                   8241: 
                   8242: @item rounding or truncation of floating-point numbers:
                   8243: @cindex rounding of floating-point numbers
                   8244: @cindex truncation of floating-point numbers
                   8245: @cindex floating-point numbers, rounding or truncation
                   8246: System dependent; the rounding behaviour is inherited from the hosting C
                   8247: compiler. IEEE-FP-based (i.e., most) systems by default round to
                   8248: nearest, and break ties by rounding to even (i.e., such that the last
                   8249: bit of the mantissa is 0).
                   8250: 
                   8251: @item size of floating-point stack:
                   8252: @cindex floating-point stack size
                   8253: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
                   8254: the floating-point stack (in floats). You can specify this on startup
                   8255: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
                   8256: 
                   8257: @item width of floating-point stack:
                   8258: @cindex floating-point stack width 
                   8259: @code{1 floats}.
                   8260: 
                   8261: @end table
                   8262: 
                   8263: 
                   8264: @c ---------------------------------------------------------------------
                   8265: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
                   8266: @subsection Ambiguous conditions
                   8267: @c ---------------------------------------------------------------------
                   8268: @cindex floating-point words, ambiguous conditions
                   8269: @cindex ambiguous conditions, floating-point words
                   8270: 
                   8271: @table @i
                   8272: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
                   8273: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
                   8274: System-dependent. Typically results in a @code{-23 THROW} like other
                   8275: alignment violations.
                   8276: 
                   8277: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
                   8278: @cindex @code{f@@} used with an address that is not float aligned
                   8279: @cindex @code{f!} used with an address that is not float aligned
                   8280: System-dependent. Typically results in a @code{-23 THROW} like other
                   8281: alignment violations.
                   8282: 
                   8283: @item floating-point result out of range:
                   8284: @cindex floating-point result out of range
                   8285: System-dependent. Can result in a @code{-55 THROW} (Floating-point
                   8286: unidentified fault), or can produce a special value representing, e.g.,
                   8287: Infinity.
                   8288: 
                   8289: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
                   8290: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
                   8291: System-dependent. Typically results in an alignment fault like other
                   8292: alignment violations.
                   8293: 
                   8294: @item @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
                   8295: @cindex @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
                   8296: The floating-point number is converted into decimal nonetheless.
                   8297: 
                   8298: @item Both arguments are equal to zero (@code{FATAN2}):
                   8299: @cindex @code{FATAN2}, both arguments are equal to zero
                   8300: System-dependent. @code{FATAN2} is implemented using the C library
                   8301: function @code{atan2()}.
                   8302: 
                   8303: @item Using @code{FTAN} on an argument @var{r1} where cos(@var{r1}) is zero:
                   8304: @cindex @code{FTAN} on an argument @var{r1} where cos(@var{r1}) is zero
                   8305: System-dependent. Anyway, typically the cos of @var{r1} will not be zero
                   8306: because of small errors and the tan will be a very large (or very small)
                   8307: but finite number.
                   8308: 
                   8309: @item @var{d} cannot be presented precisely as a float in @code{D>F}:
                   8310: @cindex @code{D>F}, @var{d} cannot be presented precisely as a float
                   8311: The result is rounded to the nearest float.
                   8312: 
                   8313: @item dividing by zero:
                   8314: @cindex dividing by zero, floating-point
                   8315: @cindex floating-point dividing by zero
                   8316: @cindex floating-point unidentified fault, FP divide-by-zero
                   8317: @code{-55 throw} (Floating-point unidentified fault)
                   8318: 
                   8319: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
                   8320: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
                   8321: System dependent. On IEEE-FP based systems the number is converted into
                   8322: an infinity.
                   8323: 
                   8324: @item @var{float}<1 (@code{FACOSH}):
                   8325: @cindex @code{FACOSH}, @var{float}<1
                   8326: @cindex floating-point unidentified fault, @code{FACOSH}
                   8327: @code{-55 throw} (Floating-point unidentified fault)
                   8328: 
                   8329: @item @var{float}=<-1 (@code{FLNP1}):
                   8330: @cindex @code{FLNP1}, @var{float}=<-1
                   8331: @cindex floating-point unidentified fault, @code{FLNP1}
                   8332: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
                   8333: negative infinity is typically produced for @var{float}=-1.
                   8334: 
                   8335: @item @var{float}=<0 (@code{FLN}, @code{FLOG}):
                   8336: @cindex @code{FLN}, @var{float}=<0
                   8337: @cindex @code{FLOG}, @var{float}=<0
                   8338: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
                   8339: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
                   8340: negative infinity is typically produced for @var{float}=0.
                   8341: 
                   8342: @item @var{float}<0 (@code{FASINH}, @code{FSQRT}):
                   8343: @cindex @code{FASINH}, @var{float}<0
                   8344: @cindex @code{FSQRT}, @var{float}<0
                   8345: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
                   8346: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
                   8347: produces values for these inputs on my Linux box (Bug in the C library?)
                   8348: 
                   8349: @item |@var{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
                   8350: @cindex @code{FACOS}, |@var{float}|>1
                   8351: @cindex @code{FASIN}, |@var{float}|>1
                   8352: @cindex @code{FATANH}, |@var{float}|>1
                   8353: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
                   8354: @code{-55 throw} (Floating-point unidentified fault).
                   8355: 
                   8356: @item integer part of float cannot be represented by @var{d} in @code{F>D}:
                   8357: @cindex @code{F>D}, integer part of float cannot be represented by @var{d}
                   8358: @cindex floating-point unidentified fault, @code{F>D}
                   8359: @code{-55 throw} (Floating-point unidentified fault).
                   8360: 
                   8361: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
                   8362: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
                   8363: This does not happen.
                   8364: @end table
                   8365: 
                   8366: @c =====================================================================
                   8367: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
                   8368: @section The optional Locals word set
                   8369: @c =====================================================================
                   8370: @cindex system documentation, locals words
                   8371: @cindex locals words, system documentation
                   8372: 
                   8373: @menu
                   8374: * locals-idef::                 Implementation Defined Options                 
                   8375: * locals-ambcond::              Ambiguous Conditions              
                   8376: @end menu
                   8377: 
                   8378: 
                   8379: @c ---------------------------------------------------------------------
                   8380: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
                   8381: @subsection Implementation Defined Options
                   8382: @c ---------------------------------------------------------------------
                   8383: @cindex implementation-defined options, locals words
                   8384: @cindex locals words, implementation-defined options
                   8385: 
                   8386: @table @i
                   8387: @item maximum number of locals in a definition:
                   8388: @cindex maximum number of locals in a definition
                   8389: @cindex locals, maximum number in a definition
                   8390: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
                   8391: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
                   8392: characters. The number of locals in a definition is bounded by the size
                   8393: of locals-buffer, which contains the names of the locals.
                   8394: 
                   8395: @end table
                   8396: 
                   8397: 
                   8398: @c ---------------------------------------------------------------------
                   8399: @node locals-ambcond,  , locals-idef, The optional Locals word set
                   8400: @subsection Ambiguous conditions
                   8401: @c ---------------------------------------------------------------------
                   8402: @cindex locals words, ambiguous conditions
                   8403: @cindex ambiguous conditions, locals words
                   8404: 
                   8405: @table @i
                   8406: @item executing a named local in interpretation state:
                   8407: @cindex local in interpretation state
                   8408: @cindex Interpreting a compile-only word, for a local
                   8409: Locals have no interpretation semantics. If you try to perform the
                   8410: interpretation semantics, you will get a @code{-14 throw} somewhere
                   8411: (Interpreting a compile-only word). If you perform the compilation
                   8412: semantics, the locals access will be compiled (irrespective of state).
                   8413: 
                   8414: @item @var{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
                   8415: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
                   8416: @cindex @code{TO} on non-@code{VALUE}s and non-locals
                   8417: @cindex Invalid name argument, @code{TO}
                   8418: @code{-32 throw} (Invalid name argument)
                   8419: 
                   8420: @end table
                   8421: 
                   8422: 
                   8423: @c =====================================================================
                   8424: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
                   8425: @section The optional Memory-Allocation word set
                   8426: @c =====================================================================
                   8427: @cindex system documentation, memory-allocation words
                   8428: @cindex memory-allocation words, system documentation
                   8429: 
                   8430: @menu
                   8431: * memory-idef::                 Implementation Defined Options                 
                   8432: @end menu
                   8433: 
                   8434: 
                   8435: @c ---------------------------------------------------------------------
                   8436: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
                   8437: @subsection Implementation Defined Options
                   8438: @c ---------------------------------------------------------------------
                   8439: @cindex implementation-defined options, memory-allocation words
                   8440: @cindex memory-allocation words, implementation-defined options
                   8441: 
                   8442: @table @i
                   8443: @item values and meaning of @var{ior}:
                   8444: @cindex  @var{ior} values and meaning
                   8445: The @var{ior}s returned by the file and memory allocation words are
                   8446: intended as throw codes. They typically are in the range
                   8447: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
                   8448: @var{ior}s is -512@minus{}@var{errno}.
                   8449: 
                   8450: @end table
                   8451: 
                   8452: @c =====================================================================
                   8453: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
                   8454: @section The optional Programming-Tools word set
                   8455: @c =====================================================================
                   8456: @cindex system documentation, programming-tools words
                   8457: @cindex programming-tools words, system documentation
                   8458: 
                   8459: @menu
                   8460: * programming-idef::            Implementation Defined Options            
                   8461: * programming-ambcond::         Ambiguous Conditions         
                   8462: @end menu
                   8463: 
                   8464: 
                   8465: @c ---------------------------------------------------------------------
                   8466: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
                   8467: @subsection Implementation Defined Options
                   8468: @c ---------------------------------------------------------------------
                   8469: @cindex implementation-defined options, programming-tools words
                   8470: @cindex programming-tools words, implementation-defined options
                   8471: 
                   8472: @table @i
                   8473: @item ending sequence for input following @code{;CODE} and @code{CODE}:
                   8474: @cindex @code{;CODE} ending sequence
                   8475: @cindex @code{CODE} ending sequence
                   8476: @code{END-CODE}
                   8477: 
                   8478: @item manner of processing input following @code{;CODE} and @code{CODE}:
                   8479: @cindex @code{;CODE}, processing input
                   8480: @cindex @code{CODE}, processing input
                   8481: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
                   8482: the input is processed by the text interpreter, (starting) in interpret
                   8483: state.
                   8484: 
                   8485: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
                   8486: @cindex @code{ASSEMBLER}, search order capability
                   8487: The ANS Forth search order word set.
                   8488: 
                   8489: @item source and format of display by @code{SEE}:
                   8490: @cindex @code{SEE}, source and format of output
                   8491: The source for @code{see} is the intermediate code used by the inner
                   8492: interpreter.  The current @code{see} tries to output Forth source code
                   8493: as well as possible.
                   8494: 
                   8495: @end table
                   8496: 
                   8497: @c ---------------------------------------------------------------------
                   8498: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
                   8499: @subsection Ambiguous conditions
                   8500: @c ---------------------------------------------------------------------
                   8501: @cindex programming-tools words, ambiguous conditions
                   8502: @cindex ambiguous conditions, programming-tools words
                   8503: 
                   8504: @table @i
                   8505: 
1.21      crook    8506: @item deleting the compilation word list (@code{FORGET}):
                   8507: @cindex @code{FORGET}, deleting the compilation word list
1.1       anton    8508: Not implemented (yet).
                   8509: 
                   8510: @item fewer than @var{u}+1 items on the control flow stack (@code{CS-PICK}, @code{CS-ROLL}):
                   8511: @cindex @code{CS-PICK}, fewer than @var{u}+1 items on the control flow stack
                   8512: @cindex @code{CS-ROLL}, fewer than @var{u}+1 items on the control flow stack
                   8513: @cindex control-flow stack underflow
                   8514: This typically results in an @code{abort"} with a descriptive error
                   8515: message (may change into a @code{-22 throw} (Control structure mismatch)
                   8516: in the future). You may also get a memory access error. If you are
                   8517: unlucky, this ambiguous condition is not caught.
                   8518: 
                   8519: @item @var{name} can't be found (@code{FORGET}):
                   8520: @cindex @code{FORGET}, @var{name} can't be found
                   8521: Not implemented (yet).
                   8522: 
                   8523: @item @var{name} not defined via @code{CREATE}:
                   8524: @cindex @code{;CODE}, @var{name} not defined via @code{CREATE}
                   8525: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
                   8526: the execution semantics of the last defined word no matter how it was
                   8527: defined.
                   8528: 
                   8529: @item @code{POSTPONE} applied to @code{[IF]}:
                   8530: @cindex @code{POSTPONE} applied to @code{[IF]}
                   8531: @cindex @code{[IF]} and @code{POSTPONE}
                   8532: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
                   8533: equivalent to @code{[IF]}.
                   8534: 
                   8535: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
                   8536: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
                   8537: Continue in the same state of conditional compilation in the next outer
                   8538: input source. Currently there is no warning to the user about this.
                   8539: 
                   8540: @item removing a needed definition (@code{FORGET}):
                   8541: @cindex @code{FORGET}, removing a needed definition
                   8542: Not implemented (yet).
                   8543: 
                   8544: @end table
                   8545: 
                   8546: 
                   8547: @c =====================================================================
                   8548: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
                   8549: @section The optional Search-Order word set
                   8550: @c =====================================================================
                   8551: @cindex system documentation, search-order words
                   8552: @cindex search-order words, system documentation
                   8553: 
                   8554: @menu
                   8555: * search-idef::                 Implementation Defined Options                 
                   8556: * search-ambcond::              Ambiguous Conditions              
                   8557: @end menu
                   8558: 
                   8559: 
                   8560: @c ---------------------------------------------------------------------
                   8561: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
                   8562: @subsection Implementation Defined Options
                   8563: @c ---------------------------------------------------------------------
                   8564: @cindex implementation-defined options, search-order words
                   8565: @cindex search-order words, implementation-defined options
                   8566: 
                   8567: @table @i
                   8568: @item maximum number of word lists in search order:
                   8569: @cindex maximum number of word lists in search order
                   8570: @cindex search order, maximum depth
                   8571: @code{s" wordlists" environment? drop .}. Currently 16.
                   8572: 
                   8573: @item minimum search order:
                   8574: @cindex minimum search order
                   8575: @cindex search order, minimum
                   8576: @code{root root}.
                   8577: 
                   8578: @end table
                   8579: 
                   8580: @c ---------------------------------------------------------------------
                   8581: @node search-ambcond,  , search-idef, The optional Search-Order word set
                   8582: @subsection Ambiguous conditions
                   8583: @c ---------------------------------------------------------------------
                   8584: @cindex search-order words, ambiguous conditions
                   8585: @cindex ambiguous conditions, search-order words
                   8586: 
                   8587: @table @i
1.21      crook    8588: @item changing the compilation word list (during compilation):
                   8589: @cindex changing the compilation word list (during compilation)
                   8590: @cindex compilation word list, change before definition ends
                   8591: The word is entered into the word list that was the compilation word list
1.1       anton    8592: at the start of the definition. Any changes to the name field (e.g.,
                   8593: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
                   8594: are applied to the latest defined word (as reported by @code{last} or
1.21      crook    8595: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1       anton    8596: 
                   8597: @item search order empty (@code{previous}):
                   8598: @cindex @code{previous}, search order empty
                   8599: @cindex Vocstack empty, @code{previous}
                   8600: @code{abort" Vocstack empty"}.
                   8601: 
                   8602: @item too many word lists in search order (@code{also}):
                   8603: @cindex @code{also}, too many word lists in search order
                   8604: @cindex Vocstack full, @code{also}
                   8605: @code{abort" Vocstack full"}.
                   8606: 
                   8607: @end table
                   8608: 
                   8609: @c ***************************************************************
                   8610: @node Model, Integrating Gforth, ANS conformance, Top
                   8611: @chapter Model
                   8612: 
                   8613: This chapter has yet to be written. It will contain information, on
                   8614: which internal structures you can rely.
                   8615: 
                   8616: @c ***************************************************************
                   8617: @node Integrating Gforth, Emacs and Gforth, Model, Top
                   8618: @chapter Integrating Gforth into C programs
                   8619: 
                   8620: This is not yet implemented.
                   8621: 
                   8622: Several people like to use Forth as scripting language for applications
                   8623: that are otherwise written in C, C++, or some other language.
                   8624: 
                   8625: The Forth system ATLAST provides facilities for embedding it into
                   8626: applications; unfortunately it has several disadvantages: most
                   8627: importantly, it is not based on ANS Forth, and it is apparently dead
                   8628: (i.e., not developed further and not supported). The facilities
1.21      crook    8629: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1       anton    8630: making the switch should not be hard.
                   8631: 
                   8632: We also tried to design the interface such that it can easily be
                   8633: implemented by other Forth systems, so that we may one day arrive at a
                   8634: standardized interface. Such a standard interface would allow you to
                   8635: replace the Forth system without having to rewrite C code.
                   8636: 
                   8637: You embed the Gforth interpreter by linking with the library
                   8638: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
                   8639: global symbols in this library that belong to the interface, have the
                   8640: prefix @code{forth_}. (Global symbols that are used internally have the
                   8641: prefix @code{gforth_}).
                   8642: 
                   8643: You can include the declarations of Forth types and the functions and
                   8644: variables of the interface with @code{#include <forth.h>}.
                   8645: 
                   8646: Types.
                   8647: 
                   8648: Variables.
                   8649: 
                   8650: Data and FP Stack pointer. Area sizes.
                   8651: 
                   8652: functions.
                   8653: 
                   8654: forth_init(imagefile)
                   8655: forth_evaluate(string) exceptions?
                   8656: forth_goto(address) (or forth_execute(xt)?)
                   8657: forth_continue() (a corountining mechanism)
                   8658: 
                   8659: Adding primitives.
                   8660: 
                   8661: No checking.
                   8662: 
                   8663: Signals?
                   8664: 
                   8665: Accessing the Stacks
                   8666: 
                   8667: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
                   8668: @chapter Emacs and Gforth
                   8669: @cindex Emacs and Gforth
                   8670: 
                   8671: @cindex @file{gforth.el}
                   8672: @cindex @file{forth.el}
                   8673: @cindex Rydqvist, Goran
                   8674: @cindex comment editing commands
                   8675: @cindex @code{\}, editing with Emacs
                   8676: @cindex debug tracer editing commands
                   8677: @cindex @code{~~}, removal with Emacs
                   8678: @cindex Forth mode in Emacs
                   8679: Gforth comes with @file{gforth.el}, an improved version of
                   8680: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
                   8681: improvements are a better (but still not perfect) handling of
                   8682: indentation. I have also added comment paragraph filling (@kbd{M-q}),
                   8683: commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) regions and
                   8684: removing debugging tracers (@kbd{C-x ~}, @pxref{Debugging}). I left the
                   8685: stuff I do not use alone, even though some of it only makes sense for
                   8686: TILE. To get a description of these features, enter Forth mode and type
                   8687: @kbd{C-h m}.
                   8688: 
                   8689: @cindex source location of error or debugging output in Emacs
                   8690: @cindex error output, finding the source location in Emacs
                   8691: @cindex debugging output, finding the source location in Emacs
                   8692: In addition, Gforth supports Emacs quite well: The source code locations
                   8693: given in error messages, debugging output (from @code{~~}) and failed
                   8694: assertion messages are in the right format for Emacs' compilation mode
                   8695: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
                   8696: Manual}) so the source location corresponding to an error or other
                   8697: message is only a few keystrokes away (@kbd{C-x `} for the next error,
                   8698: @kbd{C-c C-c} for the error under the cursor).
                   8699: 
                   8700: @cindex @file{TAGS} file
                   8701: @cindex @file{etags.fs}
                   8702: @cindex viewing the source of a word in Emacs
                   8703: Also, if you @code{include} @file{etags.fs}, a new @file{TAGS} file
                   8704: (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) will be produced that
                   8705: contains the definitions of all words defined afterwards. You can then
                   8706: find the source for a word using @kbd{M-.}. Note that emacs can use
                   8707: several tags files at the same time (e.g., one for the Gforth sources
                   8708: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
                   8709: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
                   8710: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
                   8711: @file{/usr/local/share/gforth/0.2.0/TAGS}).
                   8712: 
                   8713: @cindex @file{.emacs}
                   8714: To get all these benefits, add the following lines to your @file{.emacs}
                   8715: file:
                   8716: 
                   8717: @example
                   8718: (autoload 'forth-mode "gforth.el")
                   8719: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
                   8720: @end example
                   8721: 
                   8722: @node Image Files, Engine, Emacs and Gforth, Top
                   8723: @chapter Image Files
                   8724: @cindex image files
                   8725: @cindex @code{.fi} files
                   8726: @cindex precompiled Forth code
                   8727: @cindex dictionary in persistent form
                   8728: @cindex persistent form of dictionary
                   8729: 
                   8730: An image file is a file containing an image of the Forth dictionary,
                   8731: i.e., compiled Forth code and data residing in the dictionary.  By
                   8732: convention, we use the extension @code{.fi} for image files.
                   8733: 
                   8734: @menu
1.18      anton    8735: * Image Licensing Issues::      Distribution terms for images.
                   8736: * Image File Background::       Why have image files?
                   8737: * Non-Relocatable Image Files::  don't always work.
                   8738: * Data-Relocatable Image Files::  are better.
1.1       anton    8739: * Fully Relocatable Image Files::  better yet.
1.18      anton    8740: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
                   8741: * Running Image Files::         @code{gforth -i @var{file}} or @var{file}.
                   8742: * Modifying the Startup Sequence::  and turnkey applications.
1.1       anton    8743: @end menu
                   8744: 
1.18      anton    8745: @node Image Licensing Issues, Image File Background, Image Files, Image Files
                   8746: @section Image Licensing Issues
                   8747: @cindex license for images
                   8748: @cindex image license
                   8749: 
                   8750: An image created with @code{gforthmi} (@pxref{gforthmi}) or
                   8751: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
                   8752: original image; i.e., according to copyright law it is a derived work of
                   8753: the original image.
                   8754: 
                   8755: Since Gforth is distributed under the GNU GPL, the newly created image
                   8756: falls under the GNU GPL, too. In particular, this means that if you
                   8757: distribute the image, you have to make all of the sources for the image
                   8758: available, including those you wrote.  For details see @ref{License, ,
                   8759: GNU General Public License (Section 3)}.
                   8760: 
                   8761: If you create an image with @code{cross} (@pxref{cross.fs}), the image
                   8762: contains only code compiled from the sources you gave it; if none of
                   8763: these sources is under the GPL, the terms discussed above do not apply
                   8764: to the image. However, if your image needs an engine (a gforth binary)
                   8765: that is under the GPL, you should make sure that you distribute both in
                   8766: a way that is at most a @emph{mere aggregation}, if you don't want the
                   8767: terms of the GPL to apply to the image.
                   8768: 
                   8769: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1       anton    8770: @section Image File Background
                   8771: @cindex image file background
                   8772: 
                   8773: Our Forth system consists not only of primitives, but also of
                   8774: definitions written in Forth. Since the Forth compiler itself belongs to
                   8775: those definitions, it is not possible to start the system with the
                   8776: primitives and the Forth source alone. Therefore we provide the Forth
                   8777: code as an image file in nearly executable form. At the start of the
                   8778: system a C routine loads the image file into memory, optionally
                   8779: relocates the addresses, then sets up the memory (stacks etc.) according
                   8780: to information in the image file, and starts executing Forth code.
                   8781: 
                   8782: The image file variants represent different compromises between the
                   8783: goals of making it easy to generate image files and making them
                   8784: portable.
                   8785: 
                   8786: @cindex relocation at run-time
                   8787: Win32Forth 3.4 and Mitch Bradleys @code{cforth} use relocation at
                   8788: run-time. This avoids many of the complications discussed below (image
                   8789: files are data relocatable without further ado), but costs performance
                   8790: (one addition per memory access).
                   8791: 
                   8792: @cindex relocation at load-time
                   8793: By contrast, our loader performs relocation at image load time. The
                   8794: loader also has to replace tokens standing for primitive calls with the
                   8795: appropriate code-field addresses (or code addresses in the case of
                   8796: direct threading).
                   8797: 
                   8798: There are three kinds of image files, with different degrees of
                   8799: relocatability: non-relocatable, data-relocatable, and fully relocatable
                   8800: image files.
                   8801: 
                   8802: @cindex image file loader
                   8803: @cindex relocating loader
                   8804: @cindex loader for image files
                   8805: These image file variants have several restrictions in common; they are
                   8806: caused by the design of the image file loader:
                   8807: 
                   8808: @itemize @bullet
                   8809: @item
                   8810: There is only one segment; in particular, this means, that an image file
                   8811: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
                   8812: them). And the contents of the stacks are not represented, either.
                   8813: 
                   8814: @item
                   8815: The only kinds of relocation supported are: adding the same offset to
                   8816: all cells that represent data addresses; and replacing special tokens
                   8817: with code addresses or with pieces of machine code.
                   8818: 
                   8819: If any complex computations involving addresses are performed, the
                   8820: results cannot be represented in the image file. Several applications that
                   8821: use such computations come to mind:
                   8822: @itemize @minus
                   8823: @item
                   8824: Hashing addresses (or data structures which contain addresses) for table
                   8825: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
                   8826: purpose, you will have no problem, because the hash tables are
                   8827: recomputed automatically when the system is started. If you use your own
                   8828: hash tables, you will have to do something similar.
                   8829: 
                   8830: @item
                   8831: There's a cute implementation of doubly-linked lists that uses
                   8832: @code{XOR}ed addresses. You could represent such lists as singly-linked
                   8833: in the image file, and restore the doubly-linked representation on
                   8834: startup.@footnote{In my opinion, though, you should think thrice before
                   8835: using a doubly-linked list (whatever implementation).}
                   8836: 
                   8837: @item
                   8838: The code addresses of run-time routines like @code{docol:} cannot be
                   8839: represented in the image file (because their tokens would be replaced by
                   8840: machine code in direct threaded implementations). As a workaround,
                   8841: compute these addresses at run-time with @code{>code-address} from the
                   8842: executions tokens of appropriate words (see the definitions of
                   8843: @code{docol:} and friends in @file{kernel.fs}).
                   8844: 
                   8845: @item
                   8846: On many architectures addresses are represented in machine code in some
                   8847: shifted or mangled form. You cannot put @code{CODE} words that contain
                   8848: absolute addresses in this form in a relocatable image file. Workarounds
                   8849: are representing the address in some relative form (e.g., relative to
                   8850: the CFA, which is present in some register), or loading the address from
                   8851: a place where it is stored in a non-mangled form.
                   8852: @end itemize
                   8853: @end itemize
                   8854: 
                   8855: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
                   8856: @section Non-Relocatable Image Files
                   8857: @cindex non-relocatable image files
                   8858: @cindex image files, non-relocatable
                   8859: 
                   8860: These files are simple memory dumps of the dictionary. They are specific
                   8861: to the executable (i.e., @file{gforth} file) they were created
                   8862: with. What's worse, they are specific to the place on which the
                   8863: dictionary resided when the image was created. Now, there is no
                   8864: guarantee that the dictionary will reside at the same place the next
                   8865: time you start Gforth, so there's no guarantee that a non-relocatable
                   8866: image will work the next time (Gforth will complain instead of crashing,
                   8867: though).
                   8868: 
                   8869: You can create a non-relocatable image file with
                   8870: 
                   8871: doc-savesystem
                   8872: 
                   8873: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
                   8874: @section Data-Relocatable Image Files
                   8875: @cindex data-relocatable image files
                   8876: @cindex image files, data-relocatable
                   8877: 
                   8878: These files contain relocatable data addresses, but fixed code addresses
                   8879: (instead of tokens). They are specific to the executable (i.e.,
                   8880: @file{gforth} file) they were created with. For direct threading on some
                   8881: architectures (e.g., the i386), data-relocatable images do not work. You
                   8882: get a data-relocatable image, if you use @file{gforthmi} with a
                   8883: Gforth binary that is not doubly indirect threaded (@pxref{Fully
                   8884: Relocatable Image Files}).
                   8885: 
                   8886: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
                   8887: @section Fully Relocatable Image Files
                   8888: @cindex fully relocatable image files
                   8889: @cindex image files, fully relocatable
                   8890: 
                   8891: @cindex @file{kern*.fi}, relocatability
                   8892: @cindex @file{gforth.fi}, relocatability
                   8893: These image files have relocatable data addresses, and tokens for code
                   8894: addresses. They can be used with different binaries (e.g., with and
                   8895: without debugging) on the same machine, and even across machines with
                   8896: the same data formats (byte order, cell size, floating point
                   8897: format). However, they are usually specific to the version of Gforth
                   8898: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
                   8899: are fully relocatable.
                   8900: 
                   8901: There are two ways to create a fully relocatable image file:
                   8902: 
                   8903: @menu
                   8904: * gforthmi::            The normal way
                   8905: * cross.fs::                    The hard way
                   8906: @end menu
                   8907: 
                   8908: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
                   8909: @subsection @file{gforthmi}
                   8910: @cindex @file{comp-i.fs}
                   8911: @cindex @file{gforthmi}
                   8912: 
                   8913: You will usually use @file{gforthmi}. If you want to create an
                   8914: image @var{file} that contains everything you would load by invoking
                   8915: Gforth with @code{gforth @var{options}}, you simply say
                   8916: @example
                   8917: gforthmi @var{file} @var{options}
                   8918: @end example
                   8919: 
                   8920: E.g., if you want to create an image @file{asm.fi} that has the file
                   8921: @file{asm.fs} loaded in addition to the usual stuff, you could do it
                   8922: like this:
                   8923: 
                   8924: @example
                   8925: gforthmi asm.fi asm.fs
                   8926: @end example
                   8927: 
                   8928: @file{gforthmi} works like this: It produces two non-relocatable
                   8929: images for different addresses and then compares them. Its output
                   8930: reflects this: first you see the output (if any) of the two Gforth
                   8931: invocations that produce the nonrelocatable image files, then you see
                   8932: the output of the comparing program: It displays the offset used for
                   8933: data addresses and the offset used for code addresses;
                   8934: moreover, for each cell that cannot be represented correctly in the
                   8935: image files, it displays a line like the following one:
                   8936: 
                   8937: @example
                   8938:      78DC         BFFFFA50         BFFFFA40
                   8939: @end example
                   8940: 
                   8941: This means that at offset $78dc from @code{forthstart}, one input image
                   8942: contains $bffffa50, and the other contains $bffffa40. Since these cells
                   8943: cannot be represented correctly in the output image, you should examine
                   8944: these places in the dictionary and verify that these cells are dead
                   8945: (i.e., not read before they are written).
                   8946: 
                   8947: @cindex @code{savesystem} during @file{gforthmi}
                   8948: @cindex @code{bye} during @file{gforthmi}
                   8949: @cindex doubly indirect threaded code
                   8950: @cindex environment variable @code{GFORTHD}
                   8951: @cindex @code{GFORTHD} environment variable
                   8952: @cindex @code{gforth-ditc}
                   8953: There are a few wrinkles: After processing the passed @var{options}, the
                   8954: words @code{savesystem} and @code{bye} must be visible. A special doubly
                   8955: indirect threaded version of the @file{gforth} executable is used for
                   8956: creating the nonrelocatable images; you can pass the exact filename of
                   8957: this executable through the environment variable @code{GFORTHD}
                   8958: (default: @file{gforth-ditc}); if you pass a version that is not doubly
                   8959: indirect threaded, you will not get a fully relocatable image, but a
                   8960: data-relocatable image (because there is no code address offset).
                   8961: 
                   8962: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
                   8963: @subsection @file{cross.fs}
                   8964: @cindex @file{cross.fs}
                   8965: @cindex cross-compiler
                   8966: @cindex metacompiler
                   8967: 
                   8968: You can also use @code{cross}, a batch compiler that accepts a Forth-like
                   8969: programming language. This @code{cross} language has to be documented
                   8970: yet.
                   8971: 
                   8972: @cindex target compiler
                   8973: @code{cross} also allows you to create image files for machines with
                   8974: different data sizes and data formats than the one used for generating
                   8975: the image file. You can also use it to create an application image that
                   8976: does not contain a Forth compiler. These features are bought with
                   8977: restrictions and inconveniences in programming. E.g., addresses have to
                   8978: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
                   8979: order to make the code relocatable.
                   8980: 
                   8981: 
                   8982: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
                   8983: @section Stack and Dictionary Sizes
                   8984: @cindex image file, stack and dictionary sizes
                   8985: @cindex dictionary size default
                   8986: @cindex stack size default
                   8987: 
                   8988: If you invoke Gforth with a command line flag for the size
                   8989: (@pxref{Invoking Gforth}), the size you specify is stored in the
                   8990: dictionary. If you save the dictionary with @code{savesystem} or create
                   8991: an image with @file{gforthmi}, this size will become the default
                   8992: for the resulting image file. E.g., the following will create a
1.21      crook    8993: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1       anton    8994: 
                   8995: @example
                   8996: gforthmi gforth.fi -m 1M
                   8997: @end example
                   8998: 
                   8999: In other words, if you want to set the default size for the dictionary
                   9000: and the stacks of an image, just invoke @file{gforthmi} with the
                   9001: appropriate options when creating the image.
                   9002: 
                   9003: @cindex stack size, cache-friendly
                   9004: Note: For cache-friendly behaviour (i.e., good performance), you should
                   9005: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
                   9006: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
                   9007: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
                   9008: 
                   9009: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
                   9010: @section Running Image Files
                   9011: @cindex running image files
                   9012: @cindex invoking image files
                   9013: @cindex image file invocation
                   9014: 
                   9015: @cindex -i, invoke image file
                   9016: @cindex --image file, invoke image file
                   9017: You can invoke Gforth with an image file @var{image} instead of the
                   9018: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
                   9019: @example
                   9020: gforth -i @var{image}
                   9021: @end example
                   9022: 
                   9023: @cindex executable image file
                   9024: @cindex image files, executable
                   9025: If your operating system supports starting scripts with a line of the
                   9026: form @code{#! ...}, you just have to type the image file name to start
                   9027: Gforth with this image file (note that the file extension @code{.fi} is
                   9028: just a convention). I.e., to run Gforth with the image file @var{image},
                   9029: you can just type @var{image} instead of @code{gforth -i @var{image}}.
                   9030: 
                   9031: doc-#!
                   9032: 
                   9033: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
                   9034: @section Modifying the Startup Sequence
                   9035: @cindex startup sequence for image file
                   9036: @cindex image file initialization sequence
                   9037: @cindex initialization sequence of image file
                   9038: 
                   9039: You can add your own initialization to the startup sequence through the
                   9040: deferred word
                   9041: 
                   9042: doc-'cold
                   9043: 
                   9044: @code{'cold} is invoked just before the image-specific command line
                   9045: processing (by default, loading files and evaluating (@code{-e}) strings)
                   9046: starts.
                   9047: 
                   9048: A sequence for adding your initialization usually looks like this:
                   9049: 
                   9050: @example
                   9051: :noname
                   9052:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
                   9053:     ... \ your stuff
                   9054: ; IS 'cold
                   9055: @end example
                   9056: 
                   9057: @cindex turnkey image files
                   9058: @cindex image files, turnkey applications
                   9059: You can make a turnkey image by letting @code{'cold} execute a word
                   9060: (your turnkey application) that never returns; instead, it exits Gforth
                   9061: via @code{bye} or @code{throw}.
                   9062: 
                   9063: @cindex command-line arguments, access
                   9064: @cindex arguments on the command line, access
                   9065: You can access the (image-specific) command-line arguments through the
                   9066: variables @code{argc} and @code{argv}. @code{arg} provides conventient
                   9067: access to @code{argv}.
                   9068: 
                   9069: doc-argc
                   9070: doc-argv
                   9071: doc-arg
                   9072: 
                   9073: If @code{'cold} exits normally, Gforth processes the command-line
                   9074: arguments as files to be loaded and strings to be evaluated.  Therefore,
                   9075: @code{'cold} should remove the arguments it has used in this case.
                   9076: 
                   9077: @c ******************************************************************
1.13      pazsan   9078: @node Engine, Binding to System Library, Image Files, Top
1.1       anton    9079: @chapter Engine
                   9080: @cindex engine
                   9081: @cindex virtual machine
                   9082: 
                   9083: Reading this section is not necessary for programming with Gforth. It
                   9084: may be helpful for finding your way in the Gforth sources.
                   9085: 
                   9086: The ideas in this section have also been published in the papers
                   9087: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
                   9088: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
                   9089: Ertl, presented at EuroForth '93; the latter is available at
                   9090: @*@url{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
                   9091: 
                   9092: @menu
                   9093: * Portability::                 
                   9094: * Threading::                   
                   9095: * Primitives::                  
                   9096: * Performance::                 
                   9097: @end menu
                   9098: 
                   9099: @node Portability, Threading, Engine, Engine
                   9100: @section Portability
                   9101: @cindex engine portability
                   9102: 
                   9103: One of the main goals of the effort is availability across a wide range
                   9104: of personal machines. fig-Forth, and, to a lesser extent, F83, achieved
                   9105: this goal by manually coding the engine in assembly language for several
                   9106: then-popular processors. This approach is very labor-intensive and the
                   9107: results are short-lived due to progress in computer architecture.
                   9108: 
                   9109: @cindex C, using C for the engine
                   9110: Others have avoided this problem by coding in C, e.g., Mitch Bradley
                   9111: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
                   9112: particularly popular for UNIX-based Forths due to the large variety of
                   9113: architectures of UNIX machines. Unfortunately an implementation in C
                   9114: does not mix well with the goals of efficiency and with using
                   9115: traditional techniques: Indirect or direct threading cannot be expressed
                   9116: in C, and switch threading, the fastest technique available in C, is
                   9117: significantly slower. Another problem with C is that it is very
                   9118: cumbersome to express double integer arithmetic.
                   9119: 
                   9120: @cindex GNU C for the engine
                   9121: @cindex long long
                   9122: Fortunately, there is a portable language that does not have these
                   9123: limitations: GNU C, the version of C processed by the GNU C compiler
                   9124: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
                   9125: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
                   9126: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
                   9127: threading possible, its @code{long long} type (@pxref{Long Long, ,
                   9128: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
                   9129: double numbers@footnote{Unfortunately, long longs are not implemented
                   9130: properly on all machines (e.g., on alpha-osf1, long longs are only 64
                   9131: bits, the same size as longs (and pointers), but they should be twice as
1.4       anton    9132: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1       anton    9133: C Manual}). So, we had to implement doubles in C after all. Still, on
                   9134: most machines we can use long longs and achieve better performance than
                   9135: with the emulation package.}. GNU C is available for free on all
                   9136: important (and many unimportant) UNIX machines, VMS, 80386s running
                   9137: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
                   9138: on all these machines.
                   9139: 
                   9140: Writing in a portable language has the reputation of producing code that
                   9141: is slower than assembly. For our Forth engine we repeatedly looked at
                   9142: the code produced by the compiler and eliminated most compiler-induced
                   9143: inefficiencies by appropriate changes in the source code.
                   9144: 
                   9145: @cindex explicit register declarations
                   9146: @cindex --enable-force-reg, configuration flag
                   9147: @cindex -DFORCE_REG
                   9148: However, register allocation cannot be portably influenced by the
                   9149: programmer, leading to some inefficiencies on register-starved
                   9150: machines. We use explicit register declarations (@pxref{Explicit Reg
                   9151: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
                   9152: improve the speed on some machines. They are turned on by using the
                   9153: configuration flag @code{--enable-force-reg} (@code{gcc} switch
                   9154: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
                   9155: machine, but also on the compiler version: On some machines some
                   9156: compiler versions produce incorrect code when certain explicit register
                   9157: declarations are used. So by default @code{-DFORCE_REG} is not used.
                   9158: 
                   9159: @node Threading, Primitives, Portability, Engine
                   9160: @section Threading
                   9161: @cindex inner interpreter implementation
                   9162: @cindex threaded code implementation
                   9163: 
                   9164: @cindex labels as values
                   9165: GNU C's labels as values extension (available since @code{gcc-2.0},
                   9166: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
                   9167: makes it possible to take the address of @var{label} by writing
                   9168: @code{&&@var{label}}.  This address can then be used in a statement like
                   9169: @code{goto *@var{address}}. I.e., @code{goto *&&x} is the same as
                   9170: @code{goto x}.
                   9171: 
                   9172: @cindex NEXT, indirect threaded
                   9173: @cindex indirect threaded inner interpreter
                   9174: @cindex inner interpreter, indirect threaded
                   9175: With this feature an indirect threaded NEXT looks like:
                   9176: @example
                   9177: cfa = *ip++;
                   9178: ca = *cfa;
                   9179: goto *ca;
                   9180: @end example
                   9181: @cindex instruction pointer
                   9182: For those unfamiliar with the names: @code{ip} is the Forth instruction
                   9183: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
                   9184: execution token and points to the code field of the next word to be
                   9185: executed; The @code{ca} (code address) fetched from there points to some
                   9186: executable code, e.g., a primitive or the colon definition handler
                   9187: @code{docol}.
                   9188: 
                   9189: @cindex NEXT, direct threaded
                   9190: @cindex direct threaded inner interpreter
                   9191: @cindex inner interpreter, direct threaded
                   9192: Direct threading is even simpler:
                   9193: @example
                   9194: ca = *ip++;
                   9195: goto *ca;
                   9196: @end example
                   9197: 
                   9198: Of course we have packaged the whole thing neatly in macros called
                   9199: @code{NEXT} and @code{NEXT1} (the part of NEXT after fetching the cfa).
                   9200: 
                   9201: @menu
                   9202: * Scheduling::                  
                   9203: * Direct or Indirect Threaded?::  
                   9204: * DOES>::                       
                   9205: @end menu
                   9206: 
                   9207: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
                   9208: @subsection Scheduling
                   9209: @cindex inner interpreter optimization
                   9210: 
                   9211: There is a little complication: Pipelined and superscalar processors,
                   9212: i.e., RISC and some modern CISC machines can process independent
                   9213: instructions while waiting for the results of an instruction. The
                   9214: compiler usually reorders (schedules) the instructions in a way that
                   9215: achieves good usage of these delay slots. However, on our first tries
                   9216: the compiler did not do well on scheduling primitives. E.g., for
                   9217: @code{+} implemented as
                   9218: @example
                   9219: n=sp[0]+sp[1];
                   9220: sp++;
                   9221: sp[0]=n;
                   9222: NEXT;
                   9223: @end example
                   9224: the NEXT comes strictly after the other code, i.e., there is nearly no
                   9225: scheduling. After a little thought the problem becomes clear: The
1.21      crook    9226: compiler cannot know that @code{sp} and @code{ip} point to different
                   9227: addresses (and the version of @code{gcc} we used would not know it even
                   9228: if it was possible), so it could not move the load of the cfa above the
                   9229: store to the TOS. Indeed the pointers could be the same, if code on or
                   9230: very near the top of stack were executed. In the interest of speed we
                   9231: chose to forbid this probably unused ``feature'' and helped the compiler
                   9232: in scheduling: NEXT is divided into the loading part (@code{NEXT_P1})
                   9233: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1       anton    9234: @example
                   9235: n=sp[0]+sp[1];
                   9236: sp++;
                   9237: NEXT_P1;
                   9238: sp[0]=n;
                   9239: NEXT_P2;
                   9240: @end example
                   9241: This can be scheduled optimally by the compiler.
                   9242: 
                   9243: This division can be turned off with the switch @code{-DCISC_NEXT}. This
                   9244: switch is on by default on machines that do not profit from scheduling
                   9245: (e.g., the 80386), in order to preserve registers.
                   9246: 
                   9247: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
                   9248: @subsection Direct or Indirect Threaded?
                   9249: @cindex threading, direct or indirect?
                   9250: 
                   9251: @cindex -DDIRECT_THREADED
                   9252: Both! After packaging the nasty details in macro definitions we
                   9253: realized that we could switch between direct and indirect threading by
                   9254: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
                   9255: defining a few machine-specific macros for the direct-threading case.
                   9256: On the Forth level we also offer access words that hide the
                   9257: differences between the threading methods (@pxref{Threading Words}).
                   9258: 
                   9259: Indirect threading is implemented completely machine-independently.
                   9260: Direct threading needs routines for creating jumps to the executable
1.21      crook    9261: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
                   9262: machine-dependent, but they do not amount to many source lines. Therefore,
                   9263: even porting direct threading to a new machine requires little effort.
1.1       anton    9264: 
                   9265: @cindex --enable-indirect-threaded, configuration flag
                   9266: @cindex --enable-direct-threaded, configuration flag
                   9267: The default threading method is machine-dependent. You can enforce a
                   9268: specific threading method when building Gforth with the configuration
                   9269: flag @code{--enable-direct-threaded} or
                   9270: @code{--enable-indirect-threaded}. Note that direct threading is not
                   9271: supported on all machines.
                   9272: 
                   9273: @node DOES>,  , Direct or Indirect Threaded?, Threading
                   9274: @subsection DOES>
                   9275: @cindex @code{DOES>} implementation
                   9276: 
                   9277: @cindex dodoes routine
                   9278: @cindex DOES-code
                   9279: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
                   9280: the chunk of code executed by every word defined by a
                   9281: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
                   9282: the Forth code to be executed, i.e. the code after the
                   9283: @code{DOES>} (the DOES-code)? There are two solutions:
                   9284: 
1.21      crook    9285: In fig-Forth the code field points directly to the @code{dodoes} and the
1.1       anton    9286: DOES-code address is stored in the cell after the code address (i.e. at
                   9287: @code{@var{cfa} cell+}). It may seem that this solution is illegal in
                   9288: the Forth-79 and all later standards, because in fig-Forth this address
                   9289: lies in the body (which is illegal in these standards). However, by
                   9290: making the code field larger for all words this solution becomes legal
                   9291: again. We use this approach for the indirect threaded version and for
                   9292: direct threading on some machines. Leaving a cell unused in most words
                   9293: is a bit wasteful, but on the machines we are targeting this is hardly a
                   9294: problem. The other reason for having a code field size of two cells is
                   9295: to avoid having different image files for direct and indirect threaded
                   9296: systems (direct threaded systems require two-cell code fields on many
                   9297: machines).
                   9298: 
                   9299: @cindex DOES-handler
                   9300: The other approach is that the code field points or jumps to the cell
                   9301: after @code{DOES}. In this variant there is a jump to @code{dodoes} at
                   9302: this address (the DOES-handler). @code{dodoes} can then get the
                   9303: DOES-code address by computing the code address, i.e., the address of
                   9304: the jump to dodoes, and add the length of that jump field. A variant of
                   9305: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
                   9306: return address (which can be found in the return register on RISCs) is
                   9307: the DOES-code address. Since the two cells available in the code field
                   9308: are used up by the jump to the code address in direct threading on many
                   9309: architectures, we use this approach for direct threading on these
                   9310: architectures. We did not want to add another cell to the code field.
                   9311: 
                   9312: @node Primitives, Performance, Threading, Engine
                   9313: @section Primitives
                   9314: @cindex primitives, implementation
                   9315: @cindex virtual machine instructions, implementation
                   9316: 
                   9317: @menu
                   9318: * Automatic Generation::        
                   9319: * TOS Optimization::            
                   9320: * Produced code::               
                   9321: @end menu
                   9322: 
                   9323: @node Automatic Generation, TOS Optimization, Primitives, Primitives
                   9324: @subsection Automatic Generation
                   9325: @cindex primitives, automatic generation
                   9326: 
                   9327: @cindex @file{prims2x.fs}
                   9328: Since the primitives are implemented in a portable language, there is no
                   9329: longer any need to minimize the number of primitives. On the contrary,
                   9330: having many primitives has an advantage: speed. In order to reduce the
                   9331: number of errors in primitives and to make programming them easier, we
                   9332: provide a tool, the primitive generator (@file{prims2x.fs}), that
                   9333: automatically generates most (and sometimes all) of the C code for a
                   9334: primitive from the stack effect notation.  The source for a primitive
                   9335: has the following form:
                   9336: 
                   9337: @cindex primitive source format
                   9338: @format
                   9339: @var{Forth-name}       @var{stack-effect}      @var{category}  [@var{pronounc.}]
                   9340: [@code{""}@var{glossary entry}@code{""}]
                   9341: @var{C code}
                   9342: [@code{:}
                   9343: @var{Forth code}]
                   9344: @end format
                   9345: 
                   9346: The items in brackets are optional. The category and glossary fields
                   9347: are there for generating the documentation, the Forth code is there
                   9348: for manual implementations on machines without GNU C. E.g., the source
                   9349: for the primitive @code{+} is:
                   9350: @example
                   9351: +    n1 n2 -- n    core    plus
                   9352: n = n1+n2;
                   9353: @end example
                   9354: 
                   9355: This looks like a specification, but in fact @code{n = n1+n2} is C
                   9356: code. Our primitive generation tool extracts a lot of information from
                   9357: the stack effect notations@footnote{We use a one-stack notation, even
                   9358: though we have separate data and floating-point stacks; The separate
                   9359: notation can be generated easily from the unified notation.}: The number
                   9360: of items popped from and pushed on the stack, their type, and by what
                   9361: name they are referred to in the C code. It then generates a C code
                   9362: prelude and postlude for each primitive. The final C code for @code{+}
                   9363: looks like this:
                   9364: 
                   9365: @example
                   9366: I_plus:        /* + ( n1 n2 -- n ) */  /* label, stack effect */
                   9367: /*  */                          /* documentation */
                   9368: @{
                   9369: DEF_CA                          /* definition of variable ca (indirect threading) */
                   9370: Cell n1;                        /* definitions of variables */
                   9371: Cell n2;
                   9372: Cell n;
                   9373: n1 = (Cell) sp[1];              /* input */
                   9374: n2 = (Cell) TOS;
                   9375: sp += 1;                        /* stack adjustment */
                   9376: NAME("+")                       /* debugging output (with -DDEBUG) */
                   9377: @{
                   9378: n = n1+n2;                      /* C code taken from the source */
                   9379: @}
                   9380: NEXT_P1;                        /* NEXT part 1 */
                   9381: TOS = (Cell)n;                  /* output */
                   9382: NEXT_P2;                        /* NEXT part 2 */
                   9383: @}
                   9384: @end example
                   9385: 
                   9386: This looks long and inefficient, but the GNU C compiler optimizes quite
                   9387: well and produces optimal code for @code{+} on, e.g., the R3000 and the
                   9388: HP RISC machines: Defining the @code{n}s does not produce any code, and
                   9389: using them as intermediate storage also adds no cost.
                   9390: 
                   9391: There are also other optimizations, that are not illustrated by this
                   9392: example: Assignments between simple variables are usually for free (copy
                   9393: propagation). If one of the stack items is not used by the primitive
                   9394: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
                   9395: (dead code elimination). On the other hand, there are some things that
                   9396: the compiler does not do, therefore they are performed by
                   9397: @file{prims2x.fs}: The compiler does not optimize code away that stores
                   9398: a stack item to the place where it just came from (e.g., @code{over}).
                   9399: 
                   9400: While programming a primitive is usually easy, there are a few cases
                   9401: where the programmer has to take the actions of the generator into
                   9402: account, most notably @code{?dup}, but also words that do not (always)
                   9403: fall through to NEXT.
                   9404: 
                   9405: @node TOS Optimization, Produced code, Automatic Generation, Primitives
                   9406: @subsection TOS Optimization
                   9407: @cindex TOS optimization for primitives
                   9408: @cindex primitives, keeping the TOS in a register
                   9409: 
                   9410: An important optimization for stack machine emulators, e.g., Forth
                   9411: engines, is keeping  one or more of the top stack items in
                   9412: registers.  If a word has the stack effect @var{in1}...@var{inx} @code{--}
                   9413: @var{out1}...@var{outy}, keeping the top @var{n} items in registers
                   9414: @itemize @bullet
                   9415: @item
                   9416: is better than keeping @var{n-1} items, if @var{x>=n} and @var{y>=n},
                   9417: due to fewer loads from and stores to the stack.
                   9418: @item is slower than keeping @var{n-1} items, if @var{x<>y} and @var{x<n} and
                   9419: @var{y<n}, due to additional moves between registers.
                   9420: @end itemize
                   9421: 
                   9422: @cindex -DUSE_TOS
                   9423: @cindex -DUSE_NO_TOS
                   9424: In particular, keeping one item in a register is never a disadvantage,
                   9425: if there are enough registers. Keeping two items in registers is a
                   9426: disadvantage for frequent words like @code{?branch}, constants,
                   9427: variables, literals and @code{i}. Therefore our generator only produces
                   9428: code that keeps zero or one items in registers. The generated C code
                   9429: covers both cases; the selection between these alternatives is made at
                   9430: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
                   9431: code for @code{+} is just a simple variable name in the one-item case,
                   9432: otherwise it is a macro that expands into @code{sp[0]}. Note that the
                   9433: GNU C compiler tries to keep simple variables like @code{TOS} in
                   9434: registers, and it usually succeeds, if there are enough registers.
                   9435: 
                   9436: @cindex -DUSE_FTOS
                   9437: @cindex -DUSE_NO_FTOS
                   9438: The primitive generator performs the TOS optimization for the
                   9439: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
                   9440: operations the benefit of this optimization is even larger:
                   9441: floating-point operations take quite long on most processors, but can be
                   9442: performed in parallel with other operations as long as their results are
                   9443: not used. If the FP-TOS is kept in a register, this works. If
                   9444: it is kept on the stack, i.e., in memory, the store into memory has to
                   9445: wait for the result of the floating-point operation, lengthening the
                   9446: execution time of the primitive considerably.
                   9447: 
                   9448: The TOS optimization makes the automatic generation of primitives a
                   9449: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
                   9450: @code{TOS} is not sufficient. There are some special cases to
                   9451: consider:
                   9452: @itemize @bullet
                   9453: @item In the case of @code{dup ( w -- w w )} the generator must not
                   9454: eliminate the store to the original location of the item on the stack,
                   9455: if the TOS optimization is turned on.
                   9456: @item Primitives with stack effects of the form @code{--}
                   9457: @var{out1}...@var{outy} must store the TOS to the stack at the start.
                   9458: Likewise, primitives with the stack effect @var{in1}...@var{inx} @code{--}
                   9459: must load the TOS from the stack at the end. But for the null stack
                   9460: effect @code{--} no stores or loads should be generated.
                   9461: @end itemize
                   9462: 
                   9463: @node Produced code,  , TOS Optimization, Primitives
                   9464: @subsection Produced code
                   9465: @cindex primitives, assembly code listing
                   9466: 
                   9467: @cindex @file{engine.s}
                   9468: To see what assembly code is produced for the primitives on your machine
                   9469: with your compiler and your flag settings, type @code{make engine.s} and
                   9470: look at the resulting file @file{engine.s}.
                   9471: 
                   9472: @node  Performance,  , Primitives, Engine
                   9473: @section Performance
                   9474: @cindex performance of some Forth interpreters
                   9475: @cindex engine performance
                   9476: @cindex benchmarking Forth systems
                   9477: @cindex Gforth performance
                   9478: 
                   9479: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
                   9480: impossible to write a significantly faster engine.
                   9481: 
                   9482: On register-starved machines like the 386 architecture processors
                   9483: improvements are possible, because @code{gcc} does not utilize the
                   9484: registers as well as a human, even with explicit register declarations;
                   9485: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
                   9486: and hand-tuned it for the 486; this system is 1.19 times faster on the
                   9487: Sieve benchmark on a 486DX2/66 than Gforth compiled with
                   9488: @code{gcc-2.6.3} with @code{-DFORCE_REG}.
                   9489: 
                   9490: @cindex Win32Forth performance
                   9491: @cindex NT Forth performance
                   9492: @cindex eforth performance
                   9493: @cindex ThisForth performance
                   9494: @cindex PFE performance
                   9495: @cindex TILE performance
                   9496: However, this potential advantage of assembly language implementations
                   9497: is not necessarily realized in complete Forth systems: We compared
                   9498: Gforth (direct threaded, compiled with @code{gcc-2.6.3} and
                   9499: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
                   9500: 1994) and Eforth (with and without peephole (aka pinhole) optimization
                   9501: of the threaded code); all these systems were written in assembly
                   9502: language. We also compared Gforth with three systems written in C:
                   9503: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
                   9504: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21      crook    9505: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
                   9506: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1       anton    9507: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
                   9508: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
                   9509: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
                   9510: 486DX2/66 with similar memory performance under Windows NT. Marcel
                   9511: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
                   9512: added the peephole optimizer, ran the benchmarks and reported the
                   9513: results.
                   9514:  
                   9515: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
                   9516: matrix multiplication come from the Stanford integer benchmarks and have
                   9517: been translated into Forth by Martin Fraeman; we used the versions
                   9518: included in the TILE Forth package, but with bigger data set sizes; and
                   9519: a recursive Fibonacci number computation for benchmarking calling
                   9520: performance. The following table shows the time taken for the benchmarks
                   9521: scaled by the time taken by Gforth (in other words, it shows the speedup
                   9522: factor that Gforth achieved over the other systems).
                   9523: 
                   9524: @example
                   9525: relative      Win32-    NT       eforth       This-
                   9526:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
                   9527: sieve     1.00  1.39  1.14   1.39  0.85  1.58  3.18  8.58
                   9528: bubble    1.00  1.31  1.41   1.48  0.88  1.50        3.88
                   9529: matmul    1.00  1.47  1.35   1.46  0.74  1.58        4.09
                   9530: fib       1.00  1.52  1.34   1.22  0.86  1.74  2.99  4.30
                   9531: @end example
                   9532: 
                   9533: You may find the good performance of Gforth compared with the systems
                   9534: written in assembly language quite surprising. One important reason for
                   9535: the disappointing performance of these systems is probably that they are
                   9536: not written optimally for the 486 (e.g., they use the @code{lods}
                   9537: instruction). In addition, Win32Forth uses a comfortable, but costly
                   9538: method for relocating the Forth image: like @code{cforth}, it computes
                   9539: the actual addresses at run time, resulting in two address computations
                   9540: per NEXT (@pxref{Image File Background}).
                   9541: 
                   9542: Only Eforth with the peephole optimizer performs comparable to
                   9543: Gforth. The speedups achieved with peephole optimization of threaded
                   9544: code are quite remarkable. Adding a peephole optimizer to Gforth should
                   9545: cause similar speedups.
                   9546: 
                   9547: The speedup of Gforth over PFE, ThisForth and TILE can be easily
                   9548: explained with the self-imposed restriction of the latter systems to
                   9549: standard C, which makes efficient threading impossible (however, the
1.4       anton    9550: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1       anton    9551: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
                   9552: Moreover, current C compilers have a hard time optimizing other aspects
                   9553: of the ThisForth and the TILE source.
                   9554: 
                   9555: Note that the performance of Gforth on 386 architecture processors
                   9556: varies widely with the version of @code{gcc} used. E.g., @code{gcc-2.5.8}
                   9557: failed to allocate any of the virtual machine registers into real
                   9558: machine registers by itself and would not work correctly with explicit
                   9559: register declarations, giving a 1.3 times slower engine (on a 486DX2/66
                   9560: running the Sieve) than the one measured above.
                   9561: 
                   9562: Note also that there have been several releases of Win32Forth since the
                   9563: release presented here, so the results presented here may have little
                   9564: predictive value for the performance of Win32Forth today.
                   9565: 
                   9566: @cindex @file{Benchres}
                   9567: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
                   9568: Maierhofer (presented at EuroForth '95), an indirect threaded version of
                   9569: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
                   9570: version of Gforth is 2%@minus{}8% slower on a 486 than the direct
                   9571: threaded version used here. The paper available at
                   9572: @*@url{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
                   9573: it also contains numbers for some native code systems. You can find a
                   9574: newer version of these measurements at
                   9575: @url{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
                   9576: find numbers for Gforth on various machines in @file{Benchres}.
                   9577: 
1.13      pazsan   9578: @node Binding to System Library, Cross Compiler, Engine, Top
1.14      pazsan   9579: @chapter Binding to System Library
1.13      pazsan   9580: 
                   9581: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14      pazsan   9582: @chapter Cross Compiler
1.13      pazsan   9583: 
                   9584: Cross Compiler
                   9585: 
                   9586: @menu
                   9587: * Using the Cross Compiler::
                   9588: * How the Cross Compiler Works::
                   9589: @end menu
                   9590: 
1.21      crook    9591: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14      pazsan   9592: @section Using the Cross Compiler
1.13      pazsan   9593: 
1.21      crook    9594: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14      pazsan   9595: @section How the Cross Compiler Works
1.13      pazsan   9596: 
                   9597: @node Bugs, Origin, Cross Compiler, Top
1.21      crook    9598: @appendix Bugs
1.1       anton    9599: @cindex bug reporting
                   9600: 
1.21      crook    9601: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1       anton    9602: 
                   9603: If you find a bug, please send a bug report to
1.21      crook    9604: @email{bug-gforth@@gnu.ai.mit.edu}. A bug report should include this
                   9605: information:
                   9606: 
                   9607: @itemize @bullet
                   9608: @item
                   9609: The Gforth version used (it is announced at the start of an
                   9610: interactive Gforth session).
                   9611: @item
                   9612: The machine and operating system (on Unix
                   9613: systems @code{uname -a} will report this information).
                   9614: @item
                   9615: The installation options (send the file @file{config.status}).
                   9616: @item
                   9617: A complete list of changes (if any) you (or your installer) have made to the
                   9618: Gforth sources.
                   9619: @item
                   9620: A program (or a sequence of keyboard commands) that reproduces the bug.
                   9621: @item
                   9622: A description of what you think constitutes the buggy behaviour.
                   9623: @end itemize
1.1       anton    9624: 
                   9625: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
                   9626: to Report Bugs, gcc.info, GNU C Manual}.
                   9627: 
                   9628: 
1.21      crook    9629: @node Origin, Forth-related information, Bugs, Top
                   9630: @appendix Authors and Ancestors of Gforth
1.1       anton    9631: 
                   9632: @section Authors and Contributors
                   9633: @cindex authors of Gforth
                   9634: @cindex contributors to Gforth
                   9635: 
                   9636: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
                   9637: Ertl. The third major author was Jens Wilke.  Lennart Benschop (who was
                   9638: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
                   9639: with their continuous feedback. Lennart Benshop contributed
                   9640: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
                   9641: support for calling C libraries. Helpful comments also came from Paul
                   9642: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.12      anton    9643: Wavrik, Barrie Stott, Marc de Groot, and Jorge Acerada. Since the
                   9644: release of Gforth-0.2.1 there were also helpful comments from many
                   9645: others; thank you all, sorry for not listing you here (but digging
1.23      crook    9646: through my mailbox to extract your names is on my to-do list). Since the
                   9647: release of Gforth-0.4.0 Neal Crook worked on the manual.
1.1       anton    9648: 
                   9649: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
                   9650: and autoconf, among others), and to the creators of the Internet: Gforth
1.21      crook    9651: was developed across the Internet, and its authors did not meet
1.20      pazsan   9652: physically for the first 4 years of development.
1.1       anton    9653: 
                   9654: @section Pedigree
                   9655: @cindex Pedigree of Gforth
                   9656: 
1.20      pazsan   9657: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1       anton    9658: Dirk Zoller) will cross-fertilize each other. Of course, a significant
                   9659: part of the design of Gforth was prescribed by ANS Forth.
                   9660: 
1.20      pazsan   9661: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1       anton    9662: 32 bit native code version of VolksForth for the Atari ST, written
                   9663: mostly by Dietrich Weineck.
                   9664: 
                   9665: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
                   9666: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
                   9667: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
                   9668: 
                   9669: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
                   9670: Forth-83 standard. !! Pedigree? When?
                   9671: 
                   9672: A team led by Bill Ragsdale implemented fig-Forth on many processors in
                   9673: 1979. Robert Selzer and Bill Ragsdale developed the original
                   9674: implementation of fig-Forth for the 6502 based on microForth.
                   9675: 
                   9676: The principal architect of microForth was Dean Sanderson. microForth was
                   9677: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
                   9678: the 1802, and subsequently implemented on the 8080, the 6800 and the
                   9679: Z80.
                   9680: 
                   9681: All earlier Forth systems were custom-made, usually by Charles Moore,
                   9682: who discovered (as he puts it) Forth during the late 60s. The first full
                   9683: Forth existed in 1971.
                   9684: 
                   9685: A part of the information in this section comes from @cite{The Evolution
                   9686: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
                   9687: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
                   9688: Notices 28(3), 1993.  You can find more historical and genealogical
                   9689: information about Forth there.
                   9690: 
1.21      crook    9691: @node Forth-related information, Word Index, Origin, Top
                   9692: @appendix Other Forth-related information
                   9693: @cindex Forth-related information
                   9694: 
                   9695: @menu
                   9696: * Internet resources::
                   9697: * Books::
                   9698: * The Forth Interest Group::
                   9699: * Conferences::
                   9700: @end menu
                   9701: 
                   9702: 
                   9703: @node Internet resources, Books, Forth-related information, Forth-related information
                   9704: @section Internet resources
                   9705: @cindex Internet resources
                   9706: 
                   9707: @cindex comp.lang.forth
                   9708: @cindex frequently asked questions
                   9709: There is an active newsgroup (comp.lang.forth) discussing Forth and
                   9710: Forth-related issues. A frequently-asked-questions (FAQ) list
                   9711: is posted to the newsgroup regulary, and archived at these sites:
                   9712: 
                   9713: @itemize @bullet
                   9714: @item
                   9715: @url{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
                   9716: @item
                   9717: @url{ftp://ftp.forth.org/pub/Forth/FAQ/}
                   9718: @end itemize
                   9719: 
                   9720: The FAQ list should be considered mandatory reading before posting to
                   9721: the newsgroup.
                   9722: 
                   9723: Here are some other web sites holding Forth-related material:
                   9724: 
                   9725: @itemize @bullet
                   9726: @item
                   9727: @url{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
                   9728: @item
                   9729: @url{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
                   9730: @item
                   9731: @url{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
                   9732: @item
                   9733: @url{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
                   9734: Research page, including links to the Journal of Forth Application and
                   9735: Research (JFAR) and a searchable Forth bibliography.
                   9736: @end itemize
                   9737: 
                   9738: 
                   9739: @node Books, The Forth Interest Group, Internet resources, Forth-related information
                   9740: @section Books
                   9741: @cindex Books
                   9742: 
                   9743: As the Standard is relatively new, there are not many books out yet. It
                   9744: is not recommended to learn Forth by using Gforth and a book that is not
                   9745: written for ANS Forth, as you will not know your mistakes from the
                   9746: deviations of the book. However, books based on the Forth-83 standard
                   9747: should be ok, because ANS Forth is primarily an extension of Forth-83.
                   9748: 
                   9749: @cindex standard document for ANS Forth
                   9750: @cindex ANS Forth document
                   9751: The definite reference if you want to write ANS Forth programs is, of
                   9752: course, the ANS Forth Standard. It is available in printed form from the
                   9753: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
                   9754: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
                   9755: $200. You can also get it from Global Engineering Documents (Tel.: USA
                   9756: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
                   9757: 
                   9758: @cite{dpANS6}, the last draft of the standard, which was then submitted
                   9759: to ANSI for publication is available electronically and for free in some
                   9760: MS Word format, and it has been converted to HTML
                   9761: (@url{http://www.taygeta.com/forth/dpans.html}; this is my favourite
                   9762: format); this HTML version also includes the answers to Requests for
                   9763: Interpretation (RFIs). Some pointers to these versions can be found
                   9764: through @*@url{http://www.complang.tuwien.ac.at/projects/forth.html}.
                   9765: 
                   9766: @cindex introductory book
                   9767: @cindex book, introductory
                   9768: @cindex Woehr, Jack: @cite{Forth: The New Model}
                   9769: @cindex @cite{Forth: The new model} (book)
                   9770: @cite{Forth: The New Model} by Jack Woehr (Prentice-Hall, 1993) is an
                   9771: introductory book based on a draft version of the standard. It does not
                   9772: cover the whole standard. It also contains interesting background
                   9773: information (Jack Woehr was in the ANS Forth Technical Committee). It is
                   9774: not appropriate for complete newbies, but programmers experienced in
                   9775: other languages should find it ok.
                   9776: 
                   9777: @cindex Conklin, Edward K., and Elizabeth Rather: @cite{Forth Programmer's Handbook}
                   9778: @cindex Rather, Elizabeth and Edward K. Conklin: @cite{Forth Programmer's Handbook}
                   9779: @cindex @cite{Forth Programmer's Handbook} (book)
                   9780: @cite{Forth Programmer's Handbook} by Edward K. Conklin, Elizabeth
                   9781: D. Rather and the technical staff of Forth, Inc. (Forth, Inc., 1997;
                   9782: ISBN 0-9662156-0-5) contains little introductory material. The majority
                   9783: of the book is similar to @ref{Words}, but the book covers most of the
                   9784: standard words and some non-standard words (whereas this manual is
                   9785: quite incomplete). In addition, the book contains a chapter on
                   9786: programming style. The major drawback of this book is that it usually
                   9787: does not identify what is standard and what is specific to the Forth
                   9788: system described in the book (probably one of Forth, Inc.'s systems).
                   9789: Fortunately, many of the non-standard programming practices described in
                   9790: the book work in Gforth, too.  Still, this drawback makes the book
                   9791: hardly more useful than a pre-ANS book.
                   9792: 
                   9793: @node The Forth Interest Group, Conferences, Books, Forth-related information
                   9794: @section The Forth Interest Group
                   9795: @cindex Forth interest group (FIG)
                   9796: 
                   9797: The Forth Interest Group (FIG) is a world-wide, non-profit,
                   9798: member-supported organisation. It publishes a regular magazine and
                   9799: offers other benefits of membership. You can contact the FIG through
                   9800: their office email address: @email{office@@forth.org} or by visiting
                   9801: their web site at @url{http://www.forth.org/}. This web site also
                   9802: includes links to FIG chapters in other countries and American cities
                   9803: (@url{http://www.forth.org/chapters.html}).
                   9804: 
                   9805: @node Conferences, , The Forth Interest Group, Forth-related information
                   9806: @section Conferences
                   9807: @cindex Conferences
                   9808: 
                   9809: There are several regular conferences related to Forth. They are all
                   9810: well-publicised in FIG magazine and on the comp.lang.forth news group:
                   9811: 
                   9812: @itemize @bullet
                   9813: @item
                   9814: FORML -- the Forth modification laboratory convenes every year near
                   9815: Monterey, California.
                   9816: @item
                   9817: The Rochester Forth Conference -- an annual conference traditionally
                   9818: held in Rochester, New York.
                   9819: @item
                   9820: EuroForth -- this European conference takes place annually.
                   9821: @end itemize
                   9822: 
                   9823: 
                   9824: @node Word Index, Concept Index, Forth-related information, Top
1.1       anton    9825: @unnumbered Word Index
                   9826: 
                   9827: This index is as incomplete as the manual. Each word is listed with
                   9828: stack effect and wordset.
                   9829: 
                   9830: @printindex fn
                   9831: 
                   9832: @node Concept Index,  , Word Index, Top
                   9833: @unnumbered Concept and Word Index
                   9834: 
                   9835: This index is as incomplete as the manual. Not all entries listed are
                   9836: present verbatim in the text. Only the names are listed for the words
                   9837: here.
                   9838: 
                   9839: @printindex cp
                   9840: 
                   9841: @contents
                   9842: @bye
                   9843: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>