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

1.1       anton       1: \input texinfo   @c -*-texinfo-*-
                      2: @comment The source is gforth.ds, from which gforth.texi is generated
1.28      crook       3: 
1.21      crook       4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
1.28      crook       5: @comment 1. x-ref all ambiguous or implementation-defined features?
                      6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
                      7: @comment 3. words in miscellaneous section need a home.
                      8: @comment 4. search for TODO for other minor and major works required.
                      9: @comment 5. [rats] change all @var to @i in Forth source so that info
                     10: @comment    file looks decent.
1.29      crook      11: @comment .. would be useful to have a word that identified all deferred words
                     12: @comment should semantics stuff in intro be moved to another section
                     13: 
1.28      crook      14: 
1.1       anton      15: @comment %**start of header (This is for running Texinfo on a region.)
                     16: @setfilename gforth.info
                     17: @settitle Gforth Manual
                     18: @dircategory GNU programming tools
                     19: @direntry
                     20: * Gforth: (gforth).             A fast interpreter for the Forth language.
                     21: @end direntry
                     22: @comment @setchapternewpage odd
1.29      crook      23: @comment TODO this gets left in by HTML converter
1.12      anton      24: @macro progstyle {}
                     25: Programming style note:
1.3       anton      26: @end macro
1.1       anton      27: @comment %**end of header (This is for running Texinfo on a region.)
                     28: 
1.29      crook      29: 
                     30: @comment ----------------------------------------------------------
                     31: @comment macros for beautifying glossary entries
                     32: @comment if these are used, need to strip them out for HTML converter
                     33: @comment else they get repeated verbatim in HTML output.
                     34: @comment .. not working yet.
                     35: 
                     36: @macro GLOSS-START {}
                     37: @iftex
                     38: @ninerm
                     39: @end iftex
                     40: @end macro
                     41: 
                     42: @macro GLOSS-END {}
                     43: @iftex
                     44: @rm
                     45: @end iftex
                     46: @end macro
                     47: 
                     48: @comment ----------------------------------------------------------
                     49: 
                     50: 
1.10      anton      51: @include version.texi
                     52: 
1.1       anton      53: @ifinfo
1.11      anton      54: This file documents Gforth @value{VERSION}
1.1       anton      55: 
1.26      crook      56: Copyright @copyright{} 1995-1999 Free Software Foundation, Inc.
1.1       anton      57: 
                     58:      Permission is granted to make and distribute verbatim copies of
                     59:      this manual provided the copyright notice and this permission notice
                     60:      are preserved on all copies.
                     61:      
                     62: @ignore
                     63:      Permission is granted to process this file through TeX and print the
                     64:      results, provided the printed document carries a copying permission
                     65:      notice identical to this one except for the removal of this paragraph
                     66:      (this paragraph not being relevant to the printed manual).
                     67:      
                     68: @end ignore
                     69:      Permission is granted to copy and distribute modified versions of this
                     70:      manual under the conditions for verbatim copying, provided also that the
                     71:      sections entitled "Distribution" and "General Public License" are
                     72:      included exactly as in the original, and provided that the entire
                     73:      resulting derived work is distributed under the terms of a permission
                     74:      notice identical to this one.
                     75:      
                     76:      Permission is granted to copy and distribute translations of this manual
                     77:      into another language, under the above conditions for modified versions,
                     78:      except that the sections entitled "Distribution" and "General Public
                     79:      License" may be included in a translation approved by the author instead
                     80:      of in the original English.
                     81: @end ifinfo
                     82: 
                     83: @finalout
                     84: @titlepage
                     85: @sp 10
                     86: @center @titlefont{Gforth Manual}
                     87: @sp 2
1.11      anton      88: @center for version @value{VERSION}
1.1       anton      89: @sp 2
                     90: @center Anton Ertl
1.6       pazsan     91: @center Bernd Paysan
1.5       anton      92: @center Jens Wilke
1.23      crook      93: @center Neal Crook
1.1       anton      94: @sp 3
1.29      crook      95: @center This manual is permanently under construction and was last updated on 04-May-1999
1.1       anton      96: 
                     97: @comment  The following two commands start the copyright page.
                     98: @page
                     99: @vskip 0pt plus 1filll
1.29      crook     100: Copyright @copyright{} 1995--1999 Free Software Foundation, Inc.
1.1       anton     101: 
                    102: @comment !! Published by ... or You can get a copy of this manual ...
                    103: 
                    104:      Permission is granted to make and distribute verbatim copies of
                    105:      this manual provided the copyright notice and this permission notice
                    106:      are preserved on all copies.
                    107:      
                    108:      Permission is granted to copy and distribute modified versions of this
                    109:      manual under the conditions for verbatim copying, provided also that the
                    110:      sections entitled "Distribution" and "General Public License" are
                    111:      included exactly as in the original, and provided that the entire
                    112:      resulting derived work is distributed under the terms of a permission
                    113:      notice identical to this one.
                    114:      
                    115:      Permission is granted to copy and distribute translations of this manual
                    116:      into another language, under the above conditions for modified versions,
                    117:      except that the sections entitled "Distribution" and "General Public
                    118:      License" may be included in a translation approved by the author instead
                    119:      of in the original English.
                    120: @end titlepage
                    121: 
                    122: 
                    123: @node Top, License, (dir), (dir)
                    124: @ifinfo
                    125: Gforth is a free implementation of ANS Forth available on many
1.11      anton     126: personal machines. This manual corresponds to version @value{VERSION}.
1.1       anton     127: @end ifinfo
                    128: 
                    129: @menu
1.21      crook     130: * License::                     The GPL
1.26      crook     131: * Goals::                       About the Gforth Project
1.29      crook     132: * Gforth Environment::          Starting (and exiting) Gforth
1.21      crook     133: * Introduction::                An introduction to ANS Forth
1.1       anton     134: * Words::                       Forth words available in Gforth
1.24      anton     135: * Error messages::              How to interpret them
1.1       anton     136: * Tools::                       Programming tools
                    137: * ANS conformance::             Implementation-defined options etc.
                    138: * Model::                       The abstract machine of Gforth
                    139: * Integrating Gforth::          Forth as scripting language for applications
                    140: * Emacs and Gforth::            The Gforth Mode
                    141: * Image Files::                 @code{.fi} files contain compiled code
                    142: * Engine::                      The inner interpreter and the primitives
1.24      anton     143: * Binding to System Library::   
1.13      pazsan    144: * Cross Compiler::              The Cross Compiler
1.1       anton     145: * Bugs::                        How to report them
                    146: * Origin::                      Authors and ancestors of Gforth
1.21      crook     147: * Forth-related information::   Books and places to look on the WWW
1.1       anton     148: * Word Index::                  An item for each Forth word
                    149: * Concept Index::               A menu covering many topics
1.12      anton     150: 
1.24      anton     151: @detailmenu --- The Detailed Node Listing ---
1.12      anton     152: 
1.26      crook     153: Goals of Gforth
                    154: 
                    155: * Gforth Extensions Sinful?::
                    156: 
1.29      crook     157: Gforth Environment
                    158: 
                    159: * Invoking Gforth::
                    160: * Leaving Gforth::
                    161: * Command-line editing::
                    162: * Upper and lower case::
                    163: * Environment variables::
                    164: * Gforth Files::
                    165: 
1.24      anton     166: An Introduction to ANS Forth
                    167: 
                    168: * Introducing the Text Interpreter::
                    169: * Stacks and Postfix notation::
                    170: * Your first definition::
                    171: * How does that work?::
                    172: * Forth is written in Forth::
                    173: * Review - elements of a Forth system::
1.29      crook     174: * Where to go next::
1.24      anton     175: * Exercises::
                    176: 
1.12      anton     177: Forth Words
                    178: 
                    179: * Notation::                    
1.21      crook     180: * Comments::
                    181: * Boolean Flags::
1.12      anton     182: * Arithmetic::                  
                    183: * Stack Manipulation::          
                    184: * Memory::                      
                    185: * Control Structures::          
                    186: * Defining Words::              
1.21      crook     187: * The Text Interpreter::
1.12      anton     188: * Tokens for Words::            
1.21      crook     189: * Word Lists::                   
                    190: * Environmental Queries::
1.12      anton     191: * Files::                       
                    192: * Blocks::                      
                    193: * Other I/O::                   
                    194: * Programming Tools::           
                    195: * Assembler and Code Words::    
                    196: * Threading Words::             
1.26      crook     197: * Locals::                      
                    198: * Structures::                  
                    199: * Object-oriented Forth::       
1.21      crook     200: * Passing Commands to the OS::
                    201: * Miscellaneous Words::
1.12      anton     202: 
                    203: Arithmetic
                    204: 
                    205: * Single precision::            
                    206: * Bitwise operations::          
1.21      crook     207: * Double precision::            Double-cell integer arithmetic
                    208: * Numeric comparison::
1.12      anton     209: * Mixed precision::             operations with single and double-cell integers
                    210: * Floating Point::              
                    211: 
                    212: Stack Manipulation
                    213: 
                    214: * Data stack::                  
                    215: * Floating point stack::        
                    216: * Return stack::                
                    217: * Locals stack::                
                    218: * Stack pointer manipulation::  
                    219: 
                    220: Memory
                    221: 
1.27      crook     222: * Reserving Data Space::
1.12      anton     223: * Memory Access::      
1.27      crook     224: * Address Arithmetic::          
                    225: * Memory Blocks::
                    226: * Dynamic Allocation::        
1.12      anton     227: 
                    228: Control Structures
                    229: 
                    230: * Selection::                   
                    231: * Simple Loops::                
                    232: * Counted Loops::               
                    233: * Arbitrary control structures::  
                    234: * Calls and returns::           
                    235: * Exception Handling::          
                    236: 
                    237: Defining Words
                    238: 
                    239: * Simple Defining Words::       
                    240: * Colon Definitions::           
                    241: * User-defined Defining Words::  
                    242: * Supplying names::             
                    243: * Interpretation and Compilation Semantics::  
                    244: 
1.21      crook     245: The Text Interpreter
                    246: 
1.29      crook     247: * Input Sources::
1.21      crook     248: * Number Conversion::
                    249: * Interpret/Compile states::
                    250: * Literals::
                    251: * Interpreter Directives::
                    252: 
1.26      crook     253: Word Lists
                    254: 
                    255: * Why use word lists?::
                    256: * Word list examples::
                    257: 
                    258: Files
                    259: 
                    260: * Forth source files::
                    261: * General files::         
                    262: * Search Paths::                 
                    263: * Forth Search Paths::    
                    264: * General Search Paths::        
                    265: 
                    266: Other I/O
                    267: 
                    268: * Simple numeric output::
                    269: * Formatted numeric output::
                    270: * String Formats::
                    271: * Displaying characters and strings::
                    272: * Input::
                    273: 
                    274: Programming Tools
                    275: 
                    276: * Debugging::                   Simple and quick.
                    277: * Assertions::                  Making your programs self-checking.
                    278: * Singlestep Debugger::                Executing your program word by word.
                    279: 
                    280: Locals
                    281: 
                    282: * Gforth locals::               
                    283: * ANS Forth locals::            
                    284: 
                    285: Gforth locals
                    286: 
                    287: * Where are locals visible by name?::  
                    288: * How long do locals live?::    
                    289: * Programming Style::           
                    290: * Implementation::              
                    291: 
1.12      anton     292: Structures
                    293: 
                    294: * Why explicit structure support?::  
                    295: * Structure Usage::             
                    296: * Structure Naming Convention::  
                    297: * Structure Implementation::    
                    298: * Structure Glossary::          
                    299: 
                    300: Object-oriented Forth
                    301: 
1.24      anton     302: * Why object-oriented programming?::
                    303: * Object-Oriented Terminology::
                    304: * Objects::
                    305: * OOF::
                    306: * Mini-OOF::
1.23      crook     307: * Comparison with other object models::  
1.12      anton     308: 
1.24      anton     309: The @file{objects.fs} model
1.12      anton     310: 
                    311: * Properties of the Objects model::  
                    312: * Basic Objects Usage::         
1.23      crook     313: * The Objects base class::            
1.12      anton     314: * Creating objects::            
                    315: * Object-Oriented Programming Style::  
                    316: * Class Binding::               
                    317: * Method conveniences::         
                    318: * Classes and Scoping::         
                    319: * Object Interfaces::           
                    320: * Objects Implementation::      
                    321: * Objects Glossary::            
                    322: 
1.24      anton     323: The @file{oof.fs} model
1.12      anton     324: 
                    325: * Properties of the OOF model::
                    326: * Basic OOF Usage::
1.23      crook     327: * The OOF base class::
1.12      anton     328: * Class Declaration::
                    329: * Class Implementation::
                    330: 
1.24      anton     331: The @file{mini-oof.fs} model
1.23      crook     332: 
                    333: * Basic Mini-OOF Usage::
                    334: * Mini-OOF Example::
                    335: * Mini-OOF Implementation::
                    336: 
1.12      anton     337: Tools
                    338: 
                    339: * ANS Report::                  Report the words used, sorted by wordset.
                    340: 
                    341: ANS conformance
                    342: 
                    343: * The Core Words::              
                    344: * The optional Block word set::  
                    345: * The optional Double Number word set::  
                    346: * The optional Exception word set::  
                    347: * The optional Facility word set::  
                    348: * The optional File-Access word set::  
                    349: * The optional Floating-Point word set::  
                    350: * The optional Locals word set::  
                    351: * The optional Memory-Allocation word set::  
                    352: * The optional Programming-Tools word set::  
                    353: * The optional Search-Order word set::  
                    354: 
                    355: The Core Words
                    356: 
                    357: * core-idef::                   Implementation Defined Options                   
                    358: * core-ambcond::                Ambiguous Conditions                
                    359: * core-other::                  Other System Documentation                  
                    360: 
                    361: The optional Block word set
                    362: 
                    363: * block-idef::                  Implementation Defined Options
                    364: * block-ambcond::               Ambiguous Conditions               
                    365: * block-other::                 Other System Documentation                 
                    366: 
                    367: The optional Double Number word set
                    368: 
                    369: * double-ambcond::              Ambiguous Conditions              
                    370: 
                    371: The optional Exception word set
                    372: 
                    373: * exception-idef::              Implementation Defined Options              
                    374: 
                    375: The optional Facility word set
                    376: 
                    377: * facility-idef::               Implementation Defined Options               
                    378: * facility-ambcond::            Ambiguous Conditions            
                    379: 
                    380: The optional File-Access word set
                    381: 
                    382: * file-idef::                   Implementation Defined Options
                    383: * file-ambcond::                Ambiguous Conditions                
                    384: 
                    385: The optional Floating-Point word set
                    386: 
                    387: * floating-idef::               Implementation Defined Options
                    388: * floating-ambcond::            Ambiguous Conditions            
                    389: 
                    390: The optional Locals word set
                    391: 
                    392: * locals-idef::                 Implementation Defined Options                 
                    393: * locals-ambcond::              Ambiguous Conditions              
                    394: 
                    395: The optional Memory-Allocation word set
                    396: 
                    397: * memory-idef::                 Implementation Defined Options                 
                    398: 
                    399: The optional Programming-Tools word set
                    400: 
                    401: * programming-idef::            Implementation Defined Options            
                    402: * programming-ambcond::         Ambiguous Conditions         
                    403: 
                    404: The optional Search-Order word set
                    405: 
                    406: * search-idef::                 Implementation Defined Options                 
                    407: * search-ambcond::              Ambiguous Conditions              
                    408: 
                    409: Image Files
                    410: 
1.24      anton     411: * Image Licensing Issues::      Distribution terms for images.
                    412: * Image File Background::       Why have image files?
                    413: * Non-Relocatable Image Files::  don't always work.
                    414: * Data-Relocatable Image Files::  are better.
1.12      anton     415: * Fully Relocatable Image Files::  better yet.
1.24      anton     416: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
                    417: * Running Image Files::         @code{gforth -i @var{file}} or @var{file}.
                    418: * Modifying the Startup Sequence::  and turnkey applications.
1.12      anton     419: 
                    420: Fully Relocatable Image Files
                    421: 
1.27      crook     422: * gforthmi::                    The normal way
1.12      anton     423: * cross.fs::                    The hard way
                    424: 
                    425: Engine
                    426: 
                    427: * Portability::                 
                    428: * Threading::                   
                    429: * Primitives::                  
                    430: * Performance::                 
                    431: 
                    432: Threading
                    433: 
                    434: * Scheduling::                  
                    435: * Direct or Indirect Threaded?::  
                    436: * DOES>::                       
                    437: 
                    438: Primitives
                    439: 
                    440: * Automatic Generation::        
                    441: * TOS Optimization::            
                    442: * Produced code::               
1.13      pazsan    443: 
                    444: Cross Compiler
                    445: 
                    446: * Using the Cross Compiler::
                    447: * How the Cross Compiler Works::
                    448: 
1.24      anton     449: Other Forth-related information
1.21      crook     450: 
                    451: * Internet resources::
                    452: * Books::
                    453: * The Forth Interest Group::
                    454: * Conferences::
                    455: 
1.24      anton     456: @end detailmenu
1.1       anton     457: @end menu
                    458: 
1.26      crook     459: @node License, Goals, Top, Top
1.1       anton     460: @unnumbered GNU GENERAL PUBLIC LICENSE
                    461: @center Version 2, June 1991
                    462: 
                    463: @display
                    464: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
                    465: 675 Mass Ave, Cambridge, MA 02139, USA
                    466: 
                    467: Everyone is permitted to copy and distribute verbatim copies
                    468: of this license document, but changing it is not allowed.
                    469: @end display
                    470: 
                    471: @unnumberedsec Preamble
                    472: 
                    473:   The licenses for most software are designed to take away your
                    474: freedom to share and change it.  By contrast, the GNU General Public
                    475: License is intended to guarantee your freedom to share and change free
                    476: software---to make sure the software is free for all its users.  This
                    477: General Public License applies to most of the Free Software
                    478: Foundation's software and to any other program whose authors commit to
                    479: using it.  (Some other Free Software Foundation software is covered by
                    480: the GNU Library General Public License instead.)  You can apply it to
                    481: your programs, too.
                    482: 
                    483:   When we speak of free software, we are referring to freedom, not
                    484: price.  Our General Public Licenses are designed to make sure that you
                    485: have the freedom to distribute copies of free software (and charge for
                    486: this service if you wish), that you receive source code or can get it
                    487: if you want it, that you can change the software or use pieces of it
                    488: in new free programs; and that you know you can do these things.
                    489: 
                    490:   To protect your rights, we need to make restrictions that forbid
                    491: anyone to deny you these rights or to ask you to surrender the rights.
                    492: These restrictions translate to certain responsibilities for you if you
                    493: distribute copies of the software, or if you modify it.
                    494: 
                    495:   For example, if you distribute copies of such a program, whether
                    496: gratis or for a fee, you must give the recipients all the rights that
                    497: you have.  You must make sure that they, too, receive or can get the
                    498: source code.  And you must show them these terms so they know their
                    499: rights.
                    500: 
                    501:   We protect your rights with two steps: (1) copyright the software, and
                    502: (2) offer you this license which gives you legal permission to copy,
                    503: distribute and/or modify the software.
                    504: 
                    505:   Also, for each author's protection and ours, we want to make certain
                    506: that everyone understands that there is no warranty for this free
                    507: software.  If the software is modified by someone else and passed on, we
                    508: want its recipients to know that what they have is not the original, so
                    509: that any problems introduced by others will not reflect on the original
                    510: authors' reputations.
                    511: 
                    512:   Finally, any free program is threatened constantly by software
                    513: patents.  We wish to avoid the danger that redistributors of a free
                    514: program will individually obtain patent licenses, in effect making the
                    515: program proprietary.  To prevent this, we have made it clear that any
                    516: patent must be licensed for everyone's free use or not licensed at all.
                    517: 
                    518:   The precise terms and conditions for copying, distribution and
                    519: modification follow.
                    520: 
                    521: @iftex
                    522: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
                    523: @end iftex
                    524: @ifinfo
                    525: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
                    526: @end ifinfo
                    527: 
                    528: @enumerate 0
                    529: @item
                    530: This License applies to any program or other work which contains
                    531: a notice placed by the copyright holder saying it may be distributed
                    532: under the terms of this General Public License.  The ``Program'', below,
                    533: refers to any such program or work, and a ``work based on the Program''
                    534: means either the Program or any derivative work under copyright law:
                    535: that is to say, a work containing the Program or a portion of it,
                    536: either verbatim or with modifications and/or translated into another
                    537: language.  (Hereinafter, translation is included without limitation in
                    538: the term ``modification''.)  Each licensee is addressed as ``you''.
                    539: 
                    540: Activities other than copying, distribution and modification are not
                    541: covered by this License; they are outside its scope.  The act of
                    542: running the Program is not restricted, and the output from the Program
                    543: is covered only if its contents constitute a work based on the
                    544: Program (independent of having been made by running the Program).
                    545: Whether that is true depends on what the Program does.
                    546: 
                    547: @item
                    548: You may copy and distribute verbatim copies of the Program's
                    549: source code as you receive it, in any medium, provided that you
                    550: conspicuously and appropriately publish on each copy an appropriate
                    551: copyright notice and disclaimer of warranty; keep intact all the
                    552: notices that refer to this License and to the absence of any warranty;
                    553: and give any other recipients of the Program a copy of this License
                    554: along with the Program.
                    555: 
                    556: You may charge a fee for the physical act of transferring a copy, and
                    557: you may at your option offer warranty protection in exchange for a fee.
                    558: 
                    559: @item
                    560: You may modify your copy or copies of the Program or any portion
                    561: of it, thus forming a work based on the Program, and copy and
                    562: distribute such modifications or work under the terms of Section 1
                    563: above, provided that you also meet all of these conditions:
                    564: 
                    565: @enumerate a
                    566: @item
                    567: You must cause the modified files to carry prominent notices
                    568: stating that you changed the files and the date of any change.
                    569: 
                    570: @item
                    571: You must cause any work that you distribute or publish, that in
                    572: whole or in part contains or is derived from the Program or any
                    573: part thereof, to be licensed as a whole at no charge to all third
                    574: parties under the terms of this License.
                    575: 
                    576: @item
                    577: If the modified program normally reads commands interactively
                    578: when run, you must cause it, when started running for such
                    579: interactive use in the most ordinary way, to print or display an
                    580: announcement including an appropriate copyright notice and a
                    581: notice that there is no warranty (or else, saying that you provide
                    582: a warranty) and that users may redistribute the program under
                    583: these conditions, and telling the user how to view a copy of this
                    584: License.  (Exception: if the Program itself is interactive but
                    585: does not normally print such an announcement, your work based on
                    586: the Program is not required to print an announcement.)
                    587: @end enumerate
                    588: 
                    589: These requirements apply to the modified work as a whole.  If
                    590: identifiable sections of that work are not derived from the Program,
                    591: and can be reasonably considered independent and separate works in
                    592: themselves, then this License, and its terms, do not apply to those
                    593: sections when you distribute them as separate works.  But when you
                    594: distribute the same sections as part of a whole which is a work based
                    595: on the Program, the distribution of the whole must be on the terms of
                    596: this License, whose permissions for other licensees extend to the
                    597: entire whole, and thus to each and every part regardless of who wrote it.
                    598: 
                    599: Thus, it is not the intent of this section to claim rights or contest
                    600: your rights to work written entirely by you; rather, the intent is to
                    601: exercise the right to control the distribution of derivative or
                    602: collective works based on the Program.
                    603: 
                    604: In addition, mere aggregation of another work not based on the Program
                    605: with the Program (or with a work based on the Program) on a volume of
                    606: a storage or distribution medium does not bring the other work under
                    607: the scope of this License.
                    608: 
                    609: @item
                    610: You may copy and distribute the Program (or a work based on it,
                    611: under Section 2) in object code or executable form under the terms of
                    612: Sections 1 and 2 above provided that you also do one of the following:
                    613: 
                    614: @enumerate a
                    615: @item
                    616: Accompany it with the complete corresponding machine-readable
                    617: source code, which must be distributed under the terms of Sections
                    618: 1 and 2 above on a medium customarily used for software interchange; or,
                    619: 
                    620: @item
                    621: Accompany it with a written offer, valid for at least three
                    622: years, to give any third party, for a charge no more than your
                    623: cost of physically performing source distribution, a complete
                    624: machine-readable copy of the corresponding source code, to be
                    625: distributed under the terms of Sections 1 and 2 above on a medium
                    626: customarily used for software interchange; or,
                    627: 
                    628: @item
                    629: Accompany it with the information you received as to the offer
                    630: to distribute corresponding source code.  (This alternative is
                    631: allowed only for noncommercial distribution and only if you
                    632: received the program in object code or executable form with such
                    633: an offer, in accord with Subsection b above.)
                    634: @end enumerate
                    635: 
                    636: The source code for a work means the preferred form of the work for
                    637: making modifications to it.  For an executable work, complete source
                    638: code means all the source code for all modules it contains, plus any
                    639: associated interface definition files, plus the scripts used to
                    640: control compilation and installation of the executable.  However, as a
                    641: special exception, the source code distributed need not include
                    642: anything that is normally distributed (in either source or binary
                    643: form) with the major components (compiler, kernel, and so on) of the
                    644: operating system on which the executable runs, unless that component
                    645: itself accompanies the executable.
                    646: 
                    647: If distribution of executable or object code is made by offering
                    648: access to copy from a designated place, then offering equivalent
                    649: access to copy the source code from the same place counts as
                    650: distribution of the source code, even though third parties are not
                    651: compelled to copy the source along with the object code.
                    652: 
                    653: @item
                    654: You may not copy, modify, sublicense, or distribute the Program
                    655: except as expressly provided under this License.  Any attempt
                    656: otherwise to copy, modify, sublicense or distribute the Program is
                    657: void, and will automatically terminate your rights under this License.
                    658: However, parties who have received copies, or rights, from you under
                    659: this License will not have their licenses terminated so long as such
                    660: parties remain in full compliance.
                    661: 
                    662: @item
                    663: You are not required to accept this License, since you have not
                    664: signed it.  However, nothing else grants you permission to modify or
                    665: distribute the Program or its derivative works.  These actions are
                    666: prohibited by law if you do not accept this License.  Therefore, by
                    667: modifying or distributing the Program (or any work based on the
                    668: Program), you indicate your acceptance of this License to do so, and
                    669: all its terms and conditions for copying, distributing or modifying
                    670: the Program or works based on it.
                    671: 
                    672: @item
                    673: Each time you redistribute the Program (or any work based on the
                    674: Program), the recipient automatically receives a license from the
                    675: original licensor to copy, distribute or modify the Program subject to
                    676: these terms and conditions.  You may not impose any further
                    677: restrictions on the recipients' exercise of the rights granted herein.
                    678: You are not responsible for enforcing compliance by third parties to
                    679: this License.
                    680: 
                    681: @item
                    682: If, as a consequence of a court judgment or allegation of patent
                    683: infringement or for any other reason (not limited to patent issues),
                    684: conditions are imposed on you (whether by court order, agreement or
                    685: otherwise) that contradict the conditions of this License, they do not
                    686: excuse you from the conditions of this License.  If you cannot
                    687: distribute so as to satisfy simultaneously your obligations under this
                    688: License and any other pertinent obligations, then as a consequence you
                    689: may not distribute the Program at all.  For example, if a patent
                    690: license would not permit royalty-free redistribution of the Program by
                    691: all those who receive copies directly or indirectly through you, then
                    692: the only way you could satisfy both it and this License would be to
                    693: refrain entirely from distribution of the Program.
                    694: 
                    695: If any portion of this section is held invalid or unenforceable under
                    696: any particular circumstance, the balance of the section is intended to
                    697: apply and the section as a whole is intended to apply in other
                    698: circumstances.
                    699: 
                    700: It is not the purpose of this section to induce you to infringe any
                    701: patents or other property right claims or to contest validity of any
                    702: such claims; this section has the sole purpose of protecting the
                    703: integrity of the free software distribution system, which is
                    704: implemented by public license practices.  Many people have made
                    705: generous contributions to the wide range of software distributed
                    706: through that system in reliance on consistent application of that
                    707: system; it is up to the author/donor to decide if he or she is willing
                    708: to distribute software through any other system and a licensee cannot
                    709: impose that choice.
                    710: 
                    711: This section is intended to make thoroughly clear what is believed to
                    712: be a consequence of the rest of this License.
                    713: 
                    714: @item
                    715: If the distribution and/or use of the Program is restricted in
                    716: certain countries either by patents or by copyrighted interfaces, the
                    717: original copyright holder who places the Program under this License
                    718: may add an explicit geographical distribution limitation excluding
                    719: those countries, so that distribution is permitted only in or among
                    720: countries not thus excluded.  In such case, this License incorporates
                    721: the limitation as if written in the body of this License.
                    722: 
                    723: @item
                    724: The Free Software Foundation may publish revised and/or new versions
                    725: of the General Public License from time to time.  Such new versions will
                    726: be similar in spirit to the present version, but may differ in detail to
                    727: address new problems or concerns.
                    728: 
                    729: Each version is given a distinguishing version number.  If the Program
                    730: specifies a version number of this License which applies to it and ``any
                    731: later version'', you have the option of following the terms and conditions
                    732: either of that version or of any later version published by the Free
                    733: Software Foundation.  If the Program does not specify a version number of
                    734: this License, you may choose any version ever published by the Free Software
                    735: Foundation.
                    736: 
                    737: @item
                    738: If you wish to incorporate parts of the Program into other free
                    739: programs whose distribution conditions are different, write to the author
                    740: to ask for permission.  For software which is copyrighted by the Free
                    741: Software Foundation, write to the Free Software Foundation; we sometimes
                    742: make exceptions for this.  Our decision will be guided by the two goals
                    743: of preserving the free status of all derivatives of our free software and
                    744: of promoting the sharing and reuse of software generally.
                    745: 
                    746: @iftex
                    747: @heading NO WARRANTY
                    748: @end iftex
                    749: @ifinfo
                    750: @center NO WARRANTY
                    751: @end ifinfo
                    752: 
                    753: @item
                    754: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
                    755: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
                    756: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
                    757: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
                    758: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
                    759: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
                    760: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
                    761: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
                    762: REPAIR OR CORRECTION.
                    763: 
                    764: @item
                    765: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
                    766: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
                    767: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
                    768: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
                    769: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
                    770: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
                    771: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
                    772: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
                    773: POSSIBILITY OF SUCH DAMAGES.
                    774: @end enumerate
                    775: 
                    776: @iftex
                    777: @heading END OF TERMS AND CONDITIONS
                    778: @end iftex
                    779: @ifinfo
                    780: @center END OF TERMS AND CONDITIONS
                    781: @end ifinfo
                    782: 
                    783: @page
                    784: @unnumberedsec How to Apply These Terms to Your New Programs
                    785: 
                    786:   If you develop a new program, and you want it to be of the greatest
                    787: possible use to the public, the best way to achieve this is to make it
                    788: free software which everyone can redistribute and change under these terms.
                    789: 
                    790:   To do so, attach the following notices to the program.  It is safest
                    791: to attach them to the start of each source file to most effectively
                    792: convey the exclusion of warranty; and each file should have at least
                    793: the ``copyright'' line and a pointer to where the full notice is found.
                    794: 
                    795: @smallexample
                    796: @var{one line to give the program's name and a brief idea of what it does.}
                    797: Copyright (C) 19@var{yy}  @var{name of author}
                    798: 
                    799: This program is free software; you can redistribute it and/or modify 
                    800: it under the terms of the GNU General Public License as published by 
                    801: the Free Software Foundation; either version 2 of the License, or 
                    802: (at your option) any later version.
                    803: 
                    804: This program is distributed in the hope that it will be useful,
                    805: but WITHOUT ANY WARRANTY; without even the implied warranty of
                    806: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                    807: GNU General Public License for more details.
                    808: 
                    809: You should have received a copy of the GNU General Public License
                    810: along with this program; if not, write to the Free Software
                    811: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
                    812: @end smallexample
                    813: 
                    814: Also add information on how to contact you by electronic and paper mail.
                    815: 
                    816: If the program is interactive, make it output a short notice like this
                    817: when it starts in an interactive mode:
                    818: 
                    819: @smallexample
                    820: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
                    821: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
                    822: type `show w'.  
                    823: This is free software, and you are welcome to redistribute it 
                    824: under certain conditions; type `show c' for details.
                    825: @end smallexample
                    826: 
                    827: The hypothetical commands @samp{show w} and @samp{show c} should show
                    828: the appropriate parts of the General Public License.  Of course, the
                    829: commands you use may be called something other than @samp{show w} and
                    830: @samp{show c}; they could even be mouse-clicks or menu items---whatever
                    831: suits your program.
                    832: 
                    833: You should also get your employer (if you work as a programmer) or your
                    834: school, if any, to sign a ``copyright disclaimer'' for the program, if
                    835: necessary.  Here is a sample; alter the names:
                    836: 
                    837: @smallexample
                    838: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
                    839: `Gnomovision' (which makes passes at compilers) written by James Hacker.
                    840: 
                    841: @var{signature of Ty Coon}, 1 April 1989
                    842: Ty Coon, President of Vice
                    843: @end smallexample
                    844: 
                    845: This General Public License does not permit incorporating your program into
                    846: proprietary programs.  If your program is a subroutine library, you may
                    847: consider it more useful to permit linking proprietary applications with the
                    848: library.  If this is what you want to do, use the GNU Library General
                    849: Public License instead of this License.
                    850: 
                    851: @iftex
                    852: @unnumbered Preface
                    853: @cindex Preface
1.21      crook     854: This manual documents Gforth. Some introductory material is provided for
                    855: readers who are unfamiliar with Forth or who are migrating to Gforth
                    856: from other Forth compilers. However, this manual is primarily a
                    857: reference manual.
1.1       anton     858: @end iftex
                    859: 
1.28      crook     860: @comment TODO much more blurb here.
1.26      crook     861: 
                    862: @c ******************************************************************
1.29      crook     863: @node Goals, Gforth Environment, License, Top
1.26      crook     864: @comment node-name,     next,           previous, up
                    865: @chapter Goals of Gforth
                    866: @cindex goals of the Gforth project
                    867: The goal of the Gforth Project is to develop a standard model for
                    868: ANS Forth. This can be split into several subgoals:
                    869: 
                    870: @itemize @bullet
                    871: @item
                    872: Gforth should conform to the ANS Forth Standard.
                    873: @item
                    874: It should be a model, i.e. it should define all the
                    875: implementation-dependent things.
                    876: @item
                    877: It should become standard, i.e. widely accepted and used. This goal
                    878: is the most difficult one.
                    879: @end itemize
                    880: 
                    881: To achieve these goals Gforth should be
                    882: @itemize @bullet
                    883: @item
                    884: Similar to previous models (fig-Forth, F83)
                    885: @item
                    886: Powerful. It should provide for all the things that are considered
                    887: necessary today and even some that are not yet considered necessary.
                    888: @item
                    889: Efficient. It should not get the reputation of being exceptionally
                    890: slow.
                    891: @item
                    892: Free.
                    893: @item
                    894: Available on many machines/easy to port.
                    895: @end itemize
                    896: 
                    897: Have we achieved these goals? Gforth conforms to the ANS Forth
                    898: standard. It may be considered a model, but we have not yet documented
                    899: which parts of the model are stable and which parts we are likely to
                    900: change. It certainly has not yet become a de facto standard, but it
                    901: appears to be quite popular. It has some similarities to and some
                    902: differences from previous models. It has some powerful features, but not
                    903: yet everything that we envisioned. We certainly have achieved our
                    904: execution speed goals (@pxref{Performance}).  It is free and available
                    905: on many machines.
                    906: 
                    907: @menu
                    908: * Gforth Extensions Sinful?::
                    909: @end menu
                    910: 
                    911: @node Gforth Extensions Sinful?, , Goals, Goals
                    912: @comment node-name,     next,           previous, up
                    913: @section Is it a Sin to use Gforth Extensions?
                    914: @cindex Gforth extensions
                    915: 
                    916: If you've been paying attention, you will have realised that there is an
                    917: ANS (American National Standard) for Forth. As you read through the rest
1.29      crook     918: of this manual, you will see documentation for @i{Standard} words, and
                    919: documentation for some appealing Gforth @i{extensions}. You might ask
                    920: yourself the question: @i{``Given that there is a standard, would I be
1.26      crook     921: committing a sin to use (non-Standard) Gforth extensions?''}
                    922: 
                    923: The answer to that question is somewhat pragmatic and somewhat
                    924: philosophical. Consider these points:
                    925: 
                    926: @itemize @bullet
                    927: @item
                    928: A number of the Gforth extensions can be implemented in ANS Forth using
                    929: files provided in the @file{compat/} directory. These are mentioned in
                    930: the text in passing.
                    931: @item
                    932: Forth has a rich historical precedent for programmers taking advantage
                    933: of implementation-dependent features of their tools (for example,
                    934: relying on a knowledge of the dictionary structure). Sometimes these
                    935: techniques are necessary to extract every last bit of performance from
                    936: the hardware, sometimes they are just a programming shorthand.
                    937: @item
                    938: The best way to break the rules is to know what the rules are. To learn
                    939: the rules, there is no substitute for studying the text of the Standard
                    940: itself. In particular, Appendix A of the Standard (@var{Rationale})
                    941: provides a valuable insight into the thought processes of the technical
                    942: committee.
                    943: @item
                    944: The best reason to break a rule is because you have to; because it's
                    945: more productive to do that, because it makes your code run fast enough
                    946: or because you can see no Standard way to achieve what you want to
                    947: achieve.
                    948: @end itemize
                    949: 
                    950: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
                    951: analyse your program and determine what non-Standard definitions it
                    952: relies upon.
                    953: 
1.29      crook     954: 
1.26      crook     955: @c ******************************************************************
1.29      crook     956: @node Gforth Environment, Introduction, Goals, Top
                    957: @chapter Gforth Environment
                    958: @cindex Gforth environment
1.21      crook     959: 
1.29      crook     960: Note: ultimately, the gforth man page will be auto-generated from the
                    961: material in this chapter.
1.21      crook     962: 
                    963: @menu
1.29      crook     964: * Invoking Gforth::             Getting in
                    965: * Leaving Gforth::              Getting out
                    966: * Command-line editing::        
                    967: * Upper and lower case::
                    968: * Environment variables::       ..that affect how Gforth starts up
                    969: * Gforth Files::                What gets installed and where
1.21      crook     970: @end menu
                    971: 
1.30      anton     972: @xref{Image Files} for related information about the creation of images.
1.29      crook     973: 
1.21      crook     974: @comment ----------------------------------------------
1.29      crook     975: @node Invoking Gforth, Leaving Gforth, ,Gforth Environment
                    976: @section Invoking Gforth
                    977: @cindex invoking Gforth
                    978: @cindex running Gforth
                    979: @cindex command-line options
                    980: @cindex options on the command line
                    981: @cindex flags on the command line
1.21      crook     982: 
1.30      anton     983: Gforth is made up of two parts; an executable ``engine'' (named
                    984: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
                    985: will usually just say @code{gforth} -- this automatically loads the
                    986: default image file @file{gforth.fi}. In many other cases the default
                    987: Gforth image will be invoked like this:
1.21      crook     988: @example
1.30      anton     989: gforth [file | -e forth-code] ...
1.21      crook     990: @end example
1.29      crook     991: @noindent
                    992: This interprets the contents of the files and the Forth code in the order they
                    993: are given.
1.21      crook     994: 
1.30      anton     995: In addition to the @file{gforth} engine, there is also an engine called
                    996: @file{gforth-fast}, which is faster, but gives less informative error
                    997: messages (@pxref{Error messages}).
                    998: 
1.29      crook     999: In general, the command line looks like this:
1.21      crook    1000: 
                   1001: @example
1.30      anton    1002: gforth[-fast] [engine options] [image options]
1.21      crook    1003: @end example
                   1004: 
1.30      anton    1005: The engine options must come before the rest of the command
1.29      crook    1006: line. They are:
1.26      crook    1007: 
1.29      crook    1008: @table @code
                   1009: @cindex -i, command-line option
                   1010: @cindex --image-file, command-line option
                   1011: @item --image-file @i{file}
                   1012: @itemx -i @i{file}
                   1013: Loads the Forth image @i{file} instead of the default
                   1014: @file{gforth.fi} (@pxref{Image Files}).
1.21      crook    1015: 
1.29      crook    1016: @cindex --path, command-line option
                   1017: @cindex -p, command-line option
                   1018: @item --path @i{path}
                   1019: @itemx -p @i{path}
                   1020: Uses @i{path} for searching the image file and Forth source code files
                   1021: instead of the default in the environment variable @code{GFORTHPATH} or
                   1022: the path specified at installation time (e.g.,
                   1023: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                   1024: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21      crook    1025: 
1.29      crook    1026: @cindex --dictionary-size, command-line option
                   1027: @cindex -m, command-line option
                   1028: @cindex @i{size} parameters for command-line options
                   1029: @cindex size of the dictionary and the stacks
                   1030: @item --dictionary-size @i{size}
                   1031: @itemx -m @i{size}
                   1032: Allocate @i{size} space for the Forth dictionary space instead of
                   1033: using the default specified in the image (typically 256K). The
                   1034: @i{size} specification for this and subsequent options consists of
                   1035: an integer and a unit (e.g.,
                   1036: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
                   1037: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                   1038: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                   1039: @code{e} is used.
1.21      crook    1040: 
1.29      crook    1041: @cindex --data-stack-size, command-line option
                   1042: @cindex -d, command-line option
                   1043: @item --data-stack-size @i{size}
                   1044: @itemx -d @i{size}
                   1045: Allocate @i{size} space for the data stack instead of using the
                   1046: default specified in the image (typically 16K).
1.21      crook    1047: 
1.29      crook    1048: @cindex --return-stack-size, command-line option
                   1049: @cindex -r, command-line option
                   1050: @item --return-stack-size @i{size}
                   1051: @itemx -r @i{size}
                   1052: Allocate @i{size} space for the return stack instead of using the
                   1053: default specified in the image (typically 15K).
1.21      crook    1054: 
1.29      crook    1055: @cindex --fp-stack-size, command-line option
                   1056: @cindex -f, command-line option
                   1057: @item --fp-stack-size @i{size}
                   1058: @itemx -f @i{size}
                   1059: Allocate @i{size} space for the floating point stack instead of
                   1060: using the default specified in the image (typically 15.5K). In this case
                   1061: the unit specifier @code{e} refers to floating point numbers.
1.21      crook    1062: 
1.29      crook    1063: @cindex --locals-stack-size, command-line option
                   1064: @cindex -l, command-line option
                   1065: @item --locals-stack-size @i{size}
                   1066: @itemx -l @i{size}
                   1067: Allocate @i{size} space for the locals stack instead of using the
                   1068: default specified in the image (typically 14.5K).
1.21      crook    1069: 
1.29      crook    1070: @cindex -h, command-line option
                   1071: @cindex --help, command-line option
                   1072: @item --help
                   1073: @itemx -h
                   1074: Print a message about the command-line options
1.21      crook    1075: 
1.29      crook    1076: @cindex -v, command-line option
                   1077: @cindex --version, command-line option
                   1078: @item --version
                   1079: @itemx -v
                   1080: Print version and exit
1.21      crook    1081: 
1.29      crook    1082: @cindex --debug, command-line option
                   1083: @item --debug
                   1084: Print some information useful for debugging on startup.
1.21      crook    1085: 
1.29      crook    1086: @cindex --offset-image, command-line option
                   1087: @item --offset-image
                   1088: Start the dictionary at a slightly different position than would be used
                   1089: otherwise (useful for creating data-relocatable images,
                   1090: @pxref{Data-Relocatable Image Files}).
1.21      crook    1091: 
1.29      crook    1092: @cindex --no-offset-im, command-line option
                   1093: @item --no-offset-im
                   1094: Start the dictionary at the normal position.
1.21      crook    1095: 
1.29      crook    1096: @cindex --clear-dictionary, command-line option
                   1097: @item --clear-dictionary
                   1098: Initialize all bytes in the dictionary to 0 before loading the image
                   1099: (@pxref{Data-Relocatable Image Files}).
                   1100: 
                   1101: @cindex --die-on-signal, command-line-option
                   1102: @item --die-on-signal
                   1103: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
                   1104: or the segmentation violation SIGSEGV) by translating it into a Forth
                   1105: @code{THROW}. With this option, Gforth exits if it receives such a
                   1106: signal. This option is useful when the engine and/or the image might be
                   1107: severely broken (such that it causes another signal before recovering
                   1108: from the first); this option avoids endless loops in such cases.
                   1109: @end table
                   1110: 
                   1111: @cindex loading files at startup
                   1112: @cindex executing code on startup
                   1113: @cindex batch processing with Gforth
                   1114: As explained above, the image-specific command-line arguments for the
                   1115: default image @file{gforth.fi} consist of a sequence of filenames and
                   1116: @code{-e @var{forth-code}} options that are interpreted in the sequence
                   1117: in which they are given. The @code{-e @var{forth-code}} or
                   1118: @code{--evaluate @var{forth-code}} option evaluates the Forth
                   1119: code. This option takes only one argument; if you want to evaluate more
                   1120: Forth words, you have to quote them or use @code{-e} several times. To exit
                   1121: after processing the command line (instead of entering interactive mode)
                   1122: append @code{-e bye} to the command line.
                   1123: 
                   1124: @cindex versions, invoking other versions of Gforth
                   1125: If you have several versions of Gforth installed, @code{gforth} will
                   1126: invoke the version that was installed last. @code{gforth-@i{version}}
                   1127: invokes a specific version. You may want to use the option
                   1128: @code{--path}, if your environment contains the variable
                   1129: @code{GFORTHPATH}.
                   1130: 
                   1131: Not yet implemented:
                   1132: On startup the system first executes the system initialization file
                   1133: (unless the option @code{--no-init-file} is given; note that the system
                   1134: resulting from using this option may not be ANS Forth conformant). Then
                   1135: the user initialization file @file{.gforth.fs} is executed, unless the
                   1136: option @code{--no-rc} is given; this file is first searched in @file{.},
                   1137: then in @file{~}, then in the normal path (see above).
1.21      crook    1138: 
                   1139: 
                   1140: 
1.29      crook    1141: @comment ----------------------------------------------
                   1142: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
                   1143: @section Leaving Gforth
                   1144: @cindex Gforth - leaving
                   1145: @cindex leaving Gforth
1.21      crook    1146: 
1.30      anton    1147: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
                   1148: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
                   1149: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
                   1150: data are discarded. @xref{Image Files} for ways of saving the state of
                   1151: the system before leaving Gforth.
1.21      crook    1152: 
1.29      crook    1153: doc-bye
1.21      crook    1154: 
1.29      crook    1155: @comment ----------------------------------------------
                   1156: @node Command-line editing, Upper and lower case,Leaving Gforth,Gforth Environment
                   1157: @section Command-line editing
                   1158: @cindex command-line editing
1.21      crook    1159: 
1.29      crook    1160: Gforth maintains a history file that records every line that you type to
                   1161: the text interpreter. This file is preserved between sessions, and is
                   1162: used to provide a command-line recall facility; if you type ctrl-P
                   1163: repeatedly you can recall successively older commands from this (or
                   1164: previous) session(s). The full list of command-line editing facilities is:
1.21      crook    1165: 
1.30      anton    1166: @comment use @table? - anton
1.21      crook    1167: @itemize @bullet
                   1168: @item
1.30      anton    1169: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
1.29      crook    1170: commands from the history buffer.
                   1171: @item
1.30      anton    1172: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
1.29      crook    1173: from the history buffer.
                   1174: @item
1.30      anton    1175: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
1.29      crook    1176: @item
1.30      anton    1177: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
1.29      crook    1178: @item
1.30      anton    1179: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
1.29      crook    1180: closing up the line.
                   1181: @item
1.30      anton    1182: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
1.29      crook    1183: @item
1.30      anton    1184: @kbd{Ctrl-a} to move the cursor to the start of the line.
1.21      crook    1185: @item
1.30      anton    1186: @kbd{Ctrl-e} to move the cursor to the end of the line.
1.21      crook    1187: @item
1.30      anton    1188: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
1.29      crook    1189: line.
1.21      crook    1190: @item
1.30      anton    1191: @key{TAB} to step through all possible full-word completions of the word
1.29      crook    1192: currently being typed.
1.21      crook    1193: @item
1.30      anton    1194: @kbd{Ctrl-d} at the start of the line to terminate Gforth (gracefully,
                   1195: using @code{bye}).
1.21      crook    1196: @end itemize
                   1197: 
1.29      crook    1198: When editing, displayable characters are inserted to the left of the
                   1199: cursor position; the line is always in ``insert'' (as opposed to
                   1200: ``overstrike'') mode.
                   1201: 
                   1202: @cindex history file
                   1203: @cindex @file{.gforth-history}
                   1204: On Unix systems, the history file is @file{~/.gforth-history} by
                   1205: default@footnote{i.e. it is stored in the user's home directory.}. You
                   1206: can find out the name and location of your history file using:
                   1207: 
                   1208: @example 
                   1209: history-file type \ Unix-class systems
1.21      crook    1210: 
1.29      crook    1211: history-file type \ Other systems
                   1212: history-dir  type
1.21      crook    1213: @end example
                   1214: 
1.29      crook    1215: If you enter long definitions by hand, you can use a text editor to
                   1216: paste them out of the history file into a Forth source file for reuse at
                   1217: a later time.
                   1218: 
                   1219: Gforth never trims the size of the history file, so you should do this
                   1220: periodically, if necessary.
                   1221: 
                   1222: @comment this is all defined in history.fs
                   1223: 
                   1224: 
                   1225: 
                   1226: @comment ----------------------------------------------
                   1227: @node Upper and lower case, Environment variables,Command-line editing,Gforth Environment
                   1228: @section Upper and lower case
                   1229: @cindex case-sensitivity
                   1230: @cindex upper and lower case
                   1231: 
                   1232: Gforth is case-insensitive, so you can enter definitions and invoke
                   1233: Standard words using upper, lower or mixed case (however,
                   1234: @pxref{core-idef, Implementation-defined options, Implementation-defined
                   1235: options}).
                   1236: 
1.30      anton    1237: ANS Forth only @i{requires} implementations to recognise Standard words
                   1238: when they are typed entirely in upper case. Therefore, a Standard
                   1239: program must use upper case for all Standard words. You can use whatever
                   1240: case you like for words that you define, but in a standard program you
                   1241: have to use the words in the same case that you defined them.
                   1242: 
                   1243: Gforth supports case sensitivity through @code{table}s (case-sensitive
                   1244: wordlists, @pxref{Word Lists}).
                   1245: 
                   1246: Two people have asked how to convert Gforth to case sensitivity; while
                   1247: we think this is a bad idea, you can change all wordlists into tables
                   1248: like this:
1.29      crook    1249: 
1.30      anton    1250: @example
                   1251: ' table-find forth-wordlist wordlist-map @ !
                   1252: @end example
                   1253: 
                   1254: Note that you now have to type the predefined words in the same case
                   1255: that we defined them, which are varying.  You may want to convert them
                   1256: to your favourite case before doing this operation (I won't explain how,
                   1257: because if you are even contemplating to do this, you'd better have
                   1258: enough knowledge of Forth systems to know this already).
1.29      crook    1259: 
                   1260: @comment ----------------------------------------------
                   1261: @node Environment variables, Gforth Files, Upper and lower case,Gforth Environment
                   1262: @section Environment variables
                   1263: @cindex environment variables
1.21      crook    1264: 
1.29      crook    1265: Gforth uses these environment variables:
1.21      crook    1266: 
1.29      crook    1267: @itemize @bullet
                   1268: @item
                   1269: @cindex GFORTHHIST - environment variable
                   1270: GFORTHHIST - (Unix systems only) specifies the directory in which to
                   1271: open/create the history file, @file{.gforth-history}. Default:
                   1272: @code{$HOME}.
1.21      crook    1273: 
1.29      crook    1274: @item
                   1275: @cindex GFORTHPATH - environment variable
                   1276: GFORTHPATH - specifies the path used when searching for the gforth image file and
                   1277: for Forth source-code files.
1.21      crook    1278: 
1.29      crook    1279: @item
                   1280: @cindex GFORTH - environment variable
                   1281: GFORTH - used by @file{gforthmi} @xref{gforthmi}.
1.26      crook    1282: 
1.29      crook    1283: @item
                   1284: @cindex GFORTHD - environment variable
                   1285: GFORTHD - used by @file{gforthmi} @xref{gforthmi}.
1.21      crook    1286: 
1.29      crook    1287: @item
                   1288: @cindex TMP, TEMP - environment variable
                   1289: TMP, TEMP - (non-Unix systems only) used as a potential location for the
                   1290: history file.
                   1291: @end itemize
1.21      crook    1292: 
1.29      crook    1293: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
                   1294: @comment mentioning these.
1.21      crook    1295: 
1.29      crook    1296: All the Gforth environment variables default to sensible values if they
                   1297: are not set.
1.21      crook    1298: 
                   1299: 
1.29      crook    1300: @comment ----------------------------------------------
                   1301: @node Gforth Files, ,Environment variables,Gforth Environment
                   1302: @section Gforth files
                   1303: @cindex Gforth files
1.21      crook    1304: 
1.30      anton    1305: When you Gforth on a Unix system in the default places, it installs
                   1306: files in these locations:
1.21      crook    1307: 
1.26      crook    1308: @itemize @bullet
                   1309: @item
1.29      crook    1310: @file{/usr/local/bin/gforth}
                   1311: @item
                   1312: @file{/usr/local/bin/gforthmi}
                   1313: @item
                   1314: @file{/usr/local/man/man1/gforth.1} - man page.
                   1315: @item
                   1316: @file{/usr/local/info} - the Info version of this manual.
                   1317: @item
1.30      anton    1318: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1.29      crook    1319: @item
                   1320: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1.26      crook    1321: @item
1.30      anton    1322: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1.26      crook    1323: @item
1.30      anton    1324: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1.26      crook    1325: @end itemize
1.21      crook    1326: 
1.30      anton    1327: You can select different places for installation by using
                   1328: @code{configure} options (listed with @code{configure --help}).
1.21      crook    1329: 
1.29      crook    1330: @c ******************************************************************
                   1331: @node Introduction, Words, Gforth Environment, Top
                   1332: @comment node-name,     next,           previous, up
                   1333: @chapter An Introduction to ANS Forth
                   1334: @cindex Forth - an introduction
1.21      crook    1335: 
1.29      crook    1336: The primary purpose of this manual is to document Gforth. However, since
                   1337: Forth is not a widely-known language and there is a lack of up-to-date
                   1338: teaching material, it seems worthwhile to provide some introductory
                   1339: material. @xref{Forth-related information} for other sources of Forth-related
                   1340: information.
1.21      crook    1341: 
1.29      crook    1342: The examples in this section should work on any ANS Forth; the
                   1343: output shown was produced using Gforth. Each example attempts to
                   1344: reproduce the exact output that Gforth produces. If you try out the
                   1345: examples (and you should), what you should type is shown @kbd{like this}
                   1346: and Gforth's response is shown @code{like this}. The single exception is
1.30      anton    1347: that, where the example shows @key{RET} it means that you should
1.29      crook    1348: press the ``carriage return'' key. Unfortunately, some output formats for
                   1349: this manual cannot show the difference between @kbd{this} and
                   1350: @code{this} which will make trying out the examples harder (but not
                   1351: impossible).
1.21      crook    1352: 
1.29      crook    1353: Forth is an unusual language. It provides an interactive development
                   1354: environment which includes both an interpreter and compiler. Forth
                   1355: programming style encourages you to break a problem down into many
                   1356: @cindex factoring
                   1357: small fragments (@dfn{factoring}), and then to develop and test each
                   1358: fragment interactively. Forth advocates assert that breaking the
                   1359: edit-compile-test cycle used by conventional programming languages can
                   1360: lead to great productivity improvements.
1.21      crook    1361: 
1.29      crook    1362: @menu
                   1363: * Introducing the Text Interpreter::
                   1364: * Stacks and Postfix notation::
                   1365: * Your first definition::
                   1366: * How does that work?::
                   1367: * Forth is written in Forth::
                   1368: * Review - elements of a Forth system::
                   1369: * Where to go next::
                   1370: * Exercises::
                   1371: @end menu
1.21      crook    1372: 
1.29      crook    1373: @comment ----------------------------------------------
                   1374: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                   1375: @section Introducing the Text Interpreter
                   1376: @cindex text interpreter
                   1377: @cindex outer interpreter
1.21      crook    1378: 
1.30      anton    1379: @c IMO this is too detailed and the pace is too slow for
                   1380: @c an introduction.  If you know German, take a look at
                   1381: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
                   1382: @c to see how I do it - anton 
                   1383: 
1.29      crook    1384: When you invoke the Forth image, you will see a startup banner printed
                   1385: and nothing else (if you have Gforth installed on your system, try
1.30      anton    1386: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29      crook    1387: its command line interpreter, which is called the @dfn{Text Interpreter}
                   1388: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
1.30      anton    1389: about the text interpreter as you read through this chapter, but
                   1390: @pxref{The Text Interpreter} for more detail).
1.21      crook    1391: 
1.29      crook    1392: Although it's not obvious, Forth is actually waiting for your
1.30      anton    1393: input. Type a number and press the @key{RET} key:
1.21      crook    1394: 
1.26      crook    1395: @example
1.30      anton    1396: @kbd{45@key{RET}}  ok
1.26      crook    1397: @end example
1.21      crook    1398: 
1.29      crook    1399: Rather than give you a prompt to invite you to input something, the text
                   1400: interpreter prints a status message @i{after} it has processed a line
                   1401: of input. The status message in this case (``@code{ ok}'' followed by
                   1402: carriage-return) indicates that the text interpreter was able to process
                   1403: all of your input successfully. Now type something illegal:
                   1404: 
                   1405: @example
1.30      anton    1406: @kbd{qwer341@key{RET}}
1.29      crook    1407: :1: Undefined word
                   1408: qwer341
                   1409: ^^^^^^^
                   1410: $400D2BA8 Bounce
                   1411: $400DBDA8 no.extensions
                   1412: @end example
1.23      crook    1413: 
1.29      crook    1414: The exact text, other than the ``Undefined word'' may differ slightly on
                   1415: your system, but the effect is the same; when the text interpreter
                   1416: detects an error, it discards any remaining text on a line, resets
1.30      anton    1417: certain internal state and prints an error message. @xref{Error
                   1418: messages} for a detailed description of error messages.
1.23      crook    1419: 
1.29      crook    1420: The text interpreter waits for you to press carriage-return, and then
                   1421: processes your input line. Starting at the beginning of the line, it
                   1422: breaks the line into groups of characters separated by spaces. For each
                   1423: group of characters in turn, it makes two attempts to do something:
1.23      crook    1424: 
1.29      crook    1425: @itemize @bullet
                   1426: @item
                   1427: It tries to treat it as a command. It does this by searching a @dfn{name
                   1428: dictionary}. If the group of characters matches an entry in the name
                   1429: dictionary, the name dictionary provides the text interpreter with
                   1430: information that allows the text interpreter perform some actions. In
                   1431: Forth jargon, we say that the group
                   1432: @cindex word
                   1433: @cindex definition
                   1434: @cindex execution token
                   1435: @cindex xt
                   1436: of characters names a @dfn{word}, that the dictionary search returns an
                   1437: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
                   1438: word, and that the text interpreter executes the xt. Often, the terms
                   1439: @dfn{word} and @dfn{definition} are used interchangeably.
                   1440: @item
                   1441: If the text interpreter fails to find a match in the name dictionary, it
                   1442: tries to treat the group of characters as a number in the current number
                   1443: base (when you start up Forth, the current number base is base 10). If
                   1444: the group of characters legitimately represents a number, the text
                   1445: interpreter pushes the number onto a stack (we'll learn more about that
                   1446: in the next section).
                   1447: @end itemize
1.23      crook    1448: 
1.29      crook    1449: If the text interpreter is unable to do either of these things with any
                   1450: group of characters, it discards the group of characters and the rest of
                   1451: the line, then prints an error message. If the text interpreter reaches
                   1452: the end of the line without error, it prints the status message ``@code{ ok}''
                   1453: followed by carriage-return.
1.21      crook    1454: 
1.29      crook    1455: This is the simplest command we can give to the text interpreter:
1.23      crook    1456: 
                   1457: @example
1.30      anton    1458: @key{RET}  ok
1.23      crook    1459: @end example
1.21      crook    1460: 
1.29      crook    1461: The text interpreter did everything we asked it to do (nothing) without
                   1462: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
                   1463: command:
1.21      crook    1464: 
1.23      crook    1465: @example
1.30      anton    1466: @kbd{12 dup fred dup@key{RET}}
1.29      crook    1467: :1: Undefined word
                   1468: 12 dup fred dup
                   1469:        ^^^^
                   1470: $400D2BA8 Bounce
                   1471: $400DBDA8 no.extensions
1.23      crook    1472: @end example
1.21      crook    1473: 
1.29      crook    1474: When you press the carriage-return key, the text interpreter starts to
                   1475: work its way along the line:
1.21      crook    1476: 
1.29      crook    1477: @itemize @bullet
                   1478: @item
                   1479: When it gets to the space after the @code{2}, it takes the group of
                   1480: characters @code{12} and looks them up in the name
                   1481: dictionary@footnote{We can't tell if it found them or not, but assume
                   1482: for now that it did not}. There is no match for this group of characters
                   1483: in the name dictionary, so it tries to treat them as a number. It is
                   1484: able to do this successfully, so it puts the number, 12, ``on the stack''
                   1485: (whatever that means).
                   1486: @item
                   1487: The text interpreter resumes scanning the line and gets the next group
                   1488: of characters, @code{dup}. It looks it up in the name dictionary and
                   1489: (you'll have to take my word for this) finds it, and executes the word
                   1490: @code{dup} (whatever that means).
                   1491: @item
                   1492: Once again, the text interpreter resumes scanning the line and gets the
                   1493: group of characters @code{fred}. It looks them up in the name
                   1494: dictionary, but can't find them. It tries to treat them as a number, but
                   1495: they don't represent any legal number.
                   1496: @end itemize
1.21      crook    1497: 
1.29      crook    1498: At this point, the text interpreter gives up and prints an error
                   1499: message. The error message shows exactly how far the text interpreter
                   1500: got in processing the line. In particular, it shows that the text
                   1501: interpreter made no attempt to do anything with the final character
                   1502: group, @code{dup}, even though we have good reason to believe that the
                   1503: text interpreter would have no problem looking that word up and
                   1504: executing it a second time.
1.21      crook    1505: 
                   1506: 
1.29      crook    1507: @comment ----------------------------------------------
                   1508: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                   1509: @section Stacks, postfix notation and parameter passing
                   1510: @cindex text interpreter
                   1511: @cindex outer interpreter
1.21      crook    1512: 
1.29      crook    1513: In procedural programming languages (like C and Pascal), the
                   1514: building-block of programs is the @dfn{function} or @dfn{procedure}. These
                   1515: functions or procedures are called with @dfn{explicit parameters}. For
                   1516: example, in C we might write:
1.21      crook    1517: 
1.23      crook    1518: @example
1.29      crook    1519: total = total + new_volume(length,height,depth);
1.23      crook    1520: @end example
1.21      crook    1521: 
1.23      crook    1522: @noindent
1.29      crook    1523: where new_volume is a function-call to another piece of code, and total,
                   1524: length, height and depth are all variables. length, height and depth are
                   1525: parameters to the function-call.
1.21      crook    1526: 
1.29      crook    1527: In Forth, the equivalent of the function or procedure is the
                   1528: @dfn{definition} and parameters are implicitly passed between
                   1529: definitions using a shared stack that is visible to the
                   1530: programmer. Although Forth does support variables, the existence of the
                   1531: stack means that they are used far less often than in most other
                   1532: programming languages. When the text interpreter encounters a number, it
                   1533: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30      anton    1534: actual number is implementation-dependent ...) and the particular stack
1.29      crook    1535: used for any operation is implied unambiguously by the operation being
                   1536: performed. The stack used for all integer operations is called the @dfn{data
                   1537: stack} and, since this is the stack used most commonly, references to
                   1538: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    1539: 
1.29      crook    1540: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    1541: 
1.23      crook    1542: @example
1.30      anton    1543: @kbd{1 2 3@key{RET}}  ok
1.23      crook    1544: @end example
1.21      crook    1545: 
1.29      crook    1546: Then this instructs the text interpreter to placed three numbers on the
                   1547: (data) stack. An analogy for the behaviour of the stack is to take a
                   1548: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
                   1549: the table. The 3 was the last card onto the pile (``last-in'') and if
                   1550: you take a card off the pile then, unless you're prepared to fiddle a
                   1551: bit, the card that you take off will be the 3 (``first-out''). The
                   1552: number that will be first-out of the stack is called the @dfn{top of
                   1553: stack}, which
                   1554: @cindex TOS definition
                   1555: is often abbreviated to @dfn{TOS}.
1.21      crook    1556: 
1.29      crook    1557: To understand how parameters are passed in Forth, consider the
                   1558: behaviour of the definition @code{+} (pronounced ``plus''). You will not
                   1559: be surprised to learn that this definition performs addition. More
                   1560: precisely, it adds two number together and produces a result. Where does
                   1561: it get the two numbers from? It takes the top two numbers off the
                   1562: stack. Where does it place the result? On the stack. You can act-out the
                   1563: behaviour of @code{+} with your playing cards like this:
1.21      crook    1564: 
                   1565: @itemize @bullet
                   1566: @item
1.29      crook    1567: Pick up two cards from the stack on the table
1.21      crook    1568: @item
1.29      crook    1569: Stare at them intently and ask yourself ``what @i{is} the sum of these two
                   1570: numbers''
1.21      crook    1571: @item
1.29      crook    1572: Decide that the answer is 5
1.21      crook    1573: @item
1.29      crook    1574: Shuffle the two cards back into the pack and find a 5
1.21      crook    1575: @item
1.29      crook    1576: Put a 5 on the remaining ace that's on the table.
1.21      crook    1577: @end itemize
                   1578: 
1.29      crook    1579: If you don't have a pack of cards handy but you do have Forth running,
                   1580: you can use the definition @code{.s} to show the current state of the stack,
                   1581: without affecting the stack. Type:
1.21      crook    1582: 
                   1583: @example
1.30      anton    1584: @kbd{clearstack 1 2 3@key{RET}} ok
                   1585: @kbd{.s@key{RET}} <3> 1 2 3  ok
1.23      crook    1586: @end example
                   1587: 
1.29      crook    1588: The text interpreter looks up the word @code{clearstack} and executes
                   1589: it; it tidies up the stack and removes any entries that may have been
                   1590: left on it by earlier examples. The text interpreter pushes each of the
                   1591: three numbers in turn onto the stack. Finally, the text interpreter
                   1592: looks up the word @code{.s} and executes it. The effect of executing
                   1593: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
                   1594: followed by a list of all the items on the stack; the item on the far
                   1595: right-hand side is the TOS.
1.21      crook    1596: 
1.29      crook    1597: You can now type:
1.21      crook    1598: 
1.29      crook    1599: @example
1.30      anton    1600: @kbd{+ .s@key{RET}} <2> 1 5  ok
1.29      crook    1601: @end example
1.21      crook    1602: 
1.29      crook    1603: @noindent
                   1604: which is correct; there are now 2 items on the stack and the result of
                   1605: the addition is 5.
1.23      crook    1606: 
1.29      crook    1607: If you're playing with cards, try doing a second addition: pick up the
                   1608: two cards, work out that their sum is 6, shuffle them into the pack,
                   1609: look for a 6 and place that on the table. You now have just one item on
                   1610: the stack. What happens if you try to do a third addition? Pick up the
                   1611: first card, pick up the second card -- ah! There is no second card. This
                   1612: is called a @dfn{stack underflow} and consitutes an error. If you try to
                   1613: do the same thing with Forth it will report an error (probably a Stack
                   1614: Underflow or an Invalid Memory Address error).
1.23      crook    1615: 
1.29      crook    1616: The opposite situation to a stack underflow is a @dfn{stack overflow},
                   1617: which simply accepts that there is a finite amount of storage space
                   1618: reserved for the stack. To stretch the playing card analogy, if you had
                   1619: enough packs of cards and you piled the cards up on the table, you would
                   1620: eventually be unable to add another card; you'd hit the ceiling. Gforth
                   1621: allows you to set the maximum size of the stacks. In general, the only
                   1622: time that you will get a stack overflow is because a definition has a
                   1623: bug in it and is generating data on the stack uncontrollably.
1.23      crook    1624: 
1.29      crook    1625: There's one final use for the playing card analogy. If you model your
                   1626: stack using a pack of playing cards, the maximum number of items on
                   1627: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   1628: @i{value} of any item on the stack is 13 (the King). In fact, the only
                   1629: possible numbers are positive integer numbers 1 through 13; you can't
                   1630: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   1631: think about some of the cards, you can accommodate different
                   1632: numbers. For example, you could think of the Jack as representing 0,
                   1633: the Queen as representing -1 and the King as representing -2. Your
                   1634: *range* remains unchanged (you can still only represent a total of 13
                   1635: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    1636: 
1.29      crook    1637: In that analogy, the limit was the amount of information that a single
                   1638: stack entry could hold, and Forth has a similar limit. In Forth, the
                   1639: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
                   1640: implementation dependent and affects the maximum value that a stack
                   1641: entry can hold. A Standard Forth provides a cell size of at least
                   1642: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    1643: 
1.29      crook    1644: Forth does not do any type checking for you, so you are free to
                   1645: manipulate and combine stack items in any way you wish. A convenient way
                   1646: of treating stack items is as 2's complement signed integers, and that
                   1647: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    1648: 
1.29      crook    1649: @example
1.30      anton    1650: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
1.29      crook    1651: @end example
1.21      crook    1652: 
1.29      crook    1653: If you use numbers and definitions like @code{+} in order to turn Forth
                   1654: into a great big pocket calculator, you will realise that it's rather
                   1655: different from a normal calculator. Rather than typing 2 + 3 = you had
                   1656: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
                   1657: result). The terminology used to describe this difference is to say that
                   1658: your calculator uses @dfn{Infix Notation} (parameters and operators are
                   1659: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
                   1660: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    1661: 
1.29      crook    1662: Whilst postfix notation might look confusing to begin with, it has
                   1663: several important advantages:
1.21      crook    1664: 
1.23      crook    1665: @itemize @bullet
                   1666: @item
1.29      crook    1667: it is unambiguous
1.23      crook    1668: @item
1.29      crook    1669: it is more concise
1.23      crook    1670: @item
1.29      crook    1671: it fits naturally with a stack-based system
1.23      crook    1672: @end itemize
1.21      crook    1673: 
1.29      crook    1674: To examine these claims in more detail, consider these sums:
1.21      crook    1675: 
1.29      crook    1676: @example
                   1677: 6 + 5 * 4 =
                   1678: 4 * 5 + 6 =
                   1679: @end example
1.21      crook    1680: 
1.29      crook    1681: If you're just learning maths or your maths is very rusty, you will
                   1682: probably come up with the answer 44 for the first and 26 for the
                   1683: second. If you are a bit of a whizz at maths you will remember the
                   1684: @i{convention} that multiplication takes precendence over addition, and
                   1685: you'd come up with the answer 26 both times. To explain the answer 26
                   1686: to someone who got the answer 44, you'd probably rewrite the first sum
                   1687: like this:
1.21      crook    1688: 
1.29      crook    1689: @example
                   1690: 6 + (5 * 4) =
                   1691: @end example
1.21      crook    1692: 
1.29      crook    1693: If what you really wanted was to perform the addition before the
                   1694: multiplication, you would have to use parentheses to force it.
1.21      crook    1695: 
1.29      crook    1696: If you did the first two sums on a pocket calculator you would probably
                   1697: get the right answers, unless you were very cautious and entered them using
                   1698: these keystroke sequences:
1.21      crook    1699: 
1.29      crook    1700: 6 + 5 = * 4 =
                   1701: 4 * 5 = + 6 =
1.21      crook    1702: 
1.29      crook    1703: Postfix notation is unambiguous because the order that the operators
                   1704: are applied is always explicit; that also means that parentheses are
                   1705: never required. The operators are @i{active} (the act of quoting the
                   1706: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    1707: 
1.29      crook    1708: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   1709: equivalent ways:
1.26      crook    1710: 
                   1711: @example
1.29      crook    1712: 6 5 4 * +      or:
                   1713: 5 4 * 6 +
1.26      crook    1714: @end example
1.23      crook    1715: 
1.29      crook    1716: An important thing that you should notice about this notation is that
                   1717: the @i{order} of the numbers does not change; if you want to subtract
                   1718: 2 from 10 you type @code{10 2 -}.
1.1       anton    1719: 
1.29      crook    1720: The reason that Forth uses postfix notation is very simple to explain: it
                   1721: makes the implementation extremely simple, and it follows naturally from
                   1722: using the stack as a mechanism for passing parameters. Another way of
                   1723: thinking about this is to realise that all Forth definitions are
                   1724: @i{active}; they execute as they are encountered by the text
                   1725: interpreter. The result of this is that the syntax of Forth is trivially
                   1726: simple.
1.1       anton    1727: 
                   1728: 
                   1729: 
1.29      crook    1730: @comment ----------------------------------------------
                   1731: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   1732: @section Your first Forth definition
                   1733: @cindex first definition
1.1       anton    1734: 
1.29      crook    1735: Until now, the examples we've seen have been trivial; we've just been
                   1736: using Forth as a bigger-than-pocket calculator. Also, each calculation
                   1737: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
                   1738: again@footnote{That's not quite true. If you press the up-arrow key on
                   1739: your keyboard you should be able to scroll back to any earlier command,
                   1740: edit it and re-enter it.} In this section we'll see how to add new
                   1741: words to Forth's vocabulary.
1.1       anton    1742: 
1.29      crook    1743: The easiest way to create a new word is to use a @dfn{colon
                   1744: definition}. We'll define a few and try them out before worrying too
                   1745: much about how they work. Try typing in these examples; be careful to
                   1746: copy the spaces accurately:
1.1       anton    1747: 
1.29      crook    1748: @example
                   1749: : add-two 2 + . ;
                   1750: : greet ." Hello and welcome" ;
                   1751: : demo 5 add-two ;
                   1752: @end example
1.1       anton    1753: 
1.29      crook    1754: @noindent
                   1755: Now try them out:
1.1       anton    1756: 
1.29      crook    1757: @example
1.30      anton    1758: @kbd{greet@key{RET}} Hello and welcome  ok
                   1759: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
                   1760: @kbd{4 add-two@key{RET}} 6  ok
                   1761: @kbd{demo@key{RET}} 7  ok
                   1762: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
1.29      crook    1763: @end example
1.1       anton    1764: 
1.29      crook    1765: The first new thing that we've introduced here is the pair of words
                   1766: @code{:} and @code{;}. These are used to start and terminate a new
                   1767: definition, respectively. The first word after the @code{:} is the name
                   1768: for the new definition.
1.1       anton    1769: 
1.29      crook    1770: As you can see from the examples, a definition is built up of words that
                   1771: have already been defined; Forth makes no distinction between
                   1772: definitions that existed when you started the system up, and those that
                   1773: you define yourself.
1.1       anton    1774: 
1.29      crook    1775: The examples also introduce the words @code{.} (dot), @code{."}
                   1776: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
                   1777: the stack and displays it. It's like @code{.s} except that it only
                   1778: displays the top item of the stack and it is destructive; after it has
                   1779: executed, the number is no longer on the stack. There is always one
                   1780: space printed after the number, and no spaces before it. Dot-quote
                   1781: defines a string (a sequence of characters) that will be printed when
                   1782: the word is executed. The string can contain any printable characters
                   1783: except @code{"}. A @code{"} has a special function; it is not a Forth
                   1784: word but it acts as a delimiter (the way that delimiters work is
                   1785: described in the next section). Finally, @code{dup} duplicates the value
                   1786: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    1787: 
1.29      crook    1788: We already know that the text interpreter searches through the
                   1789: dictionary to locate names. If you've followed the examples earlier, you
                   1790: will already have a definition called @code{add-two}. Lets try modifying
                   1791: it by typing in a new definition:
1.1       anton    1792: 
1.29      crook    1793: @example
1.30      anton    1794: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
1.29      crook    1795: @end example
1.5       anton    1796: 
1.29      crook    1797: Forth recognised that we were defining a word that already exists, and
                   1798: printed a message to warn us of that fact. Let's try out the new
                   1799: definition:
1.5       anton    1800: 
1.29      crook    1801: @example
1.30      anton    1802: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
1.29      crook    1803: @end example
1.1       anton    1804: 
1.29      crook    1805: @noindent
                   1806: All that we've actually done here, though, is to create a new
                   1807: definition, with a particular name. The fact that there was already a
                   1808: definition with the same name did not make any difference to the way
                   1809: that the new definition was created (except that Forth printed a warning
                   1810: message). The old definition of add-two still exists (try @code{demo}
                   1811: again to see that this is true). Any new definition will use the new
                   1812: definition of @code{add-two}, but old definitions continue to use the
                   1813: version that already existed at the time that they were @code{compiled}.
1.1       anton    1814: 
1.29      crook    1815: Before you go on to the next section, try defining and redefining some
                   1816: words of your own.
1.1       anton    1817: 
1.29      crook    1818: @comment ----------------------------------------------
                   1819: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   1820: @section How does that work?
                   1821: @cindex parsing words
1.1       anton    1822: 
1.30      anton    1823: @c That's pretty deep (IMO way too deep) for an introduction. - anton
                   1824: 
                   1825: @c Is it a good idea to talk about the interpretation semantics of a
                   1826: @c number? We don't have an xt to go along with it. - anton
                   1827: 
                   1828: @c Now that I have eliminated execution semantics, I wonder if it would not
                   1829: @c be better to keep them (or add run-time semantics), to make it easier to
                   1830: @c explain what compilation semantics usually does. - anton
                   1831: 
1.29      crook    1832: Now we're going to take another look at the definition of @code{add-two}
                   1833: from the previous section. From our knowledge of the way that the text
                   1834: interpreter works, we would have expected this result when we tried to
                   1835: define @code{add-two}:
1.21      crook    1836: 
1.29      crook    1837: @example
1.30      anton    1838: @kbd{: add-two 2 + . " ;@key{RET}}
1.29      crook    1839:   ^^^^^^^
                   1840: Error: Undefined word
                   1841: @end example
1.28      crook    1842: 
1.29      crook    1843: The reason that this didn't happen is bound up in the way that @code{:}
                   1844: works. The word @code{:} does two special things. The first special
                   1845: thing that it does prevents the text interpreter from ever seeing the
                   1846: characters @code{add-two}. The text interpreter uses a variable called
                   1847: @cindex modifying >IN
                   1848: @code{>IN} (pronounced ''to-in'') to keep track of where it is in the
                   1849: input line. When it encounters the word @code{:} it behaves in exactly
                   1850: the same way as it does for any other word; it looks it up in the name
                   1851: dictionary, finds its xt and executes it. When @code{:} executes, it
                   1852: looks at the input buffer, finds the word @code{add-two} and advances the
                   1853: value of @code{>IN} to point past it. It then does some other stuff
                   1854: associated with creating the new definition (including creating an entry
                   1855: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   1856: completes, control returns to the text interpreter, which is oblivious
                   1857: to the fact that it has been tricked into ignoring part of the input
                   1858: line.
1.21      crook    1859: 
1.29      crook    1860: @cindex parsing words
                   1861: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   1862: prevent the text interpreter from acting on the whole of the input line
                   1863: -- are called @dfn{parsing words}.
1.21      crook    1864: 
1.29      crook    1865: @cindex @code{state} - effect on the text interpreter
                   1866: @cindex text interpreter - effect of state
                   1867: The second special thing that @code{:} does is change the value of a
                   1868: variable called @code{state}, which affects the way that the text
                   1869: interpreter behaves. When Gforth starts up, @code{state} has the value
                   1870: 0, and the text interpreter is said to be @dfn{interpreting}. During a
                   1871: colon definition (started with @code{:}), @code{state} is set to -1 and
                   1872: the text interpreter is said to be @dfn{compiling}. The word @code{;}
                   1873: ends the definition -- one of the things that it does is to change the
                   1874: value of @code{state} back to 0.
1.21      crook    1875: 
1.29      crook    1876: We have already seen how the text interpreter behaves when it is
                   1877: interpreting; it looks for each character sequence in the dictionary,
                   1878: finds its xt and executes it, or it converts it to a number and pushes
                   1879: it onto the stack, or it fails to do either and generates an error.
1.21      crook    1880: 
1.29      crook    1881: When the text interpreter is compiling, its behaviour is slightly
                   1882: different; it still looks for each character sequence in the dictionary
1.30      anton    1883: and finds it, or converts it to a number, or fails to do either and
                   1884: generates an error.  But instead of the execution token of a word it
                   1885: finds and executes the compilation token.  For most words executing the
                   1886: compilation token results in laying down (@dfn{compiling}) the execution
                   1887: token, i.e., some magic to make that xt or number get executed or pushed
                   1888: at a later time; at the time that @code{add-two} is
                   1889: @dfn{executed}. Therefore, when you execute @code{add-two} its
                   1890: @dfn{run-time effect} is exactly the same as if you had typed @code{2 +
                   1891: .} outside of a definition, and pressed carriage-return.
1.28      crook    1892: 
1.30      anton    1893: In Forth, every word or number can be described in terms of two
1.29      crook    1894: properties:
1.28      crook    1895: 
                   1896: @itemize @bullet
                   1897: @item
1.30      anton    1898: Its @dfn{interpretation semantics}, represented by the execution token.
1.28      crook    1899: @item
1.30      anton    1900: Its @dfn{compilation semantics}, represented by the compilation token.
1.29      crook    1901: @end itemize
                   1902: 
1.30      anton    1903: The value of @code{state} determines whether the text interpreter will
                   1904: use the compilation or interpretation semantics of a word or number that
                   1905: it encounters.
1.29      crook    1906: 
                   1907: @itemize @bullet
1.28      crook    1908: @item
1.29      crook    1909: @cindex interpretation semantics
                   1910: When the text interpreter encounters a word or number in @dfn{interpret}
                   1911: state, it performs the @dfn{interpretation semantics} of the word or
                   1912: number.
1.28      crook    1913: @item
1.29      crook    1914: @cindex compilation semantics
                   1915: When the text interpreter encounters a word or number in @dfn{compile}
                   1916: state, it performs the @dfn{compilation semantics} of the word or
                   1917: number.
                   1918: @end itemize
                   1919: 
                   1920: @noindent
                   1921: Numbers are always treated in a fixed way:
                   1922: 
                   1923: @itemize @bullet
1.28      crook    1924: @item
1.30      anton    1925: When the number is @dfn{interpreted}, its behaviour is to push the number onto the stack.
1.28      crook    1926: @item
1.30      anton    1927: When the number is @dfn{compiled}, a piece of code is appended to the
                   1928: current definition that pushes the number when it runs. (In other words,
                   1929: the compilation semantics of a number are to postpone its interpretation
                   1930: semantics until the run-time of the definition that it is being compiled
                   1931: into.)
1.29      crook    1932: @end itemize
                   1933: 
                   1934: The behaviour of a word is not so regular, but most have @i{default
1.30      anton    1935: compilation semantics} which means that they behave like this:
1.29      crook    1936: 
                   1937: @itemize @bullet
1.28      crook    1938: @item
1.30      anton    1939: The @dfn{interpretation semantics} of the word are to do something useful.
                   1940: @item
1.29      crook    1941: The @dfn{compilation semantics} of the word are to append its
1.30      anton    1942: @dfn{interpretation semantics} to the current definition (so that its
                   1943: run-time behaviour is to do something useful).
1.28      crook    1944: @end itemize
                   1945: 
1.30      anton    1946: @cindex immediate words
1.29      crook    1947: The actual behaviour of any particular word depends upon the way in
                   1948: which it was defined. When the text interpreter finds the word in the
                   1949: name dictionary, it not only retrieves the xt for the word, it also
                   1950: retrieves some flags: the @dfn{compile-only} flag and the @dfn{immediate
                   1951: flag}. The compile-only flag indicates that the word has no
1.30      anton    1952: interpretation semantics (the run-time behaviour for the default
                   1953: compilation semantics is not affected by this flag, however); any
                   1954: attempt to interpret a word that has the compile-only flag set will
                   1955: generate an error (for example, @code{IF} has no interpretation
                   1956: semantics). The immediate flag changes the compilation semantics of the
                   1957: word; if it is set, the compilation semantics are equal to the
                   1958: interpretation semantics (again ignoring the compile-only flag).  it. In
                   1959: other words, these so-called @dfn{immediate} words behave like this:
1.29      crook    1960: 
                   1961: @itemize @bullet
                   1962: @item
1.30      anton    1963: The @dfn{interpretation semantics} of the word are to do something useful.
1.29      crook    1964: @item
1.30      anton    1965: The @dfn{compilation semantics} of the word are to do something useful
                   1966: (and actually the same thing); i.e., it is executed during compilation.
1.29      crook    1967: @end itemize
1.28      crook    1968: 
1.29      crook    1969: This example shows the difference between an immediate and a
                   1970: non-immediate word:
1.28      crook    1971: 
1.29      crook    1972: @example
                   1973: : show-state state @@ . ;
                   1974: : show-state-now show-state ; immediate
                   1975: : word1 show-state ;
                   1976: : word2 show-state-now ;
1.28      crook    1977: @end example
1.23      crook    1978: 
1.29      crook    1979: The word @code{immediate} after the definition of @code{show-state-now}
                   1980: makes that word an immediate word. These definitions introduce a new
                   1981: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
                   1982: variable, and leaves it on the stack. Therefore, the behaviour of
                   1983: @code{show-state} is to print a number that represents the current value
                   1984: of @code{state}.
1.28      crook    1985: 
1.29      crook    1986: When you execute @code{word1}, it prints the number 0, indicating that
                   1987: the system is interpreting. When the text interpreter compiled the
                   1988: definition of @code{word1}, it encountered @code{show-state} whose
1.30      anton    1989: compilation semantics are to append its interpretation semantics to the
1.29      crook    1990: current definition. When you execute @code{word1}, it performs the
1.30      anton    1991: interpretation semantics of @code{show-state}.  At the time that @code{word1}
1.29      crook    1992: (and therefore @code{show-state}) are executed, the system is
                   1993: interpreting.
1.28      crook    1994: 
1.30      anton    1995: When you pressed @key{RET} after entering the definition of @code{word2},
1.29      crook    1996: you should have seen the number -1 printed, followed by ``@code{
                   1997: ok}''. When the text interpreter compiled the definition of
                   1998: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30      anton    1999: whose compilation semantics are therefore to perform its interpretation
1.29      crook    2000: semantics. It is executed straight away (even before the text
                   2001: interpreter has moved on to process another group of characters; the
                   2002: @code{;} in this example). The effect of executing it are to display the
                   2003: value of @code{state} @i{at the time that the definition of}
                   2004: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
                   2005: system is compiling at this time. If you execute @code{word2} it does
                   2006: nothing at all.
1.28      crook    2007: 
1.29      crook    2008: @cindex @code{."}, how it works
                   2009: Before leaving the subject of immediate words, consider the behaviour of
                   2010: @code{."} in the definition of @code{greet}, in the previous
                   2011: section. This word is both a parsing word and an immediate word. Notice
                   2012: that there is a space between @code{."} and the start of the text
                   2013: @code{Hello and welcome}, but that there is no space between the last
                   2014: letter of @code{welcome} and the @code{"} character. The reason for this
                   2015: is that @code{."} is a Forth word; it must have a space after it so that
                   2016: the text interpreter can identify it. The @code{"} is not a Forth word;
                   2017: it is a @dfn{delimiter}. The examples earlier show that, when the string
                   2018: is displayed, there is neither a space before the @code{H} nor after the
                   2019: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   2020: that @code{greet} is defined. When it executes, its behaviour is to
                   2021: search forward in the input line looking for the delimiter. When it
                   2022: finds the delimiter, it updates @code{>IN} to point past the
                   2023: delimiter. It also compiles some magic code into the definition of
                   2024: @code{greet}; the xt of a run-time routine that prints a text string. It
                   2025: compiles the string @code{Hello and welcome} into memory so that it is
                   2026: available to be printed later. When the text interpreter gains control,
                   2027: the next word it finds in the input stream is @code{;} and so it
                   2028: terminates the definition of @code{greet}.
1.28      crook    2029: 
                   2030: 
                   2031: @comment ----------------------------------------------
1.29      crook    2032: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   2033: @section Forth is written in Forth
                   2034: @cindex structure of Forth programs
                   2035: 
                   2036: When you start up a Forth compiler, a large number of definitions
                   2037: already exist. In Forth, you develop a new application using bottom-up
                   2038: programming techniques to create new definitions that are defined in
                   2039: terms of existing definitions. As you create each definition you can
                   2040: test and debug it interactively.
                   2041: 
                   2042: If you have tried out the examples in this section, you will probably
                   2043: have typed them in by hand; when you leave Gforth, your definitions will
                   2044: be lost. You can avoid this by using a text editor to enter Forth source
                   2045: code into a file, and then loading code from the file using
                   2046: @code{include} (@xref{Forth source files}). A Forth source file is
                   2047: processed by the text interpreter, just as though you had typed it in by
                   2048: hand@footnote{Actually, there are some subtle differences -- see
                   2049: @ref{The Text Interpreter}.}.
                   2050: 
                   2051: Gforth also supports the traditional Forth alternative to using text
                   2052: files for program entry (@xref{Blocks}).
1.28      crook    2053: 
1.29      crook    2054: In common with many, if not most, Forth compilers, most of Gforth is
                   2055: actually written in Forth. All of the @file{.fs} files in the
                   2056: installation directory@footnote{For example,
1.30      anton    2057: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29      crook    2058: study to see examples of Forth programming.
1.28      crook    2059: 
1.29      crook    2060: Gforth maintains a history file that records every line that you type to
                   2061: the text interpreter. This file is preserved between sessions, and is
                   2062: used to provide a command-line recall facility. If you enter long
                   2063: definitions by hand, you can use a text editor to paste them out of the
                   2064: history file into a Forth source file for reuse at a later time
                   2065: (@pxref{Command-line editing} for more information).
1.28      crook    2066: 
                   2067: 
                   2068: @comment ----------------------------------------------
1.29      crook    2069: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
                   2070: @section Review - elements of a Forth system
                   2071: @cindex elements of a Forth system
1.28      crook    2072: 
1.29      crook    2073: To summarise this chapter:
1.28      crook    2074: 
                   2075: @itemize @bullet
                   2076: @item
1.29      crook    2077: Forth programs use @dfn{factoring} to break a problem down into small
                   2078: fragments called @dfn{words} or @dfn{definitions}.
                   2079: @item
                   2080: Forth program development is an interactive process.
                   2081: @item
                   2082: The main command loop that accepts input, and controls both
                   2083: interpretation and compilation, is called the @dfn{text interpreter}
                   2084: (also known as the @dfn{outer interpreter}).
                   2085: @item
                   2086: Forth has a very simple syntax, consisting of words and numbers
                   2087: separated by spaces or carriage-return characters. Any additional syntax
                   2088: is imposed by @dfn{parsing words}.
                   2089: @item
                   2090: Forth uses a stack to pass parameters between words. As a result, it
                   2091: uses postfix notation.
                   2092: @item
                   2093: To use a word that has previously been defined, the text interpreter
                   2094: searches for the word in the @dfn{name dictionary}.
                   2095: @item
1.30      anton    2096: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28      crook    2097: @item
1.29      crook    2098: The text interpreter uses the value of @code{state} to select between
                   2099: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
                   2100: semantics} of a word that it encounters.
1.28      crook    2101: @item
1.30      anton    2102: The relationship between the @dfn{interpretation semantics} and
                   2103: @dfn{compilation semantics} for a word
1.29      crook    2104: depend upon the way in which the word was defined (for example, whether
                   2105: it is an @dfn{immediate} word).
1.28      crook    2106: @item
1.29      crook    2107: Forth definitions can be implemented in Forth (called @dfn{high-level
                   2108: definitions}) or in some other way (usually a lower-level language and
                   2109: as a result often called @dfn{low-level definitions}, @dfn{code
                   2110: definitions} or @dfn{primitives}).
1.28      crook    2111: @item
1.29      crook    2112: Many Forth systems are implemented mainly in Forth.
1.28      crook    2113: @end itemize
                   2114: 
                   2115: 
1.29      crook    2116: @comment ----------------------------------------------
                   2117: @node Where to go next,Exercises,Review - elements of a Forth system, Introduction
                   2118: @section Where To Go Next
                   2119: @cindex where to go next
1.28      crook    2120: 
1.29      crook    2121: Amazing as it may seem, if you have read (and understood) this far, you
                   2122: know almost all the fundamentals about the inner workings of a Forth
                   2123: system. You certainly know enough to be able to read and understand the
                   2124: rest of this manual and the ANS Forth document, to learn more about the
                   2125: facilities that Forth in general and Gforth in particular provide. Even
                   2126: scarier, you know almost enough to implement your own Forth system.
1.30      anton    2127: However, that's not a good idea just yet... better to try writing some
1.29      crook    2128: programs in Gforth.
1.28      crook    2129: 
1.29      crook    2130: Forth has such a rich vocabulary that it can be hard to know where to
                   2131: start in learning it. This section suggests a few sets of words that are
                   2132: enough to write small but useful programs. Use the word index in this
                   2133: document to learn more about each word, then try it out and try to write
                   2134: small definitions using it. Start by experimenting with these words:
1.28      crook    2135: 
                   2136: @itemize @bullet
                   2137: @item
1.29      crook    2138: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
                   2139: @item
                   2140: Comparison: @code{MIN MAX =}
                   2141: @item
                   2142: Logic: @code{AND OR XOR NOT}
                   2143: @item
                   2144: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    2145: @item
1.29      crook    2146: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    2147: @item
1.29      crook    2148: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    2149: @item
1.29      crook    2150: Defining words: @code{: ; CREATE}
1.28      crook    2151: @item
1.29      crook    2152: Memory allocation words: @code{ALLOT ,}
1.28      crook    2153: @item
1.29      crook    2154: Tools: @code{SEE WORDS .S MARKER}
                   2155: @end itemize
                   2156: 
                   2157: When you have mastered those, go on to:
                   2158: 
                   2159: @itemize @bullet
1.28      crook    2160: @item
1.29      crook    2161: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    2162: @item
1.29      crook    2163: Memory access: @code{@@ !}
1.28      crook    2164: @end itemize
1.23      crook    2165: 
1.29      crook    2166: When you have mastered these, there's nothing for it but to read through
                   2167: the whole of this manual and find out what you've missed.
                   2168: 
                   2169: @comment ----------------------------------------------
                   2170: @node Exercises, ,Where to go next, Introduction
                   2171: @section Exercises
                   2172: @cindex exercises
                   2173: 
                   2174: TODO: provide a set of programming excercises linked into the stuff done
                   2175: already and into other sections of the manual. Provide solutions to all
                   2176: the exercises in a .fs file in the distribution.
                   2177: 
                   2178: @c Get some inspiration from Starting Forth and Kelly&Spies.
                   2179: 
                   2180: @c excercises:
                   2181: @c 1. take inches and convert to feet and inches.
                   2182: @c 2. take temperature and convert from fahrenheight to celcius;
                   2183: @c    may need to care about symmetric vs floored??
                   2184: @c 3. take input line and do character substitution
                   2185: @c    to encipher or decipher
                   2186: @c 4. as above but work on a file for in and out
                   2187: @c 5. take input line and convert to pig-latin 
                   2188: @c
                   2189: @c thing of sets of things to exercise then come up with
                   2190: @c problems that need those things.
                   2191: 
                   2192: 
1.26      crook    2193: @c ******************************************************************
1.29      crook    2194: @node Words, Error messages, Introduction, Top
1.1       anton    2195: @chapter Forth Words
1.26      crook    2196: @cindex words
1.1       anton    2197: 
                   2198: @menu
                   2199: * Notation::                    
1.21      crook    2200: * Comments::
                   2201: * Boolean Flags::
1.1       anton    2202: * Arithmetic::                  
                   2203: * Stack Manipulation::          
1.5       anton    2204: * Memory::                      
1.1       anton    2205: * Control Structures::          
                   2206: * Defining Words::              
1.21      crook    2207: * The Text Interpreter::
1.12      anton    2208: * Tokens for Words::            
1.21      crook    2209: * Word Lists::                   
                   2210: * Environmental Queries::
1.12      anton    2211: * Files::                       
                   2212: * Blocks::                      
                   2213: * Other I/O::                   
                   2214: * Programming Tools::           
                   2215: * Assembler and Code Words::    
                   2216: * Threading Words::             
1.26      crook    2217: * Locals::                      
                   2218: * Structures::                  
                   2219: * Object-oriented Forth::       
1.21      crook    2220: * Passing Commands to the OS::
                   2221: * Miscellaneous Words::
1.1       anton    2222: @end menu
                   2223: 
1.21      crook    2224: @node Notation, Comments, Words, Words
1.1       anton    2225: @section Notation
                   2226: @cindex notation of glossary entries
                   2227: @cindex format of glossary entries
                   2228: @cindex glossary notation format
                   2229: @cindex word glossary entry format
                   2230: 
                   2231: The Forth words are described in this section in the glossary notation
                   2232: that has become a de-facto standard for Forth texts, i.e.,
                   2233: 
                   2234: @format
1.29      crook    2235: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    2236: @end format
1.29      crook    2237: @i{Description}
1.1       anton    2238: 
                   2239: @table @var
                   2240: @item word
1.28      crook    2241: The name of the word.
1.1       anton    2242: 
                   2243: @item Stack effect
                   2244: @cindex stack effect
1.29      crook    2245: The stack effect is written in the notation @code{@i{before} --
                   2246: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    2247: stack entries before and after the execution of the word. The rest of
                   2248: the stack is not touched by the word. The top of stack is rightmost,
                   2249: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   2250: uses a separate floating point stack, but a unified stack
1.29      crook    2251: notation. Also, return stack effects are not shown in @i{stack
                   2252: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    2253: the type and/or the function of the item. See below for a discussion of
                   2254: the types.
                   2255: 
                   2256: All words have two stack effects: A compile-time stack effect and a
                   2257: run-time stack effect. The compile-time stack-effect of most words is
1.29      crook    2258: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    2259: this standard behaviour, or the word does other unusual things at
                   2260: compile time, both stack effects are shown; otherwise only the run-time
                   2261: stack effect is shown.
                   2262: 
                   2263: @cindex pronounciation of words
                   2264: @item pronunciation
                   2265: How the word is pronounced.
                   2266: 
                   2267: @cindex wordset
                   2268: @item wordset
1.21      crook    2269: The ANS Forth standard is divided into several word sets. A standard
                   2270: system need not support all of them. Therefore, in theory, the fewer
                   2271: word sets your program uses the more portable it will be. However, we
                   2272: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    2273: all word sets. Words that are not defined in ANS Forth have
1.21      crook    2274: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    2275: describes words that will work in future releases of Gforth;
                   2276: @code{gforth-internal} words are more volatile. Environmental query
                   2277: strings are also displayed like words; you can recognize them by the
1.21      crook    2278: @code{environment} in the word set field.
1.1       anton    2279: 
                   2280: @item Description
                   2281: A description of the behaviour of the word.
                   2282: @end table
                   2283: 
                   2284: @cindex types of stack items
                   2285: @cindex stack item types
                   2286: The type of a stack item is specified by the character(s) the name
                   2287: starts with:
                   2288: 
                   2289: @table @code
                   2290: @item f
                   2291: @cindex @code{f}, stack item type
                   2292: Boolean flags, i.e. @code{false} or @code{true}.
                   2293: @item c
                   2294: @cindex @code{c}, stack item type
                   2295: Char
                   2296: @item w
                   2297: @cindex @code{w}, stack item type
                   2298: Cell, can contain an integer or an address
                   2299: @item n
                   2300: @cindex @code{n}, stack item type
                   2301: signed integer
                   2302: @item u
                   2303: @cindex @code{u}, stack item type
                   2304: unsigned integer
                   2305: @item d
                   2306: @cindex @code{d}, stack item type
                   2307: double sized signed integer
                   2308: @item ud
                   2309: @cindex @code{ud}, stack item type
                   2310: double sized unsigned integer
                   2311: @item r
                   2312: @cindex @code{r}, stack item type
                   2313: Float (on the FP stack)
1.21      crook    2314: @item a-
1.1       anton    2315: @cindex @code{a_}, stack item type
                   2316: Cell-aligned address
1.21      crook    2317: @item c-
1.1       anton    2318: @cindex @code{c_}, stack item type
                   2319: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    2320: @item f-
1.1       anton    2321: @cindex @code{f_}, stack item type
                   2322: Float-aligned address
1.21      crook    2323: @item df-
1.1       anton    2324: @cindex @code{df_}, stack item type
                   2325: Address aligned for IEEE double precision float
1.21      crook    2326: @item sf-
1.1       anton    2327: @cindex @code{sf_}, stack item type
                   2328: Address aligned for IEEE single precision float
                   2329: @item xt
                   2330: @cindex @code{xt}, stack item type
                   2331: Execution token, same size as Cell
                   2332: @item wid
                   2333: @cindex @code{wid}, stack item type
1.21      crook    2334: Word list ID, same size as Cell
1.1       anton    2335: @item f83name
                   2336: @cindex @code{f83name}, stack item type
                   2337: Pointer to a name structure
                   2338: @item "
                   2339: @cindex @code{"}, stack item type
1.12      anton    2340: string in the input stream (not on the stack). The terminating character
                   2341: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    2342: quotes.
                   2343: @end table
                   2344: 
1.21      crook    2345: @node Comments, Boolean Flags, Notation, Words
                   2346: @section Comments
1.26      crook    2347: @cindex comments
1.21      crook    2348: 
1.29      crook    2349: Forth supports two styles of comment; the traditional @i{in-line} comment,
                   2350: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    2351: 
1.23      crook    2352: doc-(
1.21      crook    2353: doc-\
1.23      crook    2354: doc-\G
1.21      crook    2355: 
                   2356: @node Boolean Flags, Arithmetic, Comments, Words
                   2357: @section Boolean Flags
1.26      crook    2358: @cindex Boolean flags
1.21      crook    2359: 
                   2360: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   2361: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    2362: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29      crook    2363: a cell that has @i{any} bit set as @code{true}.
1.21      crook    2364: 
                   2365: doc-true
                   2366: doc-false
1.29      crook    2367: doc-on
                   2368: doc-off
1.21      crook    2369: 
                   2370: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    2371: @section Arithmetic
                   2372: @cindex arithmetic words
                   2373: 
                   2374: @cindex division with potentially negative operands
                   2375: Forth arithmetic is not checked, i.e., you will not hear about integer
                   2376: overflow on addition or multiplication, you may hear about division by
                   2377: zero if you are lucky. The operator is written after the operands, but
                   2378: the operands are still in the original order. I.e., the infix @code{2-1}
                   2379: corresponds to @code{2 1 -}. Forth offers a variety of division
                   2380: operators. If you perform division with potentially negative operands,
                   2381: you do not want to use @code{/} or @code{/mod} with its undefined
                   2382: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   2383: former, @pxref{Mixed precision}).
1.26      crook    2384: @comment TODO discuss the different division forms and the std approach
1.1       anton    2385: 
                   2386: @menu
                   2387: * Single precision::            
                   2388: * Bitwise operations::          
1.21      crook    2389: * Double precision::            Double-cell integer arithmetic
                   2390: * Numeric comparison::
1.29      crook    2391: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    2392: * Floating Point::              
                   2393: @end menu
                   2394: 
                   2395: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
                   2396: @subsection Single precision
                   2397: @cindex single precision arithmetic words
                   2398: 
1.21      crook    2399: By default, numbers in Forth are single-precision integers that are 1
1.26      crook    2400: cell in size. They can be signed or unsigned, depending upon how you
1.21      crook    2401: treat them. @xref{Number Conversion} for the rules used by the text
                   2402: interpreter for recognising single-precision integers.
                   2403: 
1.1       anton    2404: doc-+
1.21      crook    2405: doc-1+
1.1       anton    2406: doc--
1.21      crook    2407: doc-1-
1.1       anton    2408: doc-*
                   2409: doc-/
                   2410: doc-mod
                   2411: doc-/mod
                   2412: doc-negate
                   2413: doc-abs
                   2414: doc-min
                   2415: doc-max
1.21      crook    2416: doc-d>s
1.27      crook    2417: doc-floored
1.1       anton    2418: 
1.21      crook    2419: @node Bitwise operations, Double precision, Single precision, Arithmetic
1.1       anton    2420: @subsection Bitwise operations
                   2421: @cindex bitwise operation words
                   2422: 
                   2423: doc-and
                   2424: doc-or
                   2425: doc-xor
                   2426: doc-invert
1.21      crook    2427: doc-lshift
                   2428: doc-rshift
1.1       anton    2429: doc-2*
1.21      crook    2430: doc-d2*
1.1       anton    2431: doc-2/
1.21      crook    2432: doc-d2/
                   2433: 
                   2434: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
                   2435: @subsection Double precision
                   2436: @cindex double precision arithmetic words
                   2437: 
                   2438: @xref{Number Conversion} for the rules used by the text interpreter for
                   2439: recognising double-precision integers.
                   2440: 
                   2441: A double precision number is represented by a cell pair, with the most
1.31    ! anton    2442: significant cell at the TOS. It is trivial to convert an unsigned
1.26      crook    2443: single to an (unsigned) double; simply push a @code{0} onto the
                   2444: TOS. Since numbers are represented by Gforth using 2's complement
                   2445: arithmetic, converting a signed single to a (signed) double requires
1.31    ! anton    2446: sign-extension across the most significant cell. This can be achieved
1.26      crook    2447: using @code{s>d}. The moral of the story is that you cannot convert a
                   2448: number without knowing whether it represents an unsigned or a
                   2449: signed number.
1.21      crook    2450: 
                   2451: doc-s>d
                   2452: doc-d+
                   2453: doc-d-
                   2454: doc-dnegate
                   2455: doc-dabs
                   2456: doc-dmin
                   2457: doc-dmax
                   2458: 
                   2459: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
                   2460: @subsection Numeric comparison
                   2461: @cindex numeric comparison words
                   2462: 
1.28      crook    2463: doc-<
                   2464: doc-<=
                   2465: doc-<>
                   2466: doc-=
                   2467: doc->
                   2468: doc->=
                   2469: 
1.21      crook    2470: doc-0<
1.23      crook    2471: doc-0<=
1.21      crook    2472: doc-0<>
                   2473: doc-0=
1.23      crook    2474: doc-0>
                   2475: doc-0>=
1.28      crook    2476: 
                   2477: doc-u<
                   2478: doc-u<=
1.31    ! anton    2479: @c TODO why u<> and u= ... they are the same as <> and =
        !          2480: @c commented them out because they are unnecessary
        !          2481: @c doc-u<>
        !          2482: @c doc-u=
1.28      crook    2483: doc-u>
                   2484: doc-u>=
                   2485: 
                   2486: doc-within
                   2487: 
                   2488: doc-d<
                   2489: doc-d<=
                   2490: doc-d<>
                   2491: doc-d=
                   2492: doc-d>
                   2493: doc-d>=
1.23      crook    2494: 
1.21      crook    2495: doc-d0<
1.23      crook    2496: doc-d0<=
                   2497: doc-d0<>
1.21      crook    2498: doc-d0=
1.23      crook    2499: doc-d0>
                   2500: doc-d0>=
                   2501: 
1.21      crook    2502: doc-du<
1.28      crook    2503: doc-du<=
1.31    ! anton    2504: @c doc-du<>
        !          2505: @c doc-du=
1.28      crook    2506: doc-du>
                   2507: doc-du>=
1.1       anton    2508: 
1.21      crook    2509: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    2510: @subsection Mixed precision
                   2511: @cindex mixed precision arithmetic words
                   2512: 
                   2513: doc-m+
                   2514: doc-*/
                   2515: doc-*/mod
                   2516: doc-m*
                   2517: doc-um*
                   2518: doc-m*/
                   2519: doc-um/mod
                   2520: doc-fm/mod
                   2521: doc-sm/rem
                   2522: 
1.21      crook    2523: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    2524: @subsection Floating Point
                   2525: @cindex floating point arithmetic words
                   2526: 
1.21      crook    2527: @xref{Number Conversion} for the rules used by the text interpreter for
                   2528: recognising floating-point numbers.
1.1       anton    2529: 
                   2530: @cindex angles in trigonometric operations
                   2531: @cindex trigonometric operations
                   2532: Angles in floating point operations are given in radians (a full circle
1.26      crook    2533: has 2 pi radians). Gforth has a separate floating point
                   2534: stack, but the documentation uses the unified notation.
1.1       anton    2535: 
                   2536: @cindex floating-point arithmetic, pitfalls
                   2537: Floating point numbers have a number of unpleasant surprises for the
                   2538: unwary (e.g., floating point addition is not associative) and even a few
                   2539: for the wary. You should not use them unless you know what you are doing
                   2540: or you don't care that the results you get are totally bogus. If you
                   2541: want to learn about the problems of floating point numbers (and how to
                   2542: avoid them), you might start with @cite{David Goldberg, What Every
                   2543: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
1.17      anton    2544: Computing Surveys 23(1):5@minus{}48, March 1991}
                   2545: (@url{http://www.validgh.com/goldberg/paper.ps}).
1.1       anton    2546: 
1.21      crook    2547: doc-d>f
                   2548: doc-f>d
1.1       anton    2549: doc-f+
                   2550: doc-f-
                   2551: doc-f*
                   2552: doc-f/
                   2553: doc-fnegate
                   2554: doc-fabs
                   2555: doc-fmax
                   2556: doc-fmin
                   2557: doc-floor
                   2558: doc-fround
                   2559: doc-f**
                   2560: doc-fsqrt
                   2561: doc-fexp
                   2562: doc-fexpm1
                   2563: doc-fln
                   2564: doc-flnp1
                   2565: doc-flog
                   2566: doc-falog
                   2567: doc-fsin
                   2568: doc-fcos
                   2569: doc-fsincos
                   2570: doc-ftan
                   2571: doc-fasin
                   2572: doc-facos
                   2573: doc-fatan
                   2574: doc-fatan2
                   2575: doc-fsinh
                   2576: doc-fcosh
                   2577: doc-ftanh
                   2578: doc-fasinh
                   2579: doc-facosh
                   2580: doc-fatanh
1.21      crook    2581: doc-pi
1.28      crook    2582: 
1.31    ! anton    2583: doc-f2*
        !          2584: doc-f2/
        !          2585: doc-1/f
        !          2586: doc-precision
        !          2587: doc-set-precision
        !          2588: 
        !          2589: One particular problem with floating-point arithmetic is that comparison
        !          2590: for equality often fails when you would expect it to succeed.  For this
        !          2591: reason approximate equality is often preferred (but you still have to
        !          2592: know what you are doing).  The comparison words are:
        !          2593: 
        !          2594: doc-f~rel
        !          2595: doc-f~abs
        !          2596: doc-f=
        !          2597: doc-f~
        !          2598: doc-f<>
        !          2599: 
        !          2600: doc-f<
        !          2601: doc-f<=
        !          2602: doc-f>
        !          2603: doc-f>=
        !          2604: 
1.21      crook    2605: doc-f0<
1.28      crook    2606: doc-f0<=
                   2607: doc-f0<>
1.21      crook    2608: doc-f0=
1.28      crook    2609: doc-f0>
                   2610: doc-f0>=
                   2611: 
1.1       anton    2612: 
                   2613: @node Stack Manipulation, Memory, Arithmetic, Words
                   2614: @section Stack Manipulation
                   2615: @cindex stack manipulation words
                   2616: 
                   2617: @cindex floating-point stack in the standard
1.21      crook    2618: Gforth maintains a number of separate stacks:
                   2619: 
1.29      crook    2620: @cindex data stack
                   2621: @cindex parameter stack
1.21      crook    2622: @itemize @bullet
                   2623: @item
1.29      crook    2624: A data stack (also known as the @dfn{parameter stack}) -- for
                   2625: characters, cells, addresses, and double cells.
1.21      crook    2626: 
1.29      crook    2627: @cindex floating-point stack
1.21      crook    2628: @item
                   2629: A floating point stack -- for floating point numbers.
                   2630: 
1.29      crook    2631: @cindex return stack
1.21      crook    2632: @item
                   2633: A return stack -- for storing the return addresses of colon
                   2634: definitions and other data.
                   2635: 
1.29      crook    2636: @cindex locals stack
1.21      crook    2637: @item
                   2638: A locals stack for storing local variables.
                   2639: @end itemize
                   2640: 
                   2641: Whilst every sane Forth has a separate floating-point stack, it is not
                   2642: strictly required; an ANS Forth system could theoretically keep
                   2643: floating-point numbers on the data stack. As an additional difficulty,
                   2644: you don't know how many cells a floating-point number takes. It is
                   2645: reportedly possible to write words in a way that they work also for a
                   2646: unified stack model, but we do not recommend trying it. Instead, just
                   2647: say that your program has an environmental dependency on a separate
                   2648: floating-point stack.
                   2649: 
                   2650: doc-floating-stack
1.1       anton    2651: 
                   2652: @cindex return stack and locals
                   2653: @cindex locals and return stack
1.21      crook    2654: A Forth system is allowed to keep local variables on the
1.1       anton    2655: return stack. This is reasonable, as local variables usually eliminate
                   2656: the need to use the return stack explicitly. So, if you want to produce
1.21      crook    2657: a standard compliant program and you are using local variables in a
                   2658: word, forget about return stack manipulations in that word (refer to the
1.1       anton    2659: standard document for the exact rules).
                   2660: 
                   2661: @menu
                   2662: * Data stack::                  
                   2663: * Floating point stack::        
                   2664: * Return stack::                
                   2665: * Locals stack::                
                   2666: * Stack pointer manipulation::  
                   2667: @end menu
                   2668: 
                   2669: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   2670: @subsection Data stack
                   2671: @cindex data stack manipulation words
                   2672: @cindex stack manipulations words, data stack
                   2673: 
                   2674: doc-drop
                   2675: doc-nip
                   2676: doc-dup
                   2677: doc-over
                   2678: doc-tuck
                   2679: doc-swap
1.21      crook    2680: doc-pick
1.1       anton    2681: doc-rot
                   2682: doc--rot
                   2683: doc-?dup
                   2684: doc-roll
                   2685: doc-2drop
                   2686: doc-2nip
                   2687: doc-2dup
                   2688: doc-2over
                   2689: doc-2tuck
                   2690: doc-2swap
                   2691: doc-2rot
                   2692: 
                   2693: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   2694: @subsection Floating point stack
                   2695: @cindex floating-point stack manipulation words
                   2696: @cindex stack manipulation words, floating-point stack
                   2697: 
                   2698: doc-fdrop
                   2699: doc-fnip
                   2700: doc-fdup
                   2701: doc-fover
                   2702: doc-ftuck
                   2703: doc-fswap
1.21      crook    2704: doc-fpick
1.1       anton    2705: doc-frot
                   2706: 
                   2707: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   2708: @subsection Return stack
                   2709: @cindex return stack manipulation words
                   2710: @cindex stack manipulation words, return stack
                   2711: 
                   2712: doc->r
                   2713: doc-r>
                   2714: doc-r@
                   2715: doc-rdrop
                   2716: doc-2>r
                   2717: doc-2r>
                   2718: doc-2r@
                   2719: doc-2rdrop
                   2720: 
                   2721: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   2722: @subsection Locals stack
                   2723: 
1.26      crook    2724: @comment TODO
1.21      crook    2725: 
1.1       anton    2726: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   2727: @subsection Stack pointer manipulation
                   2728: @cindex stack pointer manipulation words
                   2729: 
1.21      crook    2730: doc-sp0
                   2731: doc-s0
1.1       anton    2732: doc-sp@
                   2733: doc-sp!
1.21      crook    2734: doc-fp0
1.1       anton    2735: doc-fp@
                   2736: doc-fp!
1.21      crook    2737: doc-rp0
                   2738: doc-r0
1.1       anton    2739: doc-rp@
                   2740: doc-rp!
1.21      crook    2741: doc-lp0
                   2742: doc-l0
1.1       anton    2743: doc-lp@
                   2744: doc-lp!
                   2745: 
                   2746: @node Memory, Control Structures, Stack Manipulation, Words
                   2747: @section Memory
1.26      crook    2748: @cindex memory words
1.1       anton    2749: 
1.27      crook    2750: @cindex dictionary
                   2751: Forth definitions are organised in memory structures that are
1.29      crook    2752: collectively called the @dfn{dictionary}. The dictionary can be
1.27      crook    2753: considered as three logical memory regions:
                   2754: 
                   2755: @itemize @bullet
                   2756: @item
                   2757: @cindex code space
                   2758: @cindex code dictionary
1.29      crook    2759: Code space, also known as the @dfn{code dictionary}.
1.27      crook    2760: @item
                   2761: @cindex name space
                   2762: @cindex name dictionary
1.29      crook    2763: Name space, also known as the @dfn{name dictionary}@footnote{Sometimes,
                   2764: the term @dfn{dictionary} is used simply to refer to the name
1.27      crook    2765: dictionary, because it is the one region that is used for looking up
                   2766: names, just as you would in a conventional dictionary.}.
                   2767: @item
                   2768: @cindex data space
                   2769: Data space
                   2770: @end itemize
                   2771: 
1.29      crook    2772: When you create a colon definition, the text interpreter compiles the
                   2773: code for the definition into the code dictionary and compiles the name
1.27      crook    2774: of the definition into the name dictionary, together with other
                   2775: information about the definition (such as its execution token).
                   2776: 
                   2777: When you create a variable, the execution of @code{variable} will
                   2778: compile some code, assign once cell in data space, and compile the name
                   2779: of the variable into the name dictionary.
                   2780: 
                   2781: @cindex memory regions - relationship between them
                   2782: ANS Forth does not specify the relationship between the three memory
                   2783: regions, and specifies that a Standard program must not access code or
                   2784: data space directly -- it may only access data space directly. In
                   2785: addition, the Standard defines what relationships you may and may not
                   2786: rely on when allocating regions in data space. These constraints are
                   2787: simply a reflection of the many diverse techniques that are used to
                   2788: implement Forth systems; understanding and following the requirements of
                   2789: the Standard allows you to write portable programs -- programs that run
                   2790: in the same way on any of these diverse systems. Another way of looking
                   2791: at this is to say that ANS Forth was designed to permit compliant Forth
                   2792: systems to be implemented in many diverse ways.
                   2793: 
                   2794: @cindex memory regions - how they are assigned
1.29      crook    2795: Here are some examples of ways in which name, code and data spaces
                   2796: might be assigned in different Forth implementations:
1.27      crook    2797: 
                   2798: @itemize @bullet
                   2799: @item
                   2800: For a Forth system that runs from RAM under a general-purpose operating
                   2801: system, it can be convenient to interleave name, code and data spaces in
                   2802: a single contiguous memory region. This organisation can be
                   2803: memory-efficient (for example, because the relationship between the name
                   2804: dictionary entry and the associated code dictionary entry can be
                   2805: implicit, rather than requiring an explicit memory pointer to reference
                   2806: from the name dictionary and the code dictionary). This is the
                   2807: organisation used by Gforth, as this example@footnote{The addresses
                   2808: in the example have been truncated to fit it onto the page, and the
                   2809: addresses and data shown will not match the output from your system} shows:
                   2810: @example
                   2811: hex
                   2812: variable fred 123456 fred !
                   2813: variable jim abcd jim !
                   2814: : foo + / - ;
                   2815: ' fred 10 - 50 dump 
                   2816: ..80: 5C 46 0E 40  84 66 72 65 - 64 20 20 20  20 20 20 20  \F.@.fred       
                   2817: ..90: D0 9B 04 08  00 00 00 00 - 56 34 12 00  80 46 0E 40  ........V4...F.@
                   2818: ..A0: 83 6A 69 6D  20 20 20 20 - D0 9B 04 08  00 00 00 00  .jim    ........
                   2819: ..B0: CD AB 00 00  9C 46 0E 40 - 83 66 6F 6F  20 20 20 20  .....F.@.foo    
                   2820: ..C0: 80 9B 04 08  00 00 00 00 - E4 2E 05 08  0C 2F 05 08  ............./..
                   2821: @end example
                   2822: 
                   2823: @item
                   2824: For a high-performance system running on a modern RISC processor with a
                   2825: modified Harvard architecture (one that has a unified main memory but
                   2826: separate instruction and data caches), it is desirable to separate
                   2827: processor instructions from processor data. This encourages a high cache
                   2828: density and therefore a high cache hit rate. The Forth code dictionary
                   2829: is not necessarily made up entirely of processor instructions; its
                   2830: nature is dependent upon the Forth implementation. 
                   2831: 
                   2832: @item
                   2833: A Forth compiler that runs on a segmented 8086 processor could be
                   2834: designed to interleave the name, code and data spaces within a single
                   2835: 64Kbyte segment. A more common implementation choice is to use a
                   2836: separate 64Kbyte segment for each region, which provides more memory
                   2837: overall but provides an address map in which only the data space is
                   2838: accessible.
                   2839: 
                   2840: @item
                   2841: Microprocessors exist that run Forth (or many of the primitives required
                   2842: to implement the Forth virtual machine efficiently) directly. On these
                   2843: processors, the relationship between name, code and data spaces may be
                   2844: imposed as a side-effect of the microarchitecture of the processor.
                   2845: 
                   2846: @item
                   2847: A Forth compiler that executes from ROM on an embedded system needs its
                   2848: data space separated from the name and code spaces so that the data
                   2849: space can be mapped to a RAM area.
                   2850: 
                   2851: @item 
                   2852: A Forth compiler that runs on an embedded system may have a requirement
                   2853: for a small memory footprint. On such a system it can be useful to
                   2854: separate the name space from the data and code spaces; once the
                   2855: application has been compiled, the name dictionary is no longer
                   2856: required@footnote{more strictly speaking, most applications can be
                   2857: designed so that this is the case}. The name dictionary can be deleted
1.29      crook    2858: entirely, or could be stored in memory on a remote @i{host} system for
1.27      crook    2859: debug and development purposes. In the latter case, the compiler running
1.29      crook    2860: on the @i{target} system could implement a protocol across a
1.27      crook    2861: communication link that would allow it to interrogate the name dictionary.
                   2862: @end itemize
                   2863: 
1.1       anton    2864: @menu
1.27      crook    2865: * Reserving Data Space::
                   2866: * Memory Access::
                   2867: * Address Arithmetic::
                   2868: * Memory Blocks::
                   2869: * Dynamic Allocation::
1.1       anton    2870: @end menu
                   2871: 
1.27      crook    2872: 
                   2873: @node Reserving Data Space, Memory Access, Memory, Memory
                   2874: @subsection Reserving Data Space
                   2875: @cindex reserving data space
                   2876: @cindex data space - reserving some
                   2877: 
                   2878: @cindex data space pointer - contiguous regions
1.29      crook    2879: Data space may be reserved as individual chars or cells or in contiguous
                   2880: regions. These are the rules for reserving contiguous regions in a
                   2881: Standard (i.e., portable) way:
1.27      crook    2882: @itemize @bullet
                   2883: @item
                   2884: The value of the data-space pointer, @code{here}, always defines the
                   2885: beginning of a contiguous region of data space.
                   2886: 
                   2887: @item
                   2888: @code{CREATE} establishes the beginning of a contiguous region of data
                   2889: space (the @code{CREATE}d definition returns the initial address of the
                   2890: region).
                   2891: 
                   2892: @item
1.29      crook    2893: @code{variable} does @i{not} establish the beginning of a contiguous
1.27      crook    2894: region in data space; @code{variable} followed by @code{allot} is not
                   2895: guaranteed to allocate data space region that is contiguous with the
                   2896: storage allocated by @code{variable}. Instead, use @code{create} --
                   2897: @xref{Simple Defining Words} for examples.
                   2898: 
                   2899: @item
                   2900: Successive calls to @code{allot}, @code{,} (comma), @code{2,} (2-comma),
                   2901: @code{c,} (c-comma) and @code{align} reserve a single contiguous region
                   2902: in data space. The contiguity of the region is interrupted by compiling
                   2903: (or removing) definitions from the dictionary.
                   2904: 
                   2905: @item
                   2906: The most recently reserved contiguous region may be released by calling
                   2907: @code{allot} with a negative argument, provided that the region has not
                   2908: been interrupted by compiling (or removing) definitions from the
                   2909: dictionary.
                   2910: @end itemize
                   2911: 
1.29      crook    2912: @cindex data space pointer - alignment
                   2913: These factors affect the alignment of @code{here}, the data
                   2914: space pointer:
                   2915: 
                   2916: @itemize @bullet
                   2917: @item
                   2918: If the data-space pointer is aligned@footnote{In ANS Forth-speak,
                   2919: @i{aligned} implictly means @code{CELL}-aligned.} before an
                   2920: @code{allot}, and a whole number of characters are reserved or released, it
                   2921: will remain aligned after the @code{allot}.
                   2922: 
                   2923: @item
                   2924: If the data-space pointer is character-aligned before an @code{allot},
                   2925: and a whole number of cells are reserved or released, it will remain
                   2926: character-aligned after the @code{allot}.
                   2927: 
                   2928: @item
                   2929: The initial contents of data space reserved using @code{allot} is
                   2930: undefined.
                   2931: 
                   2932: @item
                   2933: Definitions created by @code{create}, @code{variable}, @code{2variable}
                   2934: return aligned addresses.
                   2935: 
                   2936: @item
                   2937: After a definition is compiled or @code{align} is executed, the data
                   2938: space pointer is guaranteed to be aligned.
                   2939: @end itemize
                   2940: 
1.27      crook    2941: doc-here
                   2942: doc-unused
                   2943: doc-allot
                   2944: doc-c,
1.29      crook    2945: doc-f,
1.27      crook    2946: doc-,
                   2947: doc-2,
1.29      crook    2948: @cindex user space
                   2949: doc-udp
                   2950: doc-uallot
1.27      crook    2951: 
                   2952: 
                   2953: @node Memory Access, Address Arithmetic, Reserving Data Space, Memory
1.1       anton    2954: @subsection Memory Access
                   2955: @cindex memory access words
                   2956: 
                   2957: doc-@
                   2958: doc-!
                   2959: doc-+!
                   2960: doc-c@
                   2961: doc-c!
                   2962: doc-2@
                   2963: doc-2!
                   2964: doc-f@
                   2965: doc-f!
                   2966: doc-sf@
                   2967: doc-sf!
                   2968: doc-df@
                   2969: doc-df!
                   2970: 
1.27      crook    2971: @node Address Arithmetic, Memory Blocks, Memory Access, Memory
                   2972: @subsection Address Arithmetic
1.1       anton    2973: @cindex address arithmetic words
                   2974: 
                   2975: ANS Forth does not specify the sizes of the data types. Instead, it
                   2976: offers a number of words for computing sizes and doing address
1.29      crook    2977: arithmetic. Address arithmetic is performed in terms of address units
                   2978: (aus); on most systems the address unit is one byte. Note that a
                   2979: character may have more than one au, so @code{chars} is no noop (on
                   2980: systems where it is a noop, it compiles to nothing).
1.1       anton    2981: 
                   2982: @cindex alignment of addresses for types
                   2983: ANS Forth also defines words for aligning addresses for specific
                   2984: types. Many computers require that accesses to specific data types
                   2985: must only occur at specific addresses; e.g., that cells may only be
                   2986: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   2987: accesses, it can usually perform aligned accesses faster. 
                   2988: 
                   2989: For the performance-conscious: alignment operations are usually only
                   2990: necessary during the definition of a data structure, not during the
                   2991: (more frequent) accesses to it.
                   2992: 
                   2993: ANS Forth defines no words for character-aligning addresses. This is not
                   2994: an oversight, but reflects the fact that addresses that are not
                   2995: char-aligned have no use in the standard and therefore will not be
                   2996: created.
                   2997: 
                   2998: @cindex @code{CREATE} and alignment
1.29      crook    2999: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    3000: are cell-aligned; in addition, Gforth guarantees that these addresses
                   3001: are aligned for all purposes.
                   3002: 
1.26      crook    3003: Note that the ANS Forth word @code{char} has nothing to do with address
                   3004: arithmetic.
1.1       anton    3005: 
                   3006: doc-chars
                   3007: doc-char+
                   3008: doc-cells
                   3009: doc-cell+
                   3010: doc-cell
                   3011: doc-align
                   3012: doc-aligned
                   3013: doc-floats
                   3014: doc-float+
                   3015: doc-float
                   3016: doc-falign
                   3017: doc-faligned
                   3018: doc-sfloats
                   3019: doc-sfloat+
                   3020: doc-sfalign
                   3021: doc-sfaligned
                   3022: doc-dfloats
                   3023: doc-dfloat+
                   3024: doc-dfalign
                   3025: doc-dfaligned
                   3026: doc-maxalign
                   3027: doc-maxaligned
                   3028: doc-cfalign
                   3029: doc-cfaligned
                   3030: doc-address-unit-bits
                   3031: 
1.27      crook    3032: @node Memory Blocks, Dynamic Allocation, Address Arithmetic, Memory
1.1       anton    3033: @subsection Memory Blocks
                   3034: @cindex memory block words
1.27      crook    3035: @cindex character strings - moving and copying
                   3036: 
                   3037: Memory blocks often represent character strings; @xref{String Formats}
                   3038: for ways of storing character strings in memory. @xref{Displaying
                   3039: characters and strings} for other string-processing words.
1.1       anton    3040: 
1.21      crook    3041: Some of these words work on address units (increments of @code{CELL}),
                   3042: and expect a @code{CELL}-aligned address. Others work on character units
                   3043: (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
                   3044: address. Choose the correct operation depending upon your data type. If
                   3045: you are moving a block of memory (for example, a region reserved by
                   3046: @code{allot}) it is safe to use @code{move}, and it should be faster
                   3047: than using @code{cmove}. If you are moving (for example) a string
                   3048: compiled using @code{S"}, it is not portable to use @code{move}; the
                   3049: alignment of the string in memory could change, and the relationship
                   3050: between @code{CELL} and @code{CHAR} could change.
                   3051: 
                   3052: When copying characters between overlapping memory regions, choose
                   3053: carefully between @code{cmove} and @code{cmove>}.
                   3054: 
1.29      crook    3055: You can only use any of these words @i{portably} to access data space.
1.21      crook    3056: 
1.27      crook    3057: @comment TODO - think the naming of the arguments is wrong for move
1.29      crook    3058: @comment well, really it seems to be the Standard that's wrong; it
                   3059: @comment describes MOVE as a word that requires a CELL-aligned source
                   3060: @comment and destination address but a xtranfer count that need not
                   3061: @comment be a multiple of CELL.
1.1       anton    3062: doc-move
                   3063: doc-erase
                   3064: doc-cmove
                   3065: doc-cmove>
                   3066: doc-fill
                   3067: doc-blank
1.21      crook    3068: doc-compare
                   3069: doc-search
1.27      crook    3070: doc--trailing
                   3071: doc-/string
                   3072: 
                   3073: @comment TODO examples
                   3074: 
                   3075: @node Dynamic Allocation, ,Memory Blocks, Memory
                   3076: @subsection Dynamic Allocation of Memory
                   3077: @cindex dynamic allocation of memory
                   3078: @cindex memory-allocation word set
                   3079: 
                   3080: The ANS Forth memory-allocation word set allows memory regions to be
                   3081: dynamically assigned, resized and released without affecting the data
                   3082: space pointer. In Gforth, these words are implemented using
                   3083: the standard C library calls malloc(), free() and resize().
                   3084: 
                   3085: doc-allocate
                   3086: doc-free
                   3087: doc-resize
                   3088: 
1.1       anton    3089: 
1.26      crook    3090: @node Control Structures, Defining Words, Memory, Words
1.1       anton    3091: @section Control Structures
                   3092: @cindex control structures
                   3093: 
                   3094: Control structures in Forth cannot be used in interpret state, only in
1.29      crook    3095: compile state@footnote{To be precise, they have no interpretation
                   3096: semantics (@pxref{Interpretation and Compilation Semantics}).}, i.e., in
1.1       anton    3097: a colon definition. We do not like this limitation, but have not seen a
                   3098: satisfying way around it yet, although many schemes have been proposed.
                   3099: 
                   3100: @menu
1.29      crook    3101: * Selection::                   IF.. ELSE.. ENDIF
                   3102: * Simple Loops::                BEGIN..
                   3103: * Counted Loops::               DO
                   3104: * Arbitrary control structures::
                   3105: * Calls and returns::
1.1       anton    3106: * Exception Handling::          
                   3107: @end menu
                   3108: 
                   3109: @node Selection, Simple Loops, Control Structures, Control Structures
                   3110: @subsection Selection
                   3111: @cindex selection control structures
                   3112: @cindex control structures for selection
                   3113: 
                   3114: @cindex @code{IF} control structure
                   3115: @example
1.29      crook    3116: @i{flag}
1.1       anton    3117: IF
1.29      crook    3118:   @i{code}
1.1       anton    3119: ENDIF
                   3120: @end example
1.21      crook    3121: @noindent
1.1       anton    3122: or
                   3123: @example
1.29      crook    3124: @i{flag}
1.1       anton    3125: IF
1.29      crook    3126:   @i{code1}
1.1       anton    3127: ELSE
1.29      crook    3128:   @i{code2}
1.1       anton    3129: ENDIF
                   3130: @end example
                   3131: 
                   3132: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   3133: standard, and @code{ENDIF} is not, although it is quite popular. We
                   3134: recommend using @code{ENDIF}, because it is less confusing for people
                   3135: who also know other languages (and is not prone to reinforcing negative
                   3136: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   3137: system that only supplies @code{THEN} is simple:
                   3138: @example
1.21      crook    3139: : ENDIF   POSTPONE THEN ; immediate
1.1       anton    3140: @end example
                   3141: 
                   3142: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   3143: (adv.)}  has the following meanings:
                   3144: @quotation
                   3145: ... 2b: following next after in order ... 3d: as a necessary consequence
                   3146: (if you were there, then you saw them).
                   3147: @end quotation
                   3148: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   3149: and many other programming languages has the meaning 3d.]
                   3150: 
1.21      crook    3151: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    3152: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    3153: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    3154: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   3155: @file{compat/control.fs}.
                   3156: 
                   3157: @cindex @code{CASE} control structure
                   3158: @example
1.29      crook    3159: @i{n}
1.1       anton    3160: CASE
1.29      crook    3161:   @i{n1} OF @i{code1} ENDOF
                   3162:   @i{n2} OF @i{code2} ENDOF
1.1       anton    3163:   @dots{}
                   3164: ENDCASE
                   3165: @end example
                   3166: 
1.29      crook    3167: Executes the first @i{codei}, where the @i{ni} is equal to
                   3168: @i{n}. A default case can be added by simply writing the code after
                   3169: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
1.1       anton    3170: but must not consume it.
                   3171: 
                   3172: @node Simple Loops, Counted Loops, Selection, Control Structures
                   3173: @subsection Simple Loops
                   3174: @cindex simple loops
                   3175: @cindex loops without count 
                   3176: 
                   3177: @cindex @code{WHILE} loop
                   3178: @example
                   3179: BEGIN
1.29      crook    3180:   @i{code1}
                   3181:   @i{flag}
1.1       anton    3182: WHILE
1.29      crook    3183:   @i{code2}
1.1       anton    3184: REPEAT
                   3185: @end example
                   3186: 
1.29      crook    3187: @i{code1} is executed and @i{flag} is computed. If it is true,
                   3188: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    3189: false, execution continues after the @code{REPEAT}.
                   3190: 
                   3191: @cindex @code{UNTIL} loop
                   3192: @example
                   3193: BEGIN
1.29      crook    3194:   @i{code}
                   3195:   @i{flag}
1.1       anton    3196: UNTIL
                   3197: @end example
                   3198: 
1.29      crook    3199: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    3200: 
                   3201: @cindex endless loop
                   3202: @cindex loops, endless
                   3203: @example
                   3204: BEGIN
1.29      crook    3205:   @i{code}
1.1       anton    3206: AGAIN
                   3207: @end example
                   3208: 
                   3209: This is an endless loop.
                   3210: 
                   3211: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   3212: @subsection Counted Loops
                   3213: @cindex counted loops
                   3214: @cindex loops, counted
                   3215: @cindex @code{DO} loops
                   3216: 
                   3217: The basic counted loop is:
                   3218: @example
1.29      crook    3219: @i{limit} @i{start}
1.1       anton    3220: ?DO
1.29      crook    3221:   @i{body}
1.1       anton    3222: LOOP
                   3223: @end example
                   3224: 
1.29      crook    3225: This performs one iteration for every integer, starting from @i{start}
                   3226: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    3227: accessed with @code{i}. For example, the loop:
1.1       anton    3228: @example
                   3229: 10 0 ?DO
                   3230:   i .
                   3231: LOOP
                   3232: @end example
1.21      crook    3233: @noindent
                   3234: prints @code{0 1 2 3 4 5 6 7 8 9}
                   3235: 
1.1       anton    3236: The index of the innermost loop can be accessed with @code{i}, the index
                   3237: of the next loop with @code{j}, and the index of the third loop with
                   3238: @code{k}.
                   3239: 
                   3240: doc-i
                   3241: doc-j
                   3242: doc-k
                   3243: 
                   3244: The loop control data are kept on the return stack, so there are some
1.21      crook    3245: restrictions on mixing return stack accesses and counted loop words. In
                   3246: particuler, if you put values on the return stack outside the loop, you
                   3247: cannot read them inside the loop@footnote{well, not in a way that is
                   3248: portable.}. If you put values on the return stack within a loop, you
                   3249: have to remove them before the end of the loop and before accessing the
                   3250: index of the loop.
1.1       anton    3251: 
                   3252: There are several variations on the counted loop:
                   3253: 
1.21      crook    3254: @itemize @bullet
                   3255: @item
                   3256: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   3257: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   3258: 
                   3259: @example
                   3260: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   3261: @end example
                   3262: prints @code{0 1 2 3}
                   3263: 
1.1       anton    3264: 
1.21      crook    3265: @item
                   3266: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   3267: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   3268: return stack so @code{EXIT} can get to its return address. For example:
                   3269: 
                   3270: @example
                   3271: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   3272: @end example
                   3273: prints @code{0 1 2 3}
                   3274: 
                   3275: 
                   3276: @item
1.29      crook    3277: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    3278: (and @code{LOOP} iterates until they become equal by wrap-around
                   3279: arithmetic). This behaviour is usually not what you want. Therefore,
                   3280: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29      crook    3281: @code{?DO}), which do not enter the loop if @i{start} is greater than
                   3282: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    3283: unsigned loop parameters.
                   3284: 
1.21      crook    3285: @item
                   3286: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   3287: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   3288: if you know that the loop is entered in any case. Such knowledge tends
                   3289: to become invalid during maintenance of a program, and then the
                   3290: @code{DO} will make trouble.
                   3291: 
                   3292: @item
1.29      crook    3293: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
                   3294: index by @i{n} instead of by 1. The loop is terminated when the border
                   3295: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    3296: 
1.21      crook    3297: @example
                   3298: 4 0 +DO  i .  2 +LOOP
                   3299: @end example
                   3300: @noindent
                   3301: prints @code{0 2}
                   3302: 
                   3303: @example
                   3304: 4 1 +DO  i .  2 +LOOP
                   3305: @end example
                   3306: @noindent
                   3307: prints @code{1 3}
1.1       anton    3308: 
                   3309: 
                   3310: @cindex negative increment for counted loops
                   3311: @cindex counted loops with negative increment
1.29      crook    3312: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    3313: 
1.21      crook    3314: @example
                   3315: -1 0 ?DO  i .  -1 +LOOP
                   3316: @end example
                   3317: @noindent
                   3318: prints @code{0 -1}
1.1       anton    3319: 
1.21      crook    3320: @example
                   3321: 0 0 ?DO  i .  -1 +LOOP
                   3322: @end example
                   3323: prints nothing.
1.1       anton    3324: 
1.29      crook    3325: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
                   3326: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
                   3327: index by @i{u} each iteration. The loop is terminated when the border
                   3328: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    3329: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   3330: 
1.21      crook    3331: @example
                   3332: -2 0 -DO  i .  1 -LOOP
                   3333: @end example
                   3334: @noindent
                   3335: prints @code{0 -1}
1.1       anton    3336: 
1.21      crook    3337: @example
                   3338: -1 0 -DO  i .  1 -LOOP
                   3339: @end example
                   3340: @noindent
                   3341: prints @code{0}
                   3342: 
                   3343: @example
                   3344: 0 0 -DO  i .  1 -LOOP
                   3345: @end example
                   3346: @noindent
                   3347: prints nothing.
1.1       anton    3348: 
1.21      crook    3349: @end itemize
1.1       anton    3350: 
                   3351: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    3352: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   3353: for these words that uses only standard words is provided in
                   3354: @file{compat/loops.fs}.
1.1       anton    3355: 
                   3356: 
                   3357: @cindex @code{FOR} loops
1.26      crook    3358: Another counted loop is:
1.1       anton    3359: @example
1.29      crook    3360: @i{n}
1.1       anton    3361: FOR
1.29      crook    3362:   @i{body}
1.1       anton    3363: NEXT
                   3364: @end example
                   3365: This is the preferred loop of native code compiler writers who are too
1.26      crook    3366: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29      crook    3367: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
                   3368: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    3369: Forth systems may behave differently, even if they support @code{FOR}
                   3370: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    3371: 
                   3372: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   3373: @subsection Arbitrary control structures
                   3374: @cindex control structures, user-defined
                   3375: 
                   3376: @cindex control-flow stack
                   3377: ANS Forth permits and supports using control structures in a non-nested
                   3378: way. Information about incomplete control structures is stored on the
                   3379: control-flow stack. This stack may be implemented on the Forth data
                   3380: stack, and this is what we have done in Gforth.
                   3381: 
                   3382: @cindex @code{orig}, control-flow stack item
                   3383: @cindex @code{dest}, control-flow stack item
                   3384: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   3385: entry represents a backward branch target. A few words are the basis for
                   3386: building any control structure possible (except control structures that
                   3387: need storage, like calls, coroutines, and backtracking).
                   3388: 
                   3389: doc-if
                   3390: doc-ahead
                   3391: doc-then
                   3392: doc-begin
                   3393: doc-until
                   3394: doc-again
                   3395: doc-cs-pick
                   3396: doc-cs-roll
                   3397: 
1.21      crook    3398: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   3399: manipulate the control-flow stack in a portable way. Without them, you
                   3400: would need to know how many stack items are occupied by a control-flow
                   3401: entry (many systems use one cell. In Gforth they currently take three,
                   3402: but this may change in the future).
                   3403: 
1.1       anton    3404: Some standard control structure words are built from these words:
                   3405: 
                   3406: doc-else
                   3407: doc-while
                   3408: doc-repeat
                   3409: 
                   3410: Gforth adds some more control-structure words:
                   3411: 
                   3412: doc-endif
                   3413: doc-?dup-if
                   3414: doc-?dup-0=-if
                   3415: 
                   3416: Counted loop words constitute a separate group of words:
                   3417: 
                   3418: doc-?do
                   3419: doc-+do
                   3420: doc-u+do
                   3421: doc--do
                   3422: doc-u-do
                   3423: doc-do
                   3424: doc-for
                   3425: doc-loop
                   3426: doc-+loop
                   3427: doc--loop
                   3428: doc-next
                   3429: doc-leave
                   3430: doc-?leave
                   3431: doc-unloop
                   3432: doc-done
                   3433: 
1.21      crook    3434: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   3435: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    3436: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   3437: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   3438: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   3439: resolved (by using one of the loop-ending words or @code{DONE}).
                   3440: 
1.26      crook    3441: Another group of control structure words are:
1.1       anton    3442: 
                   3443: doc-case
                   3444: doc-endcase
                   3445: doc-of
                   3446: doc-endof
                   3447: 
1.21      crook    3448: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   3449: @code{CS-ROLL}.
1.1       anton    3450: 
                   3451: @subsubsection Programming Style
                   3452: 
                   3453: In order to ensure readability we recommend that you do not create
                   3454: arbitrary control structures directly, but define new control structure
                   3455: words for the control structure you want and use these words in your
1.26      crook    3456: program. For example, instead of writing:
1.1       anton    3457: 
                   3458: @example
1.26      crook    3459: BEGIN
1.1       anton    3460:   ...
1.26      crook    3461: IF [ 1 CS-ROLL ]
1.1       anton    3462:   ...
1.26      crook    3463: AGAIN THEN
1.1       anton    3464: @end example
                   3465: 
1.21      crook    3466: @noindent
1.1       anton    3467: we recommend defining control structure words, e.g.,
                   3468: 
                   3469: @example
1.26      crook    3470: : WHILE ( DEST -- ORIG DEST )
                   3471:  POSTPONE IF
                   3472:  1 CS-ROLL ; immediate
                   3473: 
                   3474: : REPEAT ( orig dest -- )
                   3475:  POSTPONE AGAIN
                   3476:  POSTPONE THEN ; immediate
1.1       anton    3477: @end example
                   3478: 
1.21      crook    3479: @noindent
1.1       anton    3480: and then using these to create the control structure:
                   3481: 
                   3482: @example
1.26      crook    3483: BEGIN
1.1       anton    3484:   ...
1.26      crook    3485: WHILE
1.1       anton    3486:   ...
1.26      crook    3487: REPEAT
1.1       anton    3488: @end example
                   3489: 
                   3490: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   3491: @code{WHILE} are predefined, so in this example it would not be
                   3492: necessary to define them.
                   3493: 
                   3494: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   3495: @subsection Calls and returns
                   3496: @cindex calling a definition
                   3497: @cindex returning from a definition
                   3498: 
1.3       anton    3499: @cindex recursive definitions
                   3500: A definition can be called simply be writing the name of the definition
1.26      crook    3501: to be called. Normally a definition is invisible during its own
1.3       anton    3502: definition. If you want to write a directly recursive definition, you
1.26      crook    3503: can use @code{recursive} to make the current definition visible, or
                   3504: @code{recurse} to call the current definition directly.
1.3       anton    3505: 
                   3506: doc-recursive
                   3507: doc-recurse
                   3508: 
1.21      crook    3509: @comment TODO add example of the two recursion methods
1.12      anton    3510: @quotation
                   3511: @progstyle
                   3512: I prefer using @code{recursive} to @code{recurse}, because calling the
                   3513: definition by name is more descriptive (if the name is well-chosen) than
                   3514: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   3515: implementation, it is much better to read (and think) ``now sort the
                   3516: partitions'' than to read ``now do a recursive call''.
                   3517: @end quotation
1.3       anton    3518: 
1.29      crook    3519: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    3520: 
                   3521: @example
1.28      crook    3522: Defer foo
1.3       anton    3523: 
                   3524: : bar ( ... -- ... )
                   3525:  ... foo ... ;
                   3526: 
                   3527: :noname ( ... -- ... )
                   3528:  ... bar ... ;
                   3529: IS foo
                   3530: @end example
                   3531: 
1.26      crook    3532: The current definition returns control to the calling definition when
1.29      crook    3533: the end of the definition is reached or @code{EXIT} is
                   3534: encountered. Deferred words are discussed in more detail in @ref{Simple
                   3535: Defining Words}.
1.1       anton    3536: 
                   3537: doc-exit
                   3538: doc-;s
                   3539: 
                   3540: @node Exception Handling,  , Calls and returns, Control Structures
                   3541: @subsection Exception Handling
1.26      crook    3542: @cindex exceptions
1.1       anton    3543: 
1.26      crook    3544: If your program detects a fatal error condition, the simplest action
                   3545: that it can take is to @code{quit}. This resets the return stack and
                   3546: restarts the text interpreter, but does not print any error message.
1.21      crook    3547: 
1.26      crook    3548: The next stage in severity is to execute @code{abort}, which has the
                   3549: same effect as @code{quit}, with the addition that it resets the data
                   3550: stack.
1.1       anton    3551: 
1.26      crook    3552: A slightly more sophisticated approach is use use @code{abort"}, which
                   3553: compiles a string to be used as an error message and does a conditional
                   3554: @code{abort} at run-time. For example:
1.1       anton    3555: 
1.26      crook    3556: @example
1.30      anton    3557: @kbd{: checker abort" That flag was true" ." A false flag" ;@key{RET}}  ok
                   3558: @kbd{0 checker@key{RET}} A false flag ok
                   3559: @kbd{1 checker@key{RET}}
1.26      crook    3560: :1: That flag was true
                   3561: 1 checker
                   3562:   ^^^^^^^
                   3563: $400D1648 throw 
                   3564: $400E4660
                   3565: @end example
1.1       anton    3566: 
1.26      crook    3567: These simple techniques allow a program to react to a fatal error
                   3568: condition, but they are not exactly user-friendly. The ANS Forth
                   3569: Exception word set provides the pair of words @code{throw} and
                   3570: @code{catch}, which can be used to provide sophisticated error-handling.
1.1       anton    3571: 
1.26      crook    3572: @code{catch} has a similar behaviour to @code{execute}, in that it takes
1.29      crook    3573: an @i{xt} as a parameter and starts execution of the xt. However,
1.26      crook    3574: before passing control to the xt, @code{catch} pushes an
1.29      crook    3575: @dfn{exception frame} onto the @dfn{exception stack}. This exception
1.26      crook    3576: frame is used to restore the system to a known state if a detected error
                   3577: occurs during the execution of the xt. A typical way to use @code{catch}
                   3578: would be:
1.1       anton    3579: 
1.26      crook    3580: @example
                   3581: ... ['] foo catch IF ...
                   3582: @end example
1.1       anton    3583: 
1.26      crook    3584: Whilst @code{foo} executes, it can call other words to any level of
                   3585: nesting, as usual.  If @code{foo} (and all the words that it calls)
                   3586: execute successfully, control will ultimately passes to the word following
                   3587: the @code{catch}, and there will be a @code{true} flag (0) at
                   3588: TOS. However, if any word detects an error, it can terminate the
                   3589: execution of @code{foo} by pushing an error code onto the stack and then
                   3590: performing a @code{throw}. The execution of @code{throw} will pass 
                   3591: control to the word following the @code{catch}, but this time the TOS
                   3592: will hold the error code. Therefore, the @code{IF} in the example
                   3593: can be used to determine whether @code{foo} executed successfully.
1.1       anton    3594: 
1.26      crook    3595: This simple example shows how you can use @code{throw} and @code{catch}
                   3596: to ``take over'' exception handling from the system:
1.1       anton    3597: @example
1.26      crook    3598: : my-div ['] / catch if ." DIVIDE ERROR" else ." OK.. " . then ;
1.1       anton    3599: @end example
                   3600: 
1.26      crook    3601: The next example is more sophisticated and shows a multi-level
                   3602: @code{throw} and @code{catch}. To understand this example, start at the
                   3603: definition of @code{top-level} and work backwards:
                   3604: 
1.1       anton    3605: @example
1.26      crook    3606: : lowest-level ( -- c )
                   3607:     key dup 27 = if
                   3608:        1 throw \ ESCAPE key pressed
                   3609:     else
                   3610:        ." lowest-level successfull" CR
                   3611:     then
                   3612: ;
                   3613: 
                   3614: : lower-level ( -- c )
                   3615:     lowest-level
                   3616:     \ at this level consider a CTRL-U to be a fatal error
                   3617:     dup 21 = if \ CTRL-U
                   3618:        2 throw
                   3619:     else
                   3620:        ." lower-level successfull" CR
                   3621:     then
                   3622: ;
                   3623: 
                   3624: : low-level ( -- c )
                   3625:     ['] lower-level catch
                   3626:     ?dup if
                   3627:        \ error occurred - do we recognise it?
                   3628:        dup 1 = if
                   3629:            \ ESCAPE key pressed.. pretend it was an E
                   3630:            [char] E
                   3631:        else throw \ propogate the error upwards
                   3632:        then
                   3633:     then
                   3634:     ." low-level successfull" CR
                   3635: ;
                   3636: 
                   3637: : top-level ( -- )
                   3638:     CR ['] low-level catch \ CATCH is used like EXECUTE
                   3639:     ?dup if \ error occurred..
                   3640:        ." Error " . ." occurred - contact your supplier"
                   3641:     else
                   3642:        ." The '" emit ." ' key was pressed" CR
                   3643:     then
                   3644: ;
1.1       anton    3645: @end example
                   3646: 
1.26      crook    3647: The ANS Forth document assigns @code{throw} codes thus:
1.1       anton    3648: 
1.26      crook    3649: @itemize @bullet
                   3650: @item
                   3651: codes in the range -1 -- -255 are reserved to be assigned by the
                   3652: Standard. Assignments for codes in the range -1 -- -58 are currently
                   3653: documented in the Standard. In particular, @code{-1 throw} is equivalent
                   3654: to @code{abort} and @code{-2 throw} is equivalent to @code{abort"}.
                   3655: @item
                   3656: codes in the range -256 -- -4095 are reserved to be assigned by the system.
                   3657: @item
                   3658: all other codes may be assigned by programs.
                   3659: @end itemize
1.1       anton    3660: 
1.26      crook    3661: Gforth provides the word @code{exception} as a mechanism for assigning
                   3662: system throw codes to applications. This allows multiple applications to
                   3663: co-exist in memory without any clash of @code{throw} codes. A definition
                   3664: of @code{exception} in ANS Forth is provided in
                   3665: @file{compat/exception.fs}.
1.1       anton    3666: 
1.26      crook    3667: doc-quit
                   3668: doc-abort
                   3669: doc-abort"
1.1       anton    3670: 
1.26      crook    3671: doc-catch
1.29      crook    3672: doc-throw
                   3673: doc---exception-exception
                   3674: 
                   3675: 
                   3676: @c -------------------------------------------------------------
                   3677: @node Defining Words, The Text Interpreter, Control Structures, Words
                   3678: @section Defining Words
                   3679: @cindex defining words
                   3680: 
                   3681: @menu
                   3682: * Simple Defining Words::       Variables, values and constants
                   3683: * Colon Definitions::
                   3684: * User-defined Defining Words::
                   3685: * Supplying names::
                   3686: * Interpretation and Compilation Semantics::
                   3687: @end menu
                   3688: 
                   3689: @node Simple Defining Words, Colon Definitions, Defining Words, Defining Words
                   3690: @subsection Simple Defining Words
                   3691: @cindex simple defining words
                   3692: @cindex defining words, simple
                   3693: 
                   3694: Defining words are used to create new entries in the dictionary. The
                   3695: simplest defining word is @code{CREATE}. @code{CREATE} is used like
                   3696: this:
                   3697: 
                   3698: @example
                   3699: CREATE new-word1
                   3700: @end example
                   3701: 
                   3702: @code{CREATE} is a parsing word that generates a dictionary entry for
                   3703: @code{new-word1}. When @code{new-word1} is executed, all that it does is
                   3704: leave an address on the stack. The address represents the value of
                   3705: the data space pointer (@code{HERE}) at the time that @code{new-word1}
                   3706: was defined. Therefore, @code{CREATE} is a way of associating a name
                   3707: with the address of a region of memory.
                   3708: 
                   3709: By extending this example to reserve some memory in data space, we end
                   3710: up with a @i{variable}. Here are two different ways to do it:
                   3711: 
                   3712: @example
                   3713: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
                   3714: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
                   3715: @end example
                   3716: 
                   3717: The variable can be examined and modified using @code{@@} (``fetch'') and
                   3718: @code{!} (``store'') like this:
                   3719: 
                   3720: @example
                   3721: new-word2 @@ .      \ get address, fetch from it and display
                   3722: 1234 new-word2 !   \ new value, get address, store to it
                   3723: @end example
                   3724: 
                   3725: As a final refinement, the whole code sequence can be wrapped up in a
                   3726: defining word (pre-empting the subject of the next section), making it
                   3727: easier to create new variables:
                   3728: 
                   3729: @example
                   3730: : myvariable ( "name" -- a-addr ) CREATE 1 cells allot ;
                   3731: 
                   3732: myvariable foo
                   3733: myvariable joe
                   3734: 
                   3735: 45 3 * foo !   \ set foo to 135
                   3736: 1234 joe !     \ set joe to 1234
                   3737: 3 joe +!       \ increment joe by 3.. to 1237
                   3738: @end example
                   3739: 
                   3740: Not surprisingly, there is no need to define @code{myvariable}, since
                   3741: Forth already has a definition @code{Variable}. It behaves in exactly
                   3742: the same way as @code{myvariable} but it is implemented in an optimised
                   3743: way. Forth also provides @code{2Variable} and @code{fvariable} for
                   3744: double and floating-point variables, respectively.
                   3745: 
                   3746: @cindex arrays
                   3747: A similar mechanism can be used to create arrays. For example, an
                   3748: 80-character text input buffer:
                   3749: 
                   3750: @example
                   3751: CREATE text-buf 80 chars allot
                   3752: 
                   3753: text-buf 0 chars c@@ \ the 1st character (offset 0)
                   3754: text-buf 3 chars c@@ \ the 4th character (offset 3)
                   3755: @end example
                   3756: 
                   3757: You can build arbitrarily complex data structures by allocating
                   3758: appropriate areas of memory. @xref{Structures} for further discussions
                   3759: of this, and to learn about some Gforth tools that make it easier.
                   3760: 
                   3761: @cindex user variables
                   3762: @cindex user space
                   3763: The defining word @code{User} behaves in the same way as @code{Variable}.
                   3764: The difference is that it reserves space in @i{user (data) space} rather
                   3765: than normal data space. In a Forth system that has a multi-tasker, each
                   3766: task has its own set of user variables.
                   3767: 
                   3768: @comment TODO is that stuff about user variables strictly correct? Is it
                   3769: @comment just terminal tasks that have user variables?
                   3770: @comment should document tasker.fs (with some examples) elsewhere
                   3771: @comment in this manual, then expand on user space and user variables.
                   3772: 
                   3773: After @code{CREATE} and @code{Variable}s, the next defining word to
                   3774: consider is @code{Constant}. @code{Constant} allows you to declare a
                   3775: fixed value and refer to it by name. For example:
                   3776: 
                   3777: @example
                   3778: 12 Constant INCHES-PER-FOOT
                   3779: 3E+08 fconstant SPEED-O-LIGHT
                   3780: @end example
                   3781: 
                   3782: A @code{Variable} can be both read and written, so its run-time
                   3783: behaviour is to supply an address through which its current value can be
                   3784: manipulated. In contrast, the value of a @code{Constant} cannot be
                   3785: changed once it has been declared@footnote{Well, often it can be -- but
                   3786: not in a Standard, portable way. It's safer to use a @code{Value} (read
                   3787: on).} so it's not necessary to supply the address -- it is more
                   3788: efficient to return the value of the constant directly. That's exactly
                   3789: what happens; the run-time effect of a constant is to put its value on
                   3790: the top of the stack (@ref{User-defined Defining Words} describes one
                   3791: way of implementing @code{Constant}).
                   3792: 
                   3793: Gforth also provides @code{2Constant} and @code{fconstant} for defining
                   3794: double and floating-point constants, respectively.
                   3795: 
                   3796: Constants in Forth behave differently from their equivalents in other
                   3797: programming languages. In other languages, a constant (such as an EQU in
                   3798: assembler or a #define in C) only exists at compile-time; in the
                   3799: executable program the constant has been translated into an absolute
                   3800: number and, unless you are using a symbolic debugger, it's impossible to
                   3801: know what abstract thing that number represents. In Forth a constant has
                   3802: an entry in the name dictionary and remains there after the code that
                   3803: uses it has been defined. In fact, it must remain in the dictionary
                   3804: since it has run-time duties to perform. For example:
                   3805: 
                   3806: @example
                   3807: 12 Constant INCHES-PER-FOOT
                   3808: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
                   3809: @end example
                   3810: 
                   3811: @cindex in-lining of constants
                   3812: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
                   3813: associated with the constant @code{INCHES-PER-FOOT}. If you use
                   3814: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
                   3815: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
                   3816: attempt to optimise constants by in-lining them where they are used. You
                   3817: can force Gforth to in-line a constant like this:
                   3818: 
                   3819: @example
                   3820: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
                   3821: @end example
                   3822: 
                   3823: If you use @code{see} to decompile @i{this} version of
                   3824: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
                   3825: longer present. @xref{Interpret/Compile states} and @xref{Literals}
                   3826: explain to this works.
                   3827: 
                   3828: In-lining constants in this way might improve execution time
                   3829: fractionally, and can ensure that a constant is now only referenced at
                   3830: compile-time. However, the definition of the constant still remains in
                   3831: the dictionary. Some Forth compilers provide a mechanism for controlling
                   3832: a second dictionary for holding transient words such that this second
                   3833: dictionary can be deleted later in order to recover memory
                   3834: space. However, there is no standard way of doing this.
                   3835: 
                   3836: One aspect of constants and variables that can sometimes be confusing is
                   3837: that they have different stack effects; one returns its value whilst the
                   3838: other returns the address of its value. The defining word @code{Value}
                   3839: provides an alternative to @code{Variable}, and has the same stack
                   3840: effect as a constant. A @code{Value} needs an additional word, @code{TO}
                   3841: to allow its value to be changed. Here are some examples:
                   3842: 
                   3843: @example
                   3844: 12 Value APPLES \ a Value is initialised when it is declared.. like a
                   3845:                 \ constant but unlike a variable
                   3846: 34 TO APPLES    \ Change the value of APPLES. TO is a parsing word
                   3847: APPLES          \ puts 34 on the top of the stack.
                   3848: @end example
                   3849: 
                   3850: The defining word @code{Defer} allows you to define a word by name
                   3851: without defining its behaviour; the definition of its behaviour is
                   3852: deferred. Here are two situation where this can be useful:
                   3853: 
                   3854: @itemize @bullet
                   3855: @item
                   3856: Where you want to allow the behaviour of a word to be altered later, and
                   3857: for all precompiled references to the word to change when its behaviour
                   3858: is changed.
                   3859: @item
                   3860: For mutual recursion; @xref{Calls and returns}.
                   3861: @end itemize
                   3862: 
                   3863: In the following example, @code{foo} always invokes the version of
                   3864: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
                   3865: always invokes the version that prints ``@code{Hello}''. There is no way
                   3866: of getting @code{foo} to use the later version without re-ordering the
                   3867: source code and recompilng it.
                   3868: 
                   3869: @example
                   3870: : greet ." Good morning" ;
                   3871: : foo ... greet ... ;
                   3872: : greet ." Hello" ;
                   3873: : bar ... greet ... ;
                   3874: @end example
                   3875: 
                   3876: This problem can be solved by defining @code{greet} as a @code{Defer}red
                   3877: word. The behaviour of a @code{Defer}red word can be defined and
                   3878: redefined at any time by using @code{IS} to associate the xt of a
                   3879: previously-defined word with it. The previous example becomes:
                   3880: 
                   3881: @example
                   3882: Defer greet
                   3883: : foo ... greet ... ;
                   3884: : bar ... greet ... ;
                   3885: : greet1 ." Good morning" ;
                   3886: : greet2 ." Hello" ;
                   3887: ' greet2 IS greet  \ make greet behave like greet2
                   3888: @end example
                   3889: 
                   3890: A deferred word can only inherit default semantics from the xt (because
                   3891: that is all that an xt can represent -- @pxref{Tokens for Words} for
                   3892: more discussion of this). However, the semantics of the deferred word
                   3893: itself can be modified at the time that it is defined. For example:
                   3894: 
                   3895: @example
                   3896: : bar .... ; compile-only
                   3897: Defer fred immediate
                   3898: Defer jim
                   3899: 
                   3900: ' bar IS jim  \ jim has default semantics
                   3901: ' bar IS fred \ fred is immediate
                   3902: @end example
1.1       anton    3903: 
1.29      crook    3904: The defining word @code{Alias} allows you to define a word by name that
                   3905: has the same behaviour as some other word. Here are two situation where
                   3906: this can be useful:
1.1       anton    3907: 
1.29      crook    3908: @itemize @bullet
                   3909: @item
                   3910: When you want access to a word's definition from a different word list
                   3911: (for an example of this, see the definition of the @code{Root} word list
                   3912: in the Gforth source).
                   3913: @item
                   3914: When you want to create a synonym; a definition that can be known by
                   3915: either of two names (for example, @code{THEN} and @code{ENDIF} are
                   3916: aliases).
                   3917: @end itemize
1.1       anton    3918: 
1.29      crook    3919: The word whose behaviour the alias is to inherit is represented by an
                   3920: xt. Therefore, the alias can only inherits default semantics from its
                   3921: ancestor. The semantics of the alias itself can be modified at the time
                   3922: that it is defined. For example:
1.1       anton    3923: 
1.29      crook    3924: @example
                   3925: : foo ... ; immediate
1.1       anton    3926: 
1.29      crook    3927: ' foo Alias bar \ bar is not an immediate word
                   3928: ' foo Alias fooby immediate \ fooby is an immediate word
                   3929: @end example
1.26      crook    3930: 
1.29      crook    3931: Words that are aliases have the same xt. Their semantics can differ
                   3932: because the rules about a word's semantics are stored in the name
                   3933: dictionary, and the aliases each have their own dictionary entry. It
                   3934: follows that words that are aliases have different name tokens and may
                   3935: have the same or different compilation tokens. Once again, see
                   3936: @ref{Tokens for Words} for more discussions of this.
1.27      crook    3937: 
1.29      crook    3938: doc-create
1.26      crook    3939: doc-variable
                   3940: doc-2variable
                   3941: doc-fvariable
                   3942: doc-user
1.29      crook    3943: doc-constant
                   3944: doc-2constant
                   3945: doc-fconstant
1.26      crook    3946: doc-value
                   3947: doc-to
                   3948: doc-defer
                   3949: doc-is
1.29      crook    3950: doc-alias
                   3951: @comment TODO document these: what's defers <is> [is]
                   3952: doc-what's
1.28      crook    3953: doc-defers
1.26      crook    3954: 
                   3955: Definitions in ANS Forth for @code{defer}, @code{<is>} and
                   3956: @code{[is]} are provided in @file{compat/defer.fs}.
1.29      crook    3957: 
1.1       anton    3958: 
1.26      crook    3959: @node Colon Definitions, User-defined Defining Words, Simple Defining Words, Defining Words
                   3960: @subsection Colon Definitions
                   3961: @cindex colon definitions
1.1       anton    3962: 
1.26      crook    3963: @example
                   3964: : name ( ... -- ... )
                   3965:     word1 word2 word3 ;
                   3966: @end example
1.1       anton    3967: 
1.29      crook    3968: @noindent
                   3969: Creates a word called @code{name} that, upon execution, executes
1.26      crook    3970: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.1       anton    3971: 
1.29      crook    3972: The explanation above is somewhat superficial. @xref{Your first
                   3973: definition} for simple examples of colon definitions, then
                   3974: @xref{Interpretation and Compilation Semantics} for an in-depth
                   3975: discussion of some of the issues involved.
1.26      crook    3976: 
                   3977: doc-:
                   3978: doc-;
1.1       anton    3979: 
1.26      crook    3980: @node User-defined Defining Words, Supplying names, Colon Definitions, Defining Words
                   3981: @subsection User-defined Defining Words
                   3982: @cindex user-defined defining words
                   3983: @cindex defining words, user-defined
1.1       anton    3984: 
1.29      crook    3985: You can create a new defining word by wrapping defining-time code around
                   3986: an existing defining word and putting the sequence in a colon
                   3987: definition. For example, suppose that you have a word @code{stats} that
                   3988: gathers statistics about colon definitions given the @i{xt} of the
                   3989: definition, and you want every colon definition in your application to
                   3990: make a call to @code{stats}. You can define and use a new version of
                   3991: @code{:} like this:
                   3992: 
                   3993: @example
                   3994: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
                   3995:   ... ;  \ other code
                   3996: 
                   3997: : my: : lastxt postpone literal ['] stats compile, ;
                   3998: 
                   3999: my: foo + - ;
                   4000: @end example
                   4001: 
                   4002: When @code{foo} is defined using @code{my:} these steps occur:
                   4003: 
                   4004: @itemize @bullet
                   4005: @item
                   4006: @code{my:} is executed.
                   4007: @item
                   4008: The @code{:} within the definition (the one between @code{my:} and
                   4009: @code{lastxt}) is executed, and does just what it always does; it parses
                   4010: the input stream for a name, builds a dictionary header for the name
                   4011: @code{foo} and switches @code{state} from interpret to compile.
                   4012: @item
                   4013: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
                   4014: being defined -- @code{foo} -- onto the stack.
                   4015: @item
                   4016: The code that was produced by @code{postpone literal} is executed; this
                   4017: causes the value on the stack to be compiled as a literal in the code
                   4018: area of @code{foo}.
                   4019: @item
                   4020: The code @code{['] stats} compiles a literal into the definition of
                   4021: @code{my:}. When @code{compile,} is executed, that literal -- the
                   4022: execution token for @code{stats} -- is layed down in the code area of
                   4023: @code{foo} , following the literal@footnote{Strictly speaking, the
                   4024: mechanism that @code{compile,} uses to convert an @i{xt} into something
                   4025: in the code area is implementation-dependent. A threaded implementation
                   4026: might spit out the execution token directly whilst another
                   4027: implementation might spit out a native code sequence.}.
                   4028: @item
                   4029: At this point, the execution of @code{my:} is complete, and control
                   4030: returns to the text interpreter. The text interpreter is in compile
                   4031: state, so subsequent text @code{+ -} is compiled into the definition of
                   4032: @code{foo} and the @code{;} terminates the definition as always.
                   4033: @end itemize
                   4034: 
                   4035: You can use @code{see} to decompile a word that was defined using
                   4036: @code{my:} and see how it is different from a normal @code{:}
                   4037: definition. For example:
                   4038: 
                   4039: @example
                   4040: : bar + - ;  \ like foo but using : rather than my:
                   4041: see bar
                   4042: : bar
                   4043:   + - ;
                   4044: see foo
                   4045: : foo
                   4046:   107645672 stats + - ;
                   4047: 
                   4048: \ use ' stats . to show that 107645672 is the xt for stats
                   4049: @end example
                   4050: 
                   4051: 
                   4052: Rather than edit your application's source code to change every @code{:}
                   4053: to a @code{my:}, use a deferred word:
                   4054: 
                   4055: @example
                   4056: : real: : ;     \ retain access to the original
                   4057: defer :         \ redefine as a deferred word
                   4058: ' my: IS :      \ use special version of :
                   4059: \
                   4060: \ load application here
                   4061: \
                   4062: ' real: IS :    \ go back to the original
                   4063: @end example
                   4064: 
                   4065: You can use techniques like this to make new defining words in terms of
                   4066: @i{any} existing defining word.
1.1       anton    4067: 
                   4068: 
1.29      crook    4069: @cindex defining defining words
1.26      crook    4070: @cindex @code{CREATE} ... @code{DOES>}
                   4071: If you want the words defined with your defining words to behave
                   4072: differently from words defined with standard defining words, you can
                   4073: write your defining word like this:
1.1       anton    4074: 
                   4075: @example
1.26      crook    4076: : def-word ( "name" -- )
1.29      crook    4077:     CREATE @i{code1}
1.26      crook    4078: DOES> ( ... -- ... )
1.29      crook    4079:     @i{code2} ;
1.26      crook    4080: 
                   4081: def-word name
1.1       anton    4082: @end example
                   4083: 
1.29      crook    4084: @cindex child words
                   4085: This fragment defines a @dfn{defining word} @code{def-word} and then
                   4086: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
                   4087: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
                   4088: is not executed at this time. The word @code{name} is sometimes called a
                   4089: @dfn{child} of @code{def-word}.
                   4090: 
                   4091: When you execute @code{name}, the address of the body of @code{name} is
                   4092: put on the data stack and @i{code2} is executed (the address of the body
                   4093: of @code{name} is the address @code{HERE} returns immediately after the
                   4094: @code{CREATE}).
                   4095: 
                   4096: @cindex atavism in child words
                   4097: You can use @code{def-word} to define a set of child word that behave
                   4098: differently, though atavistically; they all have a common run-time
                   4099: behaviour determined by @i{code2}. Typically, the @i{code1} sequence
                   4100: builds a data area in the body of the child word. The structure of the
                   4101: data is common to all children of @code{def-word}, but the data values
                   4102: are specific -- and private -- to each child word. When a child word is
                   4103: executed, the address of its private data area is passed as a parameter
                   4104: on TOS to be used and manipulated@footnote{It is legitimate both to read
                   4105: and write to this data area.} by @i{code2}.
                   4106: 
                   4107: The two fragments of code that make up the defining words act (are
                   4108: executed) at two completely separate times:
1.1       anton    4109: 
1.29      crook    4110: @itemize @bullet
                   4111: @item
                   4112: At @i{define time}, the defining word executes @i{code1} to generate a
                   4113: child word
                   4114: @item
                   4115: At @i{child execution time}, when a child word is invoked, @i{code2}
                   4116: is executed, using parameters (data) that are private and specific to
                   4117: the child word.
                   4118: @end itemize
                   4119: 
                   4120: @c NAC I think this is a really bad example, because it diminishes
                   4121: @c rather than emphasising the fact that some important stuff happens
                   4122: @c at define time, and other important stuff happens at child-invocation
                   4123: @c time, and that those two times are potentially very different.
                   4124: @c
                   4125: @c In other words, if you make the following definitions:
                   4126: @c @example
                   4127: @c : def-word1 ( "name" -- )
                   4128: @c     CREATE @i{code1} ;
                   4129: @c 
                   4130: @c : action1 ( ... -- ... )
                   4131: @c     @i{code2} ;
                   4132: @c 
                   4133: @c def-word1 name1
                   4134: @c @end example
                   4135: @c 
                   4136: @c Using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    4137: 
1.29      crook    4138: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    4139: 
1.1       anton    4140: @example
1.29      crook    4141: : CONSTANT ( w "name" -- )
                   4142:     CREATE ,
1.26      crook    4143: DOES> ( -- w )
                   4144:     @@ ;
1.1       anton    4145: @end example
                   4146: 
1.29      crook    4147: @comment There is a beautiful description of how this works and what
                   4148: @comment it does in the Forthwrite 100th edition.. as well as an elegant
                   4149: @comment commentary on the Counting Fruits problem.
                   4150: 
                   4151: When you create a constant with @code{5 CONSTANT five}, a set of
                   4152: define-time actions take place; first a new word @code{five} is created,
                   4153: then the value 5 is laid down in the body of @code{five} with
                   4154: @code{,}. When @code{five} is invoked, the address of the body is put on
                   4155: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
                   4156: no code of its own; it simply contains a data field and a pointer to the
                   4157: code that follows @code{DOES>} in its defining word. That makes words
                   4158: created in this way very compact.
                   4159: 
                   4160: The final example in this section is intended to remind you that space
                   4161: reserved in @code{CREATE}d words is @i{data} space and therefore can be
                   4162: both read and written by a Standard program@footnote{Exercise: use this
                   4163: example as a starting point for your own implementation of @code{Value}
                   4164: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
                   4165: @code{[']}.}:
                   4166: 
                   4167: @example
                   4168: : foo ( "name" -- )
                   4169:     CREATE -1 ,
                   4170: DOES> ( -- )
                   4171:     @@ .;
                   4172: 
                   4173: foo first-word
                   4174: foo second-word
                   4175: 
                   4176: 123 ' first-word >BODY !
                   4177: @end example
                   4178: 
                   4179: If @code{first-word} had been a @code{CREATE}d word, we could simply
                   4180: have executed it to get the address of its data field. However, since it
                   4181: was defined to have @code{DOES>} actions, its execution semantics are to
                   4182: perform those @code{DOES>} actions. To get the address of its data field
                   4183: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
                   4184: translate the xt into the address of the data field.  When you execute
                   4185: @code{first-word}, it will display @code{123}. When you execute
                   4186: @code{second-word} it will display @code{-1}.
1.26      crook    4187: 
                   4188: @cindex stack effect of @code{DOES>}-parts
                   4189: @cindex @code{DOES>}-parts, stack effect
1.29      crook    4190: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    4191: the stack effect of the defined words, not the stack effect of the
                   4192: following code (the following code expects the address of the body on
                   4193: the top of stack, which is not reflected in the stack comment). This is
                   4194: the convention that I use and recommend (it clashes a bit with using
                   4195: locals declarations for stack effect specification, though).
1.1       anton    4196: 
1.26      crook    4197: @subsubsection Applications of @code{CREATE..DOES>}
                   4198: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1       anton    4199: 
1.26      crook    4200: You may wonder how to use this feature. Here are some usage patterns:
1.1       anton    4201: 
1.26      crook    4202: @cindex factoring similar colon definitions
                   4203: When you see a sequence of code occurring several times, and you can
                   4204: identify a meaning, you will factor it out as a colon definition. When
                   4205: you see similar colon definitions, you can factor them using
                   4206: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   4207: that look very similar:
1.1       anton    4208: @example
1.26      crook    4209: : ori, ( reg-target reg-source n -- )
                   4210:     0 asm-reg-reg-imm ;
                   4211: : andi, ( reg-target reg-source n -- )
                   4212:     1 asm-reg-reg-imm ;
1.1       anton    4213: @end example
                   4214: 
1.26      crook    4215: @noindent
                   4216: This could be factored with:
                   4217: @example
                   4218: : reg-reg-imm ( op-code -- )
                   4219:     CREATE ,
                   4220: DOES> ( reg-target reg-source n -- )
                   4221:     @@ asm-reg-reg-imm ;
                   4222: 
                   4223: 0 reg-reg-imm ori,
                   4224: 1 reg-reg-imm andi,
                   4225: @end example
1.1       anton    4226: 
1.26      crook    4227: @cindex currying
                   4228: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   4229: supply a part of the parameters for a word (known as @dfn{currying} in
                   4230: the functional language community). E.g., @code{+} needs two
                   4231: parameters. Creating versions of @code{+} with one parameter fixed can
                   4232: be done like this:
1.1       anton    4233: @example
1.26      crook    4234: : curry+ ( n1 -- )
                   4235:     CREATE ,
                   4236: DOES> ( n2 -- n1+n2 )
                   4237:     @@ + ;
                   4238: 
                   4239:  3 curry+ 3+
                   4240: -2 curry+ 2-
1.1       anton    4241: @end example
                   4242: 
1.26      crook    4243: @subsubsection The gory details of @code{CREATE..DOES>}
                   4244: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    4245: 
1.26      crook    4246: doc-does>
1.1       anton    4247: 
1.26      crook    4248: @cindex @code{DOES>} in a separate definition
                   4249: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   4250: same definition; you can put the @code{DOES>}-part in a separate
1.29      crook    4251: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    4252: @example
                   4253: : does1 
                   4254: DOES> ( ... -- ... )
                   4255:     ... ;
1.1       anton    4256: 
1.26      crook    4257: : does2
                   4258: DOES> ( ... -- ... )
                   4259:     ... ;
1.1       anton    4260: 
1.26      crook    4261: : def-word ( ... -- ... )
                   4262:     create ...
                   4263:     IF
                   4264:        does1
                   4265:     ELSE
                   4266:        does2
                   4267:     ENDIF ;
                   4268: @end example
1.1       anton    4269: 
1.26      crook    4270: In this example, the selection of whether to use @code{does1} or
                   4271: @code{does2} is made at compile-time; at the time that the child word is
1.29      crook    4272: @code{CREATE}d.
1.1       anton    4273: 
1.26      crook    4274: @cindex @code{DOES>} in interpretation state
                   4275: In a standard program you can apply a @code{DOES>}-part only if the last
                   4276: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   4277: will override the behaviour of the last word defined in any case. In a
                   4278: standard program, you can use @code{DOES>} only in a colon
                   4279: definition. In Gforth, you can also use it in interpretation state, in a
                   4280: kind of one-shot mode; for example:
1.1       anton    4281: @example
1.26      crook    4282: CREATE name ( ... -- ... )
1.29      crook    4283:   @i{initialization}
1.26      crook    4284: DOES>
1.29      crook    4285:   @i{code} ;
1.1       anton    4286: @end example
                   4287: 
1.26      crook    4288: @noindent
                   4289: is equivalent to the standard:
1.1       anton    4290: @example
1.26      crook    4291: :noname
                   4292: DOES>
1.29      crook    4293:     @i{code} ;
1.26      crook    4294: CREATE name EXECUTE ( ... -- ... )
1.29      crook    4295:     @i{initialization}
1.1       anton    4296: @end example
                   4297: 
1.26      crook    4298: You can get the address of the body of a word with:
                   4299: 
                   4300: doc->body
1.1       anton    4301: 
1.26      crook    4302: @node Supplying names, Interpretation and Compilation Semantics, User-defined Defining Words, Defining Words
1.29      crook    4303: @subsection Supplying the name of a defined word
1.26      crook    4304: @cindex names for defined words
                   4305: @cindex defining words, name parameter
1.1       anton    4306: 
1.26      crook    4307: @cindex defining words, name given in a string
1.29      crook    4308: By default, a defining word takes the name for the defined word from the
1.26      crook    4309: input stream. Sometimes you want to supply the name from a string. You
                   4310: can do this with:
1.1       anton    4311: 
1.26      crook    4312: doc-nextname
1.1       anton    4313: 
1.26      crook    4314: For example:
1.1       anton    4315: 
1.26      crook    4316: @example
                   4317: s" foo" nextname create
                   4318: @end example
                   4319: @noindent
                   4320: is equivalent to:
                   4321: @example
                   4322: create foo
                   4323: @end example
1.1       anton    4324: 
1.26      crook    4325: @cindex defining words without name
1.29      crook    4326: Sometimes you want to define an @dfn{anonymous word}; a word without a
1.26      crook    4327: name. You can do this with:
1.1       anton    4328: 
1.26      crook    4329: doc-:noname
1.1       anton    4330: 
1.26      crook    4331: This leaves the execution token for the word on the stack after the
                   4332: closing @code{;}. Here's an example in which a deferred word is
                   4333: initialised with an @code{xt} from an anonymous colon definition:
                   4334: @example
                   4335: Defer deferred
                   4336: :noname ( ... -- ... )
                   4337:   ... ;
                   4338: IS deferred
                   4339: @end example
1.1       anton    4340: 
1.29      crook    4341: @noindent
1.26      crook    4342: Gforth provides an alternative way of doing this, using two separate
                   4343: words:
1.1       anton    4344: 
1.26      crook    4345: doc-noname
                   4346: @cindex execution token of last defined word
                   4347: doc-lastxt
1.1       anton    4348: 
1.29      crook    4349: @noindent
1.26      crook    4350: The previous example can be rewritten using @code{noname} and
                   4351: @code{lastxt}:
1.1       anton    4352: 
1.26      crook    4353: @example
                   4354: Defer deferred
                   4355: noname : ( ... -- ... )
                   4356:   ... ;
                   4357: lastxt IS deferred
                   4358: @end example
1.1       anton    4359: 
1.29      crook    4360: @noindent
1.26      crook    4361: @code{lastxt} also works when the last word was not defined as
1.29      crook    4362: @code{noname}. It also has the useful property that is is valid as soon
                   4363: as the header for a definition has been build. Thus:
                   4364: 
                   4365: @example
                   4366: lastxt . : foo [ lastxt . ] ; ' foo .
                   4367: @end example
                   4368: 
                   4369: @noindent
                   4370: prints 3 numbers; the last two are the same.
1.1       anton    4371: 
                   4372: 
1.26      crook    4373: @node Interpretation and Compilation Semantics,  , Supplying names, Defining Words
                   4374: @subsection Interpretation and Compilation Semantics
                   4375: @cindex semantics, interpretation and compilation
1.1       anton    4376: 
1.26      crook    4377: @cindex interpretation semantics
                   4378: The @dfn{interpretation semantics} of a word are what the text
                   4379: interpreter does when it encounters the word in interpret state. It also
                   4380: appears in some other contexts, e.g., the execution token returned by
1.29      crook    4381: @code{' @i{word}} identifies the interpretation semantics of
                   4382: @i{word} (in other words, @code{' @i{word} execute} is equivalent to
                   4383: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    4384: 
1.26      crook    4385: @cindex compilation semantics
                   4386: The @dfn{compilation semantics} of a word are what the text interpreter
                   4387: does when it encounters the word in compile state. It also appears in
1.29      crook    4388: other contexts, e.g, @code{POSTPONE @i{word}} compiles@footnote{In
1.26      crook    4389: standard terminology, ``appends to the current definition''.} the
1.29      crook    4390: compilation semantics of @i{word}.
1.1       anton    4391: 
1.26      crook    4392: @cindex execution semantics
                   4393: The standard also talks about @dfn{execution semantics}. They are used
                   4394: only for defining the interpretation and compilation semantics of many
                   4395: words. By default, the interpretation semantics of a word are to
                   4396: @code{execute} its execution semantics, and the compilation semantics of
                   4397: a word are to @code{compile,} its execution semantics.@footnote{In
                   4398: standard terminology: The default interpretation semantics are its
                   4399: execution semantics; the default compilation semantics are to append its
                   4400: execution semantics to the execution semantics of the current
                   4401: definition.}
                   4402: 
                   4403: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   4404: 
                   4405: @cindex immediate words
                   4406: @cindex compile-only words
                   4407: You can change the semantics of the most-recently defined word:
                   4408: 
                   4409: doc-immediate
                   4410: doc-compile-only
                   4411: doc-restrict
                   4412: 
                   4413: Note that ticking (@code{'}) a compile-only word gives an error
                   4414: (``Interpreting a compile-only word'').
1.1       anton    4415: 
1.26      crook    4416: Gforth also allows you to define words with arbitrary combinations of
                   4417: interpretation and compilation semantics.
1.1       anton    4418: 
1.26      crook    4419: doc-interpret/compile:
1.1       anton    4420: 
1.26      crook    4421: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   4422: recommend that you do not define such words, as cute as they may be:
                   4423: they make it hard to get at both parts of the word in some contexts.
                   4424: E.g., assume you want to get an execution token for the compilation
                   4425: part. Instead, define two words, one that embodies the interpretation
                   4426: part, and one that embodies the compilation part.  Once you have done
                   4427: that, you can define a combined word with @code{interpret/compile:} for
                   4428: the convenience of your users.
1.1       anton    4429: 
1.26      crook    4430: You might try to use this feature to provide an optimizing
                   4431: implementation of the default compilation semantics of a word. For
                   4432: example, by defining:
1.1       anton    4433: @example
1.26      crook    4434: :noname
                   4435:    foo bar ;
                   4436: :noname
                   4437:    POSTPONE foo POSTPONE bar ;
1.29      crook    4438: interpret/compile: opti-foobar
1.1       anton    4439: @end example
1.26      crook    4440: 
1.23      crook    4441: @noindent
1.26      crook    4442: as an optimizing version of:
                   4443: 
1.1       anton    4444: @example
1.26      crook    4445: : foobar
                   4446:     foo bar ;
1.1       anton    4447: @end example
                   4448: 
1.26      crook    4449: Unfortunately, this does not work correctly with @code{[compile]},
                   4450: because @code{[compile]} assumes that the compilation semantics of all
                   4451: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29      crook    4452: opti-foobar} would compile compilation semantics, whereas
                   4453: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    4454: 
1.26      crook    4455: @cindex state-smart words (are a bad idea)
1.29      crook    4456: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    4457: by @code{interpret/compile:} (words are state-smart if they check
                   4458: @code{STATE} during execution). E.g., they would try to code
                   4459: @code{foobar} like this:
1.1       anton    4460: 
1.26      crook    4461: @example
                   4462: : foobar
                   4463:   STATE @@
                   4464:   IF ( compilation state )
                   4465:     POSTPONE foo POSTPONE bar
                   4466:   ELSE
                   4467:     foo bar
                   4468:   ENDIF ; immediate
                   4469: @end example
1.1       anton    4470: 
1.26      crook    4471: Although this works if @code{foobar} is only processed by the text
                   4472: interpreter, it does not work in other contexts (like @code{'} or
                   4473: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   4474: for a state-smart word, not for the interpretation semantics of the
                   4475: original @code{foobar}; when you execute this execution token (directly
                   4476: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   4477: state, the result will not be what you expected (i.e., it will not
                   4478: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   4479: write them@footnote{For a more detailed discussion of this topic, see
                   4480: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
                   4481: Ertl; presented at EuroForth '98 and available from
                   4482: @url{http://www.complang.tuwien.ac.at/papers/}}!
1.1       anton    4483: 
1.26      crook    4484: @cindex defining words with arbitrary semantics combinations
                   4485: It is also possible to write defining words that define words with
                   4486: arbitrary combinations of interpretation and compilation semantics. In
                   4487: general, they look like this:
1.1       anton    4488: 
1.26      crook    4489: @example
                   4490: : def-word
                   4491:     create-interpret/compile
1.29      crook    4492:     @i{code1}
1.26      crook    4493: interpretation>
1.29      crook    4494:     @i{code2}
1.26      crook    4495: <interpretation
                   4496: compilation>
1.29      crook    4497:     @i{code3}
1.26      crook    4498: <compilation ;
                   4499: @end example
1.1       anton    4500: 
1.29      crook    4501: For a @i{word} defined with @code{def-word}, the interpretation
                   4502: semantics are to push the address of the body of @i{word} and perform
                   4503: @i{code2}, and the compilation semantics are to push the address of
                   4504: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    4505: can also be defined like this (except that the defined constants don't
                   4506: behave correctly when @code{[compile]}d):
1.1       anton    4507: 
1.26      crook    4508: @example
                   4509: : constant ( n "name" -- )
                   4510:     create-interpret/compile
                   4511:     ,
                   4512: interpretation> ( -- n )
                   4513:     @@
                   4514: <interpretation
                   4515: compilation> ( compilation. -- ; run-time. -- n )
                   4516:     @@ postpone literal
                   4517: <compilation ;
                   4518: @end example
1.1       anton    4519: 
1.26      crook    4520: doc-create-interpret/compile
                   4521: doc-interpretation>
                   4522: doc-<interpretation
                   4523: doc-compilation>
                   4524: doc-<compilation
1.1       anton    4525: 
1.29      crook    4526: Words defined with @code{interpret/compile:} and
1.26      crook    4527: @code{create-interpret/compile} have an extended header structure that
                   4528: differs from other words; however, unless you try to access them with
                   4529: plain address arithmetic, you should not notice this. Words for
                   4530: accessing the header structure usually know how to deal with this; e.g.,
1.29      crook    4531: @code{'} @i{word} @code{>body} also gives you the body of a word created
                   4532: with @code{create-interpret/compile}.
1.1       anton    4533: 
1.27      crook    4534: doc-postpone
1.29      crook    4535: @comment TODO -- expand glossary text for POSTPONE
1.27      crook    4536: 
1.26      crook    4537: @c ----------------------------------------------------------
                   4538: @node The Text Interpreter, Tokens for Words, Defining Words, Words
                   4539: @section  The Text Interpreter
                   4540: @cindex interpreter - outer
                   4541: @cindex text interpreter
                   4542: @cindex outer interpreter
1.1       anton    4543: 
1.29      crook    4544: The text interpreter@footnote{This is an expanded version of the
                   4545: material in @ref{Introducing the Text Interpreter}.} is an endless loop
                   4546: that processes input from the current input device. A popular
                   4547: implementation technique for Forth is to implement a @dfn{forth virtual
                   4548: machine} using a loop called the @dfn{inner interpreter}. Because of
                   4549: this naming, the text interpreter is also known as the @dfn{outer
1.27      crook    4550: interpreter}.
                   4551: 
1.29      crook    4552: @cindex interpret state
                   4553: @cindex compile state
                   4554: The text interpreter operates in one of two states: @dfn{interpret
                   4555: state} and @dfn{compile state}. The current state is defined by the
                   4556: aptly-named variable, @code{state}.
                   4557: 
                   4558: This section starts by describing how the text interpreter behaves when
                   4559: it is in interpret state, processing input from the user input device --
                   4560: the keyboard. This is the mode that a Forth system is in after it starts
                   4561: up.
                   4562: 
                   4563: @cindex input buffer
                   4564: @cindex terminal input buffer
                   4565: The text interpreter works from an area of memory called the @dfn{input
                   4566: buffer}@footnote{When the text interpreter is processing input from the
                   4567: keyboard, this area of memory is called the @dfn{terminal input buffer}
                   4568: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
                   4569: @code{#TIB}.}, which stores your keyboard input when you press the
1.30      anton    4570: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29      crook    4571: leading spaces (called @dfn{delimiters}) then parses a string (a
                   4572: sequence of non-space characters) until it reaches either a space
                   4573: character or the end of the buffer. Having parsed a string, it makes two
                   4574: attempts to process it:
1.27      crook    4575: 
1.29      crook    4576: @cindex dictionary
1.27      crook    4577: @itemize @bullet
                   4578: @item
1.29      crook    4579: It looks for the string in a @dfn{dictionary} of definitions. If the
                   4580: string is found, the string names a @dfn{definition} (also known as a
                   4581: @dfn{word}) and the dictionary search returns information that allows
                   4582: the text interpreter to perform the word's @dfn{interpretation
                   4583: semantics}. In most cases, this simply means that the word will be
                   4584: executed.
1.27      crook    4585: @item
                   4586: If the string is not found in the dictionary, the text interpreter
1.29      crook    4587: attempts to treat it as a number, using the rules described in
                   4588: @ref{Number Conversion}. If the string represents a legal number in the
                   4589: current radix, the number is pushed onto a parameter stack (the data
                   4590: stack for integers, the floating-point stack for floating-point
                   4591: numbers).
                   4592: @end itemize
                   4593: 
                   4594: If both attempts fail, or if the word is found in the dictionary but has
                   4595: no interpretation semantics@footnote{This happens if the word was
                   4596: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
                   4597: remainder of the input buffer, issues an error message and waits for
                   4598: more input. If one of the attempts succeeds, the text interpreter
                   4599: repeats the parsing process until the whole of the input buffer has been
                   4600: processed, at which point it prints the status message ``@code{ ok}''
                   4601: and waits for more input.
                   4602: 
                   4603: @cindex parse area
                   4604: The text interpreter keeps track of its position in the input buffer by
                   4605: updating a variable called @code{>IN} (pronounced ``to-in''). The value
                   4606: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
                   4607: of the input buffer. The region from offset @code{>IN @@} to the end of
                   4608: the input buffer is called the @dfn{parse area}@footnote{In other words,
                   4609: the text interpreter processes the contents of the input buffer by
                   4610: parsing strings from the parse area until the parse area is empty.}.
                   4611: This example shows how @code{>IN} changes as the text interpreter parses
                   4612: the input buffer:
                   4613: 
                   4614: @example
                   4615: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
                   4616:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
                   4617: 
                   4618: 1 2 3 remaining + remaining . 
                   4619: 
                   4620: : foo 1 2 3 remaining SWAP remaining ;
                   4621: @end example
                   4622: 
                   4623: @noindent
                   4624: The result is:
                   4625: 
                   4626: @example
                   4627: ->+ remaining .<-
                   4628: ->.<-5  ok
                   4629: 
                   4630: ->SWAP remaining ;-<
                   4631: ->;<-  ok
                   4632: @end example
                   4633: 
                   4634: @cindex parsing words
                   4635: The value of @code{>IN} can also be modified by a word in the input
                   4636: buffer that is executed by the text interpreter.  This means that a word
                   4637: can ``trick'' the text interpreter into either skipping a section of the
                   4638: input buffer@footnote{This is how parsing words work.} or into parsing a
                   4639: section twice. For example:
1.27      crook    4640: 
1.29      crook    4641: @example
                   4642: : lat ." <<lat>>" ;
                   4643: : flat ." <<flat>>" >IN DUP @@ 3 - SWAP ! ;
                   4644: @end example
                   4645: 
                   4646: @noindent
                   4647: When @code{flat} is executed, this output is produced@footnote{Exercise
                   4648: for the reader: what would happen if the @code{3} were replaced with
                   4649: @code{4}?}:
                   4650: 
                   4651: @example
                   4652: <<flat>><<lat>>
                   4653: @end example
                   4654: 
                   4655: @noindent
                   4656: Two important notes about the behaviour of the text interpreter:
1.27      crook    4657: 
                   4658: @itemize @bullet
                   4659: @item
                   4660: It processes each input string to completion before parsing additional
1.29      crook    4661: characters from the input buffer.
                   4662: @item
                   4663: It treats the input buffer as a read-only region (and so must your code).
                   4664: @end itemize
                   4665: 
                   4666: @noindent
                   4667: When the text interpreter is in compile state, its behaviour changes in
                   4668: these ways:
                   4669: 
                   4670: @itemize @bullet
                   4671: @item
                   4672: If a parsed string is found in the dictionary, the text interpreter will
                   4673: perform the word's @dfn{compilation semantics}. In most cases, this
                   4674: simply means that the execution semantics of the word will be appended
                   4675: to the current definition.
1.27      crook    4676: @item
1.29      crook    4677: When a number is encountered, it is compiled into the current definition
                   4678: (as a literal) rather than being pushed onto a parameter stack.
                   4679: @item
                   4680: If an error occurs, @code{state} is modified to put the text interpreter
                   4681: back into interpret state.
                   4682: @item
                   4683: Each time a line is entered from the keyboard, Gforth prints
                   4684: ``@code{ compiled}'' rather than `` @code{ok}''.
                   4685: @end itemize
                   4686: 
                   4687: @cindex text interpreter - input sources
                   4688: When the text interpreter is using an input device other than the
                   4689: keyboard, its behaviour changes in these ways:
                   4690: 
                   4691: @itemize @bullet
                   4692: @item
                   4693: When the parse area is empty, the text interpreter attempts to refill
                   4694: the input buffer from the input source. When the input source is
                   4695: exhausted, the input source is set back to the user input device.
                   4696: @item
                   4697: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
                   4698: time the parse area is emptied.
                   4699: @item
                   4700: If an error occurs, the input source is set back to the user input
                   4701: device.
1.27      crook    4702: @end itemize
1.21      crook    4703: 
1.29      crook    4704: @ref{Input Sources} describes this in more detail.
                   4705: 
1.26      crook    4706: doc->in
1.27      crook    4707: doc-source
                   4708: 
1.26      crook    4709: doc-tib
                   4710: doc-#tib
1.1       anton    4711: 
1.26      crook    4712: @menu
1.29      crook    4713: * Input Sources::
1.26      crook    4714: * Number Conversion::
                   4715: * Interpret/Compile states::
                   4716: * Literals::
                   4717: * Interpreter Directives::
                   4718: @end menu
1.1       anton    4719: 
1.29      crook    4720: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
                   4721: @subsection Input Sources
                   4722: @cindex input sources
                   4723: @cindex text interpreter - input sources
                   4724: 
                   4725: By default, the text interpreter accepts input from the user input
                   4726: device (the keyboard) when Forth starts up. The text interpreter can
                   4727: process input from any of these sources:
                   4728: 
                   4729: @itemize @bullet
                   4730: @item
                   4731: The user input device -- the keyboard.
                   4732: @item
                   4733: A file, using the words described in @ref{Forth source files}.
                   4734: @item
                   4735: A block, using the words described in @ref{Blocks}.
                   4736: @item
                   4737: A text string, using @code{evaluate}.
                   4738: @end itemize
                   4739: 
                   4740: A program can identify the current input device from the values of
                   4741: @code{source-id} and @code{blk}.
                   4742: 
                   4743: doc-source-id
                   4744: doc-blk
                   4745: 
                   4746: doc-save-input
                   4747: doc-restore-input
                   4748: 
                   4749: doc-evaluate
1.1       anton    4750: 
1.29      crook    4751: 
                   4752: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    4753: @subsection Number Conversion
                   4754: @cindex number conversion
                   4755: @cindex double-cell numbers, input format
                   4756: @cindex input format for double-cell numbers
                   4757: @cindex single-cell numbers, input format
                   4758: @cindex input format for single-cell numbers
                   4759: @cindex floating-point numbers, input format
                   4760: @cindex input format for floating-point numbers
1.1       anton    4761: 
1.29      crook    4762: This section describes the rules that the text interpreter uses when it
                   4763: tries to convert a string into a number.
1.1       anton    4764: 
1.26      crook    4765: Let <digit> represent any character that is a legal digit in the current
1.29      crook    4766: number base@footnote{For example, 0-9 when the number base is decimal or
                   4767: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    4768: 
1.26      crook    4769: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    4770: 
1.29      crook    4771: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
                   4772: in the braces (@i{a} or @i{b} or neither).
1.1       anton    4773: 
1.26      crook    4774: Let * represent any number of instances of the previous character
                   4775: (including none).
1.1       anton    4776: 
1.26      crook    4777: Let any other character represent itself.
1.1       anton    4778: 
1.29      crook    4779: @noindent
1.26      crook    4780: Now, the conversion rules are:
1.21      crook    4781: 
1.26      crook    4782: @itemize @bullet
                   4783: @item
                   4784: A string of the form <digit><digit>* is treated as a single-precision
1.29      crook    4785: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    4786: @item
                   4787: A string of the form -<digit><digit>* is treated as a single-precision
1.29      crook    4788: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    4789: arithmetic. Examples are -45 -5681 -0
                   4790: @item
                   4791: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29      crook    4792: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
                   4793: (all three of these represent the same number).
1.26      crook    4794: @item
                   4795: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29      crook    4796: double-precision (double-cell-sized) negative integer, and is
1.26      crook    4797: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29      crook    4798: -34.65 (all three of these represent the same number).
1.26      crook    4799: @item
1.29      crook    4800: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
                   4801: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.26      crook    4802: number. Examples are 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29      crook    4803: number) +12.E-4
1.26      crook    4804: @end itemize
1.1       anton    4805: 
1.26      crook    4806: By default, the number base used for integer number conversion is given
1.29      crook    4807: by the contents of the variable @code{BASE}. Base 10 (decimal) is
1.26      crook    4808: always used for floating-point number conversion.
1.1       anton    4809: 
1.29      crook    4810: doc-dpl
1.26      crook    4811: doc-base
                   4812: doc-hex
                   4813: doc-decimal
1.1       anton    4814: 
1.26      crook    4815: @cindex '-prefix for character strings
                   4816: @cindex &-prefix for decimal numbers
                   4817: @cindex %-prefix for binary numbers
                   4818: @cindex $-prefix for hexadecimal numbers
1.29      crook    4819: Gforth allows you to override the value of @code{BASE} by using a
                   4820: prefix@footnote{Some Forth implementations provide a similar scheme by
                   4821: implementing @code{$} etc. as parsing words that process the subsequent
                   4822: number in the input stream and push it onto the stack. For example, see
                   4823: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
                   4824: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
                   4825: is required between the prefix and the number.} before the first digit
                   4826: of an (integer) number. Four prefixes are supported:
1.1       anton    4827: 
1.26      crook    4828: @itemize @bullet
                   4829: @item
                   4830: @code{&} -- decimal number
                   4831: @item
                   4832: @code{%} -- binary number
                   4833: @item
                   4834: @code{$} -- hexadecimal number
                   4835: @item
                   4836: @code{'} -- base 256 number
                   4837: @end itemize
1.1       anton    4838: 
1.26      crook    4839: Here are some examples, with the equivalent decimal number shown after
                   4840: in braces:
1.1       anton    4841: 
1.26      crook    4842: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
                   4843: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
                   4844: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
                   4845: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    4846: 
1.26      crook    4847: @cindex number conversion - traps for the unwary
1.29      crook    4848: @noindent
1.26      crook    4849: Number conversion has a number of traps for the unwary:
1.1       anton    4850: 
1.26      crook    4851: @itemize @bullet
                   4852: @item
                   4853: You cannot determine the current number base using the code sequence
                   4854: @code{BASE @@ .} -- the number base is always 10 in the current number
                   4855: base. Instead, use something like @code{BASE @@ DECIMAL DUP . BASE !}
                   4856: @item
                   4857: If the number base is set to a value greater than 14 (for example,
                   4858: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   4859: it to be intepreted as either a single-precision integer or a
                   4860: floating-point number (Gforth treats it as an integer). The ambiguity
                   4861: can be resolved by explicitly stating the sign of the mantissa and/or
                   4862: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   4863: ambiguity arises; either representation will be treated as a
                   4864: floating-point number.
                   4865: @item
1.29      crook    4866: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    4867: It is used to specify file types.
                   4868: @item
                   4869: ANS Forth requires the @code{.} of a double-precision number to
                   4870: be the final character in the string. Allowing the @code{.} to be
                   4871: anywhere after the first digit is a Gforth extension.
                   4872: @item
                   4873: The number conversion process does not check for overflow.
                   4874: @item
                   4875: In Gforth, number conversion to floating-point numbers always use base
                   4876: 10, irrespective of the value of @code{BASE}. In ANS Forth,
                   4877: conversion to floating-point numbers whilst the value of
                   4878: @code{BASE} is not 10 is an ambiguous condition.
                   4879: @end itemize
1.1       anton    4880: 
1.29      crook    4881: @ref{Input} describes words that you can use to read numbers into your
                   4882: programs.
1.1       anton    4883: 
1.26      crook    4884: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
                   4885: @subsection Interpret/Compile states
                   4886: @cindex Interpret/Compile states
1.1       anton    4887: 
1.29      crook    4888: A standard program is not permitted to change @code{state}
                   4889: explicitly. However, it can change @code{state} implicitly, using the
                   4890: words @code{[} and @code{]}. When @code{[} is executed it switches
                   4891: @code{state} to interpret state, and therefore the text interpreter
                   4892: starts interpreting. When @code{]} is executed it switches @code{state}
                   4893: to compile state and therefore the text interpreter starts
                   4894: compiling. The most common usage for these words is to compile literals,
                   4895: as shown in @ref{Literals}. However, they give you the freedom to switch
                   4896: modes at will. Here is an example of building a jump-table of execution
                   4897: tokens:
                   4898: 
                   4899: @example
                   4900: : AA ." this is A" ;
                   4901: : BB ." this is B" ;
                   4902: : CC ." this is C" ;
                   4903: 
                   4904: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
                   4905: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
                   4906:   cells table + @ execute ;
                   4907: @end example
                   4908: 
                   4909: @noindent
                   4910: Now @code{0 go} will display ``@code{this is A}''. The table can be
                   4911: built far more neatly@footnote{The source code is neater.. what is
                   4912: compiled in memory in each case is identical.} like this:
                   4913: 
                   4914: @example
                   4915: create table ] aa bb cc [
                   4916: @end example
                   4917: 
                   4918: The problem with this code is that it is not portable; it will only work
                   4919: on systems where code space and data space co-incide. The reason is that
                   4920: both tables @i{compile} execution tokens -- into code space. The
                   4921: Standard only allows data space to be assigned for a @code{CREATE}d
                   4922: word. In addition, the Standard only allows @code{@@} to access data
                   4923: space, whilst this example is using it to access code space. The only
                   4924: portable, Standard way to build this table is to build it in data space,
                   4925: like this:
                   4926: 
                   4927: @example
                   4928: create table ' aa , ' bb , ' cc ,
                   4929: @end example
                   4930: 
                   4931: @noindent
                   4932: A similar technique can be used to build a table of constants:
                   4933: 
                   4934: @example
                   4935: create primes 1 , 3 , 5 , 7 , 11 ,
                   4936: @end example
1.1       anton    4937: 
1.26      crook    4938: doc-state
                   4939: doc-[
                   4940: doc-]
1.1       anton    4941: 
1.26      crook    4942: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
                   4943: @subsection Literals
                   4944: @cindex Literals
1.21      crook    4945: 
1.29      crook    4946: Often, you want to use a number within a colon definition. When you do
                   4947: this, the text interpreter automatically compiles the number as a
                   4948: @i{literal}. A literal is a number whose run-time effect is to be pushed
                   4949: onto the stack.  If you had to do some maths to generate the number, you
                   4950: might write it like this:
                   4951: 
                   4952: @example
                   4953: : HOUR-TO-SEC ( n1 -- n2 )
                   4954:   60 *      \ to minutes
                   4955:   60 * ;    \ to seconds
                   4956: @end example
                   4957: 
                   4958: It is very clear what this definition is doing, but it's inefficient
                   4959: since it is performing 2 multiples at run-time. An alternative would be
                   4960: to write:
                   4961: 
                   4962: @example
                   4963: : HOUR-TO-SEC ( n1 -- n2 )
                   4964:   3600 * ;  \ to seconds
                   4965: @end example
                   4966: 
                   4967: Which does the same thing, and has the advantage of using a single
                   4968: multiply. Ideally, we'd like the efficiency of the second with the
                   4969: readability of the first.
                   4970: 
                   4971: @code{Literal} allows us to achieve that. It takes a number from the
                   4972: stack and lays it down in the current definition just as though the
                   4973: number had been typed directly into the definition. Our first attempt
                   4974: might look like this:
                   4975: 
                   4976: @example
                   4977: 60          \ mins per hour
                   4978: 60 *        \ seconds per minute
                   4979: : HOUR-TO-SEC ( n1 -- n2 )
                   4980:   Literal * ;  \ to seconds
                   4981: @end example
                   4982: 
                   4983: But this produces the error message @code{unstructured}. What happened?
                   4984: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
                   4985: @i{colon-sys} is implementation-defined. In other words, once we start a
                   4986: colon definition we can't portably access anything that was on the stack
                   4987: before the definition began@footnote{@cite{Two Problems in ANS Forth},
                   4988: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
                   4989: some situations where you might want to access stack items above
                   4990: colon-sys, and provides a solution to the problem.}. The correct way of
                   4991: solving this problem in this instance is to use @code{[ ]} like this:
                   4992: 
                   4993: @example
                   4994: : HOUR-TO-SEC ( n1 -- n2 )
                   4995:   [ 60          \ minutes per hour
                   4996:     60 * ]      \ seconds per minute
                   4997:   LITERAL * ;   \ to seconds
                   4998: @end example
1.23      crook    4999: 
1.26      crook    5000: doc-literal
                   5001: doc-]L
                   5002: doc-2literal
                   5003: doc-fliteral
1.1       anton    5004: 
1.29      crook    5005: @node Interpreter Directives, , Literals, The Text Interpreter
1.26      crook    5006: @subsection Interpreter Directives
                   5007: @cindex interpreter directives
1.1       anton    5008: 
1.29      crook    5009: These words are usually used in interpret state; typically to control
                   5010: which parts of a source file are processed by the text
1.26      crook    5011: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   5012: supplements these with a rich set of immediate control structure words
                   5013: to compensate for the fact that the non-immediate versions can only be
1.29      crook    5014: used in compile state (@pxref{Control Structures}). Typical usages:
                   5015: 
                   5016: @example
                   5017: FALSE Constant ASSEMBLER
                   5018: .
                   5019: .
                   5020: ASSEMBLER [IF]
                   5021: : ASSEMBLER-FEATURE
                   5022:   ...
                   5023: ;
                   5024: [ENDIF]
                   5025: .
                   5026: .
                   5027: : SEE
                   5028:   ... \ general-purpose SEE code
                   5029:   [ ASSEMBLER [IF] ]
                   5030:   ... \ assembler-specific SEE code
                   5031:   [ [ENDIF] ]
                   5032: ;
                   5033: @end example
1.1       anton    5034: 
1.26      crook    5035: doc-[IF]
                   5036: doc-[ELSE]
                   5037: doc-[THEN]
                   5038: doc-[ENDIF]
1.1       anton    5039: 
1.26      crook    5040: doc-[IFDEF]
                   5041: doc-[IFUNDEF]
1.1       anton    5042: 
1.26      crook    5043: doc-[?DO]
                   5044: doc-[DO]
                   5045: doc-[FOR]
                   5046: doc-[LOOP]
                   5047: doc-[+LOOP]
                   5048: doc-[NEXT]
1.1       anton    5049: 
1.26      crook    5050: doc-[BEGIN]
                   5051: doc-[UNTIL]
                   5052: doc-[AGAIN]
                   5053: doc-[WHILE]
                   5054: doc-[REPEAT]
1.1       anton    5055: 
1.27      crook    5056: 
                   5057: 
1.26      crook    5058: @c -------------------------------------------------------------
                   5059: @node Tokens for Words, Word Lists, The Text Interpreter, Words
                   5060: @section Tokens for Words
                   5061: @cindex tokens for words
1.1       anton    5062: 
1.28      crook    5063: This section describes the creation and use of tokens that represent
1.29      crook    5064: words.
                   5065: 
                   5066: Named words have information stored in their name dictionary entries to
                   5067: indicate any non-default semantics (@pxref{Interpretation and
                   5068: Compilation Semantics}). The semantics can be modified, using
                   5069: @code{immediate} and/or @code{compile-only}, at the time that the words
                   5070: are defined. Unnamed words have (by definition) no name dictionary
                   5071: entry, and therefore must have default semantics.
1.21      crook    5072: 
1.26      crook    5073: Named words have interpretation and compilation semantics. Unnamed words
                   5074: just have execution semantics.
1.21      crook    5075: 
1.29      crook    5076: @cindex xt
                   5077: @cindex execution token
                   5078: The execution semantics of an unnamed word are represented by an
                   5079: @dfn{execution token} (@i{xt}). As explained in @ref{Supplying names},
                   5080: the execution token of the last word defined can be produced with
                   5081: @code{lastxt}.
                   5082: 
                   5083: The interpretation semantics of a named word are also represented by an
                   5084: execution token. You can produce the execution token using @code{'} or
                   5085: @code{[']}. A simple example shows the difference between the two:
1.21      crook    5086: 
1.29      crook    5087: @example
                   5088: : greet ( -- )   ." Hello" ;
                   5089: : foo ( -- xt )  ['] greet ; \ ['] parses greet at compile-time
                   5090: : bar ( -- )     ' EXECUTE ; \  '  parses at run-time
1.1       anton    5091: 
1.29      crook    5092: \ the next four lines all do the same thing
                   5093: foo EXECUTE
                   5094: greet
                   5095: ' greet EXECUTE
                   5096: boo greet
                   5097: @end example
1.1       anton    5098: 
1.29      crook    5099: An execution token occupies one cell.
1.26      crook    5100: @cindex code field address
                   5101: @cindex CFA
1.29      crook    5102: In Gforth, the abstract data type @i{execution token} is implemented
1.26      crook    5103: as a code field address (CFA).
                   5104: @comment TODO note that the standard does not say what it represents..
                   5105: @comment and you cannot necessarily compile it in all Forths (eg native
                   5106: @comment compilers?).
1.1       anton    5107: 
1.29      crook    5108: For literals, use @code{'} in interpreted code and @code{[']} in
                   5109: compiled code. Gforth's @code{'} and @code{[']} behave somewhat
                   5110: unusually by complaining about compile-only words. To get the execution
                   5111: token for a compile-only word @i{name}, use @code{COMP' @i{name} DROP}
                   5112: or @code{[COMP'] @i{name} DROP}.
1.1       anton    5113: 
1.26      crook    5114: @cindex compilation token
1.29      crook    5115: The compilation semantics of a named word are represented by a
                   5116: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
                   5117: @i{xt} is an execution token. The compilation semantics represented by
                   5118: the compilation token can be performed with @code{execute}, which
                   5119: consumes the whole compilation token, with an additional stack effect
                   5120: determined by the represented compilation semantics.
                   5121: 
                   5122: At present, the @i{w} part of a compilation token is an execution token,
                   5123: and the @i{xt} part represents either @code{execute} or
                   5124: @code{compile,}@footnote{Depending upon the compilation semantics of the
                   5125: word. If the word has default compilation semantics, the @i{xt} will
                   5126: represent @code{compile,}. If the word is @code{immediate}, the @i{xt}
                   5127: will represent @code{execute}.}. However, don't rely on that knowledge,
                   5128: unless necessary; future versions of Gforth may introduce unusual
                   5129: compilation tokens (e.g., a compilation token that represents the
                   5130: compilation semantics of a literal).
1.1       anton    5131: 
1.26      crook    5132: You can compile the compilation semantics with @code{postpone,}. I.e.,
1.29      crook    5133: @code{COMP' @i{word} postpone,} is equivalent to @code{postpone
                   5134: @i{word}}.
1.21      crook    5135: 
1.26      crook    5136: @cindex name token
                   5137: @cindex name field address
                   5138: @cindex NFA
1.29      crook    5139: Named words are also represented by the @dfn{name token}, (@i{nt}). In
                   5140: Gforth, the abstract data type @emph{name token} is implemented as a
                   5141: name field address (NFA).
                   5142: 
                   5143: doc-execute
                   5144: doc-compile,
                   5145: doc-[']
                   5146: doc-'
                   5147: doc-[comp']
                   5148: doc-comp'
                   5149: doc-postpone,
1.1       anton    5150: 
1.26      crook    5151: doc-find-name
                   5152: doc-name>int
                   5153: doc-name?int
                   5154: doc-name>comp
                   5155: doc-name>string
1.1       anton    5156: 
1.26      crook    5157: @c -------------------------------------------------------------
                   5158: @node Word Lists, Environmental Queries, Tokens for Words, Words
                   5159: @section Word Lists
                   5160: @cindex word lists
                   5161: @cindex name dictionary
1.1       anton    5162: 
1.26      crook    5163: @cindex wid
                   5164: All definitions other than those created by @code{:noname} have an entry
                   5165: in the name dictionary. The name dictionary is fragmented into a number
1.29      crook    5166: of parts, called @dfn{word lists}. A word list is identified by a
                   5167: cell-sized word list identifier (@i{wid}) in much the same way as a
1.26      crook    5168: file is identified by a file handle. The numerical value of the wid has
                   5169: no (portable) meaning, and might change from session to session.
1.1       anton    5170: 
1.26      crook    5171: @cindex compilation word list
                   5172: At any one time, a single word list is defined as the word list to which
1.29      crook    5173: all new definitions will be added -- this is called the @dfn{compilation
1.26      crook    5174: word list}. When Gforth is started, the compilation word list is the
                   5175: word list called @code{FORTH-WORDLIST}.
1.1       anton    5176: 
1.26      crook    5177: @cindex search order stack
1.29      crook    5178: Forth maintains a stack of word lists, representing the @dfn{search
1.26      crook    5179: order}.  When the name dictionary is searched (for example, when
                   5180: attempting to find a word's execution token during compilation), only
                   5181: those word lists that are currently in the search order are
                   5182: searched. The most recently-defined word in the word list at the top of
                   5183: the word list stack is searched first, and the search proceeds until
                   5184: either the word is located or the oldest definition in the word list at
                   5185: the bottom of the stack is reached. Definitions of the word may exist in
                   5186: more than one word lists; the search order determines which version will
                   5187: be found.
1.1       anton    5188: 
1.29      crook    5189: The ANS Forth ``Search order'' word set is intended to provide a set of
                   5190: low-level tools that allow various different schemes to be
1.26      crook    5191: implemented. Gforth provides @code{vocabulary}, a traditional Forth
                   5192: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
                   5193: Standard Forth.
1.1       anton    5194: 
1.27      crook    5195: @comment TODO: locals section refers to here, saying that every word list (aka
                   5196: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.1       anton    5197: 
1.27      crook    5198: @comment the thisone- prefix is used to pick out the true definition of a
                   5199: @comment word from the source files, rather than some alias.
1.26      crook    5200: doc-forth-wordlist
                   5201: doc-definitions
                   5202: doc-get-current
                   5203: doc-set-current
                   5204: doc-get-order
1.27      crook    5205: doc---thisone-set-order
1.26      crook    5206: doc-wordlist
1.30      anton    5207: doc-table
1.26      crook    5208: doc-also
1.27      crook    5209: doc---thisone-forth
1.26      crook    5210: doc-only
1.27      crook    5211: doc---thisone-order
1.26      crook    5212: doc-previous
1.15      anton    5213: 
1.26      crook    5214: doc-find
                   5215: doc-search-wordlist
1.15      anton    5216: 
1.26      crook    5217: doc-words
                   5218: doc-vlist
1.1       anton    5219: 
1.26      crook    5220: doc-mappedwordlist
                   5221: doc-root
                   5222: doc-vocabulary
                   5223: doc-seal
                   5224: doc-vocs
                   5225: doc-current
                   5226: doc-context
1.1       anton    5227: 
1.26      crook    5228: @menu
                   5229: * Why use word lists?::
                   5230: * Word list examples::
                   5231: @end menu
                   5232: 
                   5233: @node Why use word lists?, Word list examples, Word Lists, Word Lists
                   5234: @subsection Why use word lists?
                   5235: @cindex word lists - why use them?
                   5236: 
1.29      crook    5237: Here are some reasons for using multiple word lists:
1.26      crook    5238: 
                   5239: @itemize @bullet
                   5240: @item
                   5241: To improve compilation speed by reducing the number of name dictionary
                   5242: entries that must be searched. This is achieved by creating a new
                   5243: word list that contains all of the definitions that are used in the
                   5244: definition of a Forth system but which would not usually be used by
                   5245: programs running on that system. That word list would be on the search
                   5246: list when the Forth system was compiled but would be removed from the
                   5247: search list for normal operation. This can be a useful technique for
                   5248: low-performance systems (for example, 8-bit processors in embedded
                   5249: systems) but is unlikely to be necessary in high-performance desktop
                   5250: systems.
                   5251: @item
                   5252: To prevent a set of words from being used outside the context in which
                   5253: they are valid. Two classic examples of this are an integrated editor
                   5254: (all of the edit commands are defined in a separate word list; the
                   5255: search order is set to the editor word list when the editor is invoked;
                   5256: the old search order is restored when the editor is terminated) and an
                   5257: integrated assembler (the op-codes for the machine are defined in a
                   5258: separate word list which is used when a @code{CODE} word is defined).
                   5259: @item
                   5260: To prevent a name-space clash between multiple definitions with the same
                   5261: name. For example, when building a cross-compiler you might have a word
                   5262: @code{IF} that generates conditional code for your target system. By
                   5263: placing this definition in a different word list you can control whether
                   5264: the host system's @code{IF} or the target system's @code{IF} get used in
                   5265: any particular context by controlling the order of the word lists on the
                   5266: search order stack.
                   5267: @end itemize
1.1       anton    5268: 
1.26      crook    5269: @node Word list examples, ,Why use word lists?, Word Lists
                   5270: @subsection Word list examples
                   5271: @cindex word lists - examples
1.1       anton    5272: 
1.26      crook    5273: Here is an example of creating and using a new wordlist using ANS
                   5274: Forth Standard words:
1.1       anton    5275: 
                   5276: @example
1.26      crook    5277: wordlist constant my-new-words-wordlist
                   5278: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
1.21      crook    5279: 
1.26      crook    5280: \ add it to the search order
                   5281: also my-new-words
1.21      crook    5282: 
1.26      crook    5283: \ alternatively, add it to the search order and make it
                   5284: \ the compilation word list
                   5285: also my-new-words definitions
                   5286: \ type "order" to see the problem
1.21      crook    5287: @end example
                   5288: 
1.26      crook    5289: The problem with this example is that @code{order} has no way to
                   5290: associate the name @code{my-new-words} with the wid of the word list (in
                   5291: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   5292: that has no associated name). There is no Standard way of associating a
                   5293: name with a wid.
                   5294: 
                   5295: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   5296: associates a name with a wid:
1.21      crook    5297: 
1.26      crook    5298: @example
                   5299: vocabulary my-new-words
1.21      crook    5300: 
1.26      crook    5301: \ add it to the search order
                   5302: my-new-words
1.21      crook    5303: 
1.26      crook    5304: \ alternatively, add it to the search order and make it
                   5305: \ the compilation word list
                   5306: my-new-words definitions
                   5307: \ type "order" to see that the problem is solved
                   5308: @end example
1.23      crook    5309: 
1.26      crook    5310: @c -------------------------------------------------------------
                   5311: @node Environmental Queries, Files, Word Lists, Words
                   5312: @section Environmental Queries
                   5313: @cindex environmental queries
1.21      crook    5314: 
1.26      crook    5315: ANS Forth introduced the idea of ``environmental queries'' as a way
                   5316: for a program running on a system to determine certain characteristics of the system.
                   5317: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    5318: 
1.26      crook    5319: The Standard requires that the name space used for environmental queries
                   5320: be distinct from the name space used for definitions.
1.21      crook    5321: 
1.26      crook    5322: Typically, environmental queries are supported by creating a set of
1.29      crook    5323: definitions in a word list that is @i{only} used during environmental
1.26      crook    5324: queries; that is what Gforth does. There is no Standard way of adding
                   5325: definitions to the set of recognised environmental queries, but any
                   5326: implementation that supports the loading of optional word sets must have
                   5327: some mechanism for doing this (after loading the word set, the
                   5328: associated environmental query string must return @code{true}). In
                   5329: Gforth, the word list used to honour environmental queries can be
                   5330: manipulated just like any other word list.
1.21      crook    5331: 
1.26      crook    5332: doc-environment?
                   5333: doc-environment-wordlist
1.21      crook    5334: 
1.26      crook    5335: doc-gforth
                   5336: doc-os-class
1.21      crook    5337: 
1.26      crook    5338: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   5339: returning two items on the stack, querying it using @code{environment?}
                   5340: will return an additional item; the @code{true} flag that shows that the
                   5341: string was recognised.
1.21      crook    5342: 
1.26      crook    5343: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    5344: 
1.26      crook    5345: Here are some examples of using environmental queries:
1.21      crook    5346: 
1.26      crook    5347: @example
                   5348: s" address-unit-bits" environment? 0=
                   5349: [IF]
                   5350:      cr .( environmental attribute address-units-bits unknown... ) cr
                   5351: [THEN]
1.21      crook    5352: 
1.26      crook    5353: s" block" environment? [IF] DROP include block.fs [THEN]
1.21      crook    5354: 
1.26      crook    5355: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
1.21      crook    5356: 
1.26      crook    5357: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   5358:                         [ELSE] .( Not Gforth..) [THEN]
                   5359: @end example
1.21      crook    5360: 
                   5361: 
1.26      crook    5362: Here is an example of adding a definition to the environment word list:
1.21      crook    5363: 
1.26      crook    5364: @example
                   5365: get-current environment-wordlist set-current
                   5366: true constant block
                   5367: true constant block-ext
                   5368: set-current
                   5369: @end example
1.21      crook    5370: 
1.26      crook    5371: You can see what definitions are in the environment word list like this:
1.21      crook    5372: 
1.26      crook    5373: @example
                   5374: get-order 1+ environment-wordlist swap set-order words previous
                   5375: @end example
1.21      crook    5376: 
                   5377: 
1.26      crook    5378: @c -------------------------------------------------------------
                   5379: @node Files, Blocks, Environmental Queries, Words
                   5380: @section Files
1.28      crook    5381: @cindex files
                   5382: @cindex I/O - file-handling
1.21      crook    5383: 
1.26      crook    5384: Gforth provides facilities for accessing files that are stored in the
                   5385: host operating system's file-system. Files that are processed by Gforth
                   5386: can be divided into two categories:
1.21      crook    5387: 
1.23      crook    5388: @itemize @bullet
                   5389: @item
1.29      crook    5390: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    5391: @item
1.29      crook    5392: Files that are processed by some other program (@dfn{general files}).
1.26      crook    5393: @end itemize
                   5394: 
                   5395: @menu
                   5396: * Forth source files::
                   5397: * General files::         
                   5398: * Search Paths::                 
                   5399: * Forth Search Paths::    
                   5400: * General Search Paths::        
                   5401: @end menu
                   5402: 
1.21      crook    5403: 
1.26      crook    5404: @c -------------------------------------------------------------
                   5405: @node Forth source files, General files, Files, Files
                   5406: @subsection Forth source files
                   5407: @cindex including files
                   5408: @cindex Forth source files
1.21      crook    5409: 
1.26      crook    5410: The simplest way to interpret the contents of a file is to use one of
                   5411: these two formats:
1.21      crook    5412: 
1.26      crook    5413: @example
                   5414: include mysource.fs
                   5415: s" mysource.fs" included
                   5416: @end example
1.21      crook    5417: 
1.26      crook    5418: Sometimes you want to include a file only if it is not included already
                   5419: (by, say, another source file). In that case, you can use one of these
                   5420: fomats:
1.21      crook    5421: 
1.26      crook    5422: @example
                   5423: require mysource.fs
                   5424: needs mysource.fs
                   5425: s" mysource.fs" required
                   5426: @end example
1.21      crook    5427: 
1.26      crook    5428: @cindex stack effect of included files
                   5429: @cindex including files, stack effect
                   5430: I recommend that you write your source files such that interpreting them
                   5431: does not change the stack. This allows using these files with
                   5432: @code{required} and friends without complications. For example:
1.21      crook    5433: 
1.26      crook    5434: @example
                   5435: 1 require foo.fs drop
                   5436: @end example
1.21      crook    5437: 
1.26      crook    5438: doc-include-file
                   5439: doc-included
1.28      crook    5440: doc-included?
1.26      crook    5441: doc-include
                   5442: doc-required
                   5443: doc-require
                   5444: doc-needs
1.28      crook    5445: doc-init-included-files
1.21      crook    5446: 
1.26      crook    5447: A definition in ANS Forth for @code{required} is provided in
                   5448: @file{compat/required.fs}.
1.21      crook    5449: 
1.26      crook    5450: @c -------------------------------------------------------------
                   5451: @node General files, Search Paths, Forth source files, Files
                   5452: @subsection General files
                   5453: @cindex general files
                   5454: @cindex file-handling
1.21      crook    5455: 
1.26      crook    5456: Files are opened/created by name and type. The following types are
                   5457: recognised:
1.1       anton    5458: 
1.26      crook    5459: doc-r/o
                   5460: doc-r/w
                   5461: doc-w/o
                   5462: doc-bin
1.1       anton    5463: 
1.26      crook    5464: When a file is opened/created, it returns a file identifier,
1.29      crook    5465: @i{wfileid} that is used for all other file commands. All file
                   5466: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    5467: successful operation and an implementation-defined non-zero value in the
                   5468: case of an error.
1.21      crook    5469: 
1.26      crook    5470: doc-open-file
                   5471: doc-create-file
1.21      crook    5472: 
1.26      crook    5473: doc-close-file
                   5474: doc-delete-file
                   5475: doc-rename-file
                   5476: doc-read-file
                   5477: doc-read-line
                   5478: doc-write-file
                   5479: doc-write-line
                   5480: doc-emit-file
                   5481: doc-flush-file
1.21      crook    5482: 
1.26      crook    5483: doc-file-status
                   5484: doc-file-position
                   5485: doc-reposition-file
                   5486: doc-file-size
                   5487: doc-resize-file
1.21      crook    5488: 
1.26      crook    5489: @c ---------------------------------------------------------
                   5490: @node Search Paths, Forth Search Paths, General files, Files
                   5491: @subsection Search Paths
                   5492: @cindex path for @code{included}
                   5493: @cindex file search path
                   5494: @cindex @code{include} search path
                   5495: @cindex search path for files
1.21      crook    5496: 
1.26      crook    5497: If you specify an absolute filename (i.e., a filename starting with
                   5498: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   5499: @samp{C:...})) for @code{included} and friends, that file is included
                   5500: just as you would expect.
1.21      crook    5501: 
1.26      crook    5502: For relative filenames, Gforth uses a search path similar to Forth's
                   5503: search order (@pxref{Word Lists}). It tries to find the given filename
                   5504: in the directories present in the path, and includes the first one it
                   5505: finds. There are separate search paths for Forth source files and
                   5506: general files.
1.21      crook    5507: 
1.26      crook    5508: If the search path contains the directory @file{.} (as it should), this
                   5509: refers to the directory that the present file was @code{included}
                   5510: from. This allows files to include other files relative to their own
                   5511: position (irrespective of the current working directory or the absolute
                   5512: position).  This feature is essential for libraries consisting of
                   5513: several files, where a file may include other files from the library.
                   5514: It corresponds to @code{#include "..."} in C. If the current input
                   5515: source is not a file, @file{.} refers to the directory of the innermost
                   5516: file being included, or, if there is no file being included, to the
                   5517: current working directory.
1.21      crook    5518: 
1.26      crook    5519: Use @file{~+} to refer to the current working directory (as in the
                   5520: @code{bash}).
1.1       anton    5521: 
1.26      crook    5522: If the filename starts with @file{./}, the search path is not searched
                   5523: (just as with absolute filenames), and the @file{.} has the same meaning
                   5524: as described above.
1.1       anton    5525: 
1.26      crook    5526: @c ---------------------------------------------------------
                   5527: @node Forth Search Paths, General Search Paths, Search Paths, Files
                   5528: @subsubsection Forth Search Paths
1.28      crook    5529: @cindex search path control - Forth
1.5       anton    5530: 
1.26      crook    5531: The search path is initialized when you start Gforth (@pxref{Invoking
                   5532: Gforth}). You can display it and change it using these words:
1.5       anton    5533: 
1.26      crook    5534: doc-.fpath
                   5535: doc-fpath+
                   5536: doc-fpath=
                   5537: doc-open-fpath-file
1.5       anton    5538: 
1.26      crook    5539: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    5540: 
1.26      crook    5541: @example
                   5542: fpath= /usr/lib/forth/|./
                   5543: require timer.fs
                   5544: @end example
1.5       anton    5545: 
1.26      crook    5546: @c ---------------------------------------------------------
                   5547: @node General Search Paths,  , Forth Search Paths, Files
                   5548: @subsubsection General Search Paths
                   5549: @cindex search path control - for user applications
1.5       anton    5550: 
1.26      crook    5551: Your application may need to search files in several directories, like
                   5552: @code{included} does. To facilitate this, Gforth allows you to define
                   5553: and use your own search paths, by providing generic equivalents of the
                   5554: Forth search path words:
1.5       anton    5555: 
1.26      crook    5556: doc-.path
                   5557: doc-path+
                   5558: doc-path=
                   5559: doc-open-path-file
1.5       anton    5560: 
1.26      crook    5561: Here's an example of creating a search path:
1.5       anton    5562: 
1.26      crook    5563: @example
                   5564: \ Make a buffer for the path:
                   5565: create mypath   100 chars ,     \ maximum length (is checked)
                   5566:                 0 ,             \ real len
                   5567:                 100 chars allot \ space for path
                   5568: @end example
1.5       anton    5569: 
1.26      crook    5570: @c -------------------------------------------------------------
                   5571: @node Blocks, Other I/O, Files, Words
                   5572: @section Blocks
1.28      crook    5573: @cindex I/O - blocks
                   5574: @cindex blocks
                   5575: 
                   5576: When you run Gforth on a modern desk-top computer, it runs under the
                   5577: control of an operating system which provides certain services.  One of
                   5578: these services is @var{file services}, which allows Forth source code
                   5579: and data to be stored in files and read into Gforth (@pxref{Files}).
                   5580: 
                   5581: Traditionally, Forth has been an important programming language on
                   5582: systems where it has interfaced directly to the underlying hardware with
                   5583: no intervening operating system. Forth provides a mechanism, called
1.29      crook    5584: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    5585: 
                   5586: A block is a 1024-byte data area, which can be used to hold data or
                   5587: Forth source code. No structure is imposed on the contents of the
                   5588: block. A block is identified by its number; blocks are numbered
                   5589: contiguously from 1 to an implementation-defined maximum.
                   5590: 
                   5591: A typical system that used blocks but no operating system might use a
                   5592: single floppy-disk drive for mass storage, with the disks formatted to
                   5593: provide 256-byte sectors. Blocks would be implemented by assigning the
                   5594: first four sectors of the disk to block 1, the second four sectors to
                   5595: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   5596: would not contain any file system information, just the set of blocks.
                   5597: 
1.29      crook    5598: @cindex blocks file
1.28      crook    5599: On systems that do provide file services, blocks are typically
1.29      crook    5600: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    5601: file}.  The size of the blocks file will be an exact multiple of 1024
                   5602: bytes, corresponding to the number of blocks it contains. This is the
                   5603: mechanism that Gforth uses.
                   5604: 
1.29      crook    5605: @cindex @file{blocks.fb}
1.28      crook    5606: Only 1 blocks file can be open at a time. If you use block words without
                   5607: having specified a blocks file, Gforth defaults to the blocks file
                   5608: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
                   5609: locate a blocks file (@pxref{Forth Search Paths}).
                   5610: 
1.29      crook    5611: @cindex block buffers
1.28      crook    5612: When you read and write blocks under program control, Gforth uses a
1.29      crook    5613: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    5614: not used when you use @code{load} to interpret the contents of a block.
                   5615: 
                   5616: The behaviour of the block buffers is directly analagous to that of a
                   5617: cache. Each block buffer has three states:
                   5618: 
                   5619: @itemize @bullet
                   5620: @item
                   5621: Unassigned
                   5622: @item
                   5623: Assigned-clean
                   5624: @item
                   5625: Assigned-dirty
                   5626: @end itemize
                   5627: 
1.29      crook    5628: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    5629: block, the block (specified by its block number) must be assigned to a
                   5630: block buffer.
                   5631: 
                   5632: The assignment of a block to a block buffer is performed by @code{block}
                   5633: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   5634: contents of a block. Use @code{buffer} when you don't care about the
                   5635: existing contents of the block@footnote{The ANS Forth definition of
                   5636: @code{block} is intended not to cause disk I/O; if the data associated
                   5637: with the particular block is already stored in a block buffer due to an
                   5638: earlier @code{block} command, @code{buffer} will return that block
                   5639: buffer and the existing contents of the block will be
                   5640: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29      crook    5641: block buffer for the block.}.
1.28      crook    5642: 
                   5643: Once a block has been assigned to a block buffer, the block buffer state
1.29      crook    5644: becomes @i{assigned-clean}. Data can now be manipulated within the
1.28      crook    5645: block buffer.
                   5646: 
                   5647: When the contents of a block buffer is changed it is necessary,
                   5648: @i{before calling} @code{block} @i{or} @code{buffer} @i{again}, to
                   5649: either abandon the changes (by doing nothing) or commit the changes,
                   5650: using @code{update}. Using @code{update} does not change the blocks
1.29      crook    5651: file; it simply changes a block buffer's state to @i{assigned-dirty}.
1.28      crook    5652: 
1.29      crook    5653: The word @code{flush} causes all @i{assigned-dirty} blocks to be
1.28      crook    5654: written back to the blocks file on disk. Leaving Gforth using @code{bye}
                   5655: also causes a @code{flush} to be performed.
                   5656: 
1.29      crook    5657: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    5658: algorithm to assign a block buffer to a block. That means that any
                   5659: particular block can only be assigned to one specific block buffer,
1.29      crook    5660: called (for the particular operation) the @i{victim buffer}. If the
                   5661: victim buffer is @i{unassigned} or @i{assigned-clean} it can be
                   5662: allocated to the new block immediately. If it is @i{assigned-dirty}
1.28      crook    5663: its current contents must be written out to disk before it can be
                   5664: allocated to the new block.
                   5665: 
                   5666: Although no structure is imposed on the contents of a block, it is
                   5667: traditional to display the contents as 16 lines each of 64 characters.  A
                   5668: block provides a single, continuous stream of input (for example, it
                   5669: acts as a single parse area) -- there are no end-of-line characters
                   5670: within a block, and no end-of-file character at the end of a
                   5671: block. There are two consequences of this:
1.26      crook    5672: 
1.28      crook    5673: @itemize @bullet
                   5674: @item
                   5675: The last character of one line wraps straight into the first character
                   5676: of the following line
                   5677: @item
                   5678: The word @code{\} -- comment to end of line -- requires special
                   5679: treatment; in the context of a block it causes all characters until the
                   5680: end of the current 64-character ``line'' to be ignored.
                   5681: @end itemize
                   5682: 
                   5683: In Gforth, when you use @code{block} with a non-existent block number,
                   5684: the current block file will be extended to the appropriate size and the
                   5685: block buffer will be initialised with spaces.
                   5686: 
1.29      crook    5687: Gforth doesn't encourage the use of blocks; the mechanism is only
                   5688: provided for backward compatibility -- ANS Forth requires blocks to be
                   5689: available when files are.
1.28      crook    5690: 
                   5691: Common techniques that are used when working with blocks include:
                   5692: 
                   5693: @itemize @bullet
                   5694: @item
                   5695: A screen editor that allows you to edit blocks without leaving the Forth
                   5696: environment.
                   5697: @item
                   5698: Shadow screens; where every code block has an associated block
                   5699: containing comments (for example: code in odd block numbers, comments in
                   5700: even block numbers). Typically, the block editor provides a convenient
                   5701: mechanism to toggle between code and comments.
                   5702: @item
                   5703: Load blocks; a single block (typically block 1) contains a number of
                   5704: @code{thru} commands which @code{load} the whole of the application.
                   5705: @item
                   5706: Chaining blocks; a block terminates with a @code{-->} so that a whole
                   5707: application can be @code{load}ed by @code{load}ing a single block.
                   5708: @end itemize
1.26      crook    5709: 
1.29      crook    5710: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
                   5711: integrated into a Forth programming environment.
1.26      crook    5712: 
                   5713: @comment TODO what about errors on open-blocks?
                   5714: doc-open-blocks
                   5715: doc-use
                   5716: doc-get-block-fid
                   5717: doc-block-position
1.28      crook    5718: 
                   5719: doc-scr
                   5720: doc-list
                   5721: 
                   5722: doc---block-block
                   5723: doc-buffer
                   5724: 
1.26      crook    5725: doc-update
1.28      crook    5726: doc-updated?
1.26      crook    5727: doc-save-buffers
                   5728: doc-empty-buffers
                   5729: doc-empty-buffer
                   5730: doc-flush
1.28      crook    5731: 
1.26      crook    5732: doc-load
                   5733: doc-thru
                   5734: doc-+load
                   5735: doc-+thru
                   5736: doc---block--->
                   5737: doc-block-included
                   5738: 
                   5739: @c -------------------------------------------------------------
                   5740: @node Other I/O, Programming Tools, Blocks, Words
                   5741: @section Other I/O
1.28      crook    5742: @cindex I/O - keyboard and display
1.26      crook    5743: 
                   5744: @menu
                   5745: * Simple numeric output::       Predefined formats
                   5746: * Formatted numeric output::    Formatted (pictured) output
                   5747: * String Formats::              How Forth stores strings in memory
                   5748: * Displaying characters and strings:: Other stuff
                   5749: * Input::                       Input
                   5750: @end menu
                   5751: 
                   5752: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   5753: @subsection Simple numeric output
1.28      crook    5754: @cindex numeric output - simple/free-format
1.5       anton    5755: 
1.26      crook    5756: The simplest output functions are those that display numbers from the
                   5757: data or floating-point stacks. Floating-point output is always displayed
                   5758: using base 10. Numbers displayed from the data stack use the value stored
                   5759: in @code{base}.
1.5       anton    5760: 
1.26      crook    5761: doc-.
                   5762: doc-dec.
                   5763: doc-hex.
                   5764: doc-u.
                   5765: doc-.r
                   5766: doc-u.r
                   5767: doc-d.
                   5768: doc-ud.
                   5769: doc-d.r
                   5770: doc-ud.r
                   5771: doc-f.
                   5772: doc-fe.
                   5773: doc-fs.
1.5       anton    5774: 
1.26      crook    5775: Examples of printing the number 1234.5678E23 in the different floating-point output
                   5776: formats are shown below:
1.5       anton    5777: 
                   5778: @example
1.26      crook    5779: f. 123456779999999000000000000.
                   5780: fe. 123.456779999999E24
                   5781: fs. 1.23456779999999E26
1.5       anton    5782: @end example
                   5783: 
                   5784: 
1.26      crook    5785: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   5786: @subsection Formatted numeric output
1.28      crook    5787: @cindex formatted numeric output
1.26      crook    5788: @cindex pictured numeric output
1.28      crook    5789: @cindex numeric output - formatted
1.26      crook    5790: 
1.29      crook    5791: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    5792: output} for formatted printing of integers.  In this technique, digits
                   5793: are extracted from the number (using the current output radix defined by
                   5794: @code{base}), converted to ASCII codes and appended to a string that is
                   5795: built in a scratch-pad area of memory (@pxref{core-idef,
                   5796: Implementation-defined options, Implementation-defined
                   5797: options}). Arbitrary characters can be appended to the string during the
                   5798: extraction process. The completed string is specified by an address
                   5799: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   5800: under program control.
1.5       anton    5801: 
1.26      crook    5802: All of the words described in the previous section for simple numeric
                   5803: output are implemented in Gforth using pictured numeric output.
1.5       anton    5804: 
1.26      crook    5805: Three important things to remember about Pictured Numeric Output:
1.5       anton    5806: 
1.26      crook    5807: @itemize @bullet
                   5808: @item
1.28      crook    5809: It always operates on double-precision numbers; to display a
                   5810: single-precision number, convert it first (@pxref{Double precision} for
                   5811: ways of doing this).
1.26      crook    5812: @item
1.28      crook    5813: It always treats the double-precision number as though it were
                   5814: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    5815: @item
                   5816: The string is built up from right to left; least significant digit first.
                   5817: @end itemize
1.5       anton    5818: 
1.26      crook    5819: doc-<#
                   5820: doc-#
                   5821: doc-#s
                   5822: doc-hold
                   5823: doc-sign
                   5824: doc-#>
1.5       anton    5825: 
1.26      crook    5826: doc-represent
1.5       anton    5827: 
1.26      crook    5828: Here are some examples of using pictured numeric output:
1.5       anton    5829: 
                   5830: @example
1.26      crook    5831: : my-u. ( u -- )
                   5832:   \ Simplest use of pns.. behaves like Standard u. 
                   5833:   0              \ convert to unsigned double
                   5834:   <#             \ start conversion
                   5835:   #s             \ convert all digits
                   5836:   #>             \ complete conversion
                   5837:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    5838: 
1.26      crook    5839: : cents-only ( u -- )
                   5840:   0              \ convert to unsigned double
                   5841:   <#             \ start conversion
                   5842:   # #            \ convert two least-significant digits
                   5843:   #>             \ complete conversion, discard other digits
                   5844:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    5845: 
1.26      crook    5846: : dollars-and-cents ( u -- )
                   5847:   0              \ convert to unsigned double
                   5848:   <#             \ start conversion
                   5849:   # #            \ convert two least-significant digits
                   5850:   [char] . hold  \ insert decimal point
                   5851:   #s             \ convert remaining digits
                   5852:   [char] $ hold  \ append currency symbol
                   5853:   #>             \ complete conversion
                   5854:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    5855: 
1.26      crook    5856: : my-. ( n -- )
                   5857:   \ handling negatives.. behaves like Standard .
                   5858:   s>d            \ convert to signed double
                   5859:   swap over dabs \ leave sign byte followed by unsigned double
                   5860:   <#             \ start conversion
                   5861:   #s             \ convert all digits
                   5862:   rot sign       \ get at sign byte, append "-" if needed
                   5863:   #>             \ complete conversion
                   5864:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    5865: 
1.26      crook    5866: : account. ( n -- )
                   5867:   \ accountants don't like minus signs, they use braces
                   5868:   \ for negative numbers
                   5869:   s>d            \ convert to signed double
                   5870:   swap over dabs \ leave sign byte followed by unsigned double
                   5871:   <#             \ start conversion
                   5872:   2 pick         \ get copy of sign byte
                   5873:   0< IF [char] ) hold THEN \ right-most character of output
                   5874:   #s             \ convert all digits
                   5875:   rot            \ get at sign byte
                   5876:   0< IF [char] ( hold THEN
                   5877:   #>             \ complete conversion
                   5878:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    5879: @end example
                   5880: 
1.26      crook    5881: Here are some examples of using these words:
1.5       anton    5882: 
                   5883: @example
1.26      crook    5884: 1 my-u. 1
                   5885: hex -1 my-u. decimal FFFFFFFF
                   5886: 1 cents-only 01
                   5887: 1234 cents-only 34
                   5888: 2 dollars-and-cents $0.02
                   5889: 1234 dollars-and-cents $12.34
                   5890: 123 my-. 123
                   5891: -123 my. -123
                   5892: 123 account. 123
                   5893: -456 account. (456)
1.5       anton    5894: @end example
                   5895: 
                   5896: 
1.26      crook    5897: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   5898: @subsection String Formats
1.27      crook    5899: @cindex strings - see character strings
                   5900: @cindex character strings - formats
1.28      crook    5901: @cindex I/O - see character strings
1.26      crook    5902: 
1.27      crook    5903: Forth commonly uses two different methods for representing character
                   5904: strings:
1.26      crook    5905: 
                   5906: @itemize @bullet
                   5907: @item
                   5908: @cindex address of counted string
1.29      crook    5909: As a @dfn{counted string}, represented by a @i{c-addr}. The char
                   5910: addressed by @i{c-addr} contains a character-count, @i{n}, of the
                   5911: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    5912: memory.
                   5913: @item
1.29      crook    5914: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
                   5915: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    5916: first byte of the string.
                   5917: @end itemize
                   5918: 
                   5919: ANS Forth encourages the use of the second format when representing
                   5920: strings on the stack, whilst conceeding that the counted string format
                   5921: remains useful as a way of storing strings in memory.
                   5922: 
                   5923: doc-count
                   5924: 
                   5925: @xref{Memory Blocks} for words that move, copy and search
                   5926: for strings. @xref{Displaying characters and strings,} for words that
                   5927: display characters and strings.
                   5928: 
                   5929: 
                   5930: @node Displaying characters and strings, Input, String Formats, Other I/O
                   5931: @subsection Displaying characters and strings
1.27      crook    5932: @cindex characters - compiling and displaying
                   5933: @cindex character strings - compiling and displaying
1.26      crook    5934: 
                   5935: This section starts with a glossary of Forth words and ends with a set
                   5936: of examples.
                   5937: 
                   5938: doc-bl
                   5939: doc-space
                   5940: doc-spaces
                   5941: doc-emit
                   5942: doc-toupper
                   5943: doc-."
                   5944: doc-.(
                   5945: doc-type
                   5946: doc-cr
1.27      crook    5947: @cindex cursor control
1.26      crook    5948: doc-at-xy
                   5949: doc-page
                   5950: doc-s"
                   5951: doc-c"
                   5952: doc-char
                   5953: doc-[char]
                   5954: doc-sliteral
                   5955: 
                   5956: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    5957: 
                   5958: @example
1.26      crook    5959: .( text-1)
                   5960: : my-word
                   5961:   ." text-2" cr
                   5962:   .( text-3)
                   5963: ;
                   5964: 
                   5965: ." text-4"
                   5966: 
                   5967: : my-char
                   5968:   [char] ALPHABET emit
                   5969:   char emit
                   5970: ;
1.5       anton    5971: @end example
                   5972: 
1.26      crook    5973: When you load this code into Gforth, the following output is generated:
1.5       anton    5974: 
1.26      crook    5975: @example
1.30      anton    5976: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26      crook    5977: @end example
1.5       anton    5978: 
1.26      crook    5979: @itemize @bullet
                   5980: @item
                   5981: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   5982: is an immediate word; it behaves in the same way whether it is used inside
                   5983: or outside a colon definition.
                   5984: @item
                   5985: Message @code{text-4} is displayed because of Gforth's added interpretation
                   5986: semantics for @code{."}.
                   5987: @item
1.29      crook    5988: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    5989: performs the compilation semantics for @code{."} within the definition of
                   5990: @code{my-word}.
                   5991: @end itemize
1.5       anton    5992: 
1.26      crook    5993: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    5994: 
1.26      crook    5995: @example
1.30      anton    5996: @kbd{my-word @key{RET}} text-2
1.26      crook    5997:  ok
1.30      anton    5998: @kbd{my-char fred @key{RET}} Af ok
                   5999: @kbd{my-char jim @key{RET}} Aj ok
1.26      crook    6000: @end example
1.5       anton    6001: 
                   6002: @itemize @bullet
                   6003: @item
1.26      crook    6004: Message @code{text-2} is displayed because of the run-time behaviour of
                   6005: @code{."}.
                   6006: @item
                   6007: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   6008: on the stack at run-time. @code{emit} always displays the character
                   6009: when @code{my-char} is executed.
                   6010: @item
                   6011: @code{char} parses a string at run-time and the second @code{emit} displays
                   6012: the first character of the string.
1.5       anton    6013: @item
1.26      crook    6014: If you type @code{see my-char} you can see that @code{[char]} discarded
                   6015: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   6016: definition of @code{my-char}.
1.5       anton    6017: @end itemize
                   6018: 
                   6019: 
                   6020: 
1.26      crook    6021: @node Input, , Displaying characters and strings, Other I/O
                   6022: @subsection Input
                   6023: @cindex input
1.28      crook    6024: @cindex I/O - see input
                   6025: @cindex parsing a string
1.5       anton    6026: 
1.27      crook    6027: @xref{String Formats} for ways of storing character strings in memory.
1.5       anton    6028: 
1.27      crook    6029: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29      crook    6030: @comment then index them
1.27      crook    6031: 
                   6032: doc-key
                   6033: doc-key?
1.26      crook    6034: doc->number
                   6035: doc->float
                   6036: doc-accept
1.27      crook    6037: doc-pad
                   6038: doc-parse
                   6039: doc-word
                   6040: doc-sword
                   6041: doc-refill
                   6042: @comment obsolescent words..
                   6043: doc-convert
1.26      crook    6044: doc-query
                   6045: doc-expect
1.27      crook    6046: doc-span
1.5       anton    6047: 
                   6048: 
                   6049: @c -------------------------------------------------------------
1.26      crook    6050: @node Programming Tools, Assembler and Code Words, Other I/O, Words
                   6051: @section Programming Tools
                   6052: @cindex programming tools
1.12      anton    6053: 
                   6054: @menu
1.26      crook    6055: * Debugging::                   Simple and quick.
                   6056: * Assertions::                  Making your programs self-checking.
                   6057: * Singlestep Debugger::                Executing your program word by word.
1.5       anton    6058: @end menu
                   6059: 
1.26      crook    6060: @node Debugging, Assertions, Programming Tools, Programming Tools
                   6061: @subsection Debugging
                   6062: @cindex debugging
1.5       anton    6063: 
1.26      crook    6064: Languages with a slow edit/compile/link/test development loop tend to
                   6065: require sophisticated tracing/stepping debuggers to facilate
                   6066: productive debugging.
1.5       anton    6067: 
1.26      crook    6068: A much better (faster) way in fast-compiling languages is to add
                   6069: printing code at well-selected places, let the program run, look at
                   6070: the output, see where things went wrong, add more printing code, etc.,
                   6071: until the bug is found.
1.5       anton    6072: 
1.26      crook    6073: The simple debugging aids provided in @file{debugs.fs}
                   6074: are meant to support this style of debugging. In addition, there are
                   6075: words for non-destructively inspecting the stack and memory:
1.5       anton    6076: 
1.26      crook    6077: doc-.s
                   6078: doc-f.s
1.5       anton    6079: 
1.29      crook    6080: There is a word @code{.r} but it does @i{not} display the return
1.26      crook    6081: stack! It is used for formatted numeric output.
1.5       anton    6082: 
1.26      crook    6083: doc-depth
                   6084: doc-fdepth
                   6085: doc-clearstack
                   6086: doc-?
                   6087: doc-dump
1.5       anton    6088: 
1.26      crook    6089: The word @code{~~} prints debugging information (by default the source
                   6090: location and the stack contents). It is easy to insert. If you use Emacs
                   6091: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   6092: query-replace them with nothing). The deferred words
                   6093: @code{printdebugdata} and @code{printdebugline} control the output of
                   6094: @code{~~}. The default source location output format works well with
                   6095: Emacs' compilation mode, so you can step through the program at the
                   6096: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   6097: is that you can step in any direction and you know where the crash has
                   6098: happened or where the strange data has occurred).
1.5       anton    6099: 
1.26      crook    6100: The default actions of @code{~~} clobber the contents of the pictured
                   6101: numeric output string, so you should not use @code{~~}, e.g., between
                   6102: @code{<#} and @code{#>}.
1.5       anton    6103: 
1.26      crook    6104: doc-~~
                   6105: doc-printdebugdata
                   6106: doc-printdebugline
1.5       anton    6107: 
1.26      crook    6108: doc-see
                   6109: doc-marker
1.5       anton    6110: 
1.26      crook    6111: Here's an example of using @code{marker} at the start of a source file
                   6112: that you are debugging; it ensures that you only ever have one copy of
                   6113: the file's definitions compiled at any time:
1.5       anton    6114: 
1.26      crook    6115: @example
                   6116: [IFDEF] my-code
                   6117:     my-code
                   6118: [ENDIF]
1.5       anton    6119: 
1.26      crook    6120: marker my-code
1.28      crook    6121: init-included-files
1.5       anton    6122: 
1.26      crook    6123: \ .. definitions start here
                   6124: \ .
                   6125: \ .
                   6126: \ end
                   6127: @end example
1.5       anton    6128: 
                   6129: 
                   6130: 
1.26      crook    6131: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
                   6132: @subsection Assertions
                   6133: @cindex assertions
1.5       anton    6134: 
1.26      crook    6135: It is a good idea to make your programs self-checking, especially if you
                   6136: make an assumption that may become invalid during maintenance (for
                   6137: example, that a certain field of a data structure is never zero). Gforth
1.29      crook    6138: supports @dfn{assertions} for this purpose. They are used like this:
1.23      crook    6139: 
1.26      crook    6140: @example
1.29      crook    6141: assert( @i{flag} )
1.26      crook    6142: @end example
1.23      crook    6143: 
1.26      crook    6144: The code between @code{assert(} and @code{)} should compute a flag, that
                   6145: should be true if everything is alright and false otherwise. It should
                   6146: not change anything else on the stack. The overall stack effect of the
                   6147: assertion is @code{( -- )}. E.g.
1.23      crook    6148: 
1.26      crook    6149: @example
                   6150: assert( 1 1 + 2 = ) \ what we learn in school
                   6151: assert( dup 0<> ) \ assert that the top of stack is not zero
                   6152: assert( false ) \ this code should not be reached
                   6153: @end example
1.23      crook    6154: 
1.26      crook    6155: The need for assertions is different at different times. During
                   6156: debugging, we want more checking, in production we sometimes care more
                   6157: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   6158: becomes a comment. Depending on the importance of an assertion and the
                   6159: time it takes to check it, you may want to turn off some assertions and
                   6160: keep others turned on. Gforth provides several levels of assertions for
                   6161: this purpose:
1.23      crook    6162: 
1.26      crook    6163: doc-assert0(
                   6164: doc-assert1(
                   6165: doc-assert2(
                   6166: doc-assert3(
                   6167: doc-assert(
                   6168: doc-)
1.23      crook    6169: 
1.26      crook    6170: The variable @code{assert-level} specifies the highest assertions that
                   6171: are turned on. I.e., at the default @code{assert-level} of one,
                   6172: @code{assert0(} and @code{assert1(} assertions perform checking, while
                   6173: @code{assert2(} and @code{assert3(} assertions are treated as comments.
                   6174: 
                   6175: The value of @code{assert-level} is evaluated at compile-time, not at
                   6176: run-time. Therefore you cannot turn assertions on or off at run-time;
                   6177: you have to set the @code{assert-level} appropriately before compiling a
                   6178: piece of code. You can compile different pieces of code at different
                   6179: @code{assert-level}s (e.g., a trusted library at level 1 and
                   6180: newly-written code at level 3).
1.23      crook    6181: 
1.26      crook    6182: doc-assert-level
1.23      crook    6183: 
1.26      crook    6184: If an assertion fails, a message compatible with Emacs' compilation mode
                   6185: is produced and the execution is aborted (currently with @code{ABORT"}.
                   6186: If there is interest, we will introduce a special throw code. But if you
                   6187: intend to @code{catch} a specific condition, using @code{throw} is
                   6188: probably more appropriate than an assertion).
1.23      crook    6189: 
1.26      crook    6190: Definitions in ANS Forth for these assertion words are provided
                   6191: in @file{compat/assert.fs}.
1.23      crook    6192: 
                   6193: 
1.26      crook    6194: @node Singlestep Debugger, , Assertions, Programming Tools
                   6195: @subsection Singlestep Debugger
                   6196: @cindex singlestep Debugger
                   6197: @cindex debugging Singlestep
                   6198: @cindex @code{dbg}
                   6199: @cindex @code{BREAK:}
                   6200: @cindex @code{BREAK"}
1.23      crook    6201: 
1.26      crook    6202: When you create a new word there's often the need to check whether it
                   6203: behaves correctly or not. You can do this by typing @code{dbg
                   6204: badword}. A debug session might look like this:
1.23      crook    6205: 
1.26      crook    6206: @example
                   6207: : badword 0 DO i . LOOP ;  ok
                   6208: 2 dbg badword 
                   6209: : badword  
                   6210: Scanning code...
1.23      crook    6211: 
1.26      crook    6212: Nesting debugger ready!
1.23      crook    6213: 
1.26      crook    6214: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   6215: 400D4740  8049F68 DO             -> [ 0 ] 
                   6216: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   6217: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   6218: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   6219: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   6220: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   6221: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   6222: 400D4758  804B384 ;              ->  ok
                   6223: @end example
1.23      crook    6224: 
1.26      crook    6225: Each line displayed is one step. You always have to hit return to
                   6226: execute the next word that is displayed. If you don't want to execute
                   6227: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   6228: an overview what keys are available:
1.23      crook    6229: 
1.26      crook    6230: @table @i
1.23      crook    6231: 
1.30      anton    6232: @item @key{RET}
1.26      crook    6233: Next; Execute the next word.
1.23      crook    6234: 
1.26      crook    6235: @item n
                   6236: Nest; Single step through next word.
1.5       anton    6237: 
1.26      crook    6238: @item u
                   6239: Unnest; Stop debugging and execute rest of word. If we got to this word
                   6240: with nest, continue debugging with the calling word.
1.5       anton    6241: 
1.26      crook    6242: @item d
                   6243: Done; Stop debugging and execute rest.
1.5       anton    6244: 
1.26      crook    6245: @item s
                   6246: Stop; Abort immediately.
1.5       anton    6247: 
1.26      crook    6248: @end table
1.5       anton    6249: 
1.26      crook    6250: Debugging large application with this mechanism is very difficult, because
                   6251: you have to nest very deeply into the program before the interesting part
                   6252: begins. This takes a lot of time. 
1.5       anton    6253: 
1.26      crook    6254: To do it more directly put a @code{BREAK:} command into your source code.
                   6255: When program execution reaches @code{BREAK:} the single step debugger is
                   6256: invoked and you have all the features described above.
1.23      crook    6257: 
1.26      crook    6258: If you have more than one part to debug it is useful to know where the
                   6259: program has stopped at the moment. You can do this by the 
                   6260: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   6261: string is typed out when the ``breakpoint'' is reached.
                   6262: 
                   6263: doc-dbg
                   6264: doc-BREAK:
                   6265: doc-BREAK"
                   6266: 
                   6267: 
                   6268: @c -------------------------------------------------------------
                   6269: @node Assembler and Code Words, Threading Words, Programming Tools, Words
                   6270: @section Assembler and Code Words
                   6271: @cindex assembler
                   6272: @cindex code words
1.5       anton    6273: 
1.26      crook    6274: Gforth provides some words for defining primitives (words written in
1.29      crook    6275: machine code), and for defining the machine-code equivalent of
1.26      crook    6276: @code{DOES>}-based defining words. However, the machine-independent
                   6277: nature of Gforth poses a few problems: First of all, Gforth runs on
                   6278: several architectures, so it can provide no standard assembler. What's
                   6279: worse is that the register allocation not only depends on the processor,
                   6280: but also on the @code{gcc} version and options used.
1.5       anton    6281: 
1.29      crook    6282: The words that Gforth offers encapsulate some system dependences (e.g.,
                   6283: the header structure), so a system-independent assembler may be used in
1.26      crook    6284: Gforth. If you do not have an assembler, you can compile machine code
1.29      crook    6285: directly with @code{,} and @code{c,}@footnote{This isn't portable,
                   6286: because these words emit stuff in @i{data} space; it works because
                   6287: Gforth has unified code/data spaces. Assembler isn't likely to be
                   6288: portable anyway.}.
1.5       anton    6289: 
1.26      crook    6290: doc-assembler
                   6291: doc-code
                   6292: doc-end-code
                   6293: doc-;code
                   6294: doc-flush-icache
1.5       anton    6295: 
1.26      crook    6296: If @code{flush-icache} does not work correctly, @code{code} words
                   6297: etc. will not work (reliably), either.
1.5       anton    6298: 
1.29      crook    6299: The typical usage of these @code{code} words can be shown most easily by
                   6300: analogy to the equivalent high-level defining words:
                   6301: 
                   6302: @example
                   6303: : foo                                        code foo
                   6304:    <high-level Forth words>                        <assembler>
                   6305: ;                                            end-code
                   6306: 
                   6307: : bar                                        : bar
                   6308:    <high-level Forth words>                     <high-level Forth words>
                   6309:    CREATE                                       CREATE
                   6310:       <high-level Forth words>                     <high-level Forth words>
                   6311:    DOES>                                        ;code
                   6312:       <high-level Forth words>                     <assembler>
                   6313: ;                                            end-code
                   6314: @end example
                   6315: 
1.26      crook    6316: @code{flush-icache} is always present. The other words are rarely used
                   6317: and reside in @code{code.fs}, which is usually not loaded. You can load
                   6318: it with @code{require code.fs}.
1.5       anton    6319: 
1.26      crook    6320: @cindex registers of the inner interpreter
                   6321: In the assembly code you will want to refer to the inner interpreter's
                   6322: registers (e.g., the data stack pointer) and you may want to use other
                   6323: registers for temporary storage. Unfortunately, the register allocation
                   6324: is installation-dependent.
1.5       anton    6325: 
1.26      crook    6326: The easiest solution is to use explicit register declarations
                   6327: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
                   6328: GNU C Manual}) for all of the inner interpreter's registers: You have to
                   6329: compile Gforth with @code{-DFORCE_REG} (configure option
                   6330: @code{--enable-force-reg}) and the appropriate declarations must be
                   6331: present in the @code{machine.h} file (see @code{mips.h} for an example;
                   6332: you can find a full list of all declarable register symbols with
                   6333: @code{grep register engine.c}). If you give explicit registers to all
                   6334: variables that are declared at the beginning of @code{engine()}, you
                   6335: should be able to use the other caller-saved registers for temporary
                   6336: storage. Alternatively, you can use the @code{gcc} option
                   6337: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
                   6338: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
                   6339: (however, this restriction on register allocation may slow Gforth
                   6340: significantly).
1.5       anton    6341: 
1.26      crook    6342: If this solution is not viable (e.g., because @code{gcc} does not allow
                   6343: you to explicitly declare all the registers you need), you have to find
                   6344: out by looking at the code where the inner interpreter's registers
                   6345: reside and which registers can be used for temporary storage. You can
                   6346: get an assembly listing of the engine's code with @code{make engine.s}.
1.5       anton    6347: 
1.26      crook    6348: In any case, it is good practice to abstract your assembly code from the
                   6349: actual register allocation. E.g., if the data stack pointer resides in
                   6350: register @code{$17}, create an alias for this register called @code{sp},
                   6351: and use that in your assembly code.
1.5       anton    6352: 
1.26      crook    6353: @cindex code words, portable
                   6354: Another option for implementing normal and defining words efficiently
                   6355: is to add the desired functionality to the source of Gforth. For normal
                   6356: words you just have to edit @file{primitives} (@pxref{Automatic
                   6357: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
                   6358: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
                   6359: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.5       anton    6360: 
                   6361: 
1.26      crook    6362: @c -------------------------------------------------------------
                   6363: @node Threading Words, Locals, Assembler and Code Words, Words
                   6364: @section Threading Words
                   6365: @cindex threading words
1.5       anton    6366: 
1.26      crook    6367: @cindex code address
                   6368: These words provide access to code addresses and other threading stuff
                   6369: in Gforth (and, possibly, other interpretive Forths). It more or less
                   6370: abstracts away the differences between direct and indirect threading
                   6371: (and, for direct threading, the machine dependences). However, at
                   6372: present this wordset is still incomplete. It is also pretty low-level;
                   6373: some day it will hopefully be made unnecessary by an internals wordset
                   6374: that abstracts implementation details away completely.
1.5       anton    6375: 
1.26      crook    6376: doc-threading-method
                   6377: doc->code-address
                   6378: doc->does-code
                   6379: doc-code-address!
                   6380: doc-does-code!
                   6381: doc-does-handler!
                   6382: doc-/does-handler
1.5       anton    6383: 
1.26      crook    6384: The code addresses produced by various defining words are produced by
                   6385: the following words:
1.5       anton    6386: 
1.26      crook    6387: doc-docol:
                   6388: doc-docon:
                   6389: doc-dovar:
                   6390: doc-douser:
                   6391: doc-dodefer:
                   6392: doc-dofield:
1.5       anton    6393: 
1.26      crook    6394: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
                   6395: with @code{>does-code}. If the word was defined in that way, the value
                   6396: returned is non-zero and identifies the @code{DOES>} used by the
                   6397: defining word.
                   6398: @comment TODO should that be ``identifies the xt of the DOES> ??''
1.5       anton    6399: 
1.26      crook    6400: @c -------------------------------------------------------------
                   6401: @node Locals, Structures, Threading Words, Words
                   6402: @section Locals
                   6403: @cindex locals
1.5       anton    6404: 
1.26      crook    6405: Local variables can make Forth programming more enjoyable and Forth
                   6406: programs easier to read. Unfortunately, the locals of ANS Forth are
                   6407: laden with restrictions. Therefore, we provide not only the ANS Forth
                   6408: locals wordset, but also our own, more powerful locals wordset (we
                   6409: implemented the ANS Forth locals wordset through our locals wordset).
1.5       anton    6410: 
1.26      crook    6411: The ideas in this section have also been published in the paper
                   6412: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
                   6413: at EuroForth '94; it is available at
                   6414: @*@url{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
1.5       anton    6415: 
1.26      crook    6416: @menu
                   6417: * Gforth locals::               
                   6418: * ANS Forth locals::            
                   6419: @end menu
1.5       anton    6420: 
1.26      crook    6421: @node Gforth locals, ANS Forth locals, Locals, Locals
                   6422: @subsection Gforth locals
                   6423: @cindex Gforth locals
                   6424: @cindex locals, Gforth style
1.5       anton    6425: 
1.26      crook    6426: Locals can be defined with
1.5       anton    6427: 
                   6428: @example
1.26      crook    6429: @{ local1 local2 ... -- comment @}
                   6430: @end example
                   6431: or
                   6432: @example
                   6433: @{ local1 local2 ... @}
1.5       anton    6434: @end example
                   6435: 
1.26      crook    6436: E.g.,
1.5       anton    6437: @example
1.26      crook    6438: : max @{ n1 n2 -- n3 @}
                   6439:  n1 n2 > if
                   6440:    n1
                   6441:  else
                   6442:    n2
                   6443:  endif ;
1.5       anton    6444: @end example
                   6445: 
1.26      crook    6446: The similarity of locals definitions with stack comments is intended. A
                   6447: locals definition often replaces the stack comment of a word. The order
                   6448: of the locals corresponds to the order in a stack comment and everything
                   6449: after the @code{--} is really a comment.
1.5       anton    6450: 
1.26      crook    6451: This similarity has one disadvantage: It is too easy to confuse locals
                   6452: declarations with stack comments, causing bugs and making them hard to
                   6453: find. However, this problem can be avoided by appropriate coding
                   6454: conventions: Do not use both notations in the same program. If you do,
                   6455: they should be distinguished using additional means, e.g. by position.
                   6456: 
                   6457: @cindex types of locals
                   6458: @cindex locals types
                   6459: The name of the local may be preceded by a type specifier, e.g.,
                   6460: @code{F:} for a floating point value:
                   6461: 
                   6462: @example
                   6463: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   6464: \ complex multiplication
                   6465:  Ar Br f* Ai Bi f* f-
                   6466:  Ar Bi f* Ai Br f* f+ ;
                   6467: @end example
                   6468: 
                   6469: @cindex flavours of locals
                   6470: @cindex locals flavours
                   6471: @cindex value-flavoured locals
                   6472: @cindex variable-flavoured locals
                   6473: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   6474: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   6475: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   6476: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   6477: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   6478: produces its address (which becomes invalid when the variable's scope is
                   6479: left). E.g., the standard word @code{emit} can be defined in terms of
                   6480: @code{type} like this:
1.5       anton    6481: 
                   6482: @example
1.26      crook    6483: : emit @{ C^ char* -- @}
                   6484:     char* 1 type ;
1.5       anton    6485: @end example
                   6486: 
1.26      crook    6487: @cindex default type of locals
                   6488: @cindex locals, default type
                   6489: A local without type specifier is a @code{W:} local. Both flavours of
                   6490: locals are initialized with values from the data or FP stack.
1.5       anton    6491: 
1.26      crook    6492: Currently there is no way to define locals with user-defined data
                   6493: structures, but we are working on it.
1.5       anton    6494: 
1.26      crook    6495: Gforth allows defining locals everywhere in a colon definition. This
                   6496: poses the following questions:
1.5       anton    6497: 
1.26      crook    6498: @menu
                   6499: * Where are locals visible by name?::  
                   6500: * How long do locals live?::    
                   6501: * Programming Style::           
                   6502: * Implementation::              
                   6503: @end menu
1.5       anton    6504: 
1.26      crook    6505: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   6506: @subsubsection Where are locals visible by name?
                   6507: @cindex locals visibility
                   6508: @cindex visibility of locals
                   6509: @cindex scope of locals
1.5       anton    6510: 
1.26      crook    6511: Basically, the answer is that locals are visible where you would expect
                   6512: it in block-structured languages, and sometimes a little longer. If you
                   6513: want to restrict the scope of a local, enclose its definition in
                   6514: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    6515: 
1.26      crook    6516: doc-scope
                   6517: doc-endscope
1.5       anton    6518: 
1.26      crook    6519: These words behave like control structure words, so you can use them
                   6520: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   6521: arbitrary ways.
1.5       anton    6522: 
1.26      crook    6523: If you want a more exact answer to the visibility question, here's the
                   6524: basic principle: A local is visible in all places that can only be
                   6525: reached through the definition of the local@footnote{In compiler
                   6526: construction terminology, all places dominated by the definition of the
                   6527: local.}. In other words, it is not visible in places that can be reached
                   6528: without going through the definition of the local. E.g., locals defined
                   6529: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   6530: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   6531: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.5       anton    6532: 
1.26      crook    6533: The reasoning behind this solution is: We want to have the locals
                   6534: visible as long as it is meaningful. The user can always make the
                   6535: visibility shorter by using explicit scoping. In a place that can
                   6536: only be reached through the definition of a local, the meaning of a
                   6537: local name is clear. In other places it is not: How is the local
                   6538: initialized at the control flow path that does not contain the
                   6539: definition? Which local is meant, if the same name is defined twice in
                   6540: two independent control flow paths?
1.5       anton    6541: 
1.26      crook    6542: This should be enough detail for nearly all users, so you can skip the
                   6543: rest of this section. If you really must know all the gory details and
                   6544: options, read on.
1.5       anton    6545: 
1.26      crook    6546: In order to implement this rule, the compiler has to know which places
                   6547: are unreachable. It knows this automatically after @code{AHEAD},
                   6548: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   6549: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   6550: compiler that the control flow never reaches that place. If
                   6551: @code{UNREACHABLE} is not used where it could, the only consequence is
                   6552: that the visibility of some locals is more limited than the rule above
                   6553: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   6554: lie to the compiler), buggy code will be produced.
1.5       anton    6555: 
1.26      crook    6556: doc-unreachable
1.5       anton    6557: 
1.26      crook    6558: Another problem with this rule is that at @code{BEGIN}, the compiler
                   6559: does not know which locals will be visible on the incoming
                   6560: back-edge. All problems discussed in the following are due to this
                   6561: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   6562: loops as examples; the discussion also applies to @code{?DO} and other
                   6563: loops). Perhaps the most insidious example is:
1.5       anton    6564: @example
1.26      crook    6565: AHEAD
                   6566: BEGIN
                   6567:   x
                   6568: [ 1 CS-ROLL ] THEN
                   6569:   @{ x @}
                   6570:   ...
                   6571: UNTIL
                   6572: @end example
1.5       anton    6573: 
1.26      crook    6574: This should be legal according to the visibility rule. The use of
                   6575: @code{x} can only be reached through the definition; but that appears
                   6576: textually below the use.
1.5       anton    6577: 
1.26      crook    6578: From this example it is clear that the visibility rules cannot be fully
                   6579: implemented without major headaches. Our implementation treats common
                   6580: cases as advertised and the exceptions are treated in a safe way: The
                   6581: compiler makes a reasonable guess about the locals visible after a
                   6582: @code{BEGIN}; if it is too pessimistic, the
                   6583: user will get a spurious error about the local not being defined; if the
                   6584: compiler is too optimistic, it will notice this later and issue a
                   6585: warning. In the case above the compiler would complain about @code{x}
                   6586: being undefined at its use. You can see from the obscure examples in
                   6587: this section that it takes quite unusual control structures to get the
                   6588: compiler into trouble, and even then it will often do fine.
1.5       anton    6589: 
1.26      crook    6590: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   6591: is that all locals visible before the @code{BEGIN} will also be
                   6592: visible after the @code{BEGIN}. This guess is valid for all loops that
                   6593: are entered only through the @code{BEGIN}, in particular, for normal
                   6594: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   6595: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   6596: compiler. When the branch to the @code{BEGIN} is finally generated by
                   6597: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   6598: warns the user if it was too optimistic:
                   6599: @example
                   6600: IF
                   6601:   @{ x @}
                   6602: BEGIN
                   6603:   \ x ? 
                   6604: [ 1 cs-roll ] THEN
                   6605:   ...
                   6606: UNTIL
1.5       anton    6607: @end example
                   6608: 
1.26      crook    6609: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   6610: optimistically assumes that it lives until the @code{THEN}. It notices
                   6611: this difference when it compiles the @code{UNTIL} and issues a
                   6612: warning. The user can avoid the warning, and make sure that @code{x}
                   6613: is not used in the wrong area by using explicit scoping:
                   6614: @example
                   6615: IF
                   6616:   SCOPE
                   6617:   @{ x @}
                   6618:   ENDSCOPE
                   6619: BEGIN
                   6620: [ 1 cs-roll ] THEN
                   6621:   ...
                   6622: UNTIL
                   6623: @end example
1.5       anton    6624: 
1.26      crook    6625: Since the guess is optimistic, there will be no spurious error messages
                   6626: about undefined locals.
1.5       anton    6627: 
1.26      crook    6628: If the @code{BEGIN} is not reachable from above (e.g., after
                   6629: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   6630: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   6631: defined later. Therefore, the compiler assumes that no locals are
                   6632: visible after the @code{BEGIN}. However, the user can use
                   6633: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   6634: visible at the BEGIN as at the point where the top control-flow stack
                   6635: item was created.
1.5       anton    6636: 
1.26      crook    6637: doc-assume-live
1.5       anton    6638: 
1.26      crook    6639: E.g.,
1.5       anton    6640: @example
1.26      crook    6641: @{ x @}
                   6642: AHEAD
                   6643: ASSUME-LIVE
                   6644: BEGIN
                   6645:   x
                   6646: [ 1 CS-ROLL ] THEN
                   6647:   ...
                   6648: UNTIL
1.5       anton    6649: @end example
                   6650: 
1.26      crook    6651: Other cases where the locals are defined before the @code{BEGIN} can be
                   6652: handled by inserting an appropriate @code{CS-ROLL} before the
                   6653: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   6654: behind the @code{ASSUME-LIVE}).
1.5       anton    6655: 
1.26      crook    6656: Cases where locals are defined after the @code{BEGIN} (but should be
                   6657: visible immediately after the @code{BEGIN}) can only be handled by
                   6658: rearranging the loop. E.g., the ``most insidious'' example above can be
                   6659: arranged into:
1.5       anton    6660: @example
1.26      crook    6661: BEGIN
                   6662:   @{ x @}
                   6663:   ... 0=
                   6664: WHILE
                   6665:   x
                   6666: REPEAT
1.5       anton    6667: @end example
                   6668: 
1.26      crook    6669: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
                   6670: @subsubsection How long do locals live?
                   6671: @cindex locals lifetime
                   6672: @cindex lifetime of locals
1.5       anton    6673: 
1.26      crook    6674: The right answer for the lifetime question would be: A local lives at
                   6675: least as long as it can be accessed. For a value-flavoured local this
                   6676: means: until the end of its visibility. However, a variable-flavoured
                   6677: local could be accessed through its address far beyond its visibility
                   6678: scope. Ultimately, this would mean that such locals would have to be
                   6679: garbage collected. Since this entails un-Forth-like implementation
                   6680: complexities, I adopted the same cowardly solution as some other
                   6681: languages (e.g., C): The local lives only as long as it is visible;
                   6682: afterwards its address is invalid (and programs that access it
                   6683: afterwards are erroneous).
1.5       anton    6684: 
1.26      crook    6685: @node Programming Style, Implementation, How long do locals live?, Gforth locals
                   6686: @subsubsection Programming Style
                   6687: @cindex locals programming style
                   6688: @cindex programming style, locals
1.5       anton    6689: 
1.26      crook    6690: The freedom to define locals anywhere has the potential to change
                   6691: programming styles dramatically. In particular, the need to use the
                   6692: return stack for intermediate storage vanishes. Moreover, all stack
                   6693: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   6694: determined arguments) can be eliminated: If the stack items are in the
                   6695: wrong order, just write a locals definition for all of them; then
                   6696: write the items in the order you want.
1.5       anton    6697: 
1.26      crook    6698: This seems a little far-fetched and eliminating stack manipulations is
                   6699: unlikely to become a conscious programming objective. Still, the number
                   6700: of stack manipulations will be reduced dramatically if local variables
                   6701: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
                   6702: a traditional implementation of @code{max}).
1.5       anton    6703: 
1.26      crook    6704: This shows one potential benefit of locals: making Forth programs more
                   6705: readable. Of course, this benefit will only be realized if the
                   6706: programmers continue to honour the principle of factoring instead of
                   6707: using the added latitude to make the words longer.
1.5       anton    6708: 
1.26      crook    6709: @cindex single-assignment style for locals
                   6710: Using @code{TO} can and should be avoided.  Without @code{TO},
                   6711: every value-flavoured local has only a single assignment and many
                   6712: advantages of functional languages apply to Forth. I.e., programs are
                   6713: easier to analyse, to optimize and to read: It is clear from the
                   6714: definition what the local stands for, it does not turn into something
                   6715: different later.
1.5       anton    6716: 
1.26      crook    6717: E.g., a definition using @code{TO} might look like this:
1.5       anton    6718: @example
1.26      crook    6719: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   6720:  u1 u2 min 0
                   6721:  ?do
                   6722:    addr1 c@@ addr2 c@@ -
                   6723:    ?dup-if
                   6724:      unloop exit
                   6725:    then
                   6726:    addr1 char+ TO addr1
                   6727:    addr2 char+ TO addr2
                   6728:  loop
                   6729:  u1 u2 - ;
1.5       anton    6730: @end example
1.26      crook    6731: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   6732: every loop iteration. @code{strcmp} is a typical example of the
                   6733: readability problems of using @code{TO}. When you start reading
                   6734: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   6735: string. Only near the end of the loop you realize that it is something
                   6736: else.
1.5       anton    6737: 
1.26      crook    6738: This can be avoided by defining two locals at the start of the loop that
                   6739: are initialized with the right value for the current iteration.
1.5       anton    6740: @example
1.26      crook    6741: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   6742:  addr1 addr2
                   6743:  u1 u2 min 0 
                   6744:  ?do @{ s1 s2 @}
                   6745:    s1 c@@ s2 c@@ -
                   6746:    ?dup-if
                   6747:      unloop exit
                   6748:    then
                   6749:    s1 char+ s2 char+
                   6750:  loop
                   6751:  2drop
                   6752:  u1 u2 - ;
1.5       anton    6753: @end example
1.26      crook    6754: Here it is clear from the start that @code{s1} has a different value
                   6755: in every loop iteration.
1.5       anton    6756: 
1.26      crook    6757: @node Implementation,  , Programming Style, Gforth locals
                   6758: @subsubsection Implementation
                   6759: @cindex locals implementation
                   6760: @cindex implementation of locals
1.5       anton    6761: 
1.26      crook    6762: @cindex locals stack
                   6763: Gforth uses an extra locals stack. The most compelling reason for
                   6764: this is that the return stack is not float-aligned; using an extra stack
                   6765: also eliminates the problems and restrictions of using the return stack
                   6766: as locals stack. Like the other stacks, the locals stack grows toward
                   6767: lower addresses. A few primitives allow an efficient implementation:
1.5       anton    6768: 
1.26      crook    6769: doc-@local#
                   6770: doc-f@local#
                   6771: doc-laddr#
                   6772: doc-lp+!#
                   6773: doc-lp!
                   6774: doc->l
                   6775: doc-f>l
1.5       anton    6776: 
1.26      crook    6777: In addition to these primitives, some specializations of these
                   6778: primitives for commonly occurring inline arguments are provided for
                   6779: efficiency reasons, e.g., @code{@@local0} as specialization of
                   6780: @code{@@local#} for the inline argument 0. The following compiling words
                   6781: compile the right specialized version, or the general version, as
                   6782: appropriate:
1.6       pazsan   6783: 
1.26      crook    6784: doc-compile-@local
                   6785: doc-compile-f@local
                   6786: doc-compile-lp+!
1.12      anton    6787: 
1.26      crook    6788: Combinations of conditional branches and @code{lp+!#} like
                   6789: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   6790: is taken) are provided for efficiency and correctness in loops.
1.6       pazsan   6791: 
1.26      crook    6792: A special area in the dictionary space is reserved for keeping the
                   6793: local variable names. @code{@{} switches the dictionary pointer to this
                   6794: area and @code{@}} switches it back and generates the locals
                   6795: initializing code. @code{W:} etc.@ are normal defining words. This
                   6796: special area is cleared at the start of every colon definition.
1.6       pazsan   6797: 
1.26      crook    6798: @cindex word list for defining locals
                   6799: A special feature of Gforth's dictionary is used to implement the
                   6800: definition of locals without type specifiers: every word list (aka
                   6801: vocabulary) has its own methods for searching
                   6802: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   6803: with a special search method: When it is searched for a word, it
                   6804: actually creates that word using @code{W:}. @code{@{} changes the search
                   6805: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   6806: and then the word list for defining locals without type specifiers.
1.12      anton    6807: 
1.26      crook    6808: The lifetime rules support a stack discipline within a colon
                   6809: definition: The lifetime of a local is either nested with other locals
                   6810: lifetimes or it does not overlap them.
1.6       pazsan   6811: 
1.26      crook    6812: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   6813: pointer manipulation is generated. Between control structure words
                   6814: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   6815: is the simplest of the other three control flow words. It has to
                   6816: restore the locals stack depth of the corresponding @code{BEGIN}
                   6817: before branching. The code looks like this:
                   6818: @format
                   6819: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   6820: @code{branch} <begin>
                   6821: @end format
1.6       pazsan   6822: 
1.26      crook    6823: @code{UNTIL} is a little more complicated: If it branches back, it
                   6824: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   6825: the locals stack must not be changed. The compiler generates the
                   6826: following code:
                   6827: @format
                   6828: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   6829: @end format
                   6830: The locals stack pointer is only adjusted if the branch is taken.
1.6       pazsan   6831: 
1.26      crook    6832: @code{THEN} can produce somewhat inefficient code:
                   6833: @format
                   6834: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   6835: <orig target>:
                   6836: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   6837: @end format
                   6838: The second @code{lp+!#} adjusts the locals stack pointer from the
1.29      crook    6839: level at the @i{orig} point to the level after the @code{THEN}. The
1.26      crook    6840: first @code{lp+!#} adjusts the locals stack pointer from the current
                   6841: level to the level at the orig point, so the complete effect is an
                   6842: adjustment from the current level to the right level after the
                   6843: @code{THEN}.
1.6       pazsan   6844: 
1.26      crook    6845: @cindex locals information on the control-flow stack
                   6846: @cindex control-flow stack items, locals information
                   6847: In a conventional Forth implementation a dest control-flow stack entry
                   6848: is just the target address and an orig entry is just the address to be
                   6849: patched. Our locals implementation adds a word list to every orig or dest
                   6850: item. It is the list of locals visible (or assumed visible) at the point
                   6851: described by the entry. Our implementation also adds a tag to identify
                   6852: the kind of entry, in particular to differentiate between live and dead
                   6853: (reachable and unreachable) orig entries.
1.6       pazsan   6854: 
1.26      crook    6855: A few unusual operations have to be performed on locals word lists:
1.6       pazsan   6856: 
1.26      crook    6857: doc-common-list
                   6858: doc-sub-list?
                   6859: doc-list-size
1.6       pazsan   6860: 
1.26      crook    6861: Several features of our locals word list implementation make these
                   6862: operations easy to implement: The locals word lists are organised as
                   6863: linked lists; the tails of these lists are shared, if the lists
                   6864: contain some of the same locals; and the address of a name is greater
                   6865: than the address of the names behind it in the list.
1.6       pazsan   6866: 
1.26      crook    6867: Another important implementation detail is the variable
                   6868: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   6869: determine if they can be reached directly or only through the branch
                   6870: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   6871: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   6872: definition, by @code{BEGIN} and usually by @code{THEN}.
1.6       pazsan   6873: 
1.26      crook    6874: Counted loops are similar to other loops in most respects, but
                   6875: @code{LEAVE} requires special attention: It performs basically the same
                   6876: service as @code{AHEAD}, but it does not create a control-flow stack
                   6877: entry. Therefore the information has to be stored elsewhere;
                   6878: traditionally, the information was stored in the target fields of the
                   6879: branches created by the @code{LEAVE}s, by organizing these fields into a
                   6880: linked list. Unfortunately, this clever trick does not provide enough
                   6881: space for storing our extended control flow information. Therefore, we
                   6882: introduce another stack, the leave stack. It contains the control-flow
                   6883: stack entries for all unresolved @code{LEAVE}s.
1.6       pazsan   6884: 
1.26      crook    6885: Local names are kept until the end of the colon definition, even if
                   6886: they are no longer visible in any control-flow path. In a few cases
                   6887: this may lead to increased space needs for the locals name area, but
                   6888: usually less than reclaiming this space would cost in code size.
1.6       pazsan   6889: 
                   6890: 
1.26      crook    6891: @node ANS Forth locals,  , Gforth locals, Locals
                   6892: @subsection ANS Forth locals
                   6893: @cindex locals, ANS Forth style
1.6       pazsan   6894: 
1.26      crook    6895: The ANS Forth locals wordset does not define a syntax for locals, but
                   6896: words that make it possible to define various syntaxes. One of the
                   6897: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   6898: wordset, i.e.:
1.6       pazsan   6899: 
                   6900: @example
1.26      crook    6901: @{ local1 local2 ... -- comment @}
1.6       pazsan   6902: @end example
1.23      crook    6903: @noindent
1.26      crook    6904: or
1.6       pazsan   6905: @example
1.26      crook    6906: @{ local1 local2 ... @}
1.6       pazsan   6907: @end example
                   6908: 
1.26      crook    6909: The order of the locals corresponds to the order in a stack comment. The
                   6910: restrictions are:
1.6       pazsan   6911: 
                   6912: @itemize @bullet
                   6913: @item
1.26      crook    6914: Locals can only be cell-sized values (no type specifiers are allowed).
1.6       pazsan   6915: @item
1.26      crook    6916: Locals can be defined only outside control structures.
1.6       pazsan   6917: @item
1.26      crook    6918: Locals can interfere with explicit usage of the return stack. For the
                   6919: exact (and long) rules, see the standard. If you don't use return stack
                   6920: accessing words in a definition using locals, you will be all right. The
                   6921: purpose of this rule is to make locals implementation on the return
                   6922: stack easier.
1.6       pazsan   6923: @item
1.26      crook    6924: The whole definition must be in one line.
                   6925: @end itemize
1.6       pazsan   6926: 
1.26      crook    6927: Locals defined in this way behave like @code{VALUE}s (@xref{Simple
                   6928: Defining Words}). I.e., they are initialized from the stack. Using their
                   6929: name produces their value. Their value can be changed using @code{TO}.
1.6       pazsan   6930: 
1.26      crook    6931: Since this syntax is supported by Gforth directly, you need not do
                   6932: anything to use it. If you want to port a program using this syntax to
                   6933: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   6934: syntax on the other system.
1.6       pazsan   6935: 
1.26      crook    6936: Note that a syntax shown in the standard, section A.13 looks
                   6937: similar, but is quite different in having the order of locals
                   6938: reversed. Beware!
1.6       pazsan   6939: 
1.26      crook    6940: The ANS Forth locals wordset itself consists of a word:
1.6       pazsan   6941: 
1.26      crook    6942: doc-(local)
1.6       pazsan   6943: 
1.26      crook    6944: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
                   6945: awful that we strongly recommend not to use it. We have implemented this
                   6946: syntax to make porting to Gforth easy, but do not document it here. The
                   6947: problem with this syntax is that the locals are defined in an order
                   6948: reversed with respect to the standard stack comment notation, making
                   6949: programs harder to read, and easier to misread and miswrite. The only
                   6950: merit of this syntax is that it is easy to implement using the ANS Forth
                   6951: locals wordset.
1.7       pazsan   6952: 
                   6953: 
1.26      crook    6954: @c ----------------------------------------------------------
                   6955: @node Structures, Object-oriented Forth, Locals, Words
                   6956: @section  Structures
                   6957: @cindex structures
                   6958: @cindex records
1.7       pazsan   6959: 
1.26      crook    6960: This section presents the structure package that comes with Gforth. A
                   6961: version of the package implemented in ANS Forth is available in
                   6962: @file{compat/struct.fs}. This package was inspired by a posting on
                   6963: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   6964: possibly John Hayes). A version of this section has been published in
                   6965: ???. Marcel Hendrix provided helpful comments.
1.7       pazsan   6966: 
1.26      crook    6967: @menu
                   6968: * Why explicit structure support?::  
                   6969: * Structure Usage::             
                   6970: * Structure Naming Convention::  
                   6971: * Structure Implementation::    
                   6972: * Structure Glossary::          
                   6973: @end menu
1.7       pazsan   6974: 
1.26      crook    6975: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   6976: @subsection Why explicit structure support?
1.7       pazsan   6977: 
1.26      crook    6978: @cindex address arithmetic for structures
                   6979: @cindex structures using address arithmetic
                   6980: If we want to use a structure containing several fields, we could simply
                   6981: reserve memory for it, and access the fields using address arithmetic
1.27      crook    6982: (@pxref{Address Arithmetic}). As an example, consider a structure with
1.26      crook    6983: the following fields
1.7       pazsan   6984: 
1.26      crook    6985: @table @code
                   6986: @item a
                   6987: is a float
                   6988: @item b
                   6989: is a cell
                   6990: @item c
                   6991: is a float
                   6992: @end table
1.7       pazsan   6993: 
1.26      crook    6994: Given the (float-aligned) base address of the structure we get the
                   6995: address of the field
1.13      pazsan   6996: 
1.26      crook    6997: @table @code
                   6998: @item a
                   6999: without doing anything further.
                   7000: @item b
                   7001: with @code{float+}
                   7002: @item c
                   7003: with @code{float+ cell+ faligned}
                   7004: @end table
1.13      pazsan   7005: 
1.26      crook    7006: It is easy to see that this can become quite tiring. 
1.13      pazsan   7007: 
1.26      crook    7008: Moreover, it is not very readable, because seeing a
                   7009: @code{cell+} tells us neither which kind of structure is
                   7010: accessed nor what field is accessed; we have to somehow infer the kind
                   7011: of structure, and then look up in the documentation, which field of
                   7012: that structure corresponds to that offset.
1.13      pazsan   7013: 
1.26      crook    7014: Finally, this kind of address arithmetic also causes maintenance
                   7015: troubles: If you add or delete a field somewhere in the middle of the
                   7016: structure, you have to find and change all computations for the fields
                   7017: afterwards.
1.13      pazsan   7018: 
1.26      crook    7019: So, instead of using @code{cell+} and friends directly, how
                   7020: about storing the offsets in constants:
1.13      pazsan   7021: 
                   7022: @example
1.26      crook    7023: 0 constant a-offset
                   7024: 0 float+ constant b-offset
                   7025: 0 float+ cell+ faligned c-offset
1.13      pazsan   7026: @end example
                   7027: 
1.26      crook    7028: Now we can get the address of field @code{x} with @code{x-offset
                   7029: +}. This is much better in all respects. Of course, you still
                   7030: have to change all later offset definitions if you add a field. You can
                   7031: fix this by declaring the offsets in the following way:
1.13      pazsan   7032: 
                   7033: @example
1.26      crook    7034: 0 constant a-offset
                   7035: a-offset float+ constant b-offset
                   7036: b-offset cell+ faligned constant c-offset
1.13      pazsan   7037: @end example
                   7038: 
1.26      crook    7039: Since we always use the offsets with @code{+}, we could use a defining
                   7040: word @code{cfield} that includes the @code{+} in the action of the
                   7041: defined word:
1.8       pazsan   7042: 
                   7043: @example
1.26      crook    7044: : cfield ( n "name" -- )
                   7045:     create ,
                   7046: does> ( name execution: addr1 -- addr2 )
                   7047:     @@ + ;
1.13      pazsan   7048: 
1.26      crook    7049: 0 cfield a
                   7050: 0 a float+ cfield b
                   7051: 0 b cell+ faligned cfield c
1.13      pazsan   7052: @end example
                   7053: 
1.26      crook    7054: Instead of @code{x-offset +}, we now simply write @code{x}.
                   7055: 
                   7056: The structure field words now can be used quite nicely. However,
                   7057: their definition is still a bit cumbersome: We have to repeat the
                   7058: name, the information about size and alignment is distributed before
                   7059: and after the field definitions etc.  The structure package presented
                   7060: here addresses these problems.
                   7061: 
                   7062: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   7063: @subsection Structure Usage
                   7064: @cindex structure usage
1.13      pazsan   7065: 
1.26      crook    7066: @cindex @code{field} usage
                   7067: @cindex @code{struct} usage
                   7068: @cindex @code{end-struct} usage
                   7069: You can define a structure for a (data-less) linked list with:
1.13      pazsan   7070: @example
1.26      crook    7071: struct
                   7072:     cell% field list-next
                   7073: end-struct list%
1.13      pazsan   7074: @end example
                   7075: 
1.26      crook    7076: With the address of the list node on the stack, you can compute the
                   7077: address of the field that contains the address of the next node with
                   7078: @code{list-next}. E.g., you can determine the length of a list
                   7079: with:
1.13      pazsan   7080: 
                   7081: @example
1.26      crook    7082: : list-length ( list -- n )
                   7083: \ "list" is a pointer to the first element of a linked list
                   7084: \ "n" is the length of the list
                   7085:     0 BEGIN ( list1 n1 )
                   7086:         over
                   7087:     WHILE ( list1 n1 )
                   7088:         1+ swap list-next @@ swap
                   7089:     REPEAT
                   7090:     nip ;
1.13      pazsan   7091: @end example
                   7092: 
1.26      crook    7093: You can reserve memory for a list node in the dictionary with
                   7094: @code{list% %allot}, which leaves the address of the list node on the
                   7095: stack. For the equivalent allocation on the heap you can use @code{list%
                   7096: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   7097: use @code{list% %allocate}). You can get the the size of a list
                   7098: node with @code{list% %size} and its alignment with @code{list%
                   7099: %alignment}.
1.13      pazsan   7100: 
1.26      crook    7101: Note that in ANS Forth the body of a @code{create}d word is
                   7102: @code{aligned} but not necessarily @code{faligned};
                   7103: therefore, if you do a:
1.13      pazsan   7104: @example
1.26      crook    7105: create @emph{name} foo% %allot
1.8       pazsan   7106: @end example
                   7107: 
1.26      crook    7108: @noindent
                   7109: then the memory alloted for @code{foo%} is
                   7110: guaranteed to start at the body of @code{@emph{name}} only if
                   7111: @code{foo%} contains only character, cell and double fields.
1.20      pazsan   7112: 
1.26      crook    7113: @cindex strcutures containing structures
                   7114: You can include a structure @code{foo%} as a field of
                   7115: another structure, like this:
1.20      pazsan   7116: @example
1.26      crook    7117: struct
                   7118: ...
                   7119:     foo% field ...
                   7120: ...
                   7121: end-struct ...
1.20      pazsan   7122: @end example
                   7123: 
1.26      crook    7124: @cindex structure extension
                   7125: @cindex extended records
                   7126: Instead of starting with an empty structure, you can extend an
                   7127: existing structure. E.g., a plain linked list without data, as defined
                   7128: above, is hardly useful; You can extend it to a linked list of integers,
                   7129: like this:@footnote{This feature is also known as @emph{extended
                   7130: records}. It is the main innovation in the Oberon language; in other
                   7131: words, adding this feature to Modula-2 led Wirth to create a new
                   7132: language, write a new compiler etc.  Adding this feature to Forth just
                   7133: required a few lines of code.}
1.20      pazsan   7134: 
                   7135: @example
1.26      crook    7136: list%
                   7137:     cell% field intlist-int
                   7138: end-struct intlist%
1.20      pazsan   7139: @end example
                   7140: 
1.26      crook    7141: @code{intlist%} is a structure with two fields:
                   7142: @code{list-next} and @code{intlist-int}.
1.20      pazsan   7143: 
1.26      crook    7144: @cindex structures containing arrays
                   7145: You can specify an array type containing @emph{n} elements of
                   7146: type @code{foo%} like this:
1.20      pazsan   7147: 
                   7148: @example
1.26      crook    7149: foo% @emph{n} *
1.20      pazsan   7150: @end example
                   7151: 
1.26      crook    7152: You can use this array type in any place where you can use a normal
                   7153: type, e.g., when defining a @code{field}, or with
                   7154: @code{%allot}.
1.20      pazsan   7155: 
1.26      crook    7156: @cindex first field optimization
                   7157: The first field is at the base address of a structure and the word
                   7158: for this field (e.g., @code{list-next}) actually does not change
                   7159: the address on the stack. You may be tempted to leave it away in the
                   7160: interest of run-time and space efficiency. This is not necessary,
                   7161: because the structure package optimizes this case and compiling such
                   7162: words does not generate any code. So, in the interest of readability
                   7163: and maintainability you should include the word for the field when
                   7164: accessing the field.
1.20      pazsan   7165: 
1.26      crook    7166: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   7167: @subsection Structure Naming Convention
                   7168: @cindex structure naming convention
1.20      pazsan   7169: 
1.26      crook    7170: The field names that come to (my) mind are often quite generic, and,
                   7171: if used, would cause frequent name clashes. E.g., many structures
                   7172: probably contain a @code{counter} field. The structure names
                   7173: that come to (my) mind are often also the logical choice for the names
                   7174: of words that create such a structure.
1.20      pazsan   7175: 
1.26      crook    7176: Therefore, I have adopted the following naming conventions: 
1.20      pazsan   7177: 
1.26      crook    7178: @itemize @bullet
                   7179: @cindex field naming convention
                   7180: @item
                   7181: The names of fields are of the form
                   7182: @code{@emph{struct}-@emph{field}}, where
                   7183: @code{@emph{struct}} is the basic name of the structure, and
                   7184: @code{@emph{field}} is the basic name of the field. You can
                   7185: think of field words as converting the (address of the)
                   7186: structure into the (address of the) field.
1.20      pazsan   7187: 
1.26      crook    7188: @cindex structure naming convention
                   7189: @item
                   7190: The names of structures are of the form
                   7191: @code{@emph{struct}%}, where
                   7192: @code{@emph{struct}} is the basic name of the structure.
                   7193: @end itemize
1.20      pazsan   7194: 
1.26      crook    7195: This naming convention does not work that well for fields of extended
                   7196: structures; e.g., the integer list structure has a field
                   7197: @code{intlist-int}, but has @code{list-next}, not
                   7198: @code{intlist-next}.
1.20      pazsan   7199: 
1.26      crook    7200: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   7201: @subsection Structure Implementation
                   7202: @cindex structure implementation
                   7203: @cindex implementation of structures
1.20      pazsan   7204: 
1.26      crook    7205: The central idea in the implementation is to pass the data about the
                   7206: structure being built on the stack, not in some global
                   7207: variable. Everything else falls into place naturally once this design
                   7208: decision is made.
1.20      pazsan   7209: 
1.26      crook    7210: The type description on the stack is of the form @emph{align
                   7211: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   7212: very simple.
1.20      pazsan   7213: 
1.26      crook    7214: @code{field} is a defining word that uses @code{Create}
                   7215: and @code{DOES>}. The body of the field contains the offset
                   7216: of the field, and the normal @code{DOES>} action is simply:
1.20      pazsan   7217: 
                   7218: @example
1.26      crook    7219: @ +
1.20      pazsan   7220: @end example
                   7221: 
1.23      crook    7222: @noindent
1.26      crook    7223: i.e., add the offset to the address, giving the stack effect
1.29      crook    7224: @i{addr1 -- addr2} for a field.
1.20      pazsan   7225: 
1.26      crook    7226: @cindex first field optimization, implementation
                   7227: This simple structure is slightly complicated by the optimization
                   7228: for fields with offset 0, which requires a different
                   7229: @code{DOES>}-part (because we cannot rely on there being
                   7230: something on the stack if such a field is invoked during
                   7231: compilation). Therefore, we put the different @code{DOES>}-parts
                   7232: in separate words, and decide which one to invoke based on the
                   7233: offset. For a zero offset, the field is basically a noop; it is
                   7234: immediate, and therefore no code is generated when it is compiled.
1.20      pazsan   7235: 
1.26      crook    7236: @node Structure Glossary,  , Structure Implementation, Structures
                   7237: @subsection Structure Glossary
                   7238: @cindex structure glossary
1.20      pazsan   7239: 
1.26      crook    7240: doc-%align
                   7241: doc-%alignment
                   7242: doc-%alloc
                   7243: doc-%allocate
                   7244: doc-%allot
                   7245: doc-cell%
                   7246: doc-char%
                   7247: doc-dfloat%
                   7248: doc-double%
                   7249: doc-end-struct
                   7250: doc-field
                   7251: doc-float%
                   7252: doc-naligned
                   7253: doc-sfloat%
                   7254: doc-%size
                   7255: doc-struct
1.23      crook    7256: 
1.26      crook    7257: @c -------------------------------------------------------------
                   7258: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
                   7259: @section Object-oriented Forth
1.20      pazsan   7260: 
1.26      crook    7261: Gforth comes with three packages for object-oriented programming:
                   7262: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   7263: is preloaded, so you have to @code{include} them before use. The most
                   7264: important differences between these packages (and others) are discussed
                   7265: in @ref{Comparison with other object models}. All packages are written
                   7266: in ANS Forth and can be used with any other ANS Forth.
1.20      pazsan   7267: 
1.26      crook    7268: @menu
                   7269: * Why object-oriented programming?::
                   7270: * Object-Oriented Terminology::
                   7271: * Objects::
                   7272: * OOF::
                   7273: * Mini-OOF::
                   7274: * Comparison with other object models::  
                   7275: @end menu
1.20      pazsan   7276: 
1.23      crook    7277: 
1.26      crook    7278: @node Why object-oriented programming?, Object-Oriented Terminology, , Object-oriented Forth
                   7279: @subsubsection Why object-oriented programming?
                   7280: @cindex object-oriented programming motivation
                   7281: @cindex motivation for object-oriented programming
1.23      crook    7282: 
1.26      crook    7283: Often we have to deal with several data structures (@emph{objects}),
                   7284: that have to be treated similarly in some respects, but differently in
                   7285: others. Graphical objects are the textbook example: circles, triangles,
                   7286: dinosaurs, icons, and others, and we may want to add more during program
                   7287: development. We want to apply some operations to any graphical object,
                   7288: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   7289: has to do something different for every kind of object.
                   7290: @comment TODO add some other operations eg perimeter, area
                   7291: @comment and tie in to concrete examples later..
1.23      crook    7292: 
1.26      crook    7293: We could implement @code{draw} as a big @code{CASE}
                   7294: control structure that executes the appropriate code depending on the
                   7295: kind of object to be drawn. This would be not be very elegant, and,
                   7296: moreover, we would have to change @code{draw} every time we add
                   7297: a new kind of graphical object (say, a spaceship).
1.23      crook    7298: 
1.26      crook    7299: What we would rather do is: When defining spaceships, we would tell
                   7300: the system: ``Here's how you @code{draw} a spaceship; you figure
                   7301: out the rest''.
1.23      crook    7302: 
1.26      crook    7303: This is the problem that all systems solve that (rightfully) call
                   7304: themselves object-oriented; the object-oriented packages presented here
                   7305: solve this problem (and not much else).
                   7306: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.23      crook    7307: 
1.26      crook    7308: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
                   7309: @subsubsection Object-Oriented Terminology
                   7310: @cindex object-oriented terminology
                   7311: @cindex terminology for object-oriented programming
1.23      crook    7312: 
1.26      crook    7313: This section is mainly for reference, so you don't have to understand
                   7314: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   7315: short:
1.23      crook    7316: 
1.26      crook    7317: @table @emph
                   7318: @cindex class
                   7319: @item class
                   7320: a data structure definition with some extras.
1.23      crook    7321: 
1.26      crook    7322: @cindex object
                   7323: @item object
                   7324: an instance of the data structure described by the class definition.
1.23      crook    7325: 
1.26      crook    7326: @cindex instance variables
                   7327: @item instance variables
                   7328: fields of the data structure.
1.23      crook    7329: 
1.26      crook    7330: @cindex selector
                   7331: @cindex method selector
                   7332: @cindex virtual function
                   7333: @item selector
                   7334: (or @emph{method selector}) a word (e.g.,
                   7335: @code{draw}) that performs an operation on a variety of data
                   7336: structures (classes). A selector describes @emph{what} operation to
                   7337: perform. In C++ terminology: a (pure) virtual function.
1.23      crook    7338: 
1.26      crook    7339: @cindex method
                   7340: @item method
                   7341: the concrete definition that performs the operation
                   7342: described by the selector for a specific class. A method specifies
                   7343: @emph{how} the operation is performed for a specific class.
1.23      crook    7344: 
1.26      crook    7345: @cindex selector invocation
                   7346: @cindex message send
                   7347: @cindex invoking a selector
                   7348: @item selector invocation
                   7349: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   7350: is used for determining which method is used. In Smalltalk terminology:
                   7351: a message (consisting of the selector and the other arguments) is sent
                   7352: to the object.
1.1       anton    7353: 
1.26      crook    7354: @cindex receiving object
                   7355: @item receiving object
                   7356: the object used for determining the method executed by a selector
                   7357: invocation. In the @file{objects.fs} model, it is the object that is on
                   7358: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   7359: the Smalltalk @emph{message} terminology.)
1.1       anton    7360: 
1.26      crook    7361: @cindex child class
                   7362: @cindex parent class
                   7363: @cindex inheritance
                   7364: @item child class
                   7365: a class that has (@emph{inherits}) all properties (instance variables,
                   7366: selectors, methods) from a @emph{parent class}. In Smalltalk
                   7367: terminology: The subclass inherits from the superclass. In C++
                   7368: terminology: The derived class inherits from the base class.
1.1       anton    7369: 
1.26      crook    7370: @end table
1.21      crook    7371: 
1.26      crook    7372: @c If you wonder about the message sending terminology, it comes from
                   7373: @c a time when each object had it's own task and objects communicated via
                   7374: @c message passing; eventually the Smalltalk developers realized that
                   7375: @c they can do most things through simple (indirect) calls. They kept the
                   7376: @c terminology.
1.1       anton    7377: 
                   7378: 
1.26      crook    7379: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   7380: @subsection The @file{objects.fs} model
                   7381: @cindex objects
                   7382: @cindex object-oriented programming
1.1       anton    7383: 
1.26      crook    7384: @cindex @file{objects.fs}
                   7385: @cindex @file{oof.fs}
1.1       anton    7386: 
1.26      crook    7387: This section describes the @file{objects.fs} package. 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}).
                   7388: @c McKewan's and Zsoter's packages
1.1       anton    7389: 
1.26      crook    7390: This section assumes that you have read @ref{Structures}.
1.1       anton    7391: 
1.26      crook    7392: The techniques on which this model is based have been used to implement
                   7393: the parser generator, Gray, and have also been used in Gforth for
                   7394: implementing the various flavours of word lists (hashed or not,
                   7395: case-sensitive or not, special-purpose word lists for locals etc.).
1.1       anton    7396: 
                   7397: 
1.26      crook    7398: @menu
                   7399: * Properties of the Objects model::  
                   7400: * Basic Objects Usage::         
                   7401: * The Objects base class::            
                   7402: * Creating objects::            
                   7403: * Object-Oriented Programming Style::  
                   7404: * Class Binding::               
                   7405: * Method conveniences::         
                   7406: * Classes and Scoping::         
                   7407: * Object Interfaces::           
                   7408: * Objects Implementation::      
                   7409: * Objects Glossary::            
                   7410: @end menu
1.1       anton    7411: 
1.26      crook    7412: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
                   7413: and Bernd Paysan helped me with the related works section.
1.1       anton    7414: 
1.26      crook    7415: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   7416: @subsubsection Properties of the @file{objects.fs} model
                   7417: @cindex @file{objects.fs} properties
1.1       anton    7418: 
1.26      crook    7419: @itemize @bullet
                   7420: @item
                   7421: It is straightforward to pass objects on the stack. Passing
                   7422: selectors on the stack is a little less convenient, but possible.
1.1       anton    7423: 
1.26      crook    7424: @item
                   7425: Objects are just data structures in memory, and are referenced by their
                   7426: address. You can create words for objects with normal defining words
                   7427: like @code{constant}. Likewise, there is no difference between instance
                   7428: variables that contain objects and those that contain other data.
1.1       anton    7429: 
1.26      crook    7430: @item
                   7431: Late binding is efficient and easy to use.
1.21      crook    7432: 
1.26      crook    7433: @item
                   7434: It avoids parsing, and thus avoids problems with state-smartness
                   7435: and reduced extensibility; for convenience there are a few parsing
                   7436: words, but they have non-parsing counterparts. There are also a few
                   7437: defining words that parse. This is hard to avoid, because all standard
                   7438: defining words parse (except @code{:noname}); however, such
                   7439: words are not as bad as many other parsing words, because they are not
                   7440: state-smart.
1.21      crook    7441: 
1.26      crook    7442: @item
                   7443: It does not try to incorporate everything. It does a few things and does
                   7444: them well (IMO). In particular, this model was not designed to support
                   7445: information hiding (although it has features that may help); you can use
                   7446: a separate package for achieving this.
1.21      crook    7447: 
1.26      crook    7448: @item
                   7449: It is layered; you don't have to learn and use all features to use this
                   7450: model. Only a few features are necessary (@xref{Basic Objects Usage},
                   7451: @xref{The Objects base class}, @xref{Creating objects}.), the others
                   7452: are optional and independent of each other.
1.21      crook    7453: 
1.26      crook    7454: @item
                   7455: An implementation in ANS Forth is available.
1.21      crook    7456: 
1.26      crook    7457: @end itemize
1.21      crook    7458: 
                   7459: 
1.26      crook    7460: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   7461: @subsubsection Basic @file{objects.fs} Usage
                   7462: @cindex basic objects usage
                   7463: @cindex objects, basic usage
1.21      crook    7464: 
1.26      crook    7465: You can define a class for graphical objects like this:
1.21      crook    7466: 
1.26      crook    7467: @cindex @code{class} usage
                   7468: @cindex @code{end-class} usage
                   7469: @cindex @code{selector} usage
                   7470: @example
                   7471: object class \ "object" is the parent class
                   7472:   selector draw ( x y graphical -- )
                   7473: end-class graphical
                   7474: @end example
1.21      crook    7475: 
1.26      crook    7476: This code defines a class @code{graphical} with an
                   7477: operation @code{draw}.  We can perform the operation
                   7478: @code{draw} on any @code{graphical} object, e.g.:
1.21      crook    7479: 
1.26      crook    7480: @example
                   7481: 100 100 t-rex draw
                   7482: @end example
1.21      crook    7483: 
1.26      crook    7484: @noindent
                   7485: where @code{t-rex} is a word (say, a constant) that produces a
                   7486: graphical object.
1.21      crook    7487: 
1.29      crook    7488: @comment TODO add a 2nd operation eg perimeter.. and use for
1.26      crook    7489: @comment a concrete example
1.21      crook    7490: 
1.26      crook    7491: @cindex abstract class
                   7492: How do we create a graphical object? With the present definitions,
                   7493: we cannot create a useful graphical object. The class
                   7494: @code{graphical} describes graphical objects in general, but not
                   7495: any concrete graphical object type (C++ users would call it an
                   7496: @emph{abstract class}); e.g., there is no method for the selector
                   7497: @code{draw} in the class @code{graphical}.
1.21      crook    7498: 
1.26      crook    7499: For concrete graphical objects, we define child classes of the
                   7500: class @code{graphical}, e.g.:
1.21      crook    7501: 
1.26      crook    7502: @cindex @code{overrides} usage
                   7503: @cindex @code{field} usage in class definition
                   7504: @example
                   7505: graphical class \ "graphical" is the parent class
                   7506:   cell% field circle-radius
1.21      crook    7507: 
1.26      crook    7508: :noname ( x y circle -- )
                   7509:   circle-radius @@ draw-circle ;
                   7510: overrides draw
1.21      crook    7511: 
1.26      crook    7512: :noname ( n-radius circle -- )
                   7513:   circle-radius ! ;
                   7514: overrides construct
1.21      crook    7515: 
1.26      crook    7516: end-class circle
1.21      crook    7517: @end example
                   7518: 
1.26      crook    7519: Here we define a class @code{circle} as a child of @code{graphical},
                   7520: with field @code{circle-radius} (which behaves just like a field
                   7521: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   7522: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   7523: defined in @code{object}, the parent class of @code{graphical}).
1.21      crook    7524: 
1.26      crook    7525: Now we can create a circle on the heap (i.e.,
                   7526: @code{allocate}d memory) with:
1.21      crook    7527: 
1.26      crook    7528: @cindex @code{heap-new} usage
1.21      crook    7529: @example
1.26      crook    7530: 50 circle heap-new constant my-circle
                   7531: @end example
1.21      crook    7532: 
1.26      crook    7533: @noindent
                   7534: @code{heap-new} invokes @code{construct}, thus
                   7535: initializing the field @code{circle-radius} with 50. We can draw
                   7536: this new circle at (100,100) with:
1.21      crook    7537: 
1.26      crook    7538: @example
                   7539: 100 100 my-circle draw
1.21      crook    7540: @end example
                   7541: 
1.26      crook    7542: @cindex selector invocation, restrictions
                   7543: @cindex class definition, restrictions
                   7544: Note: You can only invoke a selector if the object on the TOS
                   7545: (the receiving object) belongs to the class where the selector was
                   7546: defined or one of its descendents; e.g., you can invoke
                   7547: @code{draw} only for objects belonging to @code{graphical}
                   7548: or its descendents (e.g., @code{circle}).  Immediately before
                   7549: @code{end-class}, the search order has to be the same as
                   7550: immediately after @code{class}.
1.21      crook    7551: 
1.26      crook    7552: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   7553: @subsubsection The @file{object.fs} base class
                   7554: @cindex @code{object} class
1.21      crook    7555: 
1.26      crook    7556: When you define a class, you have to specify a parent class.  So how do
                   7557: you start defining classes? There is one class available from the start:
                   7558: @code{object}. It is ancestor for all classes and so is the
                   7559: only class that has no parent. It has two selectors: @code{construct}
                   7560: and @code{print}.
1.21      crook    7561: 
1.26      crook    7562: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   7563: @subsubsection Creating objects
                   7564: @cindex creating objects
                   7565: @cindex object creation
                   7566: @cindex object allocation options
1.21      crook    7567: 
1.26      crook    7568: @cindex @code{heap-new} discussion
                   7569: @cindex @code{dict-new} discussion
                   7570: @cindex @code{construct} discussion
                   7571: You can create and initialize an object of a class on the heap with
                   7572: @code{heap-new} ( ... class -- object ) and in the dictionary
                   7573: (allocation with @code{allot}) with @code{dict-new} (
                   7574: ... class -- object ). Both words invoke @code{construct}, which
                   7575: consumes the stack items indicated by "..." above.
1.21      crook    7576: 
1.26      crook    7577: @cindex @code{init-object} discussion
                   7578: @cindex @code{class-inst-size} discussion
                   7579: If you want to allocate memory for an object yourself, you can get its
                   7580: alignment and size with @code{class-inst-size 2@@} ( class --
                   7581: align size ). Once you have memory for an object, you can initialize
                   7582: it with @code{init-object} ( ... class object -- );
                   7583: @code{construct} does only a part of the necessary work.
1.21      crook    7584: 
1.26      crook    7585: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   7586: @subsubsection Object-Oriented Programming Style
                   7587: @cindex object-oriented programming style
1.21      crook    7588: 
1.26      crook    7589: This section is not exhaustive.
1.1       anton    7590: 
1.26      crook    7591: @cindex stack effects of selectors
                   7592: @cindex selectors and stack effects
                   7593: In general, it is a good idea to ensure that all methods for the
                   7594: same selector have the same stack effect: when you invoke a selector,
                   7595: you often have no idea which method will be invoked, so, unless all
                   7596: methods have the same stack effect, you will not know the stack effect
                   7597: of the selector invocation.
1.21      crook    7598: 
1.26      crook    7599: One exception to this rule is methods for the selector
                   7600: @code{construct}. We know which method is invoked, because we
                   7601: specify the class to be constructed at the same place. Actually, I
                   7602: defined @code{construct} as a selector only to give the users a
                   7603: convenient way to specify initialization. The way it is used, a
                   7604: mechanism different from selector invocation would be more natural
                   7605: (but probably would take more code and more space to explain).
1.21      crook    7606: 
1.26      crook    7607: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   7608: @subsubsection Class Binding
                   7609: @cindex class binding
                   7610: @cindex early binding
1.21      crook    7611: 
1.26      crook    7612: @cindex late binding
                   7613: Normal selector invocations determine the method at run-time depending
                   7614: on the class of the receiving object. This run-time selection is called
1.29      crook    7615: @i{late binding}.
1.21      crook    7616: 
1.26      crook    7617: Sometimes it's preferable to invoke a different method. For example,
                   7618: you might want to use the simple method for @code{print}ing
                   7619: @code{object}s instead of the possibly long-winded @code{print} method
                   7620: of the receiver class. You can achieve this by replacing the invocation
                   7621: of @code{print} with:
1.21      crook    7622: 
1.26      crook    7623: @cindex @code{[bind]} usage
                   7624: @example
                   7625: [bind] object print
1.21      crook    7626: @end example
                   7627: 
1.26      crook    7628: @noindent
                   7629: in compiled code or:
1.21      crook    7630: 
1.26      crook    7631: @cindex @code{bind} usage
1.21      crook    7632: @example
1.26      crook    7633: bind object print
1.21      crook    7634: @end example
                   7635: 
1.26      crook    7636: @cindex class binding, alternative to
                   7637: @noindent
                   7638: in interpreted code. Alternatively, you can define the method with a
                   7639: name (e.g., @code{print-object}), and then invoke it through the
                   7640: name. Class binding is just a (often more convenient) way to achieve
                   7641: the same effect; it avoids name clutter and allows you to invoke
                   7642: methods directly without naming them first.
                   7643: 
                   7644: @cindex superclass binding
                   7645: @cindex parent class binding
                   7646: A frequent use of class binding is this: When we define a method
                   7647: for a selector, we often want the method to do what the selector does
                   7648: in the parent class, and a little more. There is a special word for
                   7649: this purpose: @code{[parent]}; @code{[parent]
                   7650: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   7651: selector}}, where @code{@emph{parent}} is the parent
                   7652: class of the current class. E.g., a method definition might look like:
1.21      crook    7653: 
1.26      crook    7654: @cindex @code{[parent]} usage
1.21      crook    7655: @example
1.26      crook    7656: :noname
                   7657:   dup [parent] foo \ do parent's foo on the receiving object
                   7658:   ... \ do some more
                   7659: ; overrides foo
1.21      crook    7660: @end example
                   7661: 
1.26      crook    7662: @cindex class binding as optimization
                   7663: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   7664: March 1997), Andrew McKewan presents class binding as an optimization
                   7665: technique. I recommend not using it for this purpose unless you are in
                   7666: an emergency. Late binding is pretty fast with this model anyway, so the
                   7667: benefit of using class binding is small; the cost of using class binding
                   7668: where it is not appropriate is reduced maintainability.
1.21      crook    7669: 
1.26      crook    7670: While we are at programming style questions: You should bind
                   7671: selectors only to ancestor classes of the receiving object. E.g., say,
                   7672: you know that the receiving object is of class @code{foo} or its
                   7673: descendents; then you should bind only to @code{foo} and its
                   7674: ancestors.
1.21      crook    7675: 
1.26      crook    7676: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   7677: @subsubsection Method conveniences
                   7678: @cindex method conveniences
1.1       anton    7679: 
1.26      crook    7680: In a method you usually access the receiving object pretty often.  If
                   7681: you define the method as a plain colon definition (e.g., with
                   7682: @code{:noname}), you may have to do a lot of stack
                   7683: gymnastics. To avoid this, you can define the method with @code{m:
                   7684: ... ;m}. E.g., you could define the method for
                   7685: @code{draw}ing a @code{circle} with
1.20      pazsan   7686: 
1.26      crook    7687: @cindex @code{this} usage
                   7688: @cindex @code{m:} usage
                   7689: @cindex @code{;m} usage
                   7690: @example
                   7691: m: ( x y circle -- )
                   7692:   ( x y ) this circle-radius @@ draw-circle ;m
                   7693: @end example
1.20      pazsan   7694: 
1.26      crook    7695: @cindex @code{exit} in @code{m: ... ;m}
                   7696: @cindex @code{exitm} discussion
                   7697: @cindex @code{catch} in @code{m: ... ;m}
                   7698: When this method is executed, the receiver object is removed from the
                   7699: stack; you can access it with @code{this} (admittedly, in this
                   7700: example the use of @code{m: ... ;m} offers no advantage). Note
                   7701: that I specify the stack effect for the whole method (i.e. including
                   7702: the receiver object), not just for the code between @code{m:}
                   7703: and @code{;m}. You cannot use @code{exit} in
                   7704: @code{m:...;m}; instead, use
                   7705: @code{exitm}.@footnote{Moreover, for any word that calls
                   7706: @code{catch} and was defined before loading
                   7707: @code{objects.fs}, you have to redefine it like I redefined
                   7708: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.20      pazsan   7709: 
1.26      crook    7710: @cindex @code{inst-var} usage
                   7711: You will frequently use sequences of the form @code{this
                   7712: @emph{field}} (in the example above: @code{this
                   7713: circle-radius}). If you use the field only in this way, you can
                   7714: define it with @code{inst-var} and eliminate the
                   7715: @code{this} before the field name. E.g., the @code{circle}
                   7716: class above could also be defined with:
1.20      pazsan   7717: 
1.26      crook    7718: @example
                   7719: graphical class
                   7720:   cell% inst-var radius
1.20      pazsan   7721: 
1.26      crook    7722: m: ( x y circle -- )
                   7723:   radius @@ draw-circle ;m
                   7724: overrides draw
1.20      pazsan   7725: 
1.26      crook    7726: m: ( n-radius circle -- )
                   7727:   radius ! ;m
                   7728: overrides construct
1.12      anton    7729: 
1.26      crook    7730: end-class circle
                   7731: @end example
1.12      anton    7732: 
1.26      crook    7733: @code{radius} can only be used in @code{circle} and its
                   7734: descendent classes and inside @code{m:...;m}.
1.12      anton    7735: 
1.26      crook    7736: @cindex @code{inst-value} usage
                   7737: You can also define fields with @code{inst-value}, which is
                   7738: to @code{inst-var} what @code{value} is to
                   7739: @code{variable}.  You can change the value of such a field with
                   7740: @code{[to-inst]}.  E.g., we could also define the class
                   7741: @code{circle} like this:
1.12      anton    7742: 
1.26      crook    7743: @example
                   7744: graphical class
                   7745:   inst-value radius
1.12      anton    7746: 
1.26      crook    7747: m: ( x y circle -- )
                   7748:   radius draw-circle ;m
                   7749: overrides draw
1.12      anton    7750: 
1.26      crook    7751: m: ( n-radius circle -- )
                   7752:   [to-inst] radius ;m
                   7753: overrides construct
1.21      crook    7754: 
1.26      crook    7755: end-class circle
1.12      anton    7756: @end example
                   7757: 
                   7758: 
1.26      crook    7759: @node Classes and Scoping, Object Interfaces, Method conveniences, Objects
                   7760: @subsubsection Classes and Scoping
                   7761: @cindex classes and scoping
                   7762: @cindex scoping and classes
1.12      anton    7763: 
1.26      crook    7764: Inheritance is frequent, unlike structure extension. This exacerbates
                   7765: the problem with the field name convention (@pxref{Structure Naming
                   7766: Convention}): One always has to remember in which class the field was
                   7767: originally defined; changing a part of the class structure would require
                   7768: changes for renaming in otherwise unaffected code.
1.12      anton    7769: 
1.26      crook    7770: @cindex @code{inst-var} visibility
                   7771: @cindex @code{inst-value} visibility
                   7772: To solve this problem, I added a scoping mechanism (which was not in my
                   7773: original charter): A field defined with @code{inst-var} (or
                   7774: @code{inst-value}) is visible only in the class where it is defined and in
                   7775: the descendent classes of this class.  Using such fields only makes
                   7776: sense in @code{m:}-defined methods in these classes anyway.
1.12      anton    7777: 
1.26      crook    7778: This scoping mechanism allows us to use the unadorned field name,
                   7779: because name clashes with unrelated words become much less likely.
1.12      anton    7780: 
1.26      crook    7781: @cindex @code{protected} discussion
                   7782: @cindex @code{private} discussion
                   7783: Once we have this mechanism, we can also use it for controlling the
                   7784: visibility of other words: All words defined after
                   7785: @code{protected} are visible only in the current class and its
                   7786: descendents. @code{public} restores the compilation
                   7787: (i.e. @code{current}) word list that was in effect before. If you
                   7788: have several @code{protected}s without an intervening
                   7789: @code{public} or @code{set-current}, @code{public}
                   7790: will restore the compilation word list in effect before the first of
                   7791: these @code{protected}s.
1.12      anton    7792: 
1.26      crook    7793: @node Object Interfaces, Objects Implementation, Classes and Scoping, Objects
                   7794: @subsubsection Object Interfaces
                   7795: @cindex object interfaces
                   7796: @cindex interfaces for objects
1.12      anton    7797: 
1.26      crook    7798: In this model you can only call selectors defined in the class of the
                   7799: receiving objects or in one of its ancestors. If you call a selector
                   7800: with a receiving object that is not in one of these classes, the
                   7801: result is undefined; if you are lucky, the program crashes
                   7802: immediately.
1.12      anton    7803: 
1.26      crook    7804: @cindex selectors common to hardly-related classes
                   7805: Now consider the case when you want to have a selector (or several)
                   7806: available in two classes: You would have to add the selector to a
                   7807: common ancestor class, in the worst case to @code{object}. You
                   7808: may not want to do this, e.g., because someone else is responsible for
                   7809: this ancestor class.
1.12      anton    7810: 
1.26      crook    7811: The solution for this problem is interfaces. An interface is a
                   7812: collection of selectors. If a class implements an interface, the
                   7813: selectors become available to the class and its descendents. A class
                   7814: can implement an unlimited number of interfaces. For the problem
                   7815: discussed above, we would define an interface for the selector(s), and
                   7816: both classes would implement the interface.
1.12      anton    7817: 
1.26      crook    7818: As an example, consider an interface @code{storage} for
                   7819: writing objects to disk and getting them back, and a class
                   7820: @code{foo} that implements it. The code would look like this:
1.12      anton    7821: 
1.26      crook    7822: @cindex @code{interface} usage
                   7823: @cindex @code{end-interface} usage
                   7824: @cindex @code{implementation} usage
                   7825: @example
                   7826: interface
                   7827:   selector write ( file object -- )
                   7828:   selector read1 ( file object -- )
                   7829: end-interface storage
1.12      anton    7830: 
1.26      crook    7831: bar class
                   7832:   storage implementation
1.12      anton    7833: 
1.26      crook    7834: ... overrides write
                   7835: ... overrides read
                   7836: ...
                   7837: end-class foo
1.12      anton    7838: @end example
                   7839: 
1.26      crook    7840: @noindent
1.29      crook    7841: (I would add a word @code{read} @i{( file -- object )} that uses
1.26      crook    7842: @code{read1} internally, but that's beyond the point illustrated
                   7843: here.)
1.12      anton    7844: 
1.26      crook    7845: Note that you cannot use @code{protected} in an interface; and
                   7846: of course you cannot define fields.
1.12      anton    7847: 
1.26      crook    7848: In the Neon model, all selectors are available for all classes;
                   7849: therefore it does not need interfaces. The price you pay in this model
                   7850: is slower late binding, and therefore, added complexity to avoid late
                   7851: binding.
1.12      anton    7852: 
1.26      crook    7853: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   7854: @subsubsection @file{objects.fs} Implementation
                   7855: @cindex @file{objects.fs} implementation
1.12      anton    7856: 
1.26      crook    7857: @cindex @code{object-map} discussion
                   7858: An object is a piece of memory, like one of the data structures
                   7859: described with @code{struct...end-struct}. It has a field
                   7860: @code{object-map} that points to the method map for the object's
                   7861: class.
1.12      anton    7862: 
1.26      crook    7863: @cindex method map
                   7864: @cindex virtual function table
                   7865: The @emph{method map}@footnote{This is Self terminology; in C++
                   7866: terminology: virtual function table.} is an array that contains the
1.29      crook    7867: execution tokens (@i{xt}s) of the methods for the object's class. Each
1.26      crook    7868: selector contains an offset into a method map.
1.12      anton    7869: 
1.26      crook    7870: @cindex @code{selector} implementation, class
                   7871: @code{selector} is a defining word that uses
                   7872: @code{CREATE} and @code{DOES>}. The body of the
                   7873: selector contains the offset; the @code{does>} action for a
                   7874: class selector is, basically:
1.21      crook    7875: 
1.26      crook    7876: @example
                   7877: ( object addr ) @@ over object-map @@ + @@ execute
                   7878: @end example
1.12      anton    7879: 
1.26      crook    7880: Since @code{object-map} is the first field of the object, it
                   7881: does not generate any code. As you can see, calling a selector has a
                   7882: small, constant cost.
1.12      anton    7883: 
1.26      crook    7884: @cindex @code{current-interface} discussion
                   7885: @cindex class implementation and representation
                   7886: A class is basically a @code{struct} combined with a method
                   7887: map. During the class definition the alignment and size of the class
                   7888: are passed on the stack, just as with @code{struct}s, so
                   7889: @code{field} can also be used for defining class
                   7890: fields. However, passing more items on the stack would be
                   7891: inconvenient, so @code{class} builds a data structure in memory,
                   7892: which is accessed through the variable
                   7893: @code{current-interface}. After its definition is complete, the
                   7894: class is represented on the stack by a pointer (e.g., as parameter for
                   7895: a child class definition).
1.1       anton    7896: 
1.26      crook    7897: A new class starts off with the alignment and size of its parent,
                   7898: and a copy of the parent's method map. Defining new fields extends the
                   7899: size and alignment; likewise, defining new selectors extends the
1.29      crook    7900: method map. @code{overrides} just stores a new @i{xt} in the method
1.26      crook    7901: map at the offset given by the selector.
1.20      pazsan   7902: 
1.26      crook    7903: @cindex class binding, implementation
1.29      crook    7904: Class binding just gets the @i{xt} at the offset given by the selector
1.26      crook    7905: from the class's method map and @code{compile,}s (in the case of
                   7906: @code{[bind]}) it.
1.21      crook    7907: 
1.26      crook    7908: @cindex @code{this} implementation
                   7909: @cindex @code{catch} and @code{this}
                   7910: @cindex @code{this} and @code{catch}
                   7911: I implemented @code{this} as a @code{value}. At the
                   7912: start of an @code{m:...;m} method the old @code{this} is
                   7913: stored to the return stack and restored at the end; and the object on
                   7914: the TOS is stored @code{TO this}. This technique has one
                   7915: disadvantage: If the user does not leave the method via
                   7916: @code{;m}, but via @code{throw} or @code{exit},
                   7917: @code{this} is not restored (and @code{exit} may
                   7918: crash). To deal with the @code{throw} problem, I have redefined
                   7919: @code{catch} to save and restore @code{this}; the same
                   7920: should be done with any word that can catch an exception. As for
                   7921: @code{exit}, I simply forbid it (as a replacement, there is
                   7922: @code{exitm}).
1.21      crook    7923: 
1.26      crook    7924: @cindex @code{inst-var} implementation
                   7925: @code{inst-var} is just the same as @code{field}, with
                   7926: a different @code{DOES>} action:
                   7927: @example
                   7928: @@ this +
                   7929: @end example
                   7930: Similar for @code{inst-value}.
1.21      crook    7931: 
1.26      crook    7932: @cindex class scoping implementation
                   7933: Each class also has a word list that contains the words defined with
                   7934: @code{inst-var} and @code{inst-value}, and its protected
                   7935: words. It also has a pointer to its parent. @code{class} pushes
                   7936: the word lists of the class and all its ancestors onto the search order stack,
                   7937: and @code{end-class} drops them.
1.21      crook    7938: 
1.26      crook    7939: @cindex interface implementation
                   7940: An interface is like a class without fields, parent and protected
                   7941: words; i.e., it just has a method map. If a class implements an
                   7942: interface, its method map contains a pointer to the method map of the
                   7943: interface. The positive offsets in the map are reserved for class
                   7944: methods, therefore interface map pointers have negative
                   7945: offsets. Interfaces have offsets that are unique throughout the
                   7946: system, unlike class selectors, whose offsets are only unique for the
                   7947: classes where the selector is available (invokable).
1.21      crook    7948: 
1.26      crook    7949: This structure means that interface selectors have to perform one
                   7950: indirection more than class selectors to find their method. Their body
                   7951: contains the interface map pointer offset in the class method map, and
                   7952: the method offset in the interface method map. The
                   7953: @code{does>} action for an interface selector is, basically:
1.21      crook    7954: 
                   7955: @example
1.26      crook    7956: ( object selector-body )
                   7957: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   7958: swap object-map @@ + @@ ( object selector-body map )
                   7959: swap selector-offset @@ + @@ execute
1.21      crook    7960: @end example
                   7961: 
1.26      crook    7962: where @code{object-map} and @code{selector-offset} are
                   7963: first fields and generate no code.
                   7964: 
                   7965: As a concrete example, consider the following code:
1.21      crook    7966: 
1.26      crook    7967: @example
                   7968: interface
                   7969:   selector if1sel1
                   7970:   selector if1sel2
                   7971: end-interface if1
1.21      crook    7972: 
1.26      crook    7973: object class
                   7974:   if1 implementation
                   7975:   selector cl1sel1
                   7976:   cell% inst-var cl1iv1
1.21      crook    7977: 
1.26      crook    7978: ' m1 overrides construct
                   7979: ' m2 overrides if1sel1
                   7980: ' m3 overrides if1sel2
                   7981: ' m4 overrides cl1sel2
                   7982: end-class cl1
1.21      crook    7983: 
1.26      crook    7984: create obj1 object dict-new drop
                   7985: create obj2 cl1    dict-new drop
                   7986: @end example
1.21      crook    7987: 
1.26      crook    7988: The data structure created by this code (including the data structure
                   7989: for @code{object}) is shown in the <a
                   7990: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
1.29      crook    7991: @comment TODO add this diagram..
1.21      crook    7992: 
1.26      crook    7993: @node Objects Glossary,  , Objects Implementation, Objects
                   7994: @subsubsection @file{objects.fs} Glossary
                   7995: @cindex @file{objects.fs} Glossary
1.21      crook    7996: 
1.26      crook    7997: doc---objects-bind
                   7998: doc---objects-<bind>
                   7999: doc---objects-bind'
                   8000: doc---objects-[bind]
                   8001: doc---objects-class
                   8002: doc---objects-class->map
                   8003: doc---objects-class-inst-size
                   8004: doc---objects-class-override!
                   8005: doc---objects-construct
                   8006: doc---objects-current'
                   8007: doc---objects-[current]
                   8008: doc---objects-current-interface
                   8009: doc---objects-dict-new
                   8010: doc---objects-drop-order
                   8011: doc---objects-end-class
                   8012: doc---objects-end-class-noname
                   8013: doc---objects-end-interface
                   8014: doc---objects-end-interface-noname
                   8015: doc---objects-exitm
                   8016: doc---objects-heap-new
                   8017: doc---objects-implementation
                   8018: doc---objects-init-object
                   8019: doc---objects-inst-value
                   8020: doc---objects-inst-var
                   8021: doc---objects-interface
                   8022: doc---objects-;m
                   8023: doc---objects-m:
                   8024: doc---objects-method
                   8025: doc---objects-object
                   8026: doc---objects-overrides
                   8027: doc---objects-[parent]
                   8028: doc---objects-print
                   8029: doc---objects-protected
                   8030: doc---objects-public
                   8031: doc---objects-push-order
                   8032: doc---objects-selector
                   8033: doc---objects-this
                   8034: doc---objects-<to-inst>
                   8035: doc---objects-[to-inst]
                   8036: doc---objects-to-this
                   8037: doc---objects-xt-new
1.21      crook    8038: 
1.26      crook    8039: @c -------------------------------------------------------------
                   8040: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   8041: @subsection The @file{oof.fs} model
                   8042: @cindex oof
                   8043: @cindex object-oriented programming
1.21      crook    8044: 
1.26      crook    8045: @cindex @file{objects.fs}
                   8046: @cindex @file{oof.fs}
1.21      crook    8047: 
1.26      crook    8048: This section describes the @file{oof.fs} package.
1.21      crook    8049: 
1.26      crook    8050: The package described in this section has been used in bigFORTH since 1991, and
                   8051: used for two large applications: a chromatographic system used to
                   8052: create new medicaments, and a graphic user interface library (MINOS).
1.21      crook    8053: 
1.26      crook    8054: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   8055: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   8056: 10(2), 1994.
1.21      crook    8057: 
1.26      crook    8058: @menu
                   8059: * Properties of the OOF model::
                   8060: * Basic OOF Usage::
                   8061: * The OOF base class::
                   8062: * Class Declaration::
                   8063: * Class Implementation::
                   8064: @end menu
1.21      crook    8065: 
1.26      crook    8066: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   8067: @subsubsection Properties of the @file{oof.fs} model
                   8068: @cindex @file{oof.fs} properties
1.21      crook    8069: 
1.26      crook    8070: @itemize @bullet
                   8071: @item
                   8072: This model combines object oriented programming with information
                   8073: hiding. It helps you writing large application, where scoping is
                   8074: necessary, because it provides class-oriented scoping.
1.21      crook    8075: 
1.26      crook    8076: @item
                   8077: Named objects, object pointers, and object arrays can be created,
                   8078: selector invocation uses the ``object selector'' syntax. Selector invocation
                   8079: to objects and/or selectors on the stack is a bit less convenient, but
                   8080: possible.
1.21      crook    8081: 
1.26      crook    8082: @item
                   8083: Selector invocation and instance variable usage of the active object is
                   8084: straightforward, since both make use of the active object.
1.21      crook    8085: 
1.26      crook    8086: @item
                   8087: Late binding is efficient and easy to use.
1.21      crook    8088: 
1.26      crook    8089: @item
                   8090: State-smart objects parse selectors. However, extensibility is provided
                   8091: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.21      crook    8092: 
                   8093: @item
1.26      crook    8094: An implementation in ANS Forth is available.
                   8095: 
1.21      crook    8096: @end itemize
                   8097: 
                   8098: 
1.26      crook    8099: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   8100: @subsubsection Basic @file{oof.fs} Usage
                   8101: @cindex @file{oof.fs} usage
                   8102: 
                   8103: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.21      crook    8104: 
1.26      crook    8105: You can define a class for graphical objects like this:
1.21      crook    8106: 
1.26      crook    8107: @cindex @code{class} usage
                   8108: @cindex @code{class;} usage
                   8109: @cindex @code{method} usage
                   8110: @example
                   8111: object class graphical \ "object" is the parent class
                   8112:   method draw ( x y graphical -- )
                   8113: class;
                   8114: @end example
1.21      crook    8115: 
1.26      crook    8116: This code defines a class @code{graphical} with an
                   8117: operation @code{draw}.  We can perform the operation
                   8118: @code{draw} on any @code{graphical} object, e.g.:
1.21      crook    8119: 
1.26      crook    8120: @example
                   8121: 100 100 t-rex draw
                   8122: @end example
1.21      crook    8123: 
1.26      crook    8124: @noindent
                   8125: where @code{t-rex} is an object or object pointer, created with e.g.
                   8126: @code{graphical : t-rex}.
1.21      crook    8127: 
1.26      crook    8128: @cindex abstract class
                   8129: How do we create a graphical object? With the present definitions,
                   8130: we cannot create a useful graphical object. The class
                   8131: @code{graphical} describes graphical objects in general, but not
                   8132: any concrete graphical object type (C++ users would call it an
                   8133: @emph{abstract class}); e.g., there is no method for the selector
                   8134: @code{draw} in the class @code{graphical}.
1.21      crook    8135: 
1.26      crook    8136: For concrete graphical objects, we define child classes of the
                   8137: class @code{graphical}, e.g.:
1.21      crook    8138: 
                   8139: @example
1.26      crook    8140: graphical class circle \ "graphical" is the parent class
                   8141:   cell var circle-radius
                   8142: how:
                   8143:   : draw ( x y -- )
                   8144:     circle-radius @@ draw-circle ;
                   8145: 
                   8146:   : init ( n-radius -- (
                   8147:     circle-radius ! ;
                   8148: class;
                   8149: @end example
                   8150: 
                   8151: Here we define a class @code{circle} as a child of @code{graphical},
                   8152: with a field @code{circle-radius}; it defines new methods for the
                   8153: selectors @code{draw} and @code{init} (@code{init} is defined in
                   8154: @code{object}, the parent class of @code{graphical}).
1.21      crook    8155: 
1.26      crook    8156: Now we can create a circle in the dictionary with:
1.21      crook    8157: 
1.26      crook    8158: @example
                   8159: 50 circle : my-circle
1.21      crook    8160: @end example
                   8161: 
1.26      crook    8162: @noindent
                   8163: @code{:} invokes @code{init}, thus initializing the field
                   8164: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   8165: with:
1.21      crook    8166: 
                   8167: @example
1.26      crook    8168: 100 100 my-circle draw
1.21      crook    8169: @end example
                   8170: 
1.26      crook    8171: @cindex selector invocation, restrictions
                   8172: @cindex class definition, restrictions
                   8173: Note: You can only invoke a selector if the receiving object belongs to
                   8174: the class where the selector was defined or one of its descendents;
                   8175: e.g., you can invoke @code{draw} only for objects belonging to
                   8176: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   8177: mechanism will check if you try to invoke a selector that is not
                   8178: defined in this class hierarchy, so you'll get an error at compilation
                   8179: time.
                   8180: 
                   8181: 
                   8182: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   8183: @subsubsection The @file{oof.fs} base class
                   8184: @cindex @file{oof.fs} base class
                   8185: 
                   8186: When you define a class, you have to specify a parent class.  So how do
                   8187: you start defining classes? There is one class available from the start:
                   8188: @code{object}. You have to use it as ancestor for all classes. It is the
                   8189: only class that has no parent. Classes are also objects, except that
                   8190: they don't have instance variables; class manipulation such as
                   8191: inheritance or changing definitions of a class is handled through
                   8192: selectors of the class @code{object}.
                   8193: 
                   8194: @code{object} provides a number of selectors:
                   8195: 
1.21      crook    8196: @itemize @bullet
                   8197: @item
1.26      crook    8198: @code{class} for subclassing, @code{definitions} to add definitions
                   8199: later on, and @code{class?} to get type informations (is the class a
                   8200: subclass of the class passed on the stack?).
                   8201: doc---object-class
                   8202: doc---object-definitions
                   8203: doc---object-class?
                   8204: 
1.21      crook    8205: @item
1.26      crook    8206: @code{init} and @code{dispose} as constructor and destructor of the
                   8207: object. @code{init} is invocated after the object's memory is allocated,
                   8208: while @code{dispose} also handles deallocation. Thus if you redefine
                   8209: @code{dispose}, you have to call the parent's dispose with @code{super
                   8210: dispose}, too.
                   8211: doc---object-init
                   8212: doc---object-dispose
                   8213: 
1.21      crook    8214: @item
1.26      crook    8215: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   8216: @code{[]} to create named and unnamed objects and object arrays or
                   8217: object pointers.
                   8218: doc---object-new
                   8219: doc---object-new[]
                   8220: doc---object-:
                   8221: doc---object-ptr
                   8222: doc---object-asptr
                   8223: doc---object-[]
1.21      crook    8224: 
1.26      crook    8225: @item
                   8226: @code{::} and @code{super} for explicit scoping. You should use explicit
                   8227: scoping only for super classes or classes with the same set of instance
                   8228: variables. Explicitly-scoped selectors use early binding.
                   8229: doc---object-::
                   8230: doc---object-super
1.21      crook    8231: 
1.26      crook    8232: @item
                   8233: @code{self} to get the address of the object
                   8234: doc---object-self
1.21      crook    8235: 
                   8236: @item
1.26      crook    8237: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   8238: pointers and instance defers.
                   8239: doc---object-bind
                   8240: doc---object-bound
                   8241: doc---object-link
                   8242: doc---object-is
                   8243: 
1.21      crook    8244: @item
1.26      crook    8245: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   8246: form the stack, and @code{postpone} to generate selector invocation code.
                   8247: doc---object-'
                   8248: doc---object-postpone
                   8249: 
1.21      crook    8250: @item
1.26      crook    8251: @code{with} and @code{endwith} to select the active object from the
                   8252: stack, and enable its scope. Using @code{with} and @code{endwith}
                   8253: also allows you to create code using selector @code{postpone} without being
                   8254: trapped by the state-smart objects.
                   8255: doc---object-with
                   8256: doc---object-endwith
                   8257: 
1.21      crook    8258: @end itemize
                   8259: 
1.26      crook    8260: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   8261: @subsubsection Class Declaration
                   8262: @cindex class declaration
                   8263: 
                   8264: @itemize @bullet
                   8265: @item
                   8266: Instance variables
                   8267: doc---oof-var
1.21      crook    8268: 
1.26      crook    8269: @item
                   8270: Object pointers
                   8271: doc---oof-ptr
                   8272: doc---oof-asptr
1.21      crook    8273: 
1.26      crook    8274: @item
                   8275: Instance defers
                   8276: doc---oof-defer
1.21      crook    8277: 
1.26      crook    8278: @item
                   8279: Method selectors
                   8280: doc---oof-early
                   8281: doc---oof-method
1.21      crook    8282: 
1.26      crook    8283: @item
                   8284: Class-wide variables
                   8285: doc---oof-static
1.21      crook    8286: 
1.26      crook    8287: @item
                   8288: End declaration
                   8289: doc---oof-how:
                   8290: doc---oof-class;
1.21      crook    8291: 
1.26      crook    8292: @end itemize
1.21      crook    8293: 
1.26      crook    8294: @c -------------------------------------------------------------
                   8295: @node Class Implementation,  , Class Declaration, OOF
                   8296: @subsubsection Class Implementation
                   8297: @cindex class implementation
1.21      crook    8298: 
1.26      crook    8299: @c -------------------------------------------------------------
                   8300: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   8301: @subsection The @file{mini-oof.fs} model
                   8302: @cindex mini-oof
1.1       anton    8303: 
1.26      crook    8304: Gforth's third object oriented Forth package is a 12-liner. It uses a
                   8305: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
                   8306: and reduces to the bare minimum of features. This is based on a posting
                   8307: of Bernd Paysan in comp.arch.
1.1       anton    8308: 
                   8309: @menu
1.26      crook    8310: * Basic Mini-OOF Usage::
                   8311: * Mini-OOF Example::
                   8312: * Mini-OOF Implementation::
1.1       anton    8313: @end menu
                   8314: 
1.26      crook    8315: @c -------------------------------------------------------------
                   8316: @node Basic Mini-OOF Usage, Mini-OOF Example, , Mini-OOF
                   8317: @subsubsection Basic @file{mini-oof.fs} Usage
                   8318: @cindex mini-oof usage
1.1       anton    8319: 
1.28      crook    8320: There is a base class (@code{class}, which allocates one cell for the
                   8321: object pointer) plus seven other words: to define a method, a variable,
                   8322: a class; to end a class, to resolve binding, to allocate an object and
                   8323: to compile a class method.
1.26      crook    8324: @comment TODO better description of the last one
1.1       anton    8325: 
1.26      crook    8326: doc-object
                   8327: doc-method
                   8328: doc-var
                   8329: doc-class
                   8330: doc-end-class
                   8331: doc-defines
                   8332: doc-new
                   8333: doc-::
1.1       anton    8334: 
1.21      crook    8335: 
1.26      crook    8336: @c -------------------------------------------------------------
                   8337: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   8338: @subsubsection Mini-OOF Example
                   8339: @cindex mini-oof example
1.21      crook    8340: 
1.26      crook    8341: A short example shows how to use this package. This example, in slightly
                   8342: extended form, is supplied as @file{moof-exm.fs}
1.29      crook    8343: @comment TODO could flesh this out with some comments from the Forthwrite article
1.21      crook    8344: 
1.26      crook    8345: @example
                   8346: object class
                   8347:   method init
                   8348:   method draw
                   8349: end-class graphical
                   8350: @end example
1.21      crook    8351: 
1.26      crook    8352: This code defines a class @code{graphical} with an
                   8353: operation @code{draw}.  We can perform the operation
                   8354: @code{draw} on any @code{graphical} object, e.g.:
1.1       anton    8355: 
1.26      crook    8356: @example
                   8357: 100 100 t-rex draw
                   8358: @end example
1.1       anton    8359: 
1.26      crook    8360: where @code{t-rex} is an object or object pointer, created with e.g.
                   8361: @code{graphical new Constant t-rex}.
1.1       anton    8362: 
1.26      crook    8363: For concrete graphical objects, we define child classes of the
                   8364: class @code{graphical}, e.g.:
1.21      crook    8365: 
                   8366: @example
1.26      crook    8367: graphical class
                   8368:   cell var circle-radius
                   8369: end-class circle \ "graphical" is the parent class
1.21      crook    8370: 
1.26      crook    8371: :noname ( x y -- )
                   8372:   circle-radius @@ draw-circle ; circle defines draw
                   8373: :noname ( r -- )
                   8374:   circle-radius ! ; circle defines init
1.21      crook    8375: @end example
                   8376: 
1.26      crook    8377: There is no implicit init method, so we have to define one. The creation
                   8378: code of the object now has to call init explicitely.
1.21      crook    8379: 
1.26      crook    8380: @example
                   8381: circle new Constant my-circle
                   8382: 50 my-circle init
                   8383: @end example
1.21      crook    8384: 
1.26      crook    8385: It is also possible to add a function to create named objects with
                   8386: automatic call of @code{init}, given that all objects have @code{init}
                   8387: on the same place:
1.1       anton    8388: 
                   8389: @example
1.26      crook    8390: : new: ( .. o "name" -- )
                   8391:     new dup Constant init ;
                   8392: 80 circle new: large-circle
1.1       anton    8393: @end example
                   8394: 
1.26      crook    8395: We can draw this new circle at (100,100) with:
1.1       anton    8396: 
                   8397: @example
1.26      crook    8398: 100 100 my-circle draw
1.1       anton    8399: @end example
                   8400: 
1.26      crook    8401: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
                   8402: @subsubsection @file{mini-oof.fs} Implementation
1.1       anton    8403: 
1.26      crook    8404: Object-oriented systems with late binding typically use a
                   8405: ``vtable''-approach: the first variable in each object is a pointer to a
                   8406: table, which contains the methods as function pointers. The vtable
                   8407: may also contain other information.
1.1       anton    8408: 
1.26      crook    8409: So first, let's declare methods:
1.1       anton    8410: 
1.26      crook    8411: @example
                   8412: : method ( m v -- m' v ) Create  over , swap cell+ swap
                   8413:   DOES> ( ... o -- ... ) @ over @ + @ execute ;
                   8414: @end example
1.1       anton    8415: 
1.26      crook    8416: During method declaration, the number of methods and instance
                   8417: variables is on the stack (in address units). @code{method} creates
                   8418: one method and increments the method number. To execute a method, it
                   8419: takes the object, fetches the vtable pointer, adds the offset, and
1.29      crook    8420: executes the @i{xt} stored there. Each method takes the object it is
1.26      crook    8421: invoked from as top of stack parameter. The method itself should
                   8422: consume that object.
1.1       anton    8423: 
1.26      crook    8424: Now, we also have to declare instance variables
1.21      crook    8425: 
1.26      crook    8426: @example
                   8427: : var ( m v size -- m v' ) Create  over , +
                   8428:   DOES> ( o -- addr ) @ + ;
                   8429: @end example
1.21      crook    8430: 
1.26      crook    8431: As before, a word is created with the current offset. Instance
                   8432: variables can have different sizes (cells, floats, doubles, chars), so
                   8433: all we do is take the size and add it to the offset. If your machine
                   8434: has alignment restrictions, put the proper @code{aligned} or
                   8435: @code{faligned} before the variable, to adjust the variable
                   8436: offset. That's why it is on the top of stack.
1.2       jwilke   8437: 
1.26      crook    8438: We need a starting point (the base object) and some syntactic sugar:
1.21      crook    8439: 
1.26      crook    8440: @example
                   8441: Create object  1 cells , 2 cells ,
                   8442: : class ( class -- class methods vars ) dup 2@ ;
                   8443: @end example
1.21      crook    8444: 
1.26      crook    8445: For inheritance, the vtable of the parent object has to be
                   8446: copied when a new, derived class is declared. This gives all the
                   8447: methods of the parent class, which can be overridden, though.
1.21      crook    8448: 
1.2       jwilke   8449: @example
1.26      crook    8450: : end-class  ( class methods vars -- )
                   8451:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   8452:   cell+ dup cell+ r> rot @ 2 cells /string move ;
                   8453: @end example
                   8454: 
                   8455: The first line creates the vtable, initialized with
                   8456: @code{noop}s. The second line is the inheritance mechanism, it
                   8457: copies the xts from the parent vtable.
1.2       jwilke   8458: 
1.26      crook    8459: We still have no way to define new methods, let's do that now:
1.2       jwilke   8460: 
1.26      crook    8461: @example
                   8462: : defines ( xt class -- ) ' >body @ + ! ;
1.2       jwilke   8463: @end example
                   8464: 
1.26      crook    8465: To allocate a new object, we need a word, too:
1.2       jwilke   8466: 
1.26      crook    8467: @example
                   8468: : new ( class -- o )  here over @ allot swap over ! ;
                   8469: @end example
1.2       jwilke   8470: 
1.26      crook    8471: Sometimes derived classes want to access the method of the
                   8472: parent object. There are two ways to achieve this with Mini-OOF:
                   8473: first, you could use named words, and second, you could look up the
                   8474: vtable of the parent object.
1.2       jwilke   8475: 
1.26      crook    8476: @example
                   8477: : :: ( class "name" -- ) ' >body @ + @ compile, ;
                   8478: @end example
1.2       jwilke   8479: 
                   8480: 
1.26      crook    8481: Nothing can be more confusing than a good example, so here is
                   8482: one. First let's declare a text object (called
                   8483: @code{button}), that stores text and position:
1.2       jwilke   8484: 
1.26      crook    8485: @example
                   8486: object class
                   8487:   cell var text
                   8488:   cell var len
                   8489:   cell var x
                   8490:   cell var y
                   8491:   method init
                   8492:   method draw
                   8493: end-class button
                   8494: @end example
1.2       jwilke   8495: 
1.26      crook    8496: @noindent
                   8497: Now, implement the two methods, @code{draw} and @code{init}:
1.2       jwilke   8498: 
1.26      crook    8499: @example
                   8500: :noname ( o -- )
                   8501:  >r r@ x @ r@ y @ at-xy  r@ text @ r> len @ type ;
                   8502:  button defines draw
                   8503: :noname ( addr u o -- )
                   8504:  >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
                   8505:  button defines init
                   8506: @end example
1.2       jwilke   8507: 
1.26      crook    8508: @noindent
                   8509: To demonstrate inheritance, we define a class @code{bold-button}, with no
                   8510: new data and no new methods:
1.2       jwilke   8511: 
1.26      crook    8512: @example
                   8513: button class
                   8514: end-class bold-button
1.1       anton    8515: 
1.26      crook    8516: : bold   27 emit ." [1m" ;
                   8517: : normal 27 emit ." [0m" ;
                   8518: @end example
1.1       anton    8519: 
1.26      crook    8520: @noindent
                   8521: The class @code{bold-button} has a different draw method to
                   8522: @code{button}, but the new method is defined in terms of the draw method
                   8523: for @code{button}:
1.1       anton    8524: 
1.26      crook    8525: @example
                   8526: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   8527: @end example
1.1       anton    8528: 
1.26      crook    8529: @noindent
                   8530: Finally, create two objects and apply methods:
1.1       anton    8531: 
1.26      crook    8532: @example
                   8533: button new Constant foo
                   8534: s" thin foo" foo init
                   8535: page
                   8536: foo draw
                   8537: bold-button new Constant bar
                   8538: s" fat bar" bar init
                   8539: 1 bar y !
                   8540: bar draw
                   8541: @end example
1.1       anton    8542: 
                   8543: 
1.26      crook    8544: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
                   8545: @subsubsection Comparison with other object models
                   8546: @cindex comparison of object models
                   8547: @cindex object models, comparison
1.1       anton    8548: 
1.26      crook    8549: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   8550: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   8551: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   8552: relation of the object models described here to two well-known and two
                   8553: closely-related (by the use of method maps) models.
1.1       anton    8554: 
1.26      crook    8555: @cindex Neon model
                   8556: The most popular model currently seems to be the Neon model (see
                   8557: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   8558: 1997) by Andrew McKewan) but this model has a number of limitations
                   8559: @footnote{A longer version of this critique can be
                   8560: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   8561: Dimensions, May 1997) by Anton Ertl.}:
1.1       anton    8562: 
1.26      crook    8563: @itemize @bullet
                   8564: @item
                   8565: It uses a @code{@emph{selector
                   8566: object}} syntax, which makes it unnatural to pass objects on the
                   8567: stack.
1.1       anton    8568: 
1.26      crook    8569: @item
                   8570: It requires that the selector parses the input stream (at
                   8571: compile time); this leads to reduced extensibility and to bugs that are+
                   8572: hard to find.
1.1       anton    8573: 
1.26      crook    8574: @item
                   8575: It allows using every selector to every object;
                   8576: this eliminates the need for classes, but makes it harder to create
                   8577: efficient implementations. 
                   8578: @end itemize
1.1       anton    8579: 
1.26      crook    8580: @cindex Pountain's object-oriented model
                   8581: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   8582: Press, London, 1987) by Dick Pountain. However, it is not really about
                   8583: object-oriented programming, because it hardly deals with late
                   8584: binding. Instead, it focuses on features like information hiding and
                   8585: overloading that are characteristic of modular languages like Ada (83).
1.1       anton    8586: 
1.26      crook    8587: @cindex Zsoter's object-oriented model
                   8588: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1) 1996, pages 31-35)
                   8589: Andras Zsoter describes a model that makes heavy use of an active object
                   8590: (like @code{this} in @file{objects.fs}): The active object is not only
                   8591: used for accessing all fields, but also specifies the receiving object
                   8592: of every selector invocation; you have to change the active object
                   8593: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
                   8594: changes more or less implicitly at @code{m: ... ;m}. Such a change at
                   8595: the method entry point is unnecessary with the Zsoter's model, because
                   8596: the receiving object is the active object already. On the other hand, the explicit
                   8597: change is absolutely necessary in that model, because otherwise no one
                   8598: could ever change the active object. An ANS Forth implementation of this
                   8599: model is available at @url{http://www.forth.org/fig/oopf.html}.
1.1       anton    8600: 
1.26      crook    8601: @cindex @file{oof.fs}, differences to other models
                   8602: The @file{oof.fs} model combines information hiding and overloading
                   8603: resolution (by keeping names in various word lists) with object-oriented
                   8604: programming. It sets the active object implicitly on method entry, but
                   8605: also allows explicit changing (with @code{>o...o>} or with
                   8606: @code{with...endwith}). It uses parsing and state-smart objects and
                   8607: classes for resolving overloading and for early binding: the object or
                   8608: class parses the selector and determines the method from this. If the
                   8609: selector is not parsed by an object or class, it performs a call to the
                   8610: selector for the active object (late binding), like Zsoter's model.
                   8611: Fields are always accessed through the active object. The big
                   8612: disadvantage of this model is the parsing and the state-smartness, which
                   8613: reduces extensibility and increases the opportunities for subtle bugs;
                   8614: essentially, you are only safe if you never tick or @code{postpone} an
                   8615: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.1       anton    8616: 
1.26      crook    8617: @cindex @file{mini-oof.fs}, differences to other models
                   8618: The @file{mini-oof.fs} model is quite similar to a very stripped-down version of
                   8619: the @file{objects.fs} model, but syntactically it is a mixture of the @file{objects.fs} and
                   8620: @file{oof.fs} models.
1.1       anton    8621: 
1.26      crook    8622: @c -------------------------------------------------------------
                   8623: @node Passing Commands to the OS, Miscellaneous Words, Object-oriented Forth, Words
1.21      crook    8624: @section Passing Commands to the Operating System
                   8625: @cindex operating system - passing commands
                   8626: @cindex shell commands
                   8627: 
                   8628: Gforth allows you to pass an arbitrary string to the host operating
                   8629: system shell (if such a thing exists) for execution.
                   8630: 
                   8631: doc-sh
                   8632: doc-system
                   8633: doc-$?
1.23      crook    8634: doc-getenv
1.21      crook    8635: 
1.26      crook    8636: @c -------------------------------------------------------------
1.21      crook    8637: @node Miscellaneous Words,  , Passing Commands to the OS, Words
                   8638: @section Miscellaneous Words
                   8639: @cindex miscellaneous words
                   8640: 
1.29      crook    8641: @comment TODO find homes for these
                   8642: 
1.26      crook    8643: These section lists the ANS Forth words that are not documented
1.21      crook    8644: elsewhere in this manual. Ultimately, they all need proper homes.
                   8645: 
                   8646: doc-ms
                   8647: doc-time&date
1.27      crook    8648: 
1.21      crook    8649: doc-[compile]
                   8650: 
1.26      crook    8651: The following ANS Forth words are not currently supported by Gforth 
1.27      crook    8652: (@pxref{ANS conformance}):
1.21      crook    8653: 
                   8654: @code{EDITOR} 
                   8655: @code{EKEY} 
                   8656: @code{EKEY>CHAR} 
                   8657: @code{EKEY?} 
                   8658: @code{EMIT?} 
                   8659: @code{FORGET} 
                   8660: 
1.24      anton    8661: @c ******************************************************************
                   8662: @node Error messages, Tools, Words, Top
                   8663: @chapter Error messages
                   8664: @cindex error messages
                   8665: @cindex backtrace
                   8666: 
                   8667: A typical Gforth error message looks like this:
                   8668: 
                   8669: @example
                   8670: in file included from :-1
                   8671: in file included from ./yyy.fs:1
                   8672: ./xxx.fs:4: Invalid memory address
                   8673: bar
                   8674: ^^^
1.25      anton    8675: $400E664C @@
                   8676: $400E6664 foo
1.24      anton    8677: @end example
                   8678: 
                   8679: The message identifying the error is @code{Invalid memory address}.  The
                   8680: error happened when text-interpreting line 4 of the file
                   8681: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
                   8682: word on the line where the error happened, is pointed out (with
                   8683: @code{^^^}).
                   8684: 
                   8685: The file containing the error was included in line 1 of @file{./yyy.fs},
                   8686: and @file{yyy.fs} was included from a non-file (in this case, by giving
                   8687: @file{yyy.fs} as command-line parameter to Gforth).
                   8688: 
                   8689: At the end of the error message you find a return stack dump that can be
                   8690: interpreted as a backtrace (possibly empty). On top you find the top of
                   8691: the return stack when the @code{throw} happened, and at the bottom you
                   8692: find the return stack entry just above the return stack of the topmost
                   8693: text interpreter.
                   8694: 
                   8695: To the right of most return stack entries you see a guess for the word
                   8696: that pushed that return stack entry as its return address. This gives a
                   8697: backtrace. In our case we see that @code{bar} called @code{foo}, and
                   8698: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
                   8699: address} exception).
                   8700: 
                   8701: Note that the backtrace is not perfect: We don't know which return stack
                   8702: entries are return addresses (so we may get false positives); and in
                   8703: some cases (e.g., for @code{abort"}) we cannot determine from the return
                   8704: address the word that pushed the return address, so for some return
                   8705: addresses you see no names in the return stack dump.
1.25      anton    8706: 
                   8707: @cindex @code{catch} and backtraces
                   8708: The return stack dump represents the return stack at the time when a
                   8709: specific @code{throw} was executed.  In programs that make use of
                   8710: @code{catch}, it is not necessarily clear which @code{throw} should be
                   8711: used for the return stack dump (e.g., consider one @code{throw} that
                   8712: indicates an error, which is caught, and during recovery another error
                   8713: happens; which @code{throw} should be used for the stack dump).  Gforth
                   8714: presents the return stack dump for the first @code{throw} after the last
                   8715: executed (not returned-to) @code{catch}; this works well in the usual
                   8716: case.
                   8717: 
                   8718: @cindex @code{gforth-fast} and backtraces
                   8719: @cindex @code{gforth-fast}, difference from @code{gforth}
                   8720: @cindex backtraces with @code{gforth-fast}
                   8721: @cindex return stack dump with @code{gforth-fast}
                   8722: @code{gforth} is able to do a return stack dump for throws generated
                   8723: from primitives (e.g., invalid memory address, stack empty etc.);
                   8724: @code{gforth-fast} is only able to do a return stack dump from a
                   8725: directly called @code{throw} (including @code{abort} etc.).  This is the
1.30      anton    8726: only difference (apart from a speed factor of between 1.15 (K6-2) and
                   8727: 1.6 (21164A)) between @code{gforth} and @code{gforth-fast}.  Given an
                   8728: exception caused by a primitive in @code{gforth-fast}, you will
                   8729: typically see no return stack dump at all; however, if the exception is
                   8730: caught by @code{catch} (e.g., for restoring some state), and then
                   8731: @code{throw}n again, the return stack dump will be for the first such
                   8732: @code{throw}.
1.2       jwilke   8733: 
1.5       anton    8734: @c ******************************************************************
1.24      anton    8735: @node Tools, ANS conformance, Error messages, Top
1.1       anton    8736: @chapter Tools
                   8737: 
                   8738: @menu
                   8739: * ANS Report::                  Report the words used, sorted by wordset.
                   8740: @end menu
                   8741: 
                   8742: See also @ref{Emacs and Gforth}.
                   8743: 
                   8744: @node ANS Report,  , Tools, Tools
                   8745: @section @file{ans-report.fs}: Report the words used, sorted by wordset
                   8746: @cindex @file{ans-report.fs}
                   8747: @cindex report the words used in your program
                   8748: @cindex words used in your program
                   8749: 
                   8750: If you want to label a Forth program as ANS Forth Program, you must
                   8751: document which wordsets the program uses; for extension wordsets, it is
                   8752: helpful to list the words the program requires from these wordsets
                   8753: (because Forth systems are allowed to provide only some words of them).
                   8754: 
                   8755: The @file{ans-report.fs} tool makes it easy for you to determine which
                   8756: words from which wordset and which non-ANS words your application
                   8757: uses. You simply have to include @file{ans-report.fs} before loading the
                   8758: program you want to check. After loading your program, you can get the
                   8759: report with @code{print-ans-report}. A typical use is to run this as
                   8760: batch job like this:
                   8761: @example
                   8762: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
                   8763: @end example
                   8764: 
                   8765: The output looks like this (for @file{compat/control.fs}):
                   8766: @example
                   8767: The program uses the following words
                   8768: from CORE :
                   8769: : POSTPONE THEN ; immediate ?dup IF 0= 
                   8770: from BLOCK-EXT :
                   8771: \ 
                   8772: from FILE :
                   8773: ( 
                   8774: @end example
                   8775: 
                   8776: @subsection Caveats
                   8777: 
                   8778: Note that @file{ans-report.fs} just checks which words are used, not whether
                   8779: they are used in an ANS Forth conforming way!
                   8780: 
                   8781: Some words are defined in several wordsets in the
                   8782: standard. @file{ans-report.fs} reports them for only one of the
                   8783: wordsets, and not necessarily the one you expect. It depends on usage
                   8784: which wordset is the right one to specify. E.g., if you only use the
                   8785: compilation semantics of @code{S"}, it is a Core word; if you also use
                   8786: its interpretation semantics, it is a File word.
                   8787: 
                   8788: @c ******************************************************************
                   8789: @node ANS conformance, Model, Tools, Top
                   8790: @chapter ANS conformance
                   8791: @cindex ANS conformance of Gforth
                   8792: 
                   8793: To the best of our knowledge, Gforth is an
                   8794: 
                   8795: ANS Forth System
                   8796: @itemize @bullet
                   8797: @item providing the Core Extensions word set
                   8798: @item providing the Block word set
                   8799: @item providing the Block Extensions word set
                   8800: @item providing the Double-Number word set
                   8801: @item providing the Double-Number Extensions word set
                   8802: @item providing the Exception word set
                   8803: @item providing the Exception Extensions word set
                   8804: @item providing the Facility word set
                   8805: @item providing @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
                   8806: @item providing the File Access word set
                   8807: @item providing the File Access Extensions word set
                   8808: @item providing the Floating-Point word set
                   8809: @item providing the Floating-Point Extensions word set
                   8810: @item providing the Locals word set
                   8811: @item providing the Locals Extensions word set
                   8812: @item providing the Memory-Allocation word set
                   8813: @item providing the Memory-Allocation Extensions word set (that one's easy)
                   8814: @item providing the Programming-Tools word set
                   8815: @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
                   8816: @item providing the Search-Order word set
                   8817: @item providing the Search-Order Extensions word set
                   8818: @item providing the String word set
                   8819: @item providing the String Extensions word set (another easy one)
                   8820: @end itemize
                   8821: 
                   8822: @cindex system documentation
                   8823: In addition, ANS Forth systems are required to document certain
                   8824: implementation choices. This chapter tries to meet these
                   8825: requirements. In many cases it gives a way to ask the system for the
                   8826: information instead of providing the information directly, in
                   8827: particular, if the information depends on the processor, the operating
                   8828: system or the installation options chosen, or if they are likely to
                   8829: change during the maintenance of Gforth.
                   8830: 
                   8831: @comment The framework for the rest has been taken from pfe.
                   8832: 
                   8833: @menu
                   8834: * The Core Words::              
                   8835: * The optional Block word set::  
                   8836: * The optional Double Number word set::  
                   8837: * The optional Exception word set::  
                   8838: * The optional Facility word set::  
                   8839: * The optional File-Access word set::  
                   8840: * The optional Floating-Point word set::  
                   8841: * The optional Locals word set::  
                   8842: * The optional Memory-Allocation word set::  
                   8843: * The optional Programming-Tools word set::  
                   8844: * The optional Search-Order word set::  
                   8845: @end menu
                   8846: 
                   8847: 
                   8848: @c =====================================================================
                   8849: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
                   8850: @comment  node-name,  next,  previous,  up
                   8851: @section The Core Words
                   8852: @c =====================================================================
                   8853: @cindex core words, system documentation
                   8854: @cindex system documentation, core words
                   8855: 
                   8856: @menu
                   8857: * core-idef::                   Implementation Defined Options                   
                   8858: * core-ambcond::                Ambiguous Conditions                
                   8859: * core-other::                  Other System Documentation                  
                   8860: @end menu
                   8861: 
                   8862: @c ---------------------------------------------------------------------
                   8863: @node core-idef, core-ambcond, The Core Words, The Core Words
                   8864: @subsection Implementation Defined Options
                   8865: @c ---------------------------------------------------------------------
                   8866: @cindex core words, implementation-defined options
                   8867: @cindex implementation-defined options, core words
                   8868: 
                   8869: 
                   8870: @table @i
                   8871: @item (Cell) aligned addresses:
                   8872: @cindex cell-aligned addresses
                   8873: @cindex aligned addresses
                   8874: processor-dependent. Gforth's alignment words perform natural alignment
                   8875: (e.g., an address aligned for a datum of size 8 is divisible by
                   8876: 8). Unaligned accesses usually result in a @code{-23 THROW}.
                   8877: 
                   8878: @item @code{EMIT} and non-graphic characters:
                   8879: @cindex @code{EMIT} and non-graphic characters
                   8880: @cindex non-graphic characters and @code{EMIT}
                   8881: The character is output using the C library function (actually, macro)
                   8882: @code{putc}.
                   8883: 
                   8884: @item character editing of @code{ACCEPT} and @code{EXPECT}:
                   8885: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
                   8886: @cindex editing in @code{ACCEPT} and @code{EXPECT}
                   8887: @cindex @code{ACCEPT}, editing
                   8888: @cindex @code{EXPECT}, editing
                   8889: This is modeled on the GNU readline library (@pxref{Readline
                   8890: Interaction, , Command Line Editing, readline, The GNU Readline
                   8891: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
                   8892: producing a full word completion every time you type it (instead of
1.28      crook    8893: producing the common prefix of all completions). @xref{Command-line editing}.
1.1       anton    8894: 
                   8895: @item character set:
                   8896: @cindex character set
                   8897: The character set of your computer and display device. Gforth is
                   8898: 8-bit-clean (but some other component in your system may make trouble).
                   8899: 
                   8900: @item Character-aligned address requirements:
                   8901: @cindex character-aligned address requirements
                   8902: installation-dependent. Currently a character is represented by a C
                   8903: @code{unsigned char}; in the future we might switch to @code{wchar_t}
                   8904: (Comments on that requested).
                   8905: 
                   8906: @item character-set extensions and matching of names:
                   8907: @cindex character-set extensions and matching of names
1.26      crook    8908: @cindex case-sensitivity for name lookup
                   8909: @cindex name lookup, case-sensitivity
                   8910: @cindex locale and case-sensitivity
1.21      crook    8911: Any character except the ASCII NUL character can be used in a
1.1       anton    8912: name. Matching is case-insensitive (except in @code{TABLE}s). The
                   8913: matching is performed using the C function @code{strncasecmp}, whose
                   8914: function is probably influenced by the locale. E.g., the @code{C} locale
                   8915: does not know about accents and umlauts, so they are matched
                   8916: case-sensitively in that locale. For portability reasons it is best to
                   8917: write programs such that they work in the @code{C} locale. Then one can
                   8918: use libraries written by a Polish programmer (who might use words
                   8919: containing ISO Latin-2 encoded characters) and by a French programmer
                   8920: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
                   8921: funny results for some of the words (which ones, depends on the font you
                   8922: are using)). Also, the locale you prefer may not be available in other
                   8923: operating systems. Hopefully, Unicode will solve these problems one day.
                   8924: 
                   8925: @item conditions under which control characters match a space delimiter:
                   8926: @cindex space delimiters
                   8927: @cindex control characters as delimiters
                   8928: If @code{WORD} is called with the space character as a delimiter, all
                   8929: white-space characters (as identified by the C macro @code{isspace()})
                   8930: are delimiters. @code{PARSE}, on the other hand, treats space like other
                   8931: delimiters. @code{PARSE-WORD} treats space like @code{WORD}, but behaves
                   8932: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
                   8933: interpreter (aka text interpreter) by default, treats all white-space
                   8934: characters as delimiters.
                   8935: 
1.26      crook    8936: @item format of the control-flow stack:
                   8937: @cindex control-flow stack, format
                   8938: The data stack is used as control-flow stack. The size of a control-flow
1.1       anton    8939: stack item in cells is given by the constant @code{cs-item-size}. At the
                   8940: time of this writing, an item consists of a (pointer to a) locals list
                   8941: (third), an address in the code (second), and a tag for identifying the
                   8942: item (TOS). The following tags are used: @code{defstart},
                   8943: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
                   8944: @code{scopestart}.
                   8945: 
                   8946: @item conversion of digits > 35
                   8947: @cindex digits > 35
                   8948: The characters @code{[\]^_'} are the digits with the decimal value
                   8949: 36@minus{}41. There is no way to input many of the larger digits.
                   8950: 
                   8951: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
                   8952: @cindex @code{EXPECT}, display after end of input
                   8953: @cindex @code{ACCEPT}, display after end of input
                   8954: The cursor is moved to the end of the entered string. If the input is
                   8955: terminated using the @kbd{Return} key, a space is typed.
                   8956: 
                   8957: @item exception abort sequence of @code{ABORT"}:
                   8958: @cindex exception abort sequence of @code{ABORT"}
                   8959: @cindex @code{ABORT"}, exception abort sequence
                   8960: The error string is stored into the variable @code{"error} and a
                   8961: @code{-2 throw} is performed.
                   8962: 
                   8963: @item input line terminator:
                   8964: @cindex input line terminator
                   8965: @cindex line terminator on input
1.26      crook    8966: @cindex newline character on input
1.1       anton    8967: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
                   8968: lines. One of these characters is typically produced when you type the
                   8969: @kbd{Enter} or @kbd{Return} key.
                   8970: 
                   8971: @item maximum size of a counted string:
                   8972: @cindex maximum size of a counted string
                   8973: @cindex counted string, maximum size
                   8974: @code{s" /counted-string" environment? drop .}. Currently 255 characters
                   8975: on all ports, but this may change.
                   8976: 
                   8977: @item maximum size of a parsed string:
                   8978: @cindex maximum size of a parsed string
                   8979: @cindex parsed string, maximum size
                   8980: Given by the constant @code{/line}. Currently 255 characters.
                   8981: 
                   8982: @item maximum size of a definition name, in characters:
                   8983: @cindex maximum size of a definition name, in characters
                   8984: @cindex name, maximum length
                   8985: 31
                   8986: 
                   8987: @item maximum string length for @code{ENVIRONMENT?}, in characters:
                   8988: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
                   8989: @cindex @code{ENVIRONMENT?} string length, maximum
                   8990: 31
                   8991: 
                   8992: @item method of selecting the user input device:
                   8993: @cindex user input device, method of selecting
                   8994: The user input device is the standard input. There is currently no way to
                   8995: change it from within Gforth. However, the input can typically be
                   8996: redirected in the command line that starts Gforth.
                   8997: 
                   8998: @item method of selecting the user output device:
                   8999: @cindex user output device, method of selecting
                   9000: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10      anton    9001: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
                   9002: output when the user output device is a terminal, otherwise the output
                   9003: is buffered.
1.1       anton    9004: 
                   9005: @item methods of dictionary compilation:
                   9006: What are we expected to document here?
                   9007: 
                   9008: @item number of bits in one address unit:
                   9009: @cindex number of bits in one address unit
                   9010: @cindex address unit, size in bits
                   9011: @code{s" address-units-bits" environment? drop .}. 8 in all current
                   9012: ports.
                   9013: 
                   9014: @item number representation and arithmetic:
                   9015: @cindex number representation and arithmetic
                   9016: Processor-dependent. Binary two's complement on all current ports.
                   9017: 
                   9018: @item ranges for integer types:
                   9019: @cindex ranges for integer types
                   9020: @cindex integer types, ranges
                   9021: Installation-dependent. Make environmental queries for @code{MAX-N},
                   9022: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
                   9023: unsigned (and positive) types is 0. The lower bound for signed types on
                   9024: two's complement and one's complement machines machines can be computed
                   9025: by adding 1 to the upper bound.
                   9026: 
                   9027: @item read-only data space regions:
                   9028: @cindex read-only data space regions
                   9029: @cindex data-space, read-only regions
                   9030: The whole Forth data space is writable.
                   9031: 
                   9032: @item size of buffer at @code{WORD}:
                   9033: @cindex size of buffer at @code{WORD}
                   9034: @cindex @code{WORD} buffer size
                   9035: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   9036: shared with the pictured numeric output string. If overwriting
                   9037: @code{PAD} is acceptable, it is as large as the remaining dictionary
                   9038: space, although only as much can be sensibly used as fits in a counted
                   9039: string.
                   9040: 
                   9041: @item size of one cell in address units:
                   9042: @cindex cell size
                   9043: @code{1 cells .}.
                   9044: 
                   9045: @item size of one character in address units:
                   9046: @cindex char size
                   9047: @code{1 chars .}. 1 on all current ports.
                   9048: 
                   9049: @item size of the keyboard terminal buffer:
                   9050: @cindex size of the keyboard terminal buffer
                   9051: @cindex terminal buffer, size
                   9052: Varies. You can determine the size at a specific time using @code{lp@@
                   9053: tib - .}. It is shared with the locals stack and TIBs of files that
                   9054: include the current file. You can change the amount of space for TIBs
                   9055: and locals stack at Gforth startup with the command line option
                   9056: @code{-l}.
                   9057: 
                   9058: @item size of the pictured numeric output buffer:
                   9059: @cindex size of the pictured numeric output buffer
                   9060: @cindex pictured numeric output buffer, size
                   9061: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   9062: shared with @code{WORD}.
                   9063: 
                   9064: @item size of the scratch area returned by @code{PAD}:
                   9065: @cindex size of the scratch area returned by @code{PAD}
                   9066: @cindex @code{PAD} size
                   9067: The remainder of dictionary space. @code{unused pad here - - .}.
                   9068: 
                   9069: @item system case-sensitivity characteristics:
                   9070: @cindex case-sensitivity characteristics
1.26      crook    9071: Dictionary searches are case-insensitive (except in
1.1       anton    9072: @code{TABLE}s). However, as explained above under @i{character-set
                   9073: extensions}, the matching for non-ASCII characters is determined by the
                   9074: locale you are using. In the default @code{C} locale all non-ASCII
                   9075: characters are matched case-sensitively.
                   9076: 
                   9077: @item system prompt:
                   9078: @cindex system prompt
                   9079: @cindex prompt
                   9080: @code{ ok} in interpret state, @code{ compiled} in compile state.
                   9081: 
                   9082: @item division rounding:
                   9083: @cindex division rounding
                   9084: installation dependent. @code{s" floored" environment? drop .}. We leave
                   9085: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
                   9086: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
                   9087: 
                   9088: @item values of @code{STATE} when true:
                   9089: @cindex @code{STATE} values
                   9090: -1.
                   9091: 
                   9092: @item values returned after arithmetic overflow:
                   9093: On two's complement machines, arithmetic is performed modulo
                   9094: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   9095: arithmetic (with appropriate mapping for signed types). Division by zero
                   9096: typically results in a @code{-55 throw} (Floating-point unidentified
                   9097: fault), although a @code{-10 throw} (divide by zero) would be more
                   9098: appropriate.
                   9099: 
                   9100: @item whether the current definition can be found after @t{DOES>}:
                   9101: @cindex @t{DOES>}, visibility of current definition
                   9102: No.
                   9103: 
                   9104: @end table
                   9105: 
                   9106: @c ---------------------------------------------------------------------
                   9107: @node core-ambcond, core-other, core-idef, The Core Words
                   9108: @subsection Ambiguous conditions
                   9109: @c ---------------------------------------------------------------------
                   9110: @cindex core words, ambiguous conditions
                   9111: @cindex ambiguous conditions, core words
                   9112: 
                   9113: @table @i
                   9114: 
                   9115: @item a name is neither a word nor a number:
                   9116: @cindex name not found
1.26      crook    9117: @cindex undefined word
1.1       anton    9118: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
                   9119: preserves the data and FP stack, so you don't lose more work than
                   9120: necessary.
                   9121: 
                   9122: @item a definition name exceeds the maximum length allowed:
1.26      crook    9123: @cindex word name too long
1.1       anton    9124: @code{-19 throw} (Word name too long)
                   9125: 
                   9126: @item addressing a region not inside the various data spaces of the forth system:
                   9127: @cindex Invalid memory address
                   9128: The stacks, code space and name space are accessible. Machine code space is
                   9129: typically readable. Accessing other addresses gives results dependent on
                   9130: the operating system. On decent systems: @code{-9 throw} (Invalid memory
                   9131: address).
                   9132: 
                   9133: @item argument type incompatible with parameter:
1.26      crook    9134: @cindex argument type mismatch
1.1       anton    9135: This is usually not caught. Some words perform checks, e.g., the control
                   9136: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
                   9137: mismatch).
                   9138: 
                   9139: @item attempting to obtain the execution token of a word with undefined execution semantics:
                   9140: @cindex Interpreting a compile-only word, for @code{'} etc.
                   9141: @cindex execution token of words with undefined execution semantics
                   9142: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
                   9143: get an execution token for @code{compile-only-error} (which performs a
                   9144: @code{-14 throw} when executed).
                   9145: 
                   9146: @item dividing by zero:
                   9147: @cindex dividing by zero
                   9148: @cindex floating point unidentified fault, integer division
1.24      anton    9149: On better platforms, this produces a @code{-10 throw} (Division by
                   9150: zero); on other systems, this typically results in a @code{-55 throw}
                   9151: (Floating-point unidentified fault).
1.1       anton    9152: 
                   9153: @item insufficient data stack or return stack space:
                   9154: @cindex insufficient data stack or return stack space
                   9155: @cindex stack overflow
1.26      crook    9156: @cindex address alignment exception, stack overflow
1.1       anton    9157: @cindex Invalid memory address, stack overflow
                   9158: Depending on the operating system, the installation, and the invocation
                   9159: of Gforth, this is either checked by the memory management hardware, or
1.24      anton    9160: it is not checked. If it is checked, you typically get a @code{-3 throw}
                   9161: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
                   9162: throw} (Invalid memory address) (depending on the platform and how you
                   9163: achieved the overflow) as soon as the overflow happens. If it is not
                   9164: checked, overflows typically result in mysterious illegal memory
                   9165: accesses, producing @code{-9 throw} (Invalid memory address) or
                   9166: @code{-23 throw} (Address alignment exception); they might also destroy
                   9167: the internal data structure of @code{ALLOCATE} and friends, resulting in
                   9168: various errors in these words.
1.1       anton    9169: 
                   9170: @item insufficient space for loop control parameters:
                   9171: @cindex insufficient space for loop control parameters
                   9172: like other return stack overflows.
                   9173: 
                   9174: @item insufficient space in the dictionary:
                   9175: @cindex insufficient space in the dictionary
                   9176: @cindex dictionary overflow
1.12      anton    9177: If you try to allot (either directly with @code{allot}, or indirectly
                   9178: with @code{,}, @code{create} etc.) more memory than available in the
                   9179: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
                   9180: to access memory beyond the end of the dictionary, the results are
                   9181: similar to stack overflows.
1.1       anton    9182: 
                   9183: @item interpreting a word with undefined interpretation semantics:
                   9184: @cindex interpreting a word with undefined interpretation semantics
                   9185: @cindex Interpreting a compile-only word
                   9186: For some words, we have defined interpretation semantics. For the
                   9187: others: @code{-14 throw} (Interpreting a compile-only word).
                   9188: 
                   9189: @item modifying the contents of the input buffer or a string literal:
                   9190: @cindex modifying the contents of the input buffer or a string literal
                   9191: These are located in writable memory and can be modified.
                   9192: 
                   9193: @item overflow of the pictured numeric output string:
                   9194: @cindex overflow of the pictured numeric output string
                   9195: @cindex pictured numeric output string, overflow
1.24      anton    9196: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1       anton    9197: 
                   9198: @item parsed string overflow:
                   9199: @cindex parsed string overflow
                   9200: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
                   9201: 
                   9202: @item producing a result out of range:
                   9203: @cindex result out of range
                   9204: On two's complement machines, arithmetic is performed modulo
                   9205: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   9206: arithmetic (with appropriate mapping for signed types). Division by zero
1.24      anton    9207: typically results in a @code{-10 throw} (divide by zero) or @code{-55
                   9208: throw} (floating point unidentified fault). @code{convert} and
                   9209: @code{>number} currently overflow silently.
1.1       anton    9210: 
                   9211: @item reading from an empty data or return stack:
                   9212: @cindex stack empty
                   9213: @cindex stack underflow
1.24      anton    9214: @cindex return stack underflow
1.1       anton    9215: The data stack is checked by the outer (aka text) interpreter after
                   9216: every word executed. If it has underflowed, a @code{-4 throw} (Stack
                   9217: underflow) is performed. Apart from that, stacks may be checked or not,
1.24      anton    9218: depending on operating system, installation, and invocation. If they are
                   9219: caught by a check, they typically result in @code{-4 throw} (Stack
                   9220: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
                   9221: (Invalid memory address), depending on the platform and which stack
                   9222: underflows and by how much. Note that even if the system uses checking
                   9223: (through the MMU), your program may have to underflow by a significant
                   9224: number of stack items to trigger the reaction (the reason for this is
                   9225: that the MMU, and therefore the checking, works with a page-size
                   9226: granularity).  If there is no checking, the symptoms resulting from an
                   9227: underflow are similar to those from an overflow.  Unbalanced return
                   9228: stack errors result in a variaty of symptoms, including @code{-9 throw}
                   9229: (Invalid memory address) and Illegal Instruction (typically @code{-260
                   9230: throw}).
1.1       anton    9231: 
                   9232: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
                   9233: @cindex unexpected end of the input buffer
                   9234: @cindex zero-length string as a name
                   9235: @cindex Attempt to use zero-length string as a name
                   9236: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
                   9237: use zero-length string as a name). Words like @code{'} probably will not
                   9238: find what they search. Note that it is possible to create zero-length
                   9239: names with @code{nextname} (should it not?).
                   9240: 
                   9241: @item @code{>IN} greater than input buffer:
                   9242: @cindex @code{>IN} greater than input buffer
                   9243: The next invocation of a parsing word returns a string with length 0.
                   9244: 
                   9245: @item @code{RECURSE} appears after @code{DOES>}:
                   9246: @cindex @code{RECURSE} appears after @code{DOES>}
                   9247: Compiles a recursive call to the defining word, not to the defined word.
                   9248: 
                   9249: @item argument input source different than current input source for @code{RESTORE-INPUT}:
                   9250: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26      crook    9251: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1       anton    9252: @cindex @code{RESTORE-INPUT}, Argument type mismatch
                   9253: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
                   9254: the end of the file was reached), its source-id may be
                   9255: reused. Therefore, restoring an input source specification referencing a
                   9256: closed file may lead to unpredictable results instead of a @code{-12
                   9257: THROW}.
                   9258: 
                   9259: In the future, Gforth may be able to restore input source specifications
                   9260: from other than the current input source.
                   9261: 
                   9262: @item data space containing definitions gets de-allocated:
                   9263: @cindex data space containing definitions gets de-allocated
                   9264: Deallocation with @code{allot} is not checked. This typically results in
                   9265: memory access faults or execution of illegal instructions.
                   9266: 
                   9267: @item data space read/write with incorrect alignment:
                   9268: @cindex data space read/write with incorrect alignment
                   9269: @cindex alignment faults
1.26      crook    9270: @cindex address alignment exception
1.1       anton    9271: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12      anton    9272: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1       anton    9273: alignment turned on, incorrect alignment results in a @code{-9 throw}
                   9274: (Invalid memory address). There are reportedly some processors with
1.12      anton    9275: alignment restrictions that do not report violations.
1.1       anton    9276: 
                   9277: @item data space pointer not properly aligned, @code{,}, @code{C,}:
                   9278: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
                   9279: Like other alignment errors.
                   9280: 
                   9281: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
                   9282: Like other stack underflows.
                   9283: 
                   9284: @item loop control parameters not available:
                   9285: @cindex loop control parameters not available
                   9286: Not checked. The counted loop words simply assume that the top of return
                   9287: stack items are loop control parameters and behave accordingly.
                   9288: 
                   9289: @item most recent definition does not have a name (@code{IMMEDIATE}):
                   9290: @cindex most recent definition does not have a name (@code{IMMEDIATE})
                   9291: @cindex last word was headerless
                   9292: @code{abort" last word was headerless"}.
                   9293: 
                   9294: @item name not defined by @code{VALUE} used by @code{TO}:
                   9295: @cindex name not defined by @code{VALUE} used by @code{TO}
                   9296: @cindex @code{TO} on non-@code{VALUE}s
                   9297: @cindex Invalid name argument, @code{TO}
                   9298: @code{-32 throw} (Invalid name argument) (unless name is a local or was
                   9299: defined by @code{CONSTANT}; in the latter case it just changes the constant).
                   9300: 
                   9301: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
                   9302: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26      crook    9303: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1       anton    9304: @code{-13 throw} (Undefined word)
                   9305: 
                   9306: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
                   9307: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
                   9308: Gforth behaves as if they were of the same type. I.e., you can predict
                   9309: the behaviour by interpreting all parameters as, e.g., signed.
                   9310: 
                   9311: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
                   9312: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
                   9313: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
                   9314: compilation semantics of @code{TO}.
                   9315: 
                   9316: @item String longer than a counted string returned by @code{WORD}:
1.26      crook    9317: @cindex string longer than a counted string returned by @code{WORD}
1.1       anton    9318: @cindex @code{WORD}, string overflow
                   9319: Not checked. The string will be ok, but the count will, of course,
                   9320: contain only the least significant bits of the length.
                   9321: 
                   9322: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
                   9323: @cindex @code{LSHIFT}, large shift counts
                   9324: @cindex @code{RSHIFT}, large shift counts
                   9325: Processor-dependent. Typical behaviours are returning 0 and using only
                   9326: the low bits of the shift count.
                   9327: 
                   9328: @item word not defined via @code{CREATE}:
                   9329: @cindex @code{>BODY} of non-@code{CREATE}d words
                   9330: @code{>BODY} produces the PFA of the word no matter how it was defined.
                   9331: 
                   9332: @cindex @code{DOES>} of non-@code{CREATE}d words
                   9333: @code{DOES>} changes the execution semantics of the last defined word no
                   9334: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
                   9335: @code{CREATE , DOES>}.
                   9336: 
                   9337: @item words improperly used outside @code{<#} and @code{#>}:
                   9338: Not checked. As usual, you can expect memory faults.
                   9339: 
                   9340: @end table
                   9341: 
                   9342: 
                   9343: @c ---------------------------------------------------------------------
                   9344: @node core-other,  , core-ambcond, The Core Words
                   9345: @subsection Other system documentation
                   9346: @c ---------------------------------------------------------------------
                   9347: @cindex other system documentation, core words
                   9348: @cindex core words, other system documentation
                   9349: 
                   9350: @table @i
                   9351: @item nonstandard words using @code{PAD}:
                   9352: @cindex @code{PAD} use by nonstandard words
                   9353: None.
                   9354: 
                   9355: @item operator's terminal facilities available:
                   9356: @cindex operator's terminal facilities available
                   9357: After processing the command line, Gforth goes into interactive mode,
                   9358: and you can give commands to Gforth interactively. The actual facilities
                   9359: available depend on how you invoke Gforth.
                   9360: 
                   9361: @item program data space available:
                   9362: @cindex program data space available
                   9363: @cindex data space available
                   9364: @code{UNUSED .} gives the remaining dictionary space. The total
                   9365: dictionary space can be specified with the @code{-m} switch
                   9366: (@pxref{Invoking Gforth}) when Gforth starts up.
                   9367: 
                   9368: @item return stack space available:
                   9369: @cindex return stack space available
                   9370: You can compute the total return stack space in cells with
                   9371: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
                   9372: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
                   9373: 
                   9374: @item stack space available:
                   9375: @cindex stack space available
                   9376: You can compute the total data stack space in cells with
                   9377: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
                   9378: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
                   9379: 
                   9380: @item system dictionary space required, in address units:
                   9381: @cindex system dictionary space required, in address units
                   9382: Type @code{here forthstart - .} after startup. At the time of this
                   9383: writing, this gives 80080 (bytes) on a 32-bit system.
                   9384: @end table
                   9385: 
                   9386: 
                   9387: @c =====================================================================
                   9388: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
                   9389: @section The optional Block word set
                   9390: @c =====================================================================
                   9391: @cindex system documentation, block words
                   9392: @cindex block words, system documentation
                   9393: 
                   9394: @menu
                   9395: * block-idef::                  Implementation Defined Options
                   9396: * block-ambcond::               Ambiguous Conditions               
                   9397: * block-other::                 Other System Documentation                 
                   9398: @end menu
                   9399: 
                   9400: 
                   9401: @c ---------------------------------------------------------------------
                   9402: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
                   9403: @subsection Implementation Defined Options
                   9404: @c ---------------------------------------------------------------------
                   9405: @cindex implementation-defined options, block words
                   9406: @cindex block words, implementation-defined options
                   9407: 
                   9408: @table @i
                   9409: @item the format for display by @code{LIST}:
                   9410: @cindex @code{LIST} display format
                   9411: First the screen number is displayed, then 16 lines of 64 characters,
                   9412: each line preceded by the line number.
                   9413: 
                   9414: @item the length of a line affected by @code{\}:
                   9415: @cindex length of a line affected by @code{\}
                   9416: @cindex @code{\}, line length in blocks
                   9417: 64 characters.
                   9418: @end table
                   9419: 
                   9420: 
                   9421: @c ---------------------------------------------------------------------
                   9422: @node block-ambcond, block-other, block-idef, The optional Block word set
                   9423: @subsection Ambiguous conditions
                   9424: @c ---------------------------------------------------------------------
                   9425: @cindex block words, ambiguous conditions
                   9426: @cindex ambiguous conditions, block words
                   9427: 
                   9428: @table @i
                   9429: @item correct block read was not possible:
                   9430: @cindex block read not possible
                   9431: Typically results in a @code{throw} of some OS-derived value (between
                   9432: -512 and -2048). If the blocks file was just not long enough, blanks are
                   9433: supplied for the missing portion.
                   9434: 
                   9435: @item I/O exception in block transfer:
                   9436: @cindex I/O exception in block transfer
                   9437: @cindex block transfer, I/O exception
                   9438: Typically results in a @code{throw} of some OS-derived value (between
                   9439: -512 and -2048).
                   9440: 
                   9441: @item invalid block number:
                   9442: @cindex invalid block number
                   9443: @cindex block number invalid
                   9444: @code{-35 throw} (Invalid block number)
                   9445: 
                   9446: @item a program directly alters the contents of @code{BLK}:
                   9447: @cindex @code{BLK}, altering @code{BLK}
                   9448: The input stream is switched to that other block, at the same
                   9449: position. If the storing to @code{BLK} happens when interpreting
                   9450: non-block input, the system will get quite confused when the block ends.
                   9451: 
                   9452: @item no current block buffer for @code{UPDATE}:
                   9453: @cindex @code{UPDATE}, no current block buffer
                   9454: @code{UPDATE} has no effect.
                   9455: 
                   9456: @end table
                   9457: 
                   9458: @c ---------------------------------------------------------------------
                   9459: @node block-other,  , block-ambcond, The optional Block word set
                   9460: @subsection Other system documentation
                   9461: @c ---------------------------------------------------------------------
                   9462: @cindex other system documentation, block words
                   9463: @cindex block words, other system documentation
                   9464: 
                   9465: @table @i
                   9466: @item any restrictions a multiprogramming system places on the use of buffer addresses:
                   9467: No restrictions (yet).
                   9468: 
                   9469: @item the number of blocks available for source and data:
                   9470: depends on your disk space.
                   9471: 
                   9472: @end table
                   9473: 
                   9474: 
                   9475: @c =====================================================================
                   9476: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
                   9477: @section The optional Double Number word set
                   9478: @c =====================================================================
                   9479: @cindex system documentation, double words
                   9480: @cindex double words, system documentation
                   9481: 
                   9482: @menu
                   9483: * double-ambcond::              Ambiguous Conditions              
                   9484: @end menu
                   9485: 
                   9486: 
                   9487: @c ---------------------------------------------------------------------
                   9488: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
                   9489: @subsection Ambiguous conditions
                   9490: @c ---------------------------------------------------------------------
                   9491: @cindex double words, ambiguous conditions
                   9492: @cindex ambiguous conditions, double words
                   9493: 
                   9494: @table @i
1.29      crook    9495: @item @i{d} outside of range of @i{n} in @code{D>S}:
                   9496: @cindex @code{D>S}, @i{d} out of range of @i{n} 
                   9497: The least significant cell of @i{d} is produced.
1.1       anton    9498: 
                   9499: @end table
                   9500: 
                   9501: 
                   9502: @c =====================================================================
                   9503: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
                   9504: @section The optional Exception word set
                   9505: @c =====================================================================
                   9506: @cindex system documentation, exception words
                   9507: @cindex exception words, system documentation
                   9508: 
                   9509: @menu
                   9510: * exception-idef::              Implementation Defined Options              
                   9511: @end menu
                   9512: 
                   9513: 
                   9514: @c ---------------------------------------------------------------------
                   9515: @node exception-idef,  , The optional Exception word set, The optional Exception word set
                   9516: @subsection Implementation Defined Options
                   9517: @c ---------------------------------------------------------------------
                   9518: @cindex implementation-defined options, exception words
                   9519: @cindex exception words, implementation-defined options
                   9520: 
                   9521: @table @i
                   9522: @item @code{THROW}-codes used in the system:
                   9523: @cindex @code{THROW}-codes used in the system
                   9524: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29      crook    9525: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1       anton    9526: codes -512@minus{}-2047 are used for OS errors (for file and memory
                   9527: allocation operations). The mapping from OS error numbers to throw codes
                   9528: is -512@minus{}@code{errno}. One side effect of this mapping is that
                   9529: undefined OS errors produce a message with a strange number; e.g.,
                   9530: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
                   9531: @end table
                   9532: 
                   9533: @c =====================================================================
                   9534: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
                   9535: @section The optional Facility word set
                   9536: @c =====================================================================
                   9537: @cindex system documentation, facility words
                   9538: @cindex facility words, system documentation
                   9539: 
                   9540: @menu
                   9541: * facility-idef::               Implementation Defined Options               
                   9542: * facility-ambcond::            Ambiguous Conditions            
                   9543: @end menu
                   9544: 
                   9545: 
                   9546: @c ---------------------------------------------------------------------
                   9547: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
                   9548: @subsection Implementation Defined Options
                   9549: @c ---------------------------------------------------------------------
                   9550: @cindex implementation-defined options, facility words
                   9551: @cindex facility words, implementation-defined options
                   9552: 
                   9553: @table @i
                   9554: @item encoding of keyboard events (@code{EKEY}):
                   9555: @cindex keyboard events, encoding in @code{EKEY}
                   9556: @cindex @code{EKEY}, encoding of keyboard events
                   9557: Not yet implemented.
                   9558: 
                   9559: @item duration of a system clock tick:
                   9560: @cindex duration of a system clock tick
                   9561: @cindex clock tick duration
                   9562: System dependent. With respect to @code{MS}, the time is specified in
                   9563: microseconds. How well the OS and the hardware implement this, is
                   9564: another question.
                   9565: 
                   9566: @item repeatability to be expected from the execution of @code{MS}:
                   9567: @cindex repeatability to be expected from the execution of @code{MS}
                   9568: @cindex @code{MS}, repeatability to be expected
                   9569: System dependent. On Unix, a lot depends on load. If the system is
                   9570: lightly loaded, and the delay is short enough that Gforth does not get
                   9571: swapped out, the performance should be acceptable. Under MS-DOS and
                   9572: other single-tasking systems, it should be good.
                   9573: 
                   9574: @end table
                   9575: 
                   9576: 
                   9577: @c ---------------------------------------------------------------------
                   9578: @node facility-ambcond,  , facility-idef, The optional Facility word set
                   9579: @subsection Ambiguous conditions
                   9580: @c ---------------------------------------------------------------------
                   9581: @cindex facility words, ambiguous conditions
                   9582: @cindex ambiguous conditions, facility words
                   9583: 
                   9584: @table @i
                   9585: @item @code{AT-XY} can't be performed on user output device:
                   9586: @cindex @code{AT-XY} can't be performed on user output device
                   9587: Largely terminal dependent. No range checks are done on the arguments.
                   9588: No errors are reported. You may see some garbage appearing, you may see
                   9589: simply nothing happen.
                   9590: 
                   9591: @end table
                   9592: 
                   9593: 
                   9594: @c =====================================================================
                   9595: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
                   9596: @section The optional File-Access word set
                   9597: @c =====================================================================
                   9598: @cindex system documentation, file words
                   9599: @cindex file words, system documentation
                   9600: 
                   9601: @menu
                   9602: * file-idef::                   Implementation Defined Options
                   9603: * file-ambcond::                Ambiguous Conditions                
                   9604: @end menu
                   9605: 
                   9606: @c ---------------------------------------------------------------------
                   9607: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
                   9608: @subsection Implementation Defined Options
                   9609: @c ---------------------------------------------------------------------
                   9610: @cindex implementation-defined options, file words
                   9611: @cindex file words, implementation-defined options
                   9612: 
                   9613: @table @i
                   9614: @item file access methods used:
                   9615: @cindex file access methods used
                   9616: @code{R/O}, @code{R/W} and @code{BIN} work as you would
                   9617: expect. @code{W/O} translates into the C file opening mode @code{w} (or
                   9618: @code{wb}): The file is cleared, if it exists, and created, if it does
                   9619: not (with both @code{open-file} and @code{create-file}).  Under Unix
                   9620: @code{create-file} creates a file with 666 permissions modified by your
                   9621: umask.
                   9622: 
                   9623: @item file exceptions:
                   9624: @cindex file exceptions
                   9625: The file words do not raise exceptions (except, perhaps, memory access
                   9626: faults when you pass illegal addresses or file-ids).
                   9627: 
                   9628: @item file line terminator:
                   9629: @cindex file line terminator
                   9630: System-dependent. Gforth uses C's newline character as line
                   9631: terminator. What the actual character code(s) of this are is
                   9632: system-dependent.
                   9633: 
                   9634: @item file name format:
                   9635: @cindex file name format
                   9636: System dependent. Gforth just uses the file name format of your OS.
                   9637: 
                   9638: @item information returned by @code{FILE-STATUS}:
                   9639: @cindex @code{FILE-STATUS}, returned information
                   9640: @code{FILE-STATUS} returns the most powerful file access mode allowed
                   9641: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
                   9642: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
                   9643: along with the returned mode.
                   9644: 
                   9645: @item input file state after an exception when including source:
                   9646: @cindex exception when including source
                   9647: All files that are left via the exception are closed.
                   9648: 
1.29      crook    9649: @item @i{ior} values and meaning:
                   9650: @cindex @i{ior} values and meaning
                   9651: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    9652: intended as throw codes. They typically are in the range
                   9653: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    9654: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    9655: 
                   9656: @item maximum depth of file input nesting:
                   9657: @cindex maximum depth of file input nesting
                   9658: @cindex file input nesting, maximum depth
                   9659: limited by the amount of return stack, locals/TIB stack, and the number
                   9660: of open files available. This should not give you troubles.
                   9661: 
                   9662: @item maximum size of input line:
                   9663: @cindex maximum size of input line
                   9664: @cindex input line size, maximum
                   9665: @code{/line}. Currently 255.
                   9666: 
                   9667: @item methods of mapping block ranges to files:
                   9668: @cindex mapping block ranges to files
                   9669: @cindex files containing blocks
                   9670: @cindex blocks in files
                   9671: By default, blocks are accessed in the file @file{blocks.fb} in the
                   9672: current working directory. The file can be switched with @code{USE}.
                   9673: 
                   9674: @item number of string buffers provided by @code{S"}:
                   9675: @cindex @code{S"}, number of string buffers
                   9676: 1
                   9677: 
                   9678: @item size of string buffer used by @code{S"}:
                   9679: @cindex @code{S"}, size of string buffer
                   9680: @code{/line}. currently 255.
                   9681: 
                   9682: @end table
                   9683: 
                   9684: @c ---------------------------------------------------------------------
                   9685: @node file-ambcond,  , file-idef, The optional File-Access word set
                   9686: @subsection Ambiguous conditions
                   9687: @c ---------------------------------------------------------------------
                   9688: @cindex file words, ambiguous conditions
                   9689: @cindex ambiguous conditions, file words
                   9690: 
                   9691: @table @i
                   9692: @item attempting to position a file outside its boundaries:
                   9693: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
                   9694: @code{REPOSITION-FILE} is performed as usual: Afterwards,
                   9695: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
                   9696: 
                   9697: @item attempting to read from file positions not yet written:
                   9698: @cindex reading from file positions not yet written
                   9699: End-of-file, i.e., zero characters are read and no error is reported.
                   9700: 
1.29      crook    9701: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
                   9702: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
1.1       anton    9703: An appropriate exception may be thrown, but a memory fault or other
                   9704: problem is more probable.
                   9705: 
1.29      crook    9706: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
                   9707: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
                   9708: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
                   9709: The @i{ior} produced by the operation, that discovered the problem, is
1.1       anton    9710: thrown.
                   9711: 
                   9712: @item named file cannot be opened (@code{INCLUDED}):
                   9713: @cindex @code{INCLUDED}, named file cannot be opened
1.29      crook    9714: The @i{ior} produced by @code{open-file} is thrown.
1.1       anton    9715: 
                   9716: @item requesting an unmapped block number:
                   9717: @cindex unmapped block numbers
                   9718: There are no unmapped legal block numbers. On some operating systems,
                   9719: writing a block with a large number may overflow the file system and
                   9720: have an error message as consequence.
                   9721: 
                   9722: @item using @code{source-id} when @code{blk} is non-zero:
                   9723: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
                   9724: @code{source-id} performs its function. Typically it will give the id of
                   9725: the source which loaded the block. (Better ideas?)
                   9726: 
                   9727: @end table
                   9728: 
                   9729: 
                   9730: @c =====================================================================
                   9731: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
                   9732: @section The optional Floating-Point word set
                   9733: @c =====================================================================
                   9734: @cindex system documentation, floating-point words
                   9735: @cindex floating-point words, system documentation
                   9736: 
                   9737: @menu
                   9738: * floating-idef::               Implementation Defined Options
                   9739: * floating-ambcond::            Ambiguous Conditions            
                   9740: @end menu
                   9741: 
                   9742: 
                   9743: @c ---------------------------------------------------------------------
                   9744: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
                   9745: @subsection Implementation Defined Options
                   9746: @c ---------------------------------------------------------------------
                   9747: @cindex implementation-defined options, floating-point words
                   9748: @cindex floating-point words, implementation-defined options
                   9749: 
                   9750: @table @i
                   9751: @item format and range of floating point numbers:
                   9752: @cindex format and range of floating point numbers
                   9753: @cindex floating point numbers, format and range
                   9754: System-dependent; the @code{double} type of C.
                   9755: 
1.29      crook    9756: @item results of @code{REPRESENT} when @i{float} is out of range:
                   9757: @cindex  @code{REPRESENT}, results when @i{float} is out of range
1.1       anton    9758: System dependent; @code{REPRESENT} is implemented using the C library
                   9759: function @code{ecvt()} and inherits its behaviour in this respect.
                   9760: 
                   9761: @item rounding or truncation of floating-point numbers:
                   9762: @cindex rounding of floating-point numbers
                   9763: @cindex truncation of floating-point numbers
                   9764: @cindex floating-point numbers, rounding or truncation
                   9765: System dependent; the rounding behaviour is inherited from the hosting C
                   9766: compiler. IEEE-FP-based (i.e., most) systems by default round to
                   9767: nearest, and break ties by rounding to even (i.e., such that the last
                   9768: bit of the mantissa is 0).
                   9769: 
                   9770: @item size of floating-point stack:
                   9771: @cindex floating-point stack size
                   9772: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
                   9773: the floating-point stack (in floats). You can specify this on startup
                   9774: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
                   9775: 
                   9776: @item width of floating-point stack:
                   9777: @cindex floating-point stack width 
                   9778: @code{1 floats}.
                   9779: 
                   9780: @end table
                   9781: 
                   9782: 
                   9783: @c ---------------------------------------------------------------------
                   9784: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
                   9785: @subsection Ambiguous conditions
                   9786: @c ---------------------------------------------------------------------
                   9787: @cindex floating-point words, ambiguous conditions
                   9788: @cindex ambiguous conditions, floating-point words
                   9789: 
                   9790: @table @i
                   9791: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
                   9792: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
                   9793: System-dependent. Typically results in a @code{-23 THROW} like other
                   9794: alignment violations.
                   9795: 
                   9796: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
                   9797: @cindex @code{f@@} used with an address that is not float aligned
                   9798: @cindex @code{f!} used with an address that is not float aligned
                   9799: System-dependent. Typically results in a @code{-23 THROW} like other
                   9800: alignment violations.
                   9801: 
                   9802: @item floating-point result out of range:
                   9803: @cindex floating-point result out of range
                   9804: System-dependent. Can result in a @code{-55 THROW} (Floating-point
                   9805: unidentified fault), or can produce a special value representing, e.g.,
                   9806: Infinity.
                   9807: 
                   9808: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
                   9809: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
                   9810: System-dependent. Typically results in an alignment fault like other
                   9811: alignment violations.
                   9812: 
                   9813: @item @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
                   9814: @cindex @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
                   9815: The floating-point number is converted into decimal nonetheless.
                   9816: 
                   9817: @item Both arguments are equal to zero (@code{FATAN2}):
                   9818: @cindex @code{FATAN2}, both arguments are equal to zero
                   9819: System-dependent. @code{FATAN2} is implemented using the C library
                   9820: function @code{atan2()}.
                   9821: 
1.29      crook    9822: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
                   9823: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
                   9824: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1       anton    9825: because of small errors and the tan will be a very large (or very small)
                   9826: but finite number.
                   9827: 
1.29      crook    9828: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
                   9829: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1       anton    9830: The result is rounded to the nearest float.
                   9831: 
                   9832: @item dividing by zero:
                   9833: @cindex dividing by zero, floating-point
                   9834: @cindex floating-point dividing by zero
                   9835: @cindex floating-point unidentified fault, FP divide-by-zero
                   9836: @code{-55 throw} (Floating-point unidentified fault)
                   9837: 
                   9838: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
                   9839: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
                   9840: System dependent. On IEEE-FP based systems the number is converted into
                   9841: an infinity.
                   9842: 
1.29      crook    9843: @item @i{float}<1 (@code{FACOSH}):
                   9844: @cindex @code{FACOSH}, @i{float}<1
1.1       anton    9845: @cindex floating-point unidentified fault, @code{FACOSH}
                   9846: @code{-55 throw} (Floating-point unidentified fault)
                   9847: 
1.29      crook    9848: @item @i{float}=<-1 (@code{FLNP1}):
                   9849: @cindex @code{FLNP1}, @i{float}=<-1
1.1       anton    9850: @cindex floating-point unidentified fault, @code{FLNP1}
                   9851: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29      crook    9852: negative infinity is typically produced for @i{float}=-1.
1.1       anton    9853: 
1.29      crook    9854: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
                   9855: @cindex @code{FLN}, @i{float}=<0
                   9856: @cindex @code{FLOG}, @i{float}=<0
1.1       anton    9857: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
                   9858: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29      crook    9859: negative infinity is typically produced for @i{float}=0.
1.1       anton    9860: 
1.29      crook    9861: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
                   9862: @cindex @code{FASINH}, @i{float}<0
                   9863: @cindex @code{FSQRT}, @i{float}<0
1.1       anton    9864: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
                   9865: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
                   9866: produces values for these inputs on my Linux box (Bug in the C library?)
                   9867: 
1.29      crook    9868: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
                   9869: @cindex @code{FACOS}, |@i{float}|>1
                   9870: @cindex @code{FASIN}, |@i{float}|>1
                   9871: @cindex @code{FATANH}, |@i{float}|>1
1.1       anton    9872: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
                   9873: @code{-55 throw} (Floating-point unidentified fault).
                   9874: 
1.29      crook    9875: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
                   9876: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1       anton    9877: @cindex floating-point unidentified fault, @code{F>D}
                   9878: @code{-55 throw} (Floating-point unidentified fault).
                   9879: 
                   9880: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
                   9881: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
                   9882: This does not happen.
                   9883: @end table
                   9884: 
                   9885: @c =====================================================================
                   9886: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
                   9887: @section The optional Locals word set
                   9888: @c =====================================================================
                   9889: @cindex system documentation, locals words
                   9890: @cindex locals words, system documentation
                   9891: 
                   9892: @menu
                   9893: * locals-idef::                 Implementation Defined Options                 
                   9894: * locals-ambcond::              Ambiguous Conditions              
                   9895: @end menu
                   9896: 
                   9897: 
                   9898: @c ---------------------------------------------------------------------
                   9899: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
                   9900: @subsection Implementation Defined Options
                   9901: @c ---------------------------------------------------------------------
                   9902: @cindex implementation-defined options, locals words
                   9903: @cindex locals words, implementation-defined options
                   9904: 
                   9905: @table @i
                   9906: @item maximum number of locals in a definition:
                   9907: @cindex maximum number of locals in a definition
                   9908: @cindex locals, maximum number in a definition
                   9909: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
                   9910: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
                   9911: characters. The number of locals in a definition is bounded by the size
                   9912: of locals-buffer, which contains the names of the locals.
                   9913: 
                   9914: @end table
                   9915: 
                   9916: 
                   9917: @c ---------------------------------------------------------------------
                   9918: @node locals-ambcond,  , locals-idef, The optional Locals word set
                   9919: @subsection Ambiguous conditions
                   9920: @c ---------------------------------------------------------------------
                   9921: @cindex locals words, ambiguous conditions
                   9922: @cindex ambiguous conditions, locals words
                   9923: 
                   9924: @table @i
                   9925: @item executing a named local in interpretation state:
                   9926: @cindex local in interpretation state
                   9927: @cindex Interpreting a compile-only word, for a local
                   9928: Locals have no interpretation semantics. If you try to perform the
                   9929: interpretation semantics, you will get a @code{-14 throw} somewhere
                   9930: (Interpreting a compile-only word). If you perform the compilation
                   9931: semantics, the locals access will be compiled (irrespective of state).
                   9932: 
1.29      crook    9933: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1       anton    9934: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
                   9935: @cindex @code{TO} on non-@code{VALUE}s and non-locals
                   9936: @cindex Invalid name argument, @code{TO}
                   9937: @code{-32 throw} (Invalid name argument)
                   9938: 
                   9939: @end table
                   9940: 
                   9941: 
                   9942: @c =====================================================================
                   9943: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
                   9944: @section The optional Memory-Allocation word set
                   9945: @c =====================================================================
                   9946: @cindex system documentation, memory-allocation words
                   9947: @cindex memory-allocation words, system documentation
                   9948: 
                   9949: @menu
                   9950: * memory-idef::                 Implementation Defined Options                 
                   9951: @end menu
                   9952: 
                   9953: 
                   9954: @c ---------------------------------------------------------------------
                   9955: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
                   9956: @subsection Implementation Defined Options
                   9957: @c ---------------------------------------------------------------------
                   9958: @cindex implementation-defined options, memory-allocation words
                   9959: @cindex memory-allocation words, implementation-defined options
                   9960: 
                   9961: @table @i
1.29      crook    9962: @item values and meaning of @i{ior}:
                   9963: @cindex  @i{ior} values and meaning
                   9964: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    9965: intended as throw codes. They typically are in the range
                   9966: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    9967: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    9968: 
                   9969: @end table
                   9970: 
                   9971: @c =====================================================================
                   9972: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
                   9973: @section The optional Programming-Tools word set
                   9974: @c =====================================================================
                   9975: @cindex system documentation, programming-tools words
                   9976: @cindex programming-tools words, system documentation
                   9977: 
                   9978: @menu
                   9979: * programming-idef::            Implementation Defined Options            
                   9980: * programming-ambcond::         Ambiguous Conditions         
                   9981: @end menu
                   9982: 
                   9983: 
                   9984: @c ---------------------------------------------------------------------
                   9985: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
                   9986: @subsection Implementation Defined Options
                   9987: @c ---------------------------------------------------------------------
                   9988: @cindex implementation-defined options, programming-tools words
                   9989: @cindex programming-tools words, implementation-defined options
                   9990: 
                   9991: @table @i
                   9992: @item ending sequence for input following @code{;CODE} and @code{CODE}:
                   9993: @cindex @code{;CODE} ending sequence
                   9994: @cindex @code{CODE} ending sequence
                   9995: @code{END-CODE}
                   9996: 
                   9997: @item manner of processing input following @code{;CODE} and @code{CODE}:
                   9998: @cindex @code{;CODE}, processing input
                   9999: @cindex @code{CODE}, processing input
                   10000: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
                   10001: the input is processed by the text interpreter, (starting) in interpret
                   10002: state.
                   10003: 
                   10004: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
                   10005: @cindex @code{ASSEMBLER}, search order capability
                   10006: The ANS Forth search order word set.
                   10007: 
                   10008: @item source and format of display by @code{SEE}:
                   10009: @cindex @code{SEE}, source and format of output
                   10010: The source for @code{see} is the intermediate code used by the inner
                   10011: interpreter.  The current @code{see} tries to output Forth source code
                   10012: as well as possible.
                   10013: 
                   10014: @end table
                   10015: 
                   10016: @c ---------------------------------------------------------------------
                   10017: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
                   10018: @subsection Ambiguous conditions
                   10019: @c ---------------------------------------------------------------------
                   10020: @cindex programming-tools words, ambiguous conditions
                   10021: @cindex ambiguous conditions, programming-tools words
                   10022: 
                   10023: @table @i
                   10024: 
1.21      crook    10025: @item deleting the compilation word list (@code{FORGET}):
                   10026: @cindex @code{FORGET}, deleting the compilation word list
1.1       anton    10027: Not implemented (yet).
                   10028: 
1.29      crook    10029: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
                   10030: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
                   10031: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1       anton    10032: @cindex control-flow stack underflow
                   10033: This typically results in an @code{abort"} with a descriptive error
                   10034: message (may change into a @code{-22 throw} (Control structure mismatch)
                   10035: in the future). You may also get a memory access error. If you are
                   10036: unlucky, this ambiguous condition is not caught.
                   10037: 
1.29      crook    10038: @item @i{name} can't be found (@code{FORGET}):
                   10039: @cindex @code{FORGET}, @i{name} can't be found
1.1       anton    10040: Not implemented (yet).
                   10041: 
1.29      crook    10042: @item @i{name} not defined via @code{CREATE}:
                   10043: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1       anton    10044: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
                   10045: the execution semantics of the last defined word no matter how it was
                   10046: defined.
                   10047: 
                   10048: @item @code{POSTPONE} applied to @code{[IF]}:
                   10049: @cindex @code{POSTPONE} applied to @code{[IF]}
                   10050: @cindex @code{[IF]} and @code{POSTPONE}
                   10051: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
                   10052: equivalent to @code{[IF]}.
                   10053: 
                   10054: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
                   10055: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
                   10056: Continue in the same state of conditional compilation in the next outer
                   10057: input source. Currently there is no warning to the user about this.
                   10058: 
                   10059: @item removing a needed definition (@code{FORGET}):
                   10060: @cindex @code{FORGET}, removing a needed definition
                   10061: Not implemented (yet).
                   10062: 
                   10063: @end table
                   10064: 
                   10065: 
                   10066: @c =====================================================================
                   10067: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
                   10068: @section The optional Search-Order word set
                   10069: @c =====================================================================
                   10070: @cindex system documentation, search-order words
                   10071: @cindex search-order words, system documentation
                   10072: 
                   10073: @menu
                   10074: * search-idef::                 Implementation Defined Options                 
                   10075: * search-ambcond::              Ambiguous Conditions              
                   10076: @end menu
                   10077: 
                   10078: 
                   10079: @c ---------------------------------------------------------------------
                   10080: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
                   10081: @subsection Implementation Defined Options
                   10082: @c ---------------------------------------------------------------------
                   10083: @cindex implementation-defined options, search-order words
                   10084: @cindex search-order words, implementation-defined options
                   10085: 
                   10086: @table @i
                   10087: @item maximum number of word lists in search order:
                   10088: @cindex maximum number of word lists in search order
                   10089: @cindex search order, maximum depth
                   10090: @code{s" wordlists" environment? drop .}. Currently 16.
                   10091: 
                   10092: @item minimum search order:
                   10093: @cindex minimum search order
                   10094: @cindex search order, minimum
                   10095: @code{root root}.
                   10096: 
                   10097: @end table
                   10098: 
                   10099: @c ---------------------------------------------------------------------
                   10100: @node search-ambcond,  , search-idef, The optional Search-Order word set
                   10101: @subsection Ambiguous conditions
                   10102: @c ---------------------------------------------------------------------
                   10103: @cindex search-order words, ambiguous conditions
                   10104: @cindex ambiguous conditions, search-order words
                   10105: 
                   10106: @table @i
1.21      crook    10107: @item changing the compilation word list (during compilation):
                   10108: @cindex changing the compilation word list (during compilation)
                   10109: @cindex compilation word list, change before definition ends
                   10110: The word is entered into the word list that was the compilation word list
1.1       anton    10111: at the start of the definition. Any changes to the name field (e.g.,
                   10112: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
                   10113: are applied to the latest defined word (as reported by @code{last} or
1.21      crook    10114: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1       anton    10115: 
                   10116: @item search order empty (@code{previous}):
                   10117: @cindex @code{previous}, search order empty
1.26      crook    10118: @cindex vocstack empty, @code{previous}
1.1       anton    10119: @code{abort" Vocstack empty"}.
                   10120: 
                   10121: @item too many word lists in search order (@code{also}):
                   10122: @cindex @code{also}, too many word lists in search order
1.26      crook    10123: @cindex vocstack full, @code{also}
1.1       anton    10124: @code{abort" Vocstack full"}.
                   10125: 
                   10126: @end table
                   10127: 
                   10128: @c ***************************************************************
                   10129: @node Model, Integrating Gforth, ANS conformance, Top
                   10130: @chapter Model
                   10131: 
                   10132: This chapter has yet to be written. It will contain information, on
                   10133: which internal structures you can rely.
                   10134: 
                   10135: @c ***************************************************************
                   10136: @node Integrating Gforth, Emacs and Gforth, Model, Top
                   10137: @chapter Integrating Gforth into C programs
                   10138: 
                   10139: This is not yet implemented.
                   10140: 
                   10141: Several people like to use Forth as scripting language for applications
                   10142: that are otherwise written in C, C++, or some other language.
                   10143: 
                   10144: The Forth system ATLAST provides facilities for embedding it into
                   10145: applications; unfortunately it has several disadvantages: most
                   10146: importantly, it is not based on ANS Forth, and it is apparently dead
                   10147: (i.e., not developed further and not supported). The facilities
1.21      crook    10148: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1       anton    10149: making the switch should not be hard.
                   10150: 
                   10151: We also tried to design the interface such that it can easily be
                   10152: implemented by other Forth systems, so that we may one day arrive at a
                   10153: standardized interface. Such a standard interface would allow you to
                   10154: replace the Forth system without having to rewrite C code.
                   10155: 
                   10156: You embed the Gforth interpreter by linking with the library
                   10157: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
                   10158: global symbols in this library that belong to the interface, have the
                   10159: prefix @code{forth_}. (Global symbols that are used internally have the
                   10160: prefix @code{gforth_}).
                   10161: 
                   10162: You can include the declarations of Forth types and the functions and
                   10163: variables of the interface with @code{#include <forth.h>}.
                   10164: 
                   10165: Types.
                   10166: 
                   10167: Variables.
                   10168: 
                   10169: Data and FP Stack pointer. Area sizes.
                   10170: 
                   10171: functions.
                   10172: 
                   10173: forth_init(imagefile)
                   10174: forth_evaluate(string) exceptions?
                   10175: forth_goto(address) (or forth_execute(xt)?)
                   10176: forth_continue() (a corountining mechanism)
                   10177: 
                   10178: Adding primitives.
                   10179: 
                   10180: No checking.
                   10181: 
                   10182: Signals?
                   10183: 
                   10184: Accessing the Stacks
                   10185: 
1.26      crook    10186: @c ******************************************************************
1.1       anton    10187: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
                   10188: @chapter Emacs and Gforth
                   10189: @cindex Emacs and Gforth
                   10190: 
                   10191: @cindex @file{gforth.el}
                   10192: @cindex @file{forth.el}
                   10193: @cindex Rydqvist, Goran
                   10194: @cindex comment editing commands
                   10195: @cindex @code{\}, editing with Emacs
                   10196: @cindex debug tracer editing commands
                   10197: @cindex @code{~~}, removal with Emacs
                   10198: @cindex Forth mode in Emacs
                   10199: Gforth comes with @file{gforth.el}, an improved version of
                   10200: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26      crook    10201: improvements are:
                   10202: 
                   10203: @itemize @bullet
                   10204: @item
                   10205: A better (but still not perfect) handling of indentation.
                   10206: @item
                   10207: Comment paragraph filling (@kbd{M-q})
                   10208: @item
                   10209: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
                   10210: @item
                   10211: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
                   10212: @end itemize
                   10213: 
                   10214: I left the stuff I do not use alone, even though some of it only makes
                   10215: sense for TILE. To get a description of these features, enter Forth mode
                   10216: and type @kbd{C-h m}.
1.1       anton    10217: 
                   10218: @cindex source location of error or debugging output in Emacs
                   10219: @cindex error output, finding the source location in Emacs
                   10220: @cindex debugging output, finding the source location in Emacs
                   10221: In addition, Gforth supports Emacs quite well: The source code locations
                   10222: given in error messages, debugging output (from @code{~~}) and failed
                   10223: assertion messages are in the right format for Emacs' compilation mode
                   10224: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
                   10225: Manual}) so the source location corresponding to an error or other
                   10226: message is only a few keystrokes away (@kbd{C-x `} for the next error,
                   10227: @kbd{C-c C-c} for the error under the cursor).
                   10228: 
                   10229: @cindex @file{TAGS} file
                   10230: @cindex @file{etags.fs}
                   10231: @cindex viewing the source of a word in Emacs
1.26      crook    10232: Also, if you @code{include} @file{etags.fs}, a new @file{TAGS} file will
                   10233: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1       anton    10234: contains the definitions of all words defined afterwards. You can then
                   10235: find the source for a word using @kbd{M-.}. Note that emacs can use
                   10236: several tags files at the same time (e.g., one for the Gforth sources
                   10237: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
                   10238: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
                   10239: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
                   10240: @file{/usr/local/share/gforth/0.2.0/TAGS}).
                   10241: 
                   10242: @cindex @file{.emacs}
                   10243: To get all these benefits, add the following lines to your @file{.emacs}
                   10244: file:
                   10245: 
                   10246: @example
                   10247: (autoload 'forth-mode "gforth.el")
                   10248: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
                   10249: @end example
                   10250: 
1.26      crook    10251: @c ******************************************************************
1.1       anton    10252: @node Image Files, Engine, Emacs and Gforth, Top
                   10253: @chapter Image Files
1.26      crook    10254: @cindex image file
                   10255: @cindex @file{.fi} files
1.1       anton    10256: @cindex precompiled Forth code
                   10257: @cindex dictionary in persistent form
                   10258: @cindex persistent form of dictionary
                   10259: 
                   10260: An image file is a file containing an image of the Forth dictionary,
                   10261: i.e., compiled Forth code and data residing in the dictionary.  By
                   10262: convention, we use the extension @code{.fi} for image files.
                   10263: 
                   10264: @menu
1.18      anton    10265: * Image Licensing Issues::      Distribution terms for images.
                   10266: * Image File Background::       Why have image files?
1.29      crook    10267: * Non-Relocatable Image Files::   don't always work.
1.18      anton    10268: * Data-Relocatable Image Files::  are better.
1.29      crook    10269: * Fully Relocatable Image Files:: better yet.
1.18      anton    10270: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.29      crook    10271: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.18      anton    10272: * Modifying the Startup Sequence::  and turnkey applications.
1.1       anton    10273: @end menu
                   10274: 
1.18      anton    10275: @node Image Licensing Issues, Image File Background, Image Files, Image Files
                   10276: @section Image Licensing Issues
                   10277: @cindex license for images
                   10278: @cindex image license
                   10279: 
                   10280: An image created with @code{gforthmi} (@pxref{gforthmi}) or
                   10281: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
                   10282: original image; i.e., according to copyright law it is a derived work of
                   10283: the original image.
                   10284: 
                   10285: Since Gforth is distributed under the GNU GPL, the newly created image
                   10286: falls under the GNU GPL, too. In particular, this means that if you
                   10287: distribute the image, you have to make all of the sources for the image
                   10288: available, including those you wrote.  For details see @ref{License, ,
                   10289: GNU General Public License (Section 3)}.
                   10290: 
                   10291: If you create an image with @code{cross} (@pxref{cross.fs}), the image
                   10292: contains only code compiled from the sources you gave it; if none of
                   10293: these sources is under the GPL, the terms discussed above do not apply
                   10294: to the image. However, if your image needs an engine (a gforth binary)
                   10295: that is under the GPL, you should make sure that you distribute both in
                   10296: a way that is at most a @emph{mere aggregation}, if you don't want the
                   10297: terms of the GPL to apply to the image.
                   10298: 
                   10299: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1       anton    10300: @section Image File Background
                   10301: @cindex image file background
                   10302: 
                   10303: Our Forth system consists not only of primitives, but also of
                   10304: definitions written in Forth. Since the Forth compiler itself belongs to
                   10305: those definitions, it is not possible to start the system with the
                   10306: primitives and the Forth source alone. Therefore we provide the Forth
1.26      crook    10307: code as an image file in nearly executable form. When Gforth starts up,
                   10308: a C routine loads the image file into memory, optionally relocates the
                   10309: addresses, then sets up the memory (stacks etc.) according to
                   10310: information in the image file, and (finally) starts executing Forth
                   10311: code.
1.1       anton    10312: 
                   10313: The image file variants represent different compromises between the
                   10314: goals of making it easy to generate image files and making them
                   10315: portable.
                   10316: 
                   10317: @cindex relocation at run-time
1.26      crook    10318: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1       anton    10319: run-time. This avoids many of the complications discussed below (image
                   10320: files are data relocatable without further ado), but costs performance
                   10321: (one addition per memory access).
                   10322: 
                   10323: @cindex relocation at load-time
1.26      crook    10324: By contrast, the Gforth loader performs relocation at image load time. The
                   10325: loader also has to replace tokens that represent primitive calls with the
1.1       anton    10326: appropriate code-field addresses (or code addresses in the case of
                   10327: direct threading).
                   10328: 
                   10329: There are three kinds of image files, with different degrees of
                   10330: relocatability: non-relocatable, data-relocatable, and fully relocatable
                   10331: image files.
                   10332: 
                   10333: @cindex image file loader
                   10334: @cindex relocating loader
                   10335: @cindex loader for image files
                   10336: These image file variants have several restrictions in common; they are
                   10337: caused by the design of the image file loader:
                   10338: 
                   10339: @itemize @bullet
                   10340: @item
                   10341: There is only one segment; in particular, this means, that an image file
                   10342: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26      crook    10343: them). The contents of the stacks are not represented, either.
1.1       anton    10344: 
                   10345: @item
                   10346: The only kinds of relocation supported are: adding the same offset to
                   10347: all cells that represent data addresses; and replacing special tokens
                   10348: with code addresses or with pieces of machine code.
                   10349: 
                   10350: If any complex computations involving addresses are performed, the
                   10351: results cannot be represented in the image file. Several applications that
                   10352: use such computations come to mind:
                   10353: @itemize @minus
                   10354: @item
                   10355: Hashing addresses (or data structures which contain addresses) for table
                   10356: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
                   10357: purpose, you will have no problem, because the hash tables are
                   10358: recomputed automatically when the system is started. If you use your own
                   10359: hash tables, you will have to do something similar.
                   10360: 
                   10361: @item
                   10362: There's a cute implementation of doubly-linked lists that uses
                   10363: @code{XOR}ed addresses. You could represent such lists as singly-linked
                   10364: in the image file, and restore the doubly-linked representation on
                   10365: startup.@footnote{In my opinion, though, you should think thrice before
                   10366: using a doubly-linked list (whatever implementation).}
                   10367: 
                   10368: @item
                   10369: The code addresses of run-time routines like @code{docol:} cannot be
                   10370: represented in the image file (because their tokens would be replaced by
                   10371: machine code in direct threaded implementations). As a workaround,
                   10372: compute these addresses at run-time with @code{>code-address} from the
                   10373: executions tokens of appropriate words (see the definitions of
                   10374: @code{docol:} and friends in @file{kernel.fs}).
                   10375: 
                   10376: @item
                   10377: On many architectures addresses are represented in machine code in some
                   10378: shifted or mangled form. You cannot put @code{CODE} words that contain
                   10379: absolute addresses in this form in a relocatable image file. Workarounds
                   10380: are representing the address in some relative form (e.g., relative to
                   10381: the CFA, which is present in some register), or loading the address from
                   10382: a place where it is stored in a non-mangled form.
                   10383: @end itemize
                   10384: @end itemize
                   10385: 
                   10386: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
                   10387: @section Non-Relocatable Image Files
                   10388: @cindex non-relocatable image files
1.26      crook    10389: @cindex image file, non-relocatable
1.1       anton    10390: 
                   10391: These files are simple memory dumps of the dictionary. They are specific
                   10392: to the executable (i.e., @file{gforth} file) they were created
                   10393: with. What's worse, they are specific to the place on which the
                   10394: dictionary resided when the image was created. Now, there is no
                   10395: guarantee that the dictionary will reside at the same place the next
                   10396: time you start Gforth, so there's no guarantee that a non-relocatable
                   10397: image will work the next time (Gforth will complain instead of crashing,
                   10398: though).
                   10399: 
                   10400: You can create a non-relocatable image file with
                   10401: 
                   10402: doc-savesystem
                   10403: 
                   10404: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
                   10405: @section Data-Relocatable Image Files
                   10406: @cindex data-relocatable image files
1.26      crook    10407: @cindex image file, data-relocatable
1.1       anton    10408: 
                   10409: These files contain relocatable data addresses, but fixed code addresses
                   10410: (instead of tokens). They are specific to the executable (i.e.,
                   10411: @file{gforth} file) they were created with. For direct threading on some
                   10412: architectures (e.g., the i386), data-relocatable images do not work. You
                   10413: get a data-relocatable image, if you use @file{gforthmi} with a
                   10414: Gforth binary that is not doubly indirect threaded (@pxref{Fully
                   10415: Relocatable Image Files}).
                   10416: 
                   10417: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
                   10418: @section Fully Relocatable Image Files
                   10419: @cindex fully relocatable image files
1.26      crook    10420: @cindex image file, fully relocatable
1.1       anton    10421: 
                   10422: @cindex @file{kern*.fi}, relocatability
                   10423: @cindex @file{gforth.fi}, relocatability
                   10424: These image files have relocatable data addresses, and tokens for code
                   10425: addresses. They can be used with different binaries (e.g., with and
                   10426: without debugging) on the same machine, and even across machines with
                   10427: the same data formats (byte order, cell size, floating point
                   10428: format). However, they are usually specific to the version of Gforth
                   10429: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
                   10430: are fully relocatable.
                   10431: 
                   10432: There are two ways to create a fully relocatable image file:
                   10433: 
                   10434: @menu
1.29      crook    10435: * gforthmi::                    The normal way
1.1       anton    10436: * cross.fs::                    The hard way
                   10437: @end menu
                   10438: 
                   10439: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
                   10440: @subsection @file{gforthmi}
                   10441: @cindex @file{comp-i.fs}
                   10442: @cindex @file{gforthmi}
                   10443: 
                   10444: You will usually use @file{gforthmi}. If you want to create an
1.29      crook    10445: image @i{file} that contains everything you would load by invoking
                   10446: Gforth with @code{gforth @i{options}}, you simply say:
1.1       anton    10447: @example
1.29      crook    10448: gforthmi @i{file} @i{options}
1.1       anton    10449: @end example
                   10450: 
                   10451: E.g., if you want to create an image @file{asm.fi} that has the file
                   10452: @file{asm.fs} loaded in addition to the usual stuff, you could do it
                   10453: like this:
                   10454: 
                   10455: @example
                   10456: gforthmi asm.fi asm.fs
                   10457: @end example
                   10458: 
1.27      crook    10459: @file{gforthmi} is implemented as a sh script and works like this: It
                   10460: produces two non-relocatable images for different addresses and then
                   10461: compares them. Its output reflects this: first you see the output (if
                   10462: any) of the two Gforth invocations that produce the nonrelocatable image
                   10463: files, then you see the output of the comparing program: It displays the
                   10464: offset used for data addresses and the offset used for code addresses;
1.1       anton    10465: moreover, for each cell that cannot be represented correctly in the
                   10466: image files, it displays a line like the following one:
                   10467: 
                   10468: @example
                   10469:      78DC         BFFFFA50         BFFFFA40
                   10470: @end example
                   10471: 
                   10472: This means that at offset $78dc from @code{forthstart}, one input image
                   10473: contains $bffffa50, and the other contains $bffffa40. Since these cells
                   10474: cannot be represented correctly in the output image, you should examine
                   10475: these places in the dictionary and verify that these cells are dead
                   10476: (i.e., not read before they are written).
                   10477: 
1.27      crook    10478: If you type @file{gforthmi} with no arguments, it prints some usage
                   10479: instructions.
                   10480: 
1.1       anton    10481: @cindex @code{savesystem} during @file{gforthmi}
                   10482: @cindex @code{bye} during @file{gforthmi}
                   10483: @cindex doubly indirect threaded code
                   10484: @cindex environment variable @code{GFORTHD}
                   10485: @cindex @code{GFORTHD} environment variable
                   10486: @cindex @code{gforth-ditc}
1.29      crook    10487: There are a few wrinkles: After processing the passed @i{options}, the
1.1       anton    10488: words @code{savesystem} and @code{bye} must be visible. A special doubly
                   10489: indirect threaded version of the @file{gforth} executable is used for
                   10490: creating the nonrelocatable images; you can pass the exact filename of
                   10491: this executable through the environment variable @code{GFORTHD}
                   10492: (default: @file{gforth-ditc}); if you pass a version that is not doubly
                   10493: indirect threaded, you will not get a fully relocatable image, but a
1.27      crook    10494: data-relocatable image (because there is no code address offset). The
                   10495: normal @file{gforth} executable is used for creating the relocatable
                   10496: image; you can pass the exact filename of this executable through the
                   10497: environment variable @code{GFORTH}.
1.1       anton    10498: 
                   10499: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
                   10500: @subsection @file{cross.fs}
                   10501: @cindex @file{cross.fs}
                   10502: @cindex cross-compiler
                   10503: @cindex metacompiler
                   10504: 
                   10505: You can also use @code{cross}, a batch compiler that accepts a Forth-like
                   10506: programming language. This @code{cross} language has to be documented
                   10507: yet.
                   10508: 
                   10509: @cindex target compiler
                   10510: @code{cross} also allows you to create image files for machines with
                   10511: different data sizes and data formats than the one used for generating
                   10512: the image file. You can also use it to create an application image that
                   10513: does not contain a Forth compiler. These features are bought with
                   10514: restrictions and inconveniences in programming. E.g., addresses have to
                   10515: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
                   10516: order to make the code relocatable.
                   10517: 
                   10518: 
                   10519: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
                   10520: @section Stack and Dictionary Sizes
                   10521: @cindex image file, stack and dictionary sizes
                   10522: @cindex dictionary size default
                   10523: @cindex stack size default
                   10524: 
                   10525: If you invoke Gforth with a command line flag for the size
                   10526: (@pxref{Invoking Gforth}), the size you specify is stored in the
                   10527: dictionary. If you save the dictionary with @code{savesystem} or create
                   10528: an image with @file{gforthmi}, this size will become the default
                   10529: for the resulting image file. E.g., the following will create a
1.21      crook    10530: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1       anton    10531: 
                   10532: @example
                   10533: gforthmi gforth.fi -m 1M
                   10534: @end example
                   10535: 
                   10536: In other words, if you want to set the default size for the dictionary
                   10537: and the stacks of an image, just invoke @file{gforthmi} with the
                   10538: appropriate options when creating the image.
                   10539: 
                   10540: @cindex stack size, cache-friendly
                   10541: Note: For cache-friendly behaviour (i.e., good performance), you should
                   10542: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
                   10543: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
                   10544: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
                   10545: 
                   10546: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
                   10547: @section Running Image Files
                   10548: @cindex running image files
                   10549: @cindex invoking image files
                   10550: @cindex image file invocation
                   10551: 
                   10552: @cindex -i, invoke image file
                   10553: @cindex --image file, invoke image file
1.29      crook    10554: You can invoke Gforth with an image file @i{image} instead of the
1.1       anton    10555: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
                   10556: @example
1.29      crook    10557: gforth -i @i{image}
1.1       anton    10558: @end example
                   10559: 
                   10560: @cindex executable image file
1.26      crook    10561: @cindex image file, executable
1.1       anton    10562: If your operating system supports starting scripts with a line of the
                   10563: form @code{#! ...}, you just have to type the image file name to start
                   10564: Gforth with this image file (note that the file extension @code{.fi} is
1.29      crook    10565: just a convention). I.e., to run Gforth with the image file @i{image},
                   10566: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27      crook    10567: This works because every @code{.fi} file starts with a line of this
                   10568: format:
                   10569: 
                   10570: @example
                   10571: #! /usr/local/bin/gforth-0.4.0 -i
                   10572: @end example
                   10573: 
                   10574: The file and pathname for the Gforth engine specified on this line is
                   10575: the specific Gforth executable that it was built against; i.e. the value
                   10576: of the environment variable @code{GFORTH} at the time that
                   10577: @file{gforthmi} was executed.
1.1       anton    10578: 
1.27      crook    10579: You can make use of the same shell capability to make a Forth source
                   10580: file into an executable. For example, if you place this text in a file:
1.26      crook    10581: 
                   10582: @example
                   10583: #! /usr/local/bin/gforth
                   10584: 
                   10585: ." Hello, world" CR
                   10586: bye
                   10587: @end example
                   10588: 
                   10589: @noindent
1.27      crook    10590: and then make the file executable (chmod +x in Unix), you can run it
1.26      crook    10591: directly from the command line. The sequence @code{#!} is used in two
                   10592: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29      crook    10593: system@footnote{The Unix kernel actually recognises two types of files:
                   10594: executable files and files of data, where the data is processed by an
                   10595: interpreter that is specified on the ``interpreter line'' -- the first
                   10596: line of the file, starting with the sequence #!. There may be a small
                   10597: limit (e.g., 32) on the number of characters that may be specified on
                   10598: the interpreter line.} secondly it is treated as a comment character by
                   10599: Gforth. Because of the second usage, a space is required between
                   10600: @code{#!} and the path to the executable.
1.27      crook    10601: 
                   10602: The disadvantage of this latter technique, compared with using
                   10603: @file{gforthmi}, is that it is slower; the Forth source code is compiled
                   10604: on-the-fly, each time the program is invoked.
                   10605: 
1.26      crook    10606: @comment TODO describe the #! magic with reference to the Power Tools book.
                   10607: 
1.1       anton    10608: doc-#!
                   10609: 
                   10610: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
                   10611: @section Modifying the Startup Sequence
                   10612: @cindex startup sequence for image file
                   10613: @cindex image file initialization sequence
                   10614: @cindex initialization sequence of image file
                   10615: 
                   10616: You can add your own initialization to the startup sequence through the
1.26      crook    10617: deferred word @code{'cold}. @code{'cold} is invoked just before the
                   10618: image-specific command line processing (by default, loading files and
                   10619: evaluating (@code{-e}) strings) starts.
1.1       anton    10620: 
                   10621: A sequence for adding your initialization usually looks like this:
                   10622: 
                   10623: @example
                   10624: :noname
                   10625:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
                   10626:     ... \ your stuff
                   10627: ; IS 'cold
                   10628: @end example
                   10629: 
                   10630: @cindex turnkey image files
1.26      crook    10631: @cindex image file, turnkey applications
1.1       anton    10632: You can make a turnkey image by letting @code{'cold} execute a word
                   10633: (your turnkey application) that never returns; instead, it exits Gforth
                   10634: via @code{bye} or @code{throw}.
                   10635: 
                   10636: @cindex command-line arguments, access
                   10637: @cindex arguments on the command line, access
                   10638: You can access the (image-specific) command-line arguments through the
1.26      crook    10639: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1       anton    10640: access to @code{argv}.
                   10641: 
1.26      crook    10642: If @code{'cold} exits normally, Gforth processes the command-line
                   10643: arguments as files to be loaded and strings to be evaluated.  Therefore,
                   10644: @code{'cold} should remove the arguments it has used in this case.
                   10645: 
                   10646: doc-'cold
1.1       anton    10647: doc-argc
                   10648: doc-argv
                   10649: doc-arg
                   10650: 
                   10651: 
                   10652: @c ******************************************************************
1.13      pazsan   10653: @node Engine, Binding to System Library, Image Files, Top
1.1       anton    10654: @chapter Engine
                   10655: @cindex engine
                   10656: @cindex virtual machine
                   10657: 
1.26      crook    10658: Reading this chapter is not necessary for programming with Gforth. It
1.1       anton    10659: may be helpful for finding your way in the Gforth sources.
                   10660: 
                   10661: The ideas in this section have also been published in the papers
                   10662: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
                   10663: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
                   10664: Ertl, presented at EuroForth '93; the latter is available at
                   10665: @*@url{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
                   10666: 
                   10667: @menu
                   10668: * Portability::                 
                   10669: * Threading::                   
                   10670: * Primitives::                  
                   10671: * Performance::                 
                   10672: @end menu
                   10673: 
                   10674: @node Portability, Threading, Engine, Engine
                   10675: @section Portability
                   10676: @cindex engine portability
                   10677: 
1.26      crook    10678: An important goal of the Gforth Project is availability across a wide
                   10679: range of personal machines. fig-Forth, and, to a lesser extent, F83,
                   10680: achieved this goal by manually coding the engine in assembly language
                   10681: for several then-popular processors. This approach is very
                   10682: labor-intensive and the results are short-lived due to progress in
                   10683: computer architecture.
1.1       anton    10684: 
                   10685: @cindex C, using C for the engine
                   10686: Others have avoided this problem by coding in C, e.g., Mitch Bradley
                   10687: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
                   10688: particularly popular for UNIX-based Forths due to the large variety of
                   10689: architectures of UNIX machines. Unfortunately an implementation in C
                   10690: does not mix well with the goals of efficiency and with using
                   10691: traditional techniques: Indirect or direct threading cannot be expressed
                   10692: in C, and switch threading, the fastest technique available in C, is
                   10693: significantly slower. Another problem with C is that it is very
                   10694: cumbersome to express double integer arithmetic.
                   10695: 
                   10696: @cindex GNU C for the engine
                   10697: @cindex long long
                   10698: Fortunately, there is a portable language that does not have these
                   10699: limitations: GNU C, the version of C processed by the GNU C compiler
                   10700: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
                   10701: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
                   10702: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
                   10703: threading possible, its @code{long long} type (@pxref{Long Long, ,
                   10704: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
                   10705: double numbers@footnote{Unfortunately, long longs are not implemented
                   10706: properly on all machines (e.g., on alpha-osf1, long longs are only 64
                   10707: bits, the same size as longs (and pointers), but they should be twice as
1.4       anton    10708: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1       anton    10709: C Manual}). So, we had to implement doubles in C after all. Still, on
                   10710: most machines we can use long longs and achieve better performance than
                   10711: with the emulation package.}. GNU C is available for free on all
                   10712: important (and many unimportant) UNIX machines, VMS, 80386s running
                   10713: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
                   10714: on all these machines.
                   10715: 
                   10716: Writing in a portable language has the reputation of producing code that
                   10717: is slower than assembly. For our Forth engine we repeatedly looked at
                   10718: the code produced by the compiler and eliminated most compiler-induced
                   10719: inefficiencies by appropriate changes in the source code.
                   10720: 
                   10721: @cindex explicit register declarations
                   10722: @cindex --enable-force-reg, configuration flag
                   10723: @cindex -DFORCE_REG
                   10724: However, register allocation cannot be portably influenced by the
                   10725: programmer, leading to some inefficiencies on register-starved
                   10726: machines. We use explicit register declarations (@pxref{Explicit Reg
                   10727: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
                   10728: improve the speed on some machines. They are turned on by using the
                   10729: configuration flag @code{--enable-force-reg} (@code{gcc} switch
                   10730: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
                   10731: machine, but also on the compiler version: On some machines some
                   10732: compiler versions produce incorrect code when certain explicit register
                   10733: declarations are used. So by default @code{-DFORCE_REG} is not used.
                   10734: 
                   10735: @node Threading, Primitives, Portability, Engine
                   10736: @section Threading
                   10737: @cindex inner interpreter implementation
                   10738: @cindex threaded code implementation
                   10739: 
                   10740: @cindex labels as values
                   10741: GNU C's labels as values extension (available since @code{gcc-2.0},
                   10742: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29      crook    10743: makes it possible to take the address of @i{label} by writing
                   10744: @code{&&@i{label}}.  This address can then be used in a statement like
                   10745: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1       anton    10746: @code{goto x}.
                   10747: 
1.26      crook    10748: @cindex @code{NEXT}, indirect threaded
1.1       anton    10749: @cindex indirect threaded inner interpreter
                   10750: @cindex inner interpreter, indirect threaded
1.26      crook    10751: With this feature an indirect threaded @code{NEXT} looks like:
1.1       anton    10752: @example
                   10753: cfa = *ip++;
                   10754: ca = *cfa;
                   10755: goto *ca;
                   10756: @end example
                   10757: @cindex instruction pointer
                   10758: For those unfamiliar with the names: @code{ip} is the Forth instruction
                   10759: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
                   10760: execution token and points to the code field of the next word to be
                   10761: executed; The @code{ca} (code address) fetched from there points to some
                   10762: executable code, e.g., a primitive or the colon definition handler
                   10763: @code{docol}.
                   10764: 
1.26      crook    10765: @cindex @code{NEXT}, direct threaded
1.1       anton    10766: @cindex direct threaded inner interpreter
                   10767: @cindex inner interpreter, direct threaded
                   10768: Direct threading is even simpler:
                   10769: @example
                   10770: ca = *ip++;
                   10771: goto *ca;
                   10772: @end example
                   10773: 
                   10774: Of course we have packaged the whole thing neatly in macros called
1.26      crook    10775: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1       anton    10776: 
                   10777: @menu
                   10778: * Scheduling::                  
                   10779: * Direct or Indirect Threaded?::  
                   10780: * DOES>::                       
                   10781: @end menu
                   10782: 
                   10783: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
                   10784: @subsection Scheduling
                   10785: @cindex inner interpreter optimization
                   10786: 
                   10787: There is a little complication: Pipelined and superscalar processors,
                   10788: i.e., RISC and some modern CISC machines can process independent
                   10789: instructions while waiting for the results of an instruction. The
                   10790: compiler usually reorders (schedules) the instructions in a way that
                   10791: achieves good usage of these delay slots. However, on our first tries
                   10792: the compiler did not do well on scheduling primitives. E.g., for
                   10793: @code{+} implemented as
                   10794: @example
                   10795: n=sp[0]+sp[1];
                   10796: sp++;
                   10797: sp[0]=n;
                   10798: NEXT;
                   10799: @end example
1.26      crook    10800: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
1.1       anton    10801: scheduling. After a little thought the problem becomes clear: The
1.21      crook    10802: compiler cannot know that @code{sp} and @code{ip} point to different
                   10803: addresses (and the version of @code{gcc} we used would not know it even
                   10804: if it was possible), so it could not move the load of the cfa above the
                   10805: store to the TOS. Indeed the pointers could be the same, if code on or
                   10806: very near the top of stack were executed. In the interest of speed we
                   10807: chose to forbid this probably unused ``feature'' and helped the compiler
1.26      crook    10808: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
1.21      crook    10809: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1       anton    10810: @example
                   10811: n=sp[0]+sp[1];
                   10812: sp++;
                   10813: NEXT_P1;
                   10814: sp[0]=n;
                   10815: NEXT_P2;
                   10816: @end example
                   10817: This can be scheduled optimally by the compiler.
                   10818: 
                   10819: This division can be turned off with the switch @code{-DCISC_NEXT}. This
                   10820: switch is on by default on machines that do not profit from scheduling
                   10821: (e.g., the 80386), in order to preserve registers.
                   10822: 
                   10823: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
                   10824: @subsection Direct or Indirect Threaded?
                   10825: @cindex threading, direct or indirect?
                   10826: 
                   10827: @cindex -DDIRECT_THREADED
                   10828: Both! After packaging the nasty details in macro definitions we
                   10829: realized that we could switch between direct and indirect threading by
                   10830: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
                   10831: defining a few machine-specific macros for the direct-threading case.
                   10832: On the Forth level we also offer access words that hide the
                   10833: differences between the threading methods (@pxref{Threading Words}).
                   10834: 
                   10835: Indirect threading is implemented completely machine-independently.
                   10836: Direct threading needs routines for creating jumps to the executable
1.21      crook    10837: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
                   10838: machine-dependent, but they do not amount to many source lines. Therefore,
                   10839: even porting direct threading to a new machine requires little effort.
1.1       anton    10840: 
                   10841: @cindex --enable-indirect-threaded, configuration flag
                   10842: @cindex --enable-direct-threaded, configuration flag
                   10843: The default threading method is machine-dependent. You can enforce a
                   10844: specific threading method when building Gforth with the configuration
                   10845: flag @code{--enable-direct-threaded} or
                   10846: @code{--enable-indirect-threaded}. Note that direct threading is not
                   10847: supported on all machines.
                   10848: 
                   10849: @node DOES>,  , Direct or Indirect Threaded?, Threading
                   10850: @subsection DOES>
                   10851: @cindex @code{DOES>} implementation
                   10852: 
1.26      crook    10853: @cindex @code{dodoes} routine
                   10854: @cindex @code{DOES>}-code
1.1       anton    10855: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
                   10856: the chunk of code executed by every word defined by a
                   10857: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
                   10858: the Forth code to be executed, i.e. the code after the
1.26      crook    10859: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1       anton    10860: 
1.21      crook    10861: In fig-Forth the code field points directly to the @code{dodoes} and the
1.26      crook    10862: @code{DOES>}code address is stored in the cell after the code address (i.e. at
1.29      crook    10863: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1       anton    10864: the Forth-79 and all later standards, because in fig-Forth this address
                   10865: lies in the body (which is illegal in these standards). However, by
                   10866: making the code field larger for all words this solution becomes legal
                   10867: again. We use this approach for the indirect threaded version and for
                   10868: direct threading on some machines. Leaving a cell unused in most words
                   10869: is a bit wasteful, but on the machines we are targeting this is hardly a
                   10870: problem. The other reason for having a code field size of two cells is
                   10871: to avoid having different image files for direct and indirect threaded
                   10872: systems (direct threaded systems require two-cell code fields on many
                   10873: machines).
                   10874: 
1.26      crook    10875: @cindex @code{DOES>}-handler
1.1       anton    10876: The other approach is that the code field points or jumps to the cell
1.26      crook    10877: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
                   10878: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
                   10879: @code{DOES>}-code address by computing the code address, i.e., the address of
1.1       anton    10880: the jump to dodoes, and add the length of that jump field. A variant of
                   10881: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
                   10882: return address (which can be found in the return register on RISCs) is
1.26      crook    10883: the @code{DOES>}-code address. Since the two cells available in the code field
1.1       anton    10884: are used up by the jump to the code address in direct threading on many
                   10885: architectures, we use this approach for direct threading on these
                   10886: architectures. We did not want to add another cell to the code field.
                   10887: 
                   10888: @node Primitives, Performance, Threading, Engine
                   10889: @section Primitives
                   10890: @cindex primitives, implementation
                   10891: @cindex virtual machine instructions, implementation
                   10892: 
                   10893: @menu
                   10894: * Automatic Generation::        
                   10895: * TOS Optimization::            
                   10896: * Produced code::               
                   10897: @end menu
                   10898: 
                   10899: @node Automatic Generation, TOS Optimization, Primitives, Primitives
                   10900: @subsection Automatic Generation
                   10901: @cindex primitives, automatic generation
                   10902: 
                   10903: @cindex @file{prims2x.fs}
                   10904: Since the primitives are implemented in a portable language, there is no
                   10905: longer any need to minimize the number of primitives. On the contrary,
                   10906: having many primitives has an advantage: speed. In order to reduce the
                   10907: number of errors in primitives and to make programming them easier, we
                   10908: provide a tool, the primitive generator (@file{prims2x.fs}), that
                   10909: automatically generates most (and sometimes all) of the C code for a
                   10910: primitive from the stack effect notation.  The source for a primitive
                   10911: has the following form:
                   10912: 
                   10913: @cindex primitive source format
                   10914: @format
1.29      crook    10915: @i{Forth-name} @i{stack-effect}        @i{category}    [@i{pronounc.}]
                   10916: [@code{""}@i{glossary entry}@code{""}]
                   10917: @i{C code}
1.1       anton    10918: [@code{:}
1.29      crook    10919: @i{Forth code}]
1.1       anton    10920: @end format
                   10921: 
                   10922: The items in brackets are optional. The category and glossary fields
                   10923: are there for generating the documentation, the Forth code is there
                   10924: for manual implementations on machines without GNU C. E.g., the source
                   10925: for the primitive @code{+} is:
                   10926: @example
                   10927: +    n1 n2 -- n    core    plus
                   10928: n = n1+n2;
                   10929: @end example
                   10930: 
                   10931: This looks like a specification, but in fact @code{n = n1+n2} is C
                   10932: code. Our primitive generation tool extracts a lot of information from
                   10933: the stack effect notations@footnote{We use a one-stack notation, even
                   10934: though we have separate data and floating-point stacks; The separate
                   10935: notation can be generated easily from the unified notation.}: The number
                   10936: of items popped from and pushed on the stack, their type, and by what
                   10937: name they are referred to in the C code. It then generates a C code
                   10938: prelude and postlude for each primitive. The final C code for @code{+}
                   10939: looks like this:
                   10940: 
                   10941: @example
                   10942: I_plus:        /* + ( n1 n2 -- n ) */  /* label, stack effect */
                   10943: /*  */                          /* documentation */
                   10944: @{
                   10945: DEF_CA                          /* definition of variable ca (indirect threading) */
                   10946: Cell n1;                        /* definitions of variables */
                   10947: Cell n2;
                   10948: Cell n;
                   10949: n1 = (Cell) sp[1];              /* input */
                   10950: n2 = (Cell) TOS;
                   10951: sp += 1;                        /* stack adjustment */
                   10952: NAME("+")                       /* debugging output (with -DDEBUG) */
                   10953: @{
                   10954: n = n1+n2;                      /* C code taken from the source */
                   10955: @}
                   10956: NEXT_P1;                        /* NEXT part 1 */
                   10957: TOS = (Cell)n;                  /* output */
                   10958: NEXT_P2;                        /* NEXT part 2 */
                   10959: @}
                   10960: @end example
                   10961: 
                   10962: This looks long and inefficient, but the GNU C compiler optimizes quite
                   10963: well and produces optimal code for @code{+} on, e.g., the R3000 and the
                   10964: HP RISC machines: Defining the @code{n}s does not produce any code, and
                   10965: using them as intermediate storage also adds no cost.
                   10966: 
1.26      crook    10967: There are also other optimizations that are not illustrated by this
                   10968: example: assignments between simple variables are usually for free (copy
1.1       anton    10969: propagation). If one of the stack items is not used by the primitive
                   10970: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
                   10971: (dead code elimination). On the other hand, there are some things that
                   10972: the compiler does not do, therefore they are performed by
                   10973: @file{prims2x.fs}: The compiler does not optimize code away that stores
                   10974: a stack item to the place where it just came from (e.g., @code{over}).
                   10975: 
                   10976: While programming a primitive is usually easy, there are a few cases
                   10977: where the programmer has to take the actions of the generator into
                   10978: account, most notably @code{?dup}, but also words that do not (always)
1.26      crook    10979: fall through to @code{NEXT}.
1.1       anton    10980: 
                   10981: @node TOS Optimization, Produced code, Automatic Generation, Primitives
                   10982: @subsection TOS Optimization
                   10983: @cindex TOS optimization for primitives
                   10984: @cindex primitives, keeping the TOS in a register
                   10985: 
                   10986: An important optimization for stack machine emulators, e.g., Forth
                   10987: engines, is keeping  one or more of the top stack items in
1.29      crook    10988: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
                   10989: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1       anton    10990: @itemize @bullet
                   10991: @item
1.29      crook    10992: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1       anton    10993: due to fewer loads from and stores to the stack.
1.29      crook    10994: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
                   10995: @i{y<n}, due to additional moves between registers.
1.1       anton    10996: @end itemize
                   10997: 
                   10998: @cindex -DUSE_TOS
                   10999: @cindex -DUSE_NO_TOS
                   11000: In particular, keeping one item in a register is never a disadvantage,
                   11001: if there are enough registers. Keeping two items in registers is a
                   11002: disadvantage for frequent words like @code{?branch}, constants,
                   11003: variables, literals and @code{i}. Therefore our generator only produces
                   11004: code that keeps zero or one items in registers. The generated C code
                   11005: covers both cases; the selection between these alternatives is made at
                   11006: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
                   11007: code for @code{+} is just a simple variable name in the one-item case,
                   11008: otherwise it is a macro that expands into @code{sp[0]}. Note that the
                   11009: GNU C compiler tries to keep simple variables like @code{TOS} in
                   11010: registers, and it usually succeeds, if there are enough registers.
                   11011: 
                   11012: @cindex -DUSE_FTOS
                   11013: @cindex -DUSE_NO_FTOS
                   11014: The primitive generator performs the TOS optimization for the
                   11015: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
                   11016: operations the benefit of this optimization is even larger:
                   11017: floating-point operations take quite long on most processors, but can be
                   11018: performed in parallel with other operations as long as their results are
                   11019: not used. If the FP-TOS is kept in a register, this works. If
                   11020: it is kept on the stack, i.e., in memory, the store into memory has to
                   11021: wait for the result of the floating-point operation, lengthening the
                   11022: execution time of the primitive considerably.
                   11023: 
                   11024: The TOS optimization makes the automatic generation of primitives a
                   11025: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
                   11026: @code{TOS} is not sufficient. There are some special cases to
                   11027: consider:
                   11028: @itemize @bullet
                   11029: @item In the case of @code{dup ( w -- w w )} the generator must not
                   11030: eliminate the store to the original location of the item on the stack,
                   11031: if the TOS optimization is turned on.
                   11032: @item Primitives with stack effects of the form @code{--}
1.29      crook    11033: @i{out1}...@i{outy} must store the TOS to the stack at the start.
                   11034: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1       anton    11035: must load the TOS from the stack at the end. But for the null stack
                   11036: effect @code{--} no stores or loads should be generated.
                   11037: @end itemize
                   11038: 
                   11039: @node Produced code,  , TOS Optimization, Primitives
                   11040: @subsection Produced code
                   11041: @cindex primitives, assembly code listing
                   11042: 
                   11043: @cindex @file{engine.s}
                   11044: To see what assembly code is produced for the primitives on your machine
                   11045: with your compiler and your flag settings, type @code{make engine.s} and
                   11046: look at the resulting file @file{engine.s}.
                   11047: 
                   11048: @node  Performance,  , Primitives, Engine
                   11049: @section Performance
                   11050: @cindex performance of some Forth interpreters
                   11051: @cindex engine performance
                   11052: @cindex benchmarking Forth systems
                   11053: @cindex Gforth performance
                   11054: 
                   11055: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
                   11056: impossible to write a significantly faster engine.
                   11057: 
                   11058: On register-starved machines like the 386 architecture processors
                   11059: improvements are possible, because @code{gcc} does not utilize the
                   11060: registers as well as a human, even with explicit register declarations;
                   11061: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
                   11062: and hand-tuned it for the 486; this system is 1.19 times faster on the
                   11063: Sieve benchmark on a 486DX2/66 than Gforth compiled with
                   11064: @code{gcc-2.6.3} with @code{-DFORCE_REG}.
                   11065: 
                   11066: @cindex Win32Forth performance
                   11067: @cindex NT Forth performance
                   11068: @cindex eforth performance
                   11069: @cindex ThisForth performance
                   11070: @cindex PFE performance
                   11071: @cindex TILE performance
                   11072: However, this potential advantage of assembly language implementations
                   11073: is not necessarily realized in complete Forth systems: We compared
                   11074: Gforth (direct threaded, compiled with @code{gcc-2.6.3} and
                   11075: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
                   11076: 1994) and Eforth (with and without peephole (aka pinhole) optimization
                   11077: of the threaded code); all these systems were written in assembly
                   11078: language. We also compared Gforth with three systems written in C:
                   11079: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
                   11080: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21      crook    11081: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
                   11082: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1       anton    11083: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
                   11084: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
                   11085: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
                   11086: 486DX2/66 with similar memory performance under Windows NT. Marcel
                   11087: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
                   11088: added the peephole optimizer, ran the benchmarks and reported the
                   11089: results.
                   11090:  
                   11091: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
                   11092: matrix multiplication come from the Stanford integer benchmarks and have
                   11093: been translated into Forth by Martin Fraeman; we used the versions
                   11094: included in the TILE Forth package, but with bigger data set sizes; and
                   11095: a recursive Fibonacci number computation for benchmarking calling
                   11096: performance. The following table shows the time taken for the benchmarks
                   11097: scaled by the time taken by Gforth (in other words, it shows the speedup
                   11098: factor that Gforth achieved over the other systems).
                   11099: 
                   11100: @example
                   11101: relative      Win32-    NT       eforth       This-
                   11102:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
                   11103: sieve     1.00  1.39  1.14   1.39  0.85  1.58  3.18  8.58
                   11104: bubble    1.00  1.31  1.41   1.48  0.88  1.50        3.88
                   11105: matmul    1.00  1.47  1.35   1.46  0.74  1.58        4.09
                   11106: fib       1.00  1.52  1.34   1.22  0.86  1.74  2.99  4.30
                   11107: @end example
                   11108: 
1.26      crook    11109: You may be quite surprised by the good performance of Gforth when
                   11110: compared with systems written in assembly language. One important reason
                   11111: for the disappointing performance of these other systems is probably
                   11112: that they are not written optimally for the 486 (e.g., they use the
                   11113: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
                   11114: but costly method for relocating the Forth image: like @code{cforth}, it
                   11115: computes the actual addresses at run time, resulting in two address
                   11116: computations per @code{NEXT} (@pxref{Image File Background}).
                   11117: 
                   11118: Only Eforth with the peephole optimizer has a performance that is
                   11119: comparable to Gforth. The speedups achieved with peephole optimization
                   11120: of threaded code are quite remarkable. Adding a peephole optimizer to
                   11121: Gforth should cause similar speedups.
1.1       anton    11122: 
                   11123: The speedup of Gforth over PFE, ThisForth and TILE can be easily
                   11124: explained with the self-imposed restriction of the latter systems to
                   11125: standard C, which makes efficient threading impossible (however, the
1.4       anton    11126: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1       anton    11127: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
                   11128: Moreover, current C compilers have a hard time optimizing other aspects
                   11129: of the ThisForth and the TILE source.
                   11130: 
1.26      crook    11131: The performance of Gforth on 386 architecture processors varies widely
                   11132: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
                   11133: allocate any of the virtual machine registers into real machine
                   11134: registers by itself and would not work correctly with explicit register
                   11135: declarations, giving a 1.3 times slower engine (on a 486DX2/66 running
                   11136: the Sieve) than the one measured above.
1.1       anton    11137: 
1.26      crook    11138: Note that there have been several releases of Win32Forth since the
                   11139: release presented here, so the results presented above may have little
1.1       anton    11140: predictive value for the performance of Win32Forth today.
                   11141: 
                   11142: @cindex @file{Benchres}
                   11143: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
                   11144: Maierhofer (presented at EuroForth '95), an indirect threaded version of
                   11145: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
                   11146: version of Gforth is 2%@minus{}8% slower on a 486 than the direct
                   11147: threaded version used here. The paper available at
                   11148: @*@url{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
                   11149: it also contains numbers for some native code systems. You can find a
                   11150: newer version of these measurements at
                   11151: @url{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
                   11152: find numbers for Gforth on various machines in @file{Benchres}.
                   11153: 
1.26      crook    11154: @c ******************************************************************
1.13      pazsan   11155: @node Binding to System Library, Cross Compiler, Engine, Top
1.14      pazsan   11156: @chapter Binding to System Library
1.13      pazsan   11157: 
                   11158: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14      pazsan   11159: @chapter Cross Compiler
1.13      pazsan   11160: 
                   11161: Cross Compiler
                   11162: 
                   11163: @menu
                   11164: * Using the Cross Compiler::
                   11165: * How the Cross Compiler Works::
                   11166: @end menu
                   11167: 
1.21      crook    11168: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14      pazsan   11169: @section Using the Cross Compiler
1.13      pazsan   11170: 
1.21      crook    11171: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14      pazsan   11172: @section How the Cross Compiler Works
1.13      pazsan   11173: 
                   11174: @node Bugs, Origin, Cross Compiler, Top
1.21      crook    11175: @appendix Bugs
1.1       anton    11176: @cindex bug reporting
                   11177: 
1.21      crook    11178: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1       anton    11179: 
                   11180: If you find a bug, please send a bug report to
1.21      crook    11181: @email{bug-gforth@@gnu.ai.mit.edu}. A bug report should include this
                   11182: information:
                   11183: 
                   11184: @itemize @bullet
                   11185: @item
                   11186: The Gforth version used (it is announced at the start of an
                   11187: interactive Gforth session).
                   11188: @item
                   11189: The machine and operating system (on Unix
                   11190: systems @code{uname -a} will report this information).
                   11191: @item
                   11192: The installation options (send the file @file{config.status}).
                   11193: @item
                   11194: A complete list of changes (if any) you (or your installer) have made to the
                   11195: Gforth sources.
                   11196: @item
                   11197: A program (or a sequence of keyboard commands) that reproduces the bug.
                   11198: @item
                   11199: A description of what you think constitutes the buggy behaviour.
                   11200: @end itemize
1.1       anton    11201: 
                   11202: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
                   11203: to Report Bugs, gcc.info, GNU C Manual}.
                   11204: 
                   11205: 
1.21      crook    11206: @node Origin, Forth-related information, Bugs, Top
                   11207: @appendix Authors and Ancestors of Gforth
1.1       anton    11208: 
                   11209: @section Authors and Contributors
                   11210: @cindex authors of Gforth
                   11211: @cindex contributors to Gforth
                   11212: 
                   11213: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
                   11214: Ertl. The third major author was Jens Wilke.  Lennart Benschop (who was
                   11215: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
                   11216: with their continuous feedback. Lennart Benshop contributed
                   11217: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
                   11218: support for calling C libraries. Helpful comments also came from Paul
                   11219: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.12      anton    11220: Wavrik, Barrie Stott, Marc de Groot, and Jorge Acerada. Since the
                   11221: release of Gforth-0.2.1 there were also helpful comments from many
                   11222: others; thank you all, sorry for not listing you here (but digging
1.23      crook    11223: through my mailbox to extract your names is on my to-do list). Since the
                   11224: release of Gforth-0.4.0 Neal Crook worked on the manual.
1.1       anton    11225: 
                   11226: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
                   11227: and autoconf, among others), and to the creators of the Internet: Gforth
1.21      crook    11228: was developed across the Internet, and its authors did not meet
1.20      pazsan   11229: physically for the first 4 years of development.
1.1       anton    11230: 
                   11231: @section Pedigree
1.26      crook    11232: @cindex pedigree of Gforth
1.1       anton    11233: 
1.20      pazsan   11234: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1       anton    11235: Dirk Zoller) will cross-fertilize each other. Of course, a significant
                   11236: part of the design of Gforth was prescribed by ANS Forth.
                   11237: 
1.20      pazsan   11238: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1       anton    11239: 32 bit native code version of VolksForth for the Atari ST, written
                   11240: mostly by Dietrich Weineck.
                   11241: 
                   11242: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
                   11243: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
                   11244: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
                   11245: 
                   11246: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
                   11247: Forth-83 standard. !! Pedigree? When?
                   11248: 
                   11249: A team led by Bill Ragsdale implemented fig-Forth on many processors in
                   11250: 1979. Robert Selzer and Bill Ragsdale developed the original
                   11251: implementation of fig-Forth for the 6502 based on microForth.
                   11252: 
                   11253: The principal architect of microForth was Dean Sanderson. microForth was
                   11254: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
                   11255: the 1802, and subsequently implemented on the 8080, the 6800 and the
                   11256: Z80.
                   11257: 
                   11258: All earlier Forth systems were custom-made, usually by Charles Moore,
                   11259: who discovered (as he puts it) Forth during the late 60s. The first full
                   11260: Forth existed in 1971.
                   11261: 
                   11262: A part of the information in this section comes from @cite{The Evolution
                   11263: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
                   11264: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
                   11265: Notices 28(3), 1993.  You can find more historical and genealogical
                   11266: information about Forth there.
                   11267: 
1.21      crook    11268: @node Forth-related information, Word Index, Origin, Top
                   11269: @appendix Other Forth-related information
                   11270: @cindex Forth-related information
                   11271: 
                   11272: @menu
                   11273: * Internet resources::
                   11274: * Books::
                   11275: * The Forth Interest Group::
                   11276: * Conferences::
                   11277: @end menu
                   11278: 
                   11279: 
                   11280: @node Internet resources, Books, Forth-related information, Forth-related information
                   11281: @section Internet resources
1.26      crook    11282: @cindex internet resources
1.21      crook    11283: 
                   11284: @cindex comp.lang.forth
                   11285: @cindex frequently asked questions
                   11286: There is an active newsgroup (comp.lang.forth) discussing Forth and
                   11287: Forth-related issues. A frequently-asked-questions (FAQ) list
                   11288: is posted to the newsgroup regulary, and archived at these sites:
                   11289: 
                   11290: @itemize @bullet
                   11291: @item
                   11292: @url{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
                   11293: @item
                   11294: @url{ftp://ftp.forth.org/pub/Forth/FAQ/}
                   11295: @end itemize
                   11296: 
                   11297: The FAQ list should be considered mandatory reading before posting to
                   11298: the newsgroup.
                   11299: 
                   11300: Here are some other web sites holding Forth-related material:
                   11301: 
                   11302: @itemize @bullet
                   11303: @item
                   11304: @url{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
                   11305: @item
                   11306: @url{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
                   11307: @item
                   11308: @url{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
                   11309: @item
                   11310: @url{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
                   11311: Research page, including links to the Journal of Forth Application and
                   11312: Research (JFAR) and a searchable Forth bibliography.
                   11313: @end itemize
                   11314: 
                   11315: 
                   11316: @node Books, The Forth Interest Group, Internet resources, Forth-related information
                   11317: @section Books
1.26      crook    11318: @cindex books on Forth
1.21      crook    11319: 
                   11320: As the Standard is relatively new, there are not many books out yet. It
                   11321: is not recommended to learn Forth by using Gforth and a book that is not
                   11322: written for ANS Forth, as you will not know your mistakes from the
                   11323: deviations of the book. However, books based on the Forth-83 standard
                   11324: should be ok, because ANS Forth is primarily an extension of Forth-83.
                   11325: 
                   11326: @cindex standard document for ANS Forth
                   11327: @cindex ANS Forth document
                   11328: The definite reference if you want to write ANS Forth programs is, of
1.26      crook    11329: course, the ANS Forth document. It is available in printed form from the
1.21      crook    11330: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
                   11331: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
                   11332: $200. You can also get it from Global Engineering Documents (Tel.: USA
                   11333: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
                   11334: 
                   11335: @cite{dpANS6}, the last draft of the standard, which was then submitted
                   11336: to ANSI for publication is available electronically and for free in some
                   11337: MS Word format, and it has been converted to HTML
                   11338: (@url{http://www.taygeta.com/forth/dpans.html}; this is my favourite
                   11339: format); this HTML version also includes the answers to Requests for
                   11340: Interpretation (RFIs). Some pointers to these versions can be found
                   11341: through @*@url{http://www.complang.tuwien.ac.at/projects/forth.html}.
                   11342: 
1.26      crook    11343: @cindex introductory book on Forth
                   11344: @cindex book on Forth, introductory
1.21      crook    11345: @cindex Woehr, Jack: @cite{Forth: The New Model}
                   11346: @cindex @cite{Forth: The new model} (book)
                   11347: @cite{Forth: The New Model} by Jack Woehr (Prentice-Hall, 1993) is an
                   11348: introductory book based on a draft version of the standard. It does not
                   11349: cover the whole standard. It also contains interesting background
                   11350: information (Jack Woehr was in the ANS Forth Technical Committee). It is
                   11351: not appropriate for complete newbies, but programmers experienced in
                   11352: other languages should find it ok.
                   11353: 
                   11354: @cindex Conklin, Edward K., and Elizabeth Rather: @cite{Forth Programmer's Handbook}
                   11355: @cindex Rather, Elizabeth and Edward K. Conklin: @cite{Forth Programmer's Handbook}
                   11356: @cindex @cite{Forth Programmer's Handbook} (book)
                   11357: @cite{Forth Programmer's Handbook} by Edward K. Conklin, Elizabeth
                   11358: D. Rather and the technical staff of Forth, Inc. (Forth, Inc., 1997;
                   11359: ISBN 0-9662156-0-5) contains little introductory material. The majority
                   11360: of the book is similar to @ref{Words}, but the book covers most of the
                   11361: standard words and some non-standard words (whereas this manual is
                   11362: quite incomplete). In addition, the book contains a chapter on
                   11363: programming style. The major drawback of this book is that it usually
                   11364: does not identify what is standard and what is specific to the Forth
                   11365: system described in the book (probably one of Forth, Inc.'s systems).
                   11366: Fortunately, many of the non-standard programming practices described in
                   11367: the book work in Gforth, too.  Still, this drawback makes the book
                   11368: hardly more useful than a pre-ANS book.
                   11369: 
                   11370: @node The Forth Interest Group, Conferences, Books, Forth-related information
                   11371: @section The Forth Interest Group
                   11372: @cindex Forth interest group (FIG)
                   11373: 
                   11374: The Forth Interest Group (FIG) is a world-wide, non-profit,
1.26      crook    11375: member-supported organisation. It publishes a regular magazine,
                   11376: @var{FORTH Dimensions}, and offers other benefits of membership. You can
                   11377: contact the FIG through their office email address:
                   11378: @email{office@@forth.org} or by visiting their web site at
                   11379: @url{http://www.forth.org/}. This web site also includes links to FIG
                   11380: chapters in other countries and American cities
1.21      crook    11381: (@url{http://www.forth.org/chapters.html}).
                   11382: 
                   11383: @node Conferences, , The Forth Interest Group, Forth-related information
                   11384: @section Conferences
                   11385: @cindex Conferences
                   11386: 
                   11387: There are several regular conferences related to Forth. They are all
1.26      crook    11388: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
                   11389: news group:
1.21      crook    11390: 
                   11391: @itemize @bullet
                   11392: @item
                   11393: FORML -- the Forth modification laboratory convenes every year near
                   11394: Monterey, California.
                   11395: @item
                   11396: The Rochester Forth Conference -- an annual conference traditionally
                   11397: held in Rochester, New York.
                   11398: @item
                   11399: EuroForth -- this European conference takes place annually.
                   11400: @end itemize
                   11401: 
                   11402: 
                   11403: @node Word Index, Concept Index, Forth-related information, Top
1.1       anton    11404: @unnumbered Word Index
                   11405: 
1.26      crook    11406: This index is a list of Forth words that have ``glossary'' entries
                   11407: within this manual. Each word is listed with its stack effect and
                   11408: wordset.
1.1       anton    11409: 
                   11410: @printindex fn
                   11411: 
                   11412: @node Concept Index,  , Word Index, Top
                   11413: @unnumbered Concept and Word Index
                   11414: 
1.26      crook    11415: Not all entries listed in this index are present verbatim in the
                   11416: text. This index also duplicates, in abbreviated form, all of the words
                   11417: listed in the Word Index (only the names are listed for the words here).
1.1       anton    11418: 
                   11419: @printindex cp
                   11420: 
                   11421: @contents
                   11422: @bye
                   11423: 

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