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

1.1       anton       1: \input texinfo   @c -*-texinfo-*-
                      2: @comment The source is gforth.ds, from which gforth.texi is generated
                      3: @comment %**start of header (This is for running Texinfo on a region.)
                      4: @setfilename gforth.info
                      5: @settitle Gforth Manual
                      6: @dircategory GNU programming tools
                      7: @direntry
                      8: * Gforth: (gforth).             A fast interpreter for the Forth language.
                      9: @end direntry
                     10: @comment @setchapternewpage odd
1.12      anton      11: @macro progstyle {}
                     12: Programming style note:
1.3       anton      13: @end macro
1.1       anton      14: @comment %**end of header (This is for running Texinfo on a region.)
                     15: 
1.10      anton      16: @include version.texi
                     17: 
1.1       anton      18: @ifinfo
1.11      anton      19: This file documents Gforth @value{VERSION}
1.1       anton      20: 
1.13      pazsan     21: Copyright @copyright{} 1995-1998 Free Software Foundation, Inc.
1.1       anton      22: 
                     23:      Permission is granted to make and distribute verbatim copies of
                     24:      this manual provided the copyright notice and this permission notice
                     25:      are preserved on all copies.
                     26:      
                     27: @ignore
                     28:      Permission is granted to process this file through TeX and print the
                     29:      results, provided the printed document carries a copying permission
                     30:      notice identical to this one except for the removal of this paragraph
                     31:      (this paragraph not being relevant to the printed manual).
                     32:      
                     33: @end ignore
                     34:      Permission is granted to copy and distribute modified versions of this
                     35:      manual under the conditions for verbatim copying, provided also that the
                     36:      sections entitled "Distribution" and "General Public License" are
                     37:      included exactly as in the original, and provided that the entire
                     38:      resulting derived work is distributed under the terms of a permission
                     39:      notice identical to this one.
                     40:      
                     41:      Permission is granted to copy and distribute translations of this manual
                     42:      into another language, under the above conditions for modified versions,
                     43:      except that the sections entitled "Distribution" and "General Public
                     44:      License" may be included in a translation approved by the author instead
                     45:      of in the original English.
                     46: @end ifinfo
                     47: 
                     48: @finalout
                     49: @titlepage
                     50: @sp 10
                     51: @center @titlefont{Gforth Manual}
                     52: @sp 2
1.11      anton      53: @center for version @value{VERSION}
1.1       anton      54: @sp 2
                     55: @center Anton Ertl
1.6       pazsan     56: @center Bernd Paysan
1.5       anton      57: @center Jens Wilke
1.1       anton      58: @sp 3
1.6       pazsan     59: @center This manual is permanently under construction
1.1       anton      60: 
                     61: @comment  The following two commands start the copyright page.
                     62: @page
                     63: @vskip 0pt plus 1filll
1.13      pazsan     64: Copyright @copyright{} 1995--1998 Free Software Foundation, Inc.
1.1       anton      65: 
                     66: @comment !! Published by ... or You can get a copy of this manual ...
                     67: 
                     68:      Permission is granted to make and distribute verbatim copies of
                     69:      this manual provided the copyright notice and this permission notice
                     70:      are preserved on all copies.
                     71:      
                     72:      Permission is granted to copy and distribute modified versions of this
                     73:      manual under the conditions for verbatim copying, provided also that the
                     74:      sections entitled "Distribution" and "General Public License" are
                     75:      included exactly as in the original, and provided that the entire
                     76:      resulting derived work is distributed under the terms of a permission
                     77:      notice identical to this one.
                     78:      
                     79:      Permission is granted to copy and distribute translations of this manual
                     80:      into another language, under the above conditions for modified versions,
                     81:      except that the sections entitled "Distribution" and "General Public
                     82:      License" may be included in a translation approved by the author instead
                     83:      of in the original English.
                     84: @end titlepage
                     85: 
                     86: 
                     87: @node Top, License, (dir), (dir)
                     88: @ifinfo
                     89: Gforth is a free implementation of ANS Forth available on many
1.11      anton      90: personal machines. This manual corresponds to version @value{VERSION}.
1.1       anton      91: @end ifinfo
                     92: 
                     93: @menu
                     94: * License::                     
                     95: * Goals::                       About the Gforth Project
                     96: * Other Books::                 Things you might want to read
                     97: * Invoking Gforth::             Starting Gforth
                     98: * Words::                       Forth words available in Gforth
                     99: * Tools::                       Programming tools
                    100: * ANS conformance::             Implementation-defined options etc.
                    101: * Model::                       The abstract machine of Gforth
                    102: * Integrating Gforth::          Forth as scripting language for applications
                    103: * Emacs and Gforth::            The Gforth Mode
                    104: * Image Files::                 @code{.fi} files contain compiled code
                    105: * Engine::                      The inner interpreter and the primitives
1.13      pazsan    106: * Cross Compiler::              The Cross Compiler
1.1       anton     107: * Bugs::                        How to report them
                    108: * Origin::                      Authors and ancestors of Gforth
                    109: * Word Index::                  An item for each Forth word
                    110: * Concept Index::               A menu covering many topics
1.12      anton     111: 
                    112:  --- The Detailed Node Listing ---
                    113: 
                    114: Forth Words
                    115: 
                    116: * Notation::                    
                    117: * Arithmetic::                  
                    118: * Stack Manipulation::          
                    119: * Memory::                      
                    120: * Control Structures::          
                    121: * Locals::                      
                    122: * Defining Words::              
                    123: * Structures::                  
                    124: * Object-oriented Forth::       
                    125: * Tokens for Words::            
                    126: * Wordlists::                   
                    127: * Files::                       
                    128: * Including Files::             
                    129: * Blocks::                      
                    130: * Other I/O::                   
                    131: * Programming Tools::           
                    132: * Assembler and Code Words::    
                    133: * Threading Words::             
                    134: 
                    135: Arithmetic
                    136: 
                    137: * Single precision::            
                    138: * Bitwise operations::          
                    139: * Mixed precision::             operations with single and double-cell integers
                    140: * Double precision::            Double-cell integer arithmetic
                    141: * Floating Point::              
                    142: 
                    143: Stack Manipulation
                    144: 
                    145: * Data stack::                  
                    146: * Floating point stack::        
                    147: * Return stack::                
                    148: * Locals stack::                
                    149: * Stack pointer manipulation::  
                    150: 
                    151: Memory
                    152: 
                    153: * Memory Access::      
                    154: * Address arithmetic::          
                    155: * Memory Blocks::         
                    156: 
                    157: Control Structures
                    158: 
                    159: * Selection::                   
                    160: * Simple Loops::                
                    161: * Counted Loops::               
                    162: * Arbitrary control structures::  
                    163: * Calls and returns::           
                    164: * Exception Handling::          
                    165: 
                    166: Locals
                    167: 
                    168: * Gforth locals::               
                    169: * ANS Forth locals::            
                    170: 
                    171: Gforth locals
                    172: 
                    173: * Where are locals visible by name?::  
                    174: * How long do locals live?::    
                    175: * Programming Style::           
                    176: * Implementation::              
                    177: 
                    178: Defining Words
                    179: 
                    180: * Simple Defining Words::       
                    181: * Colon Definitions::           
                    182: * User-defined Defining Words::  
                    183: * Supplying names::             
                    184: * Interpretation and Compilation Semantics::  
                    185: 
                    186: Structures
                    187: 
                    188: * Why explicit structure support?::  
                    189: * Structure Usage::             
                    190: * Structure Naming Convention::  
                    191: * Structure Implementation::    
                    192: * Structure Glossary::          
                    193: 
                    194: Object-oriented Forth
                    195: 
                    196: * Objects::                     
                    197: * OOF::                         
                    198: * Mini-OOF::                    
                    199: 
                    200: Objects
                    201: 
                    202: * Properties of the Objects model::  
                    203: * Why object-oriented programming?::  
                    204: * Object-Oriented Terminology::  
                    205: * Basic Objects Usage::         
                    206: * The class Object::            
                    207: * Creating objects::            
                    208: * Object-Oriented Programming Style::  
                    209: * Class Binding::               
                    210: * Method conveniences::         
                    211: * Classes and Scoping::         
                    212: * Object Interfaces::           
                    213: * Objects Implementation::      
                    214: * Comparison with other object models::  
                    215: * Objects Glossary::            
                    216: 
                    217: OOF
                    218: 
                    219: * Properties of the OOF model::
                    220: * Basic OOF Usage::
                    221: * The base class object::
                    222: * Class Declaration::
                    223: * Class Implementation::
                    224: 
                    225: Including Files
                    226: 
                    227: * Words for Including::         
                    228: * Search Path::                 
                    229: * Changing the Search Path::    
                    230: * General Search Paths::        
                    231: 
                    232: Programming Tools
                    233: 
                    234: * Debugging::                   Simple and quick.
                    235: * Assertions::                  Making your programs self-checking.
                    236: * Singlestep Debugger::                Executing your program word by word.
                    237: 
                    238: Tools
                    239: 
                    240: * ANS Report::                  Report the words used, sorted by wordset.
                    241: 
                    242: ANS conformance
                    243: 
                    244: * The Core Words::              
                    245: * The optional Block word set::  
                    246: * The optional Double Number word set::  
                    247: * The optional Exception word set::  
                    248: * The optional Facility word set::  
                    249: * The optional File-Access word set::  
                    250: * The optional Floating-Point word set::  
                    251: * The optional Locals word set::  
                    252: * The optional Memory-Allocation word set::  
                    253: * The optional Programming-Tools word set::  
                    254: * The optional Search-Order word set::  
                    255: 
                    256: The Core Words
                    257: 
                    258: * core-idef::                   Implementation Defined Options                   
                    259: * core-ambcond::                Ambiguous Conditions                
                    260: * core-other::                  Other System Documentation                  
                    261: 
                    262: The optional Block word set
                    263: 
                    264: * block-idef::                  Implementation Defined Options
                    265: * block-ambcond::               Ambiguous Conditions               
                    266: * block-other::                 Other System Documentation                 
                    267: 
                    268: The optional Double Number word set
                    269: 
                    270: * double-ambcond::              Ambiguous Conditions              
                    271: 
                    272: The optional Exception word set
                    273: 
                    274: * exception-idef::              Implementation Defined Options              
                    275: 
                    276: The optional Facility word set
                    277: 
                    278: * facility-idef::               Implementation Defined Options               
                    279: * facility-ambcond::            Ambiguous Conditions            
                    280: 
                    281: The optional File-Access word set
                    282: 
                    283: * file-idef::                   Implementation Defined Options
                    284: * file-ambcond::                Ambiguous Conditions                
                    285: 
                    286: The optional Floating-Point word set
                    287: 
                    288: * floating-idef::               Implementation Defined Options
                    289: * floating-ambcond::            Ambiguous Conditions            
                    290: 
                    291: The optional Locals word set
                    292: 
                    293: * locals-idef::                 Implementation Defined Options                 
                    294: * locals-ambcond::              Ambiguous Conditions              
                    295: 
                    296: The optional Memory-Allocation word set
                    297: 
                    298: * memory-idef::                 Implementation Defined Options                 
                    299: 
                    300: The optional Programming-Tools word set
                    301: 
                    302: * programming-idef::            Implementation Defined Options            
                    303: * programming-ambcond::         Ambiguous Conditions         
                    304: 
                    305: The optional Search-Order word set
                    306: 
                    307: * search-idef::                 Implementation Defined Options                 
                    308: * search-ambcond::              Ambiguous Conditions              
                    309: 
                    310: Image Files
                    311: 
                    312: * Image File Background::          Why have image files?
                    313: * Non-Relocatable Image Files::    don't always work.
                    314: * Data-Relocatable Image Files::   are better.
                    315: * Fully Relocatable Image Files::  better yet.
                    316: * Stack and Dictionary Sizes::     Setting the default sizes for an image.
                    317: * Running Image Files::            @code{gforth -i @var{file}} or @var{file}.
                    318: * Modifying the Startup Sequence:: and turnkey applications.
                    319: 
                    320: Fully Relocatable Image Files
                    321: 
                    322: * gforthmi::            The normal way
                    323: * cross.fs::                    The hard way
                    324: 
                    325: Engine
                    326: 
                    327: * Portability::                 
                    328: * Threading::                   
                    329: * Primitives::                  
                    330: * Performance::                 
                    331: 
                    332: Threading
                    333: 
                    334: * Scheduling::                  
                    335: * Direct or Indirect Threaded?::  
                    336: * DOES>::                       
                    337: 
                    338: Primitives
                    339: 
                    340: * Automatic Generation::        
                    341: * TOS Optimization::            
                    342: * Produced code::               
1.13      pazsan    343: 
                    344: System Libraries
                    345: 
                    346: * Binding to System Library::
                    347: 
                    348: Cross Compiler
                    349: 
                    350: * Using the Cross Compiler::
                    351: * How the Cross Compiler Works::
                    352: 
1.1       anton     353: @end menu
                    354: 
                    355: @node License, Goals, Top, Top
                    356: @unnumbered GNU GENERAL PUBLIC LICENSE
                    357: @center Version 2, June 1991
                    358: 
                    359: @display
                    360: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
                    361: 675 Mass Ave, Cambridge, MA 02139, USA
                    362: 
                    363: Everyone is permitted to copy and distribute verbatim copies
                    364: of this license document, but changing it is not allowed.
                    365: @end display
                    366: 
                    367: @unnumberedsec Preamble
                    368: 
                    369:   The licenses for most software are designed to take away your
                    370: freedom to share and change it.  By contrast, the GNU General Public
                    371: License is intended to guarantee your freedom to share and change free
                    372: software---to make sure the software is free for all its users.  This
                    373: General Public License applies to most of the Free Software
                    374: Foundation's software and to any other program whose authors commit to
                    375: using it.  (Some other Free Software Foundation software is covered by
                    376: the GNU Library General Public License instead.)  You can apply it to
                    377: your programs, too.
                    378: 
                    379:   When we speak of free software, we are referring to freedom, not
                    380: price.  Our General Public Licenses are designed to make sure that you
                    381: have the freedom to distribute copies of free software (and charge for
                    382: this service if you wish), that you receive source code or can get it
                    383: if you want it, that you can change the software or use pieces of it
                    384: in new free programs; and that you know you can do these things.
                    385: 
                    386:   To protect your rights, we need to make restrictions that forbid
                    387: anyone to deny you these rights or to ask you to surrender the rights.
                    388: These restrictions translate to certain responsibilities for you if you
                    389: distribute copies of the software, or if you modify it.
                    390: 
                    391:   For example, if you distribute copies of such a program, whether
                    392: gratis or for a fee, you must give the recipients all the rights that
                    393: you have.  You must make sure that they, too, receive or can get the
                    394: source code.  And you must show them these terms so they know their
                    395: rights.
                    396: 
                    397:   We protect your rights with two steps: (1) copyright the software, and
                    398: (2) offer you this license which gives you legal permission to copy,
                    399: distribute and/or modify the software.
                    400: 
                    401:   Also, for each author's protection and ours, we want to make certain
                    402: that everyone understands that there is no warranty for this free
                    403: software.  If the software is modified by someone else and passed on, we
                    404: want its recipients to know that what they have is not the original, so
                    405: that any problems introduced by others will not reflect on the original
                    406: authors' reputations.
                    407: 
                    408:   Finally, any free program is threatened constantly by software
                    409: patents.  We wish to avoid the danger that redistributors of a free
                    410: program will individually obtain patent licenses, in effect making the
                    411: program proprietary.  To prevent this, we have made it clear that any
                    412: patent must be licensed for everyone's free use or not licensed at all.
                    413: 
                    414:   The precise terms and conditions for copying, distribution and
                    415: modification follow.
                    416: 
                    417: @iftex
                    418: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
                    419: @end iftex
                    420: @ifinfo
                    421: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
                    422: @end ifinfo
                    423: 
                    424: @enumerate 0
                    425: @item
                    426: This License applies to any program or other work which contains
                    427: a notice placed by the copyright holder saying it may be distributed
                    428: under the terms of this General Public License.  The ``Program'', below,
                    429: refers to any such program or work, and a ``work based on the Program''
                    430: means either the Program or any derivative work under copyright law:
                    431: that is to say, a work containing the Program or a portion of it,
                    432: either verbatim or with modifications and/or translated into another
                    433: language.  (Hereinafter, translation is included without limitation in
                    434: the term ``modification''.)  Each licensee is addressed as ``you''.
                    435: 
                    436: Activities other than copying, distribution and modification are not
                    437: covered by this License; they are outside its scope.  The act of
                    438: running the Program is not restricted, and the output from the Program
                    439: is covered only if its contents constitute a work based on the
                    440: Program (independent of having been made by running the Program).
                    441: Whether that is true depends on what the Program does.
                    442: 
                    443: @item
                    444: You may copy and distribute verbatim copies of the Program's
                    445: source code as you receive it, in any medium, provided that you
                    446: conspicuously and appropriately publish on each copy an appropriate
                    447: copyright notice and disclaimer of warranty; keep intact all the
                    448: notices that refer to this License and to the absence of any warranty;
                    449: and give any other recipients of the Program a copy of this License
                    450: along with the Program.
                    451: 
                    452: You may charge a fee for the physical act of transferring a copy, and
                    453: you may at your option offer warranty protection in exchange for a fee.
                    454: 
                    455: @item
                    456: You may modify your copy or copies of the Program or any portion
                    457: of it, thus forming a work based on the Program, and copy and
                    458: distribute such modifications or work under the terms of Section 1
                    459: above, provided that you also meet all of these conditions:
                    460: 
                    461: @enumerate a
                    462: @item
                    463: You must cause the modified files to carry prominent notices
                    464: stating that you changed the files and the date of any change.
                    465: 
                    466: @item
                    467: You must cause any work that you distribute or publish, that in
                    468: whole or in part contains or is derived from the Program or any
                    469: part thereof, to be licensed as a whole at no charge to all third
                    470: parties under the terms of this License.
                    471: 
                    472: @item
                    473: If the modified program normally reads commands interactively
                    474: when run, you must cause it, when started running for such
                    475: interactive use in the most ordinary way, to print or display an
                    476: announcement including an appropriate copyright notice and a
                    477: notice that there is no warranty (or else, saying that you provide
                    478: a warranty) and that users may redistribute the program under
                    479: these conditions, and telling the user how to view a copy of this
                    480: License.  (Exception: if the Program itself is interactive but
                    481: does not normally print such an announcement, your work based on
                    482: the Program is not required to print an announcement.)
                    483: @end enumerate
                    484: 
                    485: These requirements apply to the modified work as a whole.  If
                    486: identifiable sections of that work are not derived from the Program,
                    487: and can be reasonably considered independent and separate works in
                    488: themselves, then this License, and its terms, do not apply to those
                    489: sections when you distribute them as separate works.  But when you
                    490: distribute the same sections as part of a whole which is a work based
                    491: on the Program, the distribution of the whole must be on the terms of
                    492: this License, whose permissions for other licensees extend to the
                    493: entire whole, and thus to each and every part regardless of who wrote it.
                    494: 
                    495: Thus, it is not the intent of this section to claim rights or contest
                    496: your rights to work written entirely by you; rather, the intent is to
                    497: exercise the right to control the distribution of derivative or
                    498: collective works based on the Program.
                    499: 
                    500: In addition, mere aggregation of another work not based on the Program
                    501: with the Program (or with a work based on the Program) on a volume of
                    502: a storage or distribution medium does not bring the other work under
                    503: the scope of this License.
                    504: 
                    505: @item
                    506: You may copy and distribute the Program (or a work based on it,
                    507: under Section 2) in object code or executable form under the terms of
                    508: Sections 1 and 2 above provided that you also do one of the following:
                    509: 
                    510: @enumerate a
                    511: @item
                    512: Accompany it with the complete corresponding machine-readable
                    513: source code, which must be distributed under the terms of Sections
                    514: 1 and 2 above on a medium customarily used for software interchange; or,
                    515: 
                    516: @item
                    517: Accompany it with a written offer, valid for at least three
                    518: years, to give any third party, for a charge no more than your
                    519: cost of physically performing source distribution, a complete
                    520: machine-readable copy of the corresponding source code, to be
                    521: distributed under the terms of Sections 1 and 2 above on a medium
                    522: customarily used for software interchange; or,
                    523: 
                    524: @item
                    525: Accompany it with the information you received as to the offer
                    526: to distribute corresponding source code.  (This alternative is
                    527: allowed only for noncommercial distribution and only if you
                    528: received the program in object code or executable form with such
                    529: an offer, in accord with Subsection b above.)
                    530: @end enumerate
                    531: 
                    532: The source code for a work means the preferred form of the work for
                    533: making modifications to it.  For an executable work, complete source
                    534: code means all the source code for all modules it contains, plus any
                    535: associated interface definition files, plus the scripts used to
                    536: control compilation and installation of the executable.  However, as a
                    537: special exception, the source code distributed need not include
                    538: anything that is normally distributed (in either source or binary
                    539: form) with the major components (compiler, kernel, and so on) of the
                    540: operating system on which the executable runs, unless that component
                    541: itself accompanies the executable.
                    542: 
                    543: If distribution of executable or object code is made by offering
                    544: access to copy from a designated place, then offering equivalent
                    545: access to copy the source code from the same place counts as
                    546: distribution of the source code, even though third parties are not
                    547: compelled to copy the source along with the object code.
                    548: 
                    549: @item
                    550: You may not copy, modify, sublicense, or distribute the Program
                    551: except as expressly provided under this License.  Any attempt
                    552: otherwise to copy, modify, sublicense or distribute the Program is
                    553: void, and will automatically terminate your rights under this License.
                    554: However, parties who have received copies, or rights, from you under
                    555: this License will not have their licenses terminated so long as such
                    556: parties remain in full compliance.
                    557: 
                    558: @item
                    559: You are not required to accept this License, since you have not
                    560: signed it.  However, nothing else grants you permission to modify or
                    561: distribute the Program or its derivative works.  These actions are
                    562: prohibited by law if you do not accept this License.  Therefore, by
                    563: modifying or distributing the Program (or any work based on the
                    564: Program), you indicate your acceptance of this License to do so, and
                    565: all its terms and conditions for copying, distributing or modifying
                    566: the Program or works based on it.
                    567: 
                    568: @item
                    569: Each time you redistribute the Program (or any work based on the
                    570: Program), the recipient automatically receives a license from the
                    571: original licensor to copy, distribute or modify the Program subject to
                    572: these terms and conditions.  You may not impose any further
                    573: restrictions on the recipients' exercise of the rights granted herein.
                    574: You are not responsible for enforcing compliance by third parties to
                    575: this License.
                    576: 
                    577: @item
                    578: If, as a consequence of a court judgment or allegation of patent
                    579: infringement or for any other reason (not limited to patent issues),
                    580: conditions are imposed on you (whether by court order, agreement or
                    581: otherwise) that contradict the conditions of this License, they do not
                    582: excuse you from the conditions of this License.  If you cannot
                    583: distribute so as to satisfy simultaneously your obligations under this
                    584: License and any other pertinent obligations, then as a consequence you
                    585: may not distribute the Program at all.  For example, if a patent
                    586: license would not permit royalty-free redistribution of the Program by
                    587: all those who receive copies directly or indirectly through you, then
                    588: the only way you could satisfy both it and this License would be to
                    589: refrain entirely from distribution of the Program.
                    590: 
                    591: If any portion of this section is held invalid or unenforceable under
                    592: any particular circumstance, the balance of the section is intended to
                    593: apply and the section as a whole is intended to apply in other
                    594: circumstances.
                    595: 
                    596: It is not the purpose of this section to induce you to infringe any
                    597: patents or other property right claims or to contest validity of any
                    598: such claims; this section has the sole purpose of protecting the
                    599: integrity of the free software distribution system, which is
                    600: implemented by public license practices.  Many people have made
                    601: generous contributions to the wide range of software distributed
                    602: through that system in reliance on consistent application of that
                    603: system; it is up to the author/donor to decide if he or she is willing
                    604: to distribute software through any other system and a licensee cannot
                    605: impose that choice.
                    606: 
                    607: This section is intended to make thoroughly clear what is believed to
                    608: be a consequence of the rest of this License.
                    609: 
                    610: @item
                    611: If the distribution and/or use of the Program is restricted in
                    612: certain countries either by patents or by copyrighted interfaces, the
                    613: original copyright holder who places the Program under this License
                    614: may add an explicit geographical distribution limitation excluding
                    615: those countries, so that distribution is permitted only in or among
                    616: countries not thus excluded.  In such case, this License incorporates
                    617: the limitation as if written in the body of this License.
                    618: 
                    619: @item
                    620: The Free Software Foundation may publish revised and/or new versions
                    621: of the General Public License from time to time.  Such new versions will
                    622: be similar in spirit to the present version, but may differ in detail to
                    623: address new problems or concerns.
                    624: 
                    625: Each version is given a distinguishing version number.  If the Program
                    626: specifies a version number of this License which applies to it and ``any
                    627: later version'', you have the option of following the terms and conditions
                    628: either of that version or of any later version published by the Free
                    629: Software Foundation.  If the Program does not specify a version number of
                    630: this License, you may choose any version ever published by the Free Software
                    631: Foundation.
                    632: 
                    633: @item
                    634: If you wish to incorporate parts of the Program into other free
                    635: programs whose distribution conditions are different, write to the author
                    636: to ask for permission.  For software which is copyrighted by the Free
                    637: Software Foundation, write to the Free Software Foundation; we sometimes
                    638: make exceptions for this.  Our decision will be guided by the two goals
                    639: of preserving the free status of all derivatives of our free software and
                    640: of promoting the sharing and reuse of software generally.
                    641: 
                    642: @iftex
                    643: @heading NO WARRANTY
                    644: @end iftex
                    645: @ifinfo
                    646: @center NO WARRANTY
                    647: @end ifinfo
                    648: 
                    649: @item
                    650: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
                    651: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
                    652: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
                    653: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
                    654: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
                    655: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
                    656: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
                    657: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
                    658: REPAIR OR CORRECTION.
                    659: 
                    660: @item
                    661: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
                    662: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
                    663: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
                    664: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
                    665: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
                    666: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
                    667: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
                    668: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
                    669: POSSIBILITY OF SUCH DAMAGES.
                    670: @end enumerate
                    671: 
                    672: @iftex
                    673: @heading END OF TERMS AND CONDITIONS
                    674: @end iftex
                    675: @ifinfo
                    676: @center END OF TERMS AND CONDITIONS
                    677: @end ifinfo
                    678: 
                    679: @page
                    680: @unnumberedsec How to Apply These Terms to Your New Programs
                    681: 
                    682:   If you develop a new program, and you want it to be of the greatest
                    683: possible use to the public, the best way to achieve this is to make it
                    684: free software which everyone can redistribute and change under these terms.
                    685: 
                    686:   To do so, attach the following notices to the program.  It is safest
                    687: to attach them to the start of each source file to most effectively
                    688: convey the exclusion of warranty; and each file should have at least
                    689: the ``copyright'' line and a pointer to where the full notice is found.
                    690: 
                    691: @smallexample
                    692: @var{one line to give the program's name and a brief idea of what it does.}
                    693: Copyright (C) 19@var{yy}  @var{name of author}
                    694: 
                    695: This program is free software; you can redistribute it and/or modify 
                    696: it under the terms of the GNU General Public License as published by 
                    697: the Free Software Foundation; either version 2 of the License, or 
                    698: (at your option) any later version.
                    699: 
                    700: This program is distributed in the hope that it will be useful,
                    701: but WITHOUT ANY WARRANTY; without even the implied warranty of
                    702: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                    703: GNU General Public License for more details.
                    704: 
                    705: You should have received a copy of the GNU General Public License
                    706: along with this program; if not, write to the Free Software
                    707: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
                    708: @end smallexample
                    709: 
                    710: Also add information on how to contact you by electronic and paper mail.
                    711: 
                    712: If the program is interactive, make it output a short notice like this
                    713: when it starts in an interactive mode:
                    714: 
                    715: @smallexample
                    716: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
                    717: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
                    718: type `show w'.  
                    719: This is free software, and you are welcome to redistribute it 
                    720: under certain conditions; type `show c' for details.
                    721: @end smallexample
                    722: 
                    723: The hypothetical commands @samp{show w} and @samp{show c} should show
                    724: the appropriate parts of the General Public License.  Of course, the
                    725: commands you use may be called something other than @samp{show w} and
                    726: @samp{show c}; they could even be mouse-clicks or menu items---whatever
                    727: suits your program.
                    728: 
                    729: You should also get your employer (if you work as a programmer) or your
                    730: school, if any, to sign a ``copyright disclaimer'' for the program, if
                    731: necessary.  Here is a sample; alter the names:
                    732: 
                    733: @smallexample
                    734: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
                    735: `Gnomovision' (which makes passes at compilers) written by James Hacker.
                    736: 
                    737: @var{signature of Ty Coon}, 1 April 1989
                    738: Ty Coon, President of Vice
                    739: @end smallexample
                    740: 
                    741: This General Public License does not permit incorporating your program into
                    742: proprietary programs.  If your program is a subroutine library, you may
                    743: consider it more useful to permit linking proprietary applications with the
                    744: library.  If this is what you want to do, use the GNU Library General
                    745: Public License instead of this License.
                    746: 
                    747: @iftex
                    748: @unnumbered Preface
                    749: @cindex Preface
                    750: This manual documents Gforth. The reader is expected to know
                    751: Forth. This manual is primarily a reference manual. @xref{Other Books}
                    752: for introductory material.
                    753: @end iftex
                    754: 
                    755: @node    Goals, Other Books, License, Top
                    756: @comment node-name,     next,           previous, up
                    757: @chapter Goals of Gforth
                    758: @cindex Goals
                    759: The goal of the Gforth Project is to develop a standard model for
                    760: ANS Forth. This can be split into several subgoals:
                    761: 
                    762: @itemize @bullet
                    763: @item
                    764: Gforth should conform to the Forth standard (ANS Forth).
                    765: @item
                    766: It should be a model, i.e. it should define all the
                    767: implementation-dependent things.
                    768: @item
                    769: It should become standard, i.e. widely accepted and used. This goal
                    770: is the most difficult one.
                    771: @end itemize
                    772: 
                    773: To achieve these goals Gforth should be
                    774: @itemize @bullet
                    775: @item
                    776: Similar to previous models (fig-Forth, F83)
                    777: @item
                    778: Powerful. It should provide for all the things that are considered
                    779: necessary today and even some that are not yet considered necessary.
                    780: @item
                    781: Efficient. It should not get the reputation of being exceptionally
                    782: slow.
                    783: @item
                    784: Free.
                    785: @item
                    786: Available on many machines/easy to port.
                    787: @end itemize
                    788: 
                    789: Have we achieved these goals? Gforth conforms to the ANS Forth
                    790: standard. It may be considered a model, but we have not yet documented
                    791: which parts of the model are stable and which parts we are likely to
1.12      anton     792: change. It certainly has not yet become a de facto standard, but it
                    793: appears to be quite popular. It has some similarities to and some
                    794: differences from previous models. It has some powerful features, but not
                    795: yet everything that we envisioned. We certainly have achieved our
                    796: execution speed goals (@pxref{Performance}).  It is free and available
                    797: on many machines.
1.1       anton     798: 
                    799: @node Other Books, Invoking Gforth, Goals, Top
                    800: @chapter Other books on ANS Forth
                    801: @cindex books on Forth
                    802: 
                    803: As the standard is relatively new, there are not many books out yet. It
1.16      anton     804: is not recommended to learn Forth by using Gforth and a book that is not
                    805: written for ANS Forth, as you will not know your mistakes from the
                    806: deviations of the book. However, books based on the Forth-83 standard
                    807: should be ok, because ANS Forth is primarily an extension of Forth-83.
1.1       anton     808: 
                    809: @cindex standard document for ANS Forth
                    810: @cindex ANS Forth document
                    811: There is, of course, the standard, the definite reference if you want to
                    812: write ANS Forth programs. It is available in printed form from the
                    813: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
                    814: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about $200. You
                    815: can also get it from Global Engineering Documents (Tel.: USA (800)
                    816: 854-7179; Fax.: (303) 843-9880) for about $300.
                    817: 
1.12      anton     818: @cite{dpANS6}, the last draft of the standard, which was then submitted
                    819: to ANSI for publication is available electronically and for free in some
1.16      anton     820: MS Word format, and it has been converted to HTML
                    821: (@url{http://www.taygeta.com/forth/dpans.html}; this is my favourite
                    822: format); this HTML version also includes the answers to Requests for
                    823: Interpretation (RFIs). Some pointers to these versions can be found
                    824: through @*@url{http://www.complang.tuwien.ac.at/projects/forth.html}.
1.1       anton     825: 
                    826: @cindex introductory book
                    827: @cindex book, introductory
                    828: @cindex Woehr, Jack: @cite{Forth: The New Model}
                    829: @cindex @cite{Forth: The new model} (book)
                    830: @cite{Forth: The New Model} by Jack Woehr (Prentice-Hall, 1993) is an
                    831: introductory book based on a draft version of the standard. It does not
                    832: cover the whole standard. It also contains interesting background
                    833: information (Jack Woehr was in the ANS Forth Technical Committee). It is
                    834: not appropriate for complete newbies, but programmers experienced in
                    835: other languages should find it ok.
                    836: 
1.16      anton     837: @cindex Conklin, Edward K., and Elizabeth Rather: @cite{Forth Programmer's Handbook}
                    838: @cindex Rather, Elizabeth and Edward K. Conklin: @cite{Forth Programmer's Handbook}
                    839: @cindex @cite{Forth Programmer's Handbook} (book)
                    840: @cite{Forth Programmer's Handbook} by Edward K. Conklin, Elizabeth
                    841: D. Rather and the technical staff of Forth, Inc. (Forth, Inc., 1997;
                    842: ISBN 0-9662156-0-5) contains little introductory material. The majority
                    843: of the book is similar to @ref{Words}, but the book covers most of the
                    844: standard words and some non-standard words (whereas this manual is
                    845: quite incomplete). In addition, the book contains a chapter on
                    846: programming style. The major drawback of this book is that it usually
                    847: does not identify what is standard and what is specific to the Forth
                    848: system described in the book (probably one of Forth, Inc.'s systems).
                    849: Fortunately, many of the non-standard programming practices described in
                    850: the book work in Gforth, too.  Still, this drawback makes the book
                    851: hardly more useful than a pre-ANS book.
1.12      anton     852: 
1.1       anton     853: @node Invoking Gforth, Words, Other Books, Top
                    854: @chapter Invoking Gforth
                    855: @cindex invoking Gforth
                    856: @cindex running Gforth
                    857: @cindex command-line options
                    858: @cindex options on the command line
                    859: @cindex flags on the command line
                    860: 
                    861: You will usually just say @code{gforth}. In many other cases the default
                    862: Gforth image will be invoked like this:
                    863: @example
                    864: gforth [files] [-e forth-code]
                    865: @end example
1.12      anton     866: This interprets the contents of the files and the Forth code in the order they
1.1       anton     867: are given.
                    868: 
                    869: In general, the command line looks like this:
                    870: 
                    871: @example
                    872: gforth [initialization options] [image-specific options]
                    873: @end example
                    874: 
                    875: The initialization options must come before the rest of the command
                    876: line. They are:
                    877: 
                    878: @table @code
                    879: @cindex -i, command-line option
                    880: @cindex --image-file, command-line option
                    881: @item --image-file @var{file}
                    882: @itemx -i @var{file}
                    883: Loads the Forth image @var{file} instead of the default
                    884: @file{gforth.fi} (@pxref{Image Files}).
                    885: 
                    886: @cindex --path, command-line option
                    887: @cindex -p, command-line option
                    888: @item --path @var{path}
                    889: @itemx -p @var{path}
                    890: Uses @var{path} for searching the image file and Forth source code files
                    891: instead of the default in the environment variable @code{GFORTHPATH} or
                    892: the path specified at installation time (e.g.,
                    893: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                    894: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
                    895: 
                    896: @cindex --dictionary-size, command-line option
                    897: @cindex -m, command-line option
                    898: @cindex @var{size} parameters for command-line options
                    899: @cindex size of the dictionary and the stacks
                    900: @item --dictionary-size @var{size}
                    901: @itemx -m @var{size}
                    902: Allocate @var{size} space for the Forth dictionary space instead of
                    903: using the default specified in the image (typically 256K). The
                    904: @var{size} specification consists of an integer and a unit (e.g.,
                    905: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
1.12      anton     906: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                    907: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                    908: @code{e} is used.
1.1       anton     909: 
                    910: @cindex --data-stack-size, command-line option
                    911: @cindex -d, command-line option
                    912: @item --data-stack-size @var{size}
                    913: @itemx -d @var{size}
                    914: Allocate @var{size} space for the data stack instead of using the
                    915: default specified in the image (typically 16K).
                    916: 
                    917: @cindex --return-stack-size, command-line option
                    918: @cindex -r, command-line option
                    919: @item --return-stack-size @var{size}
                    920: @itemx -r @var{size}
                    921: Allocate @var{size} space for the return stack instead of using the
                    922: default specified in the image (typically 15K).
                    923: 
                    924: @cindex --fp-stack-size, command-line option
                    925: @cindex -f, command-line option
                    926: @item --fp-stack-size @var{size}
                    927: @itemx -f @var{size}
                    928: Allocate @var{size} space for the floating point stack instead of
                    929: using the default specified in the image (typically 15.5K). In this case
                    930: the unit specifier @code{e} refers to floating point numbers.
                    931: 
                    932: @cindex --locals-stack-size, command-line option
                    933: @cindex -l, command-line option
                    934: @item --locals-stack-size @var{size}
                    935: @itemx -l @var{size}
                    936: Allocate @var{size} space for the locals stack instead of using the
                    937: default specified in the image (typically 14.5K).
                    938: 
                    939: @cindex -h, command-line option
                    940: @cindex --help, command-line option
                    941: @item --help
                    942: @itemx -h
                    943: Print a message about the command-line options
                    944: 
                    945: @cindex -v, command-line option
                    946: @cindex --version, command-line option
                    947: @item --version
                    948: @itemx -v
                    949: Print version and exit
                    950: 
                    951: @cindex --debug, command-line option
                    952: @item --debug
                    953: Print some information useful for debugging on startup.
                    954: 
                    955: @cindex --offset-image, command-line option
                    956: @item --offset-image
                    957: Start the dictionary at a slightly different position than would be used
                    958: otherwise (useful for creating data-relocatable images,
                    959: @pxref{Data-Relocatable Image Files}).
                    960: 
1.5       anton     961: @cindex --no-offset-im, command-line option
                    962: @item --no-offset-im
                    963: Start the dictionary at the normal position.
                    964: 
1.1       anton     965: @cindex --clear-dictionary, command-line option
                    966: @item --clear-dictionary
                    967: Initialize all bytes in the dictionary to 0 before loading the image
                    968: (@pxref{Data-Relocatable Image Files}).
1.5       anton     969: 
                    970: @cindex --die-on-signal, command-line-option
                    971: @item --die-on-signal
                    972: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
                    973: or the segmentation violation SIGSEGV) by translating it into a Forth
                    974: @code{THROW}. With this option, Gforth exits if it receives such a
                    975: signal. This option is useful when the engine and/or the image might be
                    976: severely broken (such that it causes another signal before recovering
                    977: from the first); this option avoids endless loops in such cases.
1.1       anton     978: @end table
                    979: 
                    980: @cindex loading files at startup
                    981: @cindex executing code on startup
                    982: @cindex batch processing with Gforth
                    983: As explained above, the image-specific command-line arguments for the
                    984: default image @file{gforth.fi} consist of a sequence of filenames and
                    985: @code{-e @var{forth-code}} options that are interpreted in the sequence
                    986: in which they are given. The @code{-e @var{forth-code}} or
                    987: @code{--evaluate @var{forth-code}} option evaluates the forth
                    988: code. This option takes only one argument; if you want to evaluate more
                    989: Forth words, you have to quote them or use several @code{-e}s. To exit
                    990: after processing the command line (instead of entering interactive mode)
                    991: append @code{-e bye} to the command line.
                    992: 
                    993: @cindex versions, invoking other versions of Gforth
                    994: If you have several versions of Gforth installed, @code{gforth} will
                    995: invoke the version that was installed last. @code{gforth-@var{version}}
                    996: invokes a specific version. You may want to use the option
                    997: @code{--path}, if your environment contains the variable
                    998: @code{GFORTHPATH}.
                    999: 
                   1000: Not yet implemented:
                   1001: On startup the system first executes the system initialization file
                   1002: (unless the option @code{--no-init-file} is given; note that the system
                   1003: resulting from using this option may not be ANS Forth conformant). Then
                   1004: the user initialization file @file{.gforth.fs} is executed, unless the
                   1005: option @code{--no-rc} is given; this file is first searched in @file{.},
                   1006: then in @file{~}, then in the normal path (see above).
                   1007: 
                   1008: @node Words, Tools, Invoking Gforth, Top
                   1009: @chapter Forth Words
                   1010: @cindex Words
                   1011: 
                   1012: @menu
                   1013: * Notation::                    
                   1014: * Arithmetic::                  
                   1015: * Stack Manipulation::          
1.5       anton    1016: * Memory::                      
1.1       anton    1017: * Control Structures::          
                   1018: * Locals::                      
                   1019: * Defining Words::              
1.5       anton    1020: * Structures::                  
1.12      anton    1021: * Object-oriented Forth::       
                   1022: * Tokens for Words::            
                   1023: * Wordlists::                   
                   1024: * Files::                       
                   1025: * Including Files::             
                   1026: * Blocks::                      
                   1027: * Other I/O::                   
                   1028: * Programming Tools::           
                   1029: * Assembler and Code Words::    
                   1030: * Threading Words::             
1.1       anton    1031: @end menu
                   1032: 
                   1033: @node Notation, Arithmetic, Words, Words
                   1034: @section Notation
                   1035: @cindex notation of glossary entries
                   1036: @cindex format of glossary entries
                   1037: @cindex glossary notation format
                   1038: @cindex word glossary entry format
                   1039: 
                   1040: The Forth words are described in this section in the glossary notation
                   1041: that has become a de-facto standard for Forth texts, i.e.,
                   1042: 
                   1043: @format
                   1044: @var{word}     @var{Stack effect}   @var{wordset}   @var{pronunciation}
                   1045: @end format
                   1046: @var{Description}
                   1047: 
                   1048: @table @var
                   1049: @item word
                   1050: @cindex case insensitivity
                   1051: The name of the word. BTW, Gforth is case insensitive, so you can
                   1052: type the words in in lower case (However, @pxref{core-idef}).
                   1053: 
                   1054: @item Stack effect
                   1055: @cindex stack effect
                   1056: The stack effect is written in the notation @code{@var{before} --
                   1057: @var{after}}, where @var{before} and @var{after} describe the top of
                   1058: stack entries before and after the execution of the word. The rest of
                   1059: the stack is not touched by the word. The top of stack is rightmost,
                   1060: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   1061: uses a separate floating point stack, but a unified stack
                   1062: notation. Also, return stack effects are not shown in @var{stack
                   1063: effect}, but in @var{Description}. The name of a stack item describes
                   1064: the type and/or the function of the item. See below for a discussion of
                   1065: the types.
                   1066: 
                   1067: All words have two stack effects: A compile-time stack effect and a
                   1068: run-time stack effect. The compile-time stack-effect of most words is
                   1069: @var{ -- }. If the compile-time stack-effect of a word deviates from
                   1070: this standard behaviour, or the word does other unusual things at
                   1071: compile time, both stack effects are shown; otherwise only the run-time
                   1072: stack effect is shown.
                   1073: 
                   1074: @cindex pronounciation of words
                   1075: @item pronunciation
                   1076: How the word is pronounced.
                   1077: 
                   1078: @cindex wordset
                   1079: @item wordset
                   1080: The ANS Forth standard is divided into several wordsets. A standard
                   1081: system need not support all of them. So, the fewer wordsets your program
                   1082: uses the more portable it will be in theory. However, we suspect that
                   1083: most ANS Forth systems on personal machines will feature all
                   1084: wordsets. Words that are not defined in the ANS standard have
                   1085: @code{gforth} or @code{gforth-internal} as wordset. @code{gforth}
                   1086: describes words that will work in future releases of Gforth;
                   1087: @code{gforth-internal} words are more volatile. Environmental query
                   1088: strings are also displayed like words; you can recognize them by the
                   1089: @code{environment} in the wordset field.
                   1090: 
                   1091: @item Description
                   1092: A description of the behaviour of the word.
                   1093: @end table
                   1094: 
                   1095: @cindex types of stack items
                   1096: @cindex stack item types
                   1097: The type of a stack item is specified by the character(s) the name
                   1098: starts with:
                   1099: 
                   1100: @table @code
                   1101: @item f
                   1102: @cindex @code{f}, stack item type
                   1103: Boolean flags, i.e. @code{false} or @code{true}.
                   1104: @item c
                   1105: @cindex @code{c}, stack item type
                   1106: Char
                   1107: @item w
                   1108: @cindex @code{w}, stack item type
                   1109: Cell, can contain an integer or an address
                   1110: @item n
                   1111: @cindex @code{n}, stack item type
                   1112: signed integer
                   1113: @item u
                   1114: @cindex @code{u}, stack item type
                   1115: unsigned integer
                   1116: @item d
                   1117: @cindex @code{d}, stack item type
                   1118: double sized signed integer
                   1119: @item ud
                   1120: @cindex @code{ud}, stack item type
                   1121: double sized unsigned integer
                   1122: @item r
                   1123: @cindex @code{r}, stack item type
                   1124: Float (on the FP stack)
                   1125: @item a_
                   1126: @cindex @code{a_}, stack item type
                   1127: Cell-aligned address
                   1128: @item c_
                   1129: @cindex @code{c_}, stack item type
                   1130: Char-aligned address (note that a Char may have two bytes in Windows NT)
                   1131: @item f_
                   1132: @cindex @code{f_}, stack item type
                   1133: Float-aligned address
                   1134: @item df_
                   1135: @cindex @code{df_}, stack item type
                   1136: Address aligned for IEEE double precision float
                   1137: @item sf_
                   1138: @cindex @code{sf_}, stack item type
                   1139: Address aligned for IEEE single precision float
                   1140: @item xt
                   1141: @cindex @code{xt}, stack item type
                   1142: Execution token, same size as Cell
                   1143: @item wid
                   1144: @cindex @code{wid}, stack item type
                   1145: Wordlist ID, same size as Cell
                   1146: @item f83name
                   1147: @cindex @code{f83name}, stack item type
                   1148: Pointer to a name structure
                   1149: @item "
                   1150: @cindex @code{"}, stack item type
1.12      anton    1151: string in the input stream (not on the stack). The terminating character
                   1152: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    1153: quotes.
                   1154: @end table
                   1155: 
                   1156: @node Arithmetic, Stack Manipulation, Notation, Words
                   1157: @section Arithmetic
                   1158: @cindex arithmetic words
                   1159: 
                   1160: @cindex division with potentially negative operands
                   1161: Forth arithmetic is not checked, i.e., you will not hear about integer
                   1162: overflow on addition or multiplication, you may hear about division by
                   1163: zero if you are lucky. The operator is written after the operands, but
                   1164: the operands are still in the original order. I.e., the infix @code{2-1}
                   1165: corresponds to @code{2 1 -}. Forth offers a variety of division
                   1166: operators. If you perform division with potentially negative operands,
                   1167: you do not want to use @code{/} or @code{/mod} with its undefined
                   1168: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   1169: former, @pxref{Mixed precision}).
                   1170: 
                   1171: @menu
                   1172: * Single precision::            
                   1173: * Bitwise operations::          
                   1174: * Mixed precision::             operations with single and double-cell integers
                   1175: * Double precision::            Double-cell integer arithmetic
                   1176: * Floating Point::              
                   1177: @end menu
                   1178: 
                   1179: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
                   1180: @subsection Single precision
                   1181: @cindex single precision arithmetic words
                   1182: 
                   1183: doc-+
                   1184: doc--
                   1185: doc-*
                   1186: doc-/
                   1187: doc-mod
                   1188: doc-/mod
                   1189: doc-negate
                   1190: doc-abs
                   1191: doc-min
                   1192: doc-max
                   1193: 
                   1194: @node Bitwise operations, Mixed precision, Single precision, Arithmetic
                   1195: @subsection Bitwise operations
                   1196: @cindex bitwise operation words
                   1197: 
                   1198: doc-and
                   1199: doc-or
                   1200: doc-xor
                   1201: doc-invert
                   1202: doc-2*
                   1203: doc-2/
                   1204: 
                   1205: @node Mixed precision, Double precision, Bitwise operations, Arithmetic
                   1206: @subsection Mixed precision
                   1207: @cindex mixed precision arithmetic words
                   1208: 
                   1209: doc-m+
                   1210: doc-*/
                   1211: doc-*/mod
                   1212: doc-m*
                   1213: doc-um*
                   1214: doc-m*/
                   1215: doc-um/mod
                   1216: doc-fm/mod
                   1217: doc-sm/rem
                   1218: 
                   1219: @node Double precision, Floating Point, Mixed precision, Arithmetic
                   1220: @subsection Double precision
                   1221: @cindex double precision arithmetic words
                   1222: 
                   1223: @cindex double-cell numbers, input format
                   1224: @cindex input format for double-cell numbers
                   1225: The outer (aka text) interpreter converts numbers containing a dot into
                   1226: a double precision number. Note that only numbers with the dot as last
                   1227: character are standard-conforming.
                   1228: 
                   1229: doc-d+
                   1230: doc-d-
                   1231: doc-dnegate
                   1232: doc-dabs
                   1233: doc-dmin
                   1234: doc-dmax
                   1235: 
                   1236: @node Floating Point,  , Double precision, Arithmetic
                   1237: @subsection Floating Point
                   1238: @cindex floating point arithmetic words
                   1239: 
                   1240: @cindex floating-point numbers, input format
                   1241: @cindex input format for floating-point numbers
                   1242: The format of floating point numbers recognized by the outer (aka text)
                   1243: interpreter is: a signed decimal number, possibly containing a decimal
                   1244: point (@code{.}), followed by @code{E} or @code{e}, optionally followed
                   1245: by a signed integer (the exponent). E.g., @code{1e} is the same as
1.12      anton    1246: @code{+1.0e+0}. Note that a number without @code{e} is not interpreted
                   1247: as floating-point number, but as double (if the number contains a
                   1248: @code{.}) or single precision integer. Also, conversions between string
                   1249: and floating point numbers always use base 10, irrespective of the value
                   1250: of @code{BASE} (in Gforth; for the standard this is an ambiguous
                   1251: condition). If @code{BASE} contains a value greater then 14, the
                   1252: @code{E} may be interpreted as digit and the number will be interpreted
                   1253: as integer, unless it has a signed exponent (both @code{+} and @code{-}
                   1254: are allowed as signs).
1.1       anton    1255: 
                   1256: @cindex angles in trigonometric operations
                   1257: @cindex trigonometric operations
                   1258: Angles in floating point operations are given in radians (a full circle
                   1259: has 2 pi radians). Note, that Gforth has a separate floating point
                   1260: stack, but we use the unified notation.
                   1261: 
                   1262: @cindex floating-point arithmetic, pitfalls
                   1263: Floating point numbers have a number of unpleasant surprises for the
                   1264: unwary (e.g., floating point addition is not associative) and even a few
                   1265: for the wary. You should not use them unless you know what you are doing
                   1266: or you don't care that the results you get are totally bogus. If you
                   1267: want to learn about the problems of floating point numbers (and how to
                   1268: avoid them), you might start with @cite{David Goldberg, What Every
                   1269: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
1.17      anton    1270: Computing Surveys 23(1):5@minus{}48, March 1991}
                   1271: (@url{http://www.validgh.com/goldberg/paper.ps}).
1.1       anton    1272: 
                   1273: doc-f+
                   1274: doc-f-
                   1275: doc-f*
                   1276: doc-f/
                   1277: doc-fnegate
                   1278: doc-fabs
                   1279: doc-fmax
                   1280: doc-fmin
                   1281: doc-floor
                   1282: doc-fround
                   1283: doc-f**
                   1284: doc-fsqrt
                   1285: doc-fexp
                   1286: doc-fexpm1
                   1287: doc-fln
                   1288: doc-flnp1
                   1289: doc-flog
                   1290: doc-falog
                   1291: doc-fsin
                   1292: doc-fcos
                   1293: doc-fsincos
                   1294: doc-ftan
                   1295: doc-fasin
                   1296: doc-facos
                   1297: doc-fatan
                   1298: doc-fatan2
                   1299: doc-fsinh
                   1300: doc-fcosh
                   1301: doc-ftanh
                   1302: doc-fasinh
                   1303: doc-facosh
                   1304: doc-fatanh
                   1305: 
                   1306: @node Stack Manipulation, Memory, Arithmetic, Words
                   1307: @section Stack Manipulation
                   1308: @cindex stack manipulation words
                   1309: 
                   1310: @cindex floating-point stack in the standard
                   1311: Gforth has a data stack (aka parameter stack) for characters, cells,
                   1312: addresses, and double cells, a floating point stack for floating point
                   1313: numbers, a return stack for storing the return addresses of colon
                   1314: definitions and other data, and a locals stack for storing local
                   1315: variables. Note that while every sane Forth has a separate floating
                   1316: point stack, this is not strictly required; an ANS Forth system could
                   1317: theoretically keep floating point numbers on the data stack. As an
                   1318: additional difficulty, you don't know how many cells a floating point
                   1319: number takes. It is reportedly possible to write words in a way that
                   1320: they work also for a unified stack model, but we do not recommend trying
                   1321: it. Instead, just say that your program has an environmental dependency
                   1322: on a separate FP stack.
                   1323: 
                   1324: @cindex return stack and locals
                   1325: @cindex locals and return stack
                   1326: Also, a Forth system is allowed to keep the local variables on the
                   1327: return stack. This is reasonable, as local variables usually eliminate
                   1328: the need to use the return stack explicitly. So, if you want to produce
                   1329: a standard complying program and if you are using local variables in a
                   1330: word, forget about return stack manipulations in that word (see the
                   1331: standard document for the exact rules).
                   1332: 
                   1333: @menu
                   1334: * Data stack::                  
                   1335: * Floating point stack::        
                   1336: * Return stack::                
                   1337: * Locals stack::                
                   1338: * Stack pointer manipulation::  
                   1339: @end menu
                   1340: 
                   1341: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   1342: @subsection Data stack
                   1343: @cindex data stack manipulation words
                   1344: @cindex stack manipulations words, data stack
                   1345: 
                   1346: doc-drop
                   1347: doc-nip
                   1348: doc-dup
                   1349: doc-over
                   1350: doc-tuck
                   1351: doc-swap
                   1352: doc-rot
                   1353: doc--rot
                   1354: doc-?dup
                   1355: doc-pick
                   1356: doc-roll
                   1357: doc-2drop
                   1358: doc-2nip
                   1359: doc-2dup
                   1360: doc-2over
                   1361: doc-2tuck
                   1362: doc-2swap
                   1363: doc-2rot
                   1364: 
                   1365: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   1366: @subsection Floating point stack
                   1367: @cindex floating-point stack manipulation words
                   1368: @cindex stack manipulation words, floating-point stack
                   1369: 
                   1370: doc-fdrop
                   1371: doc-fnip
                   1372: doc-fdup
                   1373: doc-fover
                   1374: doc-ftuck
                   1375: doc-fswap
                   1376: doc-frot
                   1377: 
                   1378: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   1379: @subsection Return stack
                   1380: @cindex return stack manipulation words
                   1381: @cindex stack manipulation words, return stack
                   1382: 
                   1383: doc->r
                   1384: doc-r>
                   1385: doc-r@
                   1386: doc-rdrop
                   1387: doc-2>r
                   1388: doc-2r>
                   1389: doc-2r@
                   1390: doc-2rdrop
                   1391: 
                   1392: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   1393: @subsection Locals stack
                   1394: 
                   1395: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   1396: @subsection Stack pointer manipulation
                   1397: @cindex stack pointer manipulation words
                   1398: 
                   1399: doc-sp@
                   1400: doc-sp!
                   1401: doc-fp@
                   1402: doc-fp!
                   1403: doc-rp@
                   1404: doc-rp!
                   1405: doc-lp@
                   1406: doc-lp!
                   1407: 
                   1408: @node Memory, Control Structures, Stack Manipulation, Words
                   1409: @section Memory
                   1410: @cindex Memory words
                   1411: 
                   1412: @menu
                   1413: * Memory Access::      
                   1414: * Address arithmetic::          
                   1415: * Memory Blocks::         
                   1416: @end menu
                   1417: 
                   1418: @node Memory Access, Address arithmetic, Memory, Memory
                   1419: @subsection Memory Access
                   1420: @cindex memory access words
                   1421: 
                   1422: doc-@
                   1423: doc-!
                   1424: doc-+!
                   1425: doc-c@
                   1426: doc-c!
                   1427: doc-2@
                   1428: doc-2!
                   1429: doc-f@
                   1430: doc-f!
                   1431: doc-sf@
                   1432: doc-sf!
                   1433: doc-df@
                   1434: doc-df!
                   1435: 
                   1436: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   1437: @subsection Address arithmetic
                   1438: @cindex address arithmetic words
                   1439: 
                   1440: ANS Forth does not specify the sizes of the data types. Instead, it
                   1441: offers a number of words for computing sizes and doing address
                   1442: arithmetic. Basically, address arithmetic is performed in terms of
                   1443: address units (aus); on most systems the address unit is one byte. Note
                   1444: that a character may have more than one au, so @code{chars} is no noop
                   1445: (on systems where it is a noop, it compiles to nothing).
                   1446: 
                   1447: @cindex alignment of addresses for types
                   1448: ANS Forth also defines words for aligning addresses for specific
                   1449: types. Many computers require that accesses to specific data types
                   1450: must only occur at specific addresses; e.g., that cells may only be
                   1451: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   1452: accesses, it can usually perform aligned accesses faster. 
                   1453: 
                   1454: For the performance-conscious: alignment operations are usually only
                   1455: necessary during the definition of a data structure, not during the
                   1456: (more frequent) accesses to it.
                   1457: 
                   1458: ANS Forth defines no words for character-aligning addresses. This is not
                   1459: an oversight, but reflects the fact that addresses that are not
                   1460: char-aligned have no use in the standard and therefore will not be
                   1461: created.
                   1462: 
                   1463: @cindex @code{CREATE} and alignment
                   1464: The standard guarantees that addresses returned by @code{CREATE}d words
                   1465: are cell-aligned; in addition, Gforth guarantees that these addresses
                   1466: are aligned for all purposes.
                   1467: 
                   1468: Note that the standard defines a word @code{char}, which has nothing to
                   1469: do with address arithmetic.
                   1470: 
                   1471: doc-chars
                   1472: doc-char+
                   1473: doc-cells
                   1474: doc-cell+
                   1475: doc-cell
                   1476: doc-align
                   1477: doc-aligned
                   1478: doc-floats
                   1479: doc-float+
                   1480: doc-float
                   1481: doc-falign
                   1482: doc-faligned
                   1483: doc-sfloats
                   1484: doc-sfloat+
                   1485: doc-sfalign
                   1486: doc-sfaligned
                   1487: doc-dfloats
                   1488: doc-dfloat+
                   1489: doc-dfalign
                   1490: doc-dfaligned
                   1491: doc-maxalign
                   1492: doc-maxaligned
                   1493: doc-cfalign
                   1494: doc-cfaligned
                   1495: doc-address-unit-bits
                   1496: 
                   1497: @node Memory Blocks,  , Address arithmetic, Memory
                   1498: @subsection Memory Blocks
                   1499: @cindex memory block words
                   1500: 
                   1501: doc-move
                   1502: doc-erase
                   1503: 
                   1504: While the previous words work on address units, the rest works on
                   1505: characters.
                   1506: 
                   1507: doc-cmove
                   1508: doc-cmove>
                   1509: doc-fill
                   1510: doc-blank
                   1511: 
                   1512: @node Control Structures, Locals, Memory, Words
                   1513: @section Control Structures
                   1514: @cindex control structures
                   1515: 
                   1516: Control structures in Forth cannot be used in interpret state, only in
                   1517: compile state@footnote{More precisely, they have no interpretation
                   1518: semantics (@pxref{Interpretation and Compilation Semantics})}, i.e., in
                   1519: a colon definition. We do not like this limitation, but have not seen a
                   1520: satisfying way around it yet, although many schemes have been proposed.
                   1521: 
                   1522: @menu
                   1523: * Selection::                   
                   1524: * Simple Loops::                
                   1525: * Counted Loops::               
                   1526: * Arbitrary control structures::  
                   1527: * Calls and returns::           
                   1528: * Exception Handling::          
                   1529: @end menu
                   1530: 
                   1531: @node Selection, Simple Loops, Control Structures, Control Structures
                   1532: @subsection Selection
                   1533: @cindex selection control structures
                   1534: @cindex control structures for selection
                   1535: 
                   1536: @cindex @code{IF} control structure
                   1537: @example
                   1538: @var{flag}
                   1539: IF
                   1540:   @var{code}
                   1541: ENDIF
                   1542: @end example
                   1543: or
                   1544: @example
                   1545: @var{flag}
                   1546: IF
                   1547:   @var{code1}
                   1548: ELSE
                   1549:   @var{code2}
                   1550: ENDIF
                   1551: @end example
                   1552: 
                   1553: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   1554: standard, and @code{ENDIF} is not, although it is quite popular. We
                   1555: recommend using @code{ENDIF}, because it is less confusing for people
                   1556: who also know other languages (and is not prone to reinforcing negative
                   1557: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   1558: system that only supplies @code{THEN} is simple:
                   1559: @example
                   1560: : endif   POSTPONE then ; immediate
                   1561: @end example
                   1562: 
                   1563: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   1564: (adv.)}  has the following meanings:
                   1565: @quotation
                   1566: ... 2b: following next after in order ... 3d: as a necessary consequence
                   1567: (if you were there, then you saw them).
                   1568: @end quotation
                   1569: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   1570: and many other programming languages has the meaning 3d.]
                   1571: 
                   1572: Gforth also provides the words @code{?dup-if} and @code{?dup-0=-if}, so
                   1573: you can avoid using @code{?dup}. Using these alternatives is also more
                   1574: efficient than using @code{?dup}. Definitions in plain standard Forth
                   1575: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   1576: @file{compat/control.fs}.
                   1577: 
                   1578: @cindex @code{CASE} control structure
                   1579: @example
                   1580: @var{n}
                   1581: CASE
                   1582:   @var{n1} OF @var{code1} ENDOF
                   1583:   @var{n2} OF @var{code2} ENDOF
                   1584:   @dots{}
                   1585: ENDCASE
                   1586: @end example
                   1587: 
                   1588: Executes the first @var{codei}, where the @var{ni} is equal to
                   1589: @var{n}. A default case can be added by simply writing the code after
                   1590: the last @code{ENDOF}. It may use @var{n}, which is on top of the stack,
                   1591: but must not consume it.
                   1592: 
                   1593: @node Simple Loops, Counted Loops, Selection, Control Structures
                   1594: @subsection Simple Loops
                   1595: @cindex simple loops
                   1596: @cindex loops without count 
                   1597: 
                   1598: @cindex @code{WHILE} loop
                   1599: @example
                   1600: BEGIN
                   1601:   @var{code1}
                   1602:   @var{flag}
                   1603: WHILE
                   1604:   @var{code2}
                   1605: REPEAT
                   1606: @end example
                   1607: 
                   1608: @var{code1} is executed and @var{flag} is computed. If it is true,
                   1609: @var{code2} is executed and the loop is restarted; If @var{flag} is
                   1610: false, execution continues after the @code{REPEAT}.
                   1611: 
                   1612: @cindex @code{UNTIL} loop
                   1613: @example
                   1614: BEGIN
                   1615:   @var{code}
                   1616:   @var{flag}
                   1617: UNTIL
                   1618: @end example
                   1619: 
                   1620: @var{code} is executed. The loop is restarted if @code{flag} is false.
                   1621: 
                   1622: @cindex endless loop
                   1623: @cindex loops, endless
                   1624: @example
                   1625: BEGIN
                   1626:   @var{code}
                   1627: AGAIN
                   1628: @end example
                   1629: 
                   1630: This is an endless loop.
                   1631: 
                   1632: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   1633: @subsection Counted Loops
                   1634: @cindex counted loops
                   1635: @cindex loops, counted
                   1636: @cindex @code{DO} loops
                   1637: 
                   1638: The basic counted loop is:
                   1639: @example
                   1640: @var{limit} @var{start}
                   1641: ?DO
                   1642:   @var{body}
                   1643: LOOP
                   1644: @end example
                   1645: 
                   1646: This performs one iteration for every integer, starting from @var{start}
                   1647: and up to, but excluding @var{limit}. The counter, aka index, can be
                   1648: accessed with @code{i}. E.g., the loop
                   1649: @example
                   1650: 10 0 ?DO
                   1651:   i .
                   1652: LOOP
                   1653: @end example
                   1654: prints
                   1655: @example
                   1656: 0 1 2 3 4 5 6 7 8 9
                   1657: @end example
                   1658: The index of the innermost loop can be accessed with @code{i}, the index
                   1659: of the next loop with @code{j}, and the index of the third loop with
                   1660: @code{k}.
                   1661: 
                   1662: doc-i
                   1663: doc-j
                   1664: doc-k
                   1665: 
                   1666: The loop control data are kept on the return stack, so there are some
                   1667: restrictions on mixing return stack accesses and counted loop
                   1668: words. E.g., if you put values on the return stack outside the loop, you
                   1669: cannot read them inside the loop. If you put values on the return stack
                   1670: within a loop, you have to remove them before the end of the loop and
                   1671: before accessing the index of the loop.
                   1672: 
                   1673: There are several variations on the counted loop:
                   1674: 
                   1675: @code{LEAVE} leaves the innermost counted loop immediately.
                   1676: 
                   1677: If @var{start} is greater than @var{limit}, a @code{?DO} loop is entered
                   1678: (and @code{LOOP} iterates until they become equal by wrap-around
                   1679: arithmetic). This behaviour is usually not what you want. Therefore,
                   1680: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
                   1681: @code{?DO}), which do not enter the loop if @var{start} is greater than
                   1682: @var{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
                   1683: unsigned loop parameters.
                   1684: 
                   1685: @code{LOOP} can be replaced with @code{@var{n} +LOOP}; this updates the
                   1686: index by @var{n} instead of by 1. The loop is terminated when the border
                   1687: between @var{limit-1} and @var{limit} is crossed. E.g.:
                   1688: 
                   1689: @code{4 0 +DO  i .  2 +LOOP}   prints @code{0 2}
                   1690: 
                   1691: @code{4 1 +DO  i .  2 +LOOP}   prints @code{1 3}
                   1692: 
                   1693: @cindex negative increment for counted loops
                   1694: @cindex counted loops with negative increment
                   1695: The behaviour of @code{@var{n} +LOOP} is peculiar when @var{n} is negative:
                   1696: 
                   1697: @code{-1 0 ?DO  i .  -1 +LOOP}  prints @code{0 -1}
                   1698: 
                   1699: @code{ 0 0 ?DO  i .  -1 +LOOP}  prints nothing
                   1700: 
                   1701: Therefore we recommend avoiding @code{@var{n} +LOOP} with negative
                   1702: @var{n}. One alternative is @code{@var{u} -LOOP}, which reduces the
                   1703: index by @var{u} each iteration. The loop is terminated when the border
                   1704: between @var{limit+1} and @var{limit} is crossed. Gforth also provides
                   1705: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   1706: 
                   1707: @code{-2 0 -DO  i .  1 -LOOP}  prints @code{0 -1}
                   1708: 
                   1709: @code{-1 0 -DO  i .  1 -LOOP}  prints @code{0}
                   1710: 
                   1711: @code{ 0 0 -DO  i .  1 -LOOP}  prints nothing
                   1712: 
                   1713: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
                   1714: @code{-LOOP} are not in the ANS Forth standard. However, an
                   1715: implementation for these words that uses only standard words is provided
                   1716: in @file{compat/loops.fs}.
                   1717: 
                   1718: @code{?DO} can also be replaced by @code{DO}. @code{DO} always enters
                   1719: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   1720: if you know that the loop is entered in any case. Such knowledge tends
                   1721: to become invalid during maintenance of a program, and then the
                   1722: @code{DO} will make trouble.
                   1723: 
                   1724: @code{UNLOOP} is used to prepare for an abnormal loop exit, e.g., via
                   1725: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   1726: return stack so @code{EXIT} can get to its return address.
                   1727: 
                   1728: @cindex @code{FOR} loops
                   1729: Another counted loop is
                   1730: @example
                   1731: @var{n}
                   1732: FOR
                   1733:   @var{body}
                   1734: NEXT
                   1735: @end example
                   1736: This is the preferred loop of native code compiler writers who are too
                   1737: lazy to optimize @code{?DO} loops properly. In Gforth, this loop
                   1738: iterates @var{n+1} times; @code{i} produces values starting with @var{n}
                   1739: and ending with 0. Other Forth systems may behave differently, even if
                   1740: they support @code{FOR} loops. To avoid problems, don't use @code{FOR}
                   1741: loops.
                   1742: 
                   1743: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   1744: @subsection Arbitrary control structures
                   1745: @cindex control structures, user-defined
                   1746: 
                   1747: @cindex control-flow stack
                   1748: ANS Forth permits and supports using control structures in a non-nested
                   1749: way. Information about incomplete control structures is stored on the
                   1750: control-flow stack. This stack may be implemented on the Forth data
                   1751: stack, and this is what we have done in Gforth.
                   1752: 
                   1753: @cindex @code{orig}, control-flow stack item
                   1754: @cindex @code{dest}, control-flow stack item
                   1755: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   1756: entry represents a backward branch target. A few words are the basis for
                   1757: building any control structure possible (except control structures that
                   1758: need storage, like calls, coroutines, and backtracking).
                   1759: 
                   1760: doc-if
                   1761: doc-ahead
                   1762: doc-then
                   1763: doc-begin
                   1764: doc-until
                   1765: doc-again
                   1766: doc-cs-pick
                   1767: doc-cs-roll
                   1768: 
                   1769: On many systems control-flow stack items take one word, in Gforth they
                   1770: currently take three (this may change in the future). Therefore it is a
                   1771: really good idea to manipulate the control flow stack with
                   1772: @code{cs-pick} and @code{cs-roll}, not with data stack manipulation
                   1773: words.
                   1774: 
                   1775: Some standard control structure words are built from these words:
                   1776: 
                   1777: doc-else
                   1778: doc-while
                   1779: doc-repeat
                   1780: 
                   1781: Gforth adds some more control-structure words:
                   1782: 
                   1783: doc-endif
                   1784: doc-?dup-if
                   1785: doc-?dup-0=-if
                   1786: 
                   1787: Counted loop words constitute a separate group of words:
                   1788: 
                   1789: doc-?do
                   1790: doc-+do
                   1791: doc-u+do
                   1792: doc--do
                   1793: doc-u-do
                   1794: doc-do
                   1795: doc-for
                   1796: doc-loop
                   1797: doc-+loop
                   1798: doc--loop
                   1799: doc-next
                   1800: doc-leave
                   1801: doc-?leave
                   1802: doc-unloop
                   1803: doc-done
                   1804: 
                   1805: The standard does not allow using @code{cs-pick} and @code{cs-roll} on
                   1806: @i{do-sys}. Our system allows it, but it's your job to ensure that for
                   1807: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   1808: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   1809: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   1810: resolved (by using one of the loop-ending words or @code{DONE}).
                   1811: 
                   1812: Another group of control structure words are
                   1813: 
                   1814: doc-case
                   1815: doc-endcase
                   1816: doc-of
                   1817: doc-endof
                   1818: 
                   1819: @i{case-sys} and @i{of-sys} cannot be processed using @code{cs-pick} and
                   1820: @code{cs-roll}.
                   1821: 
                   1822: @subsubsection Programming Style
                   1823: 
                   1824: In order to ensure readability we recommend that you do not create
                   1825: arbitrary control structures directly, but define new control structure
                   1826: words for the control structure you want and use these words in your
                   1827: program.
                   1828: 
                   1829: E.g., instead of writing
                   1830: 
                   1831: @example
                   1832: begin
                   1833:   ...
                   1834: if [ 1 cs-roll ]
                   1835:   ...
                   1836: again then
                   1837: @end example
                   1838: 
                   1839: we recommend defining control structure words, e.g.,
                   1840: 
                   1841: @example
                   1842: : while ( dest -- orig dest )
                   1843:  POSTPONE if
                   1844:  1 cs-roll ; immediate
                   1845: 
                   1846: : repeat ( orig dest -- )
                   1847:  POSTPONE again
                   1848:  POSTPONE then ; immediate
                   1849: @end example
                   1850: 
                   1851: and then using these to create the control structure:
                   1852: 
                   1853: @example
                   1854: begin
                   1855:   ...
                   1856: while
                   1857:   ...
                   1858: repeat
                   1859: @end example
                   1860: 
                   1861: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   1862: @code{WHILE} are predefined, so in this example it would not be
                   1863: necessary to define them.
                   1864: 
                   1865: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   1866: @subsection Calls and returns
                   1867: @cindex calling a definition
                   1868: @cindex returning from a definition
                   1869: 
1.3       anton    1870: @cindex recursive definitions
                   1871: A definition can be called simply be writing the name of the definition
                   1872: to be called. Note that normally a definition is invisible during its
                   1873: definition. If you want to write a directly recursive definition, you
                   1874: can use @code{recursive} to make the current definition visible.
                   1875: 
                   1876: doc-recursive
                   1877: 
                   1878: Another way to perform a recursive call is
                   1879: 
                   1880: doc-recurse
                   1881: 
1.12      anton    1882: @quotation
                   1883: @progstyle
                   1884: I prefer using @code{recursive} to @code{recurse}, because calling the
                   1885: definition by name is more descriptive (if the name is well-chosen) than
                   1886: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   1887: implementation, it is much better to read (and think) ``now sort the
                   1888: partitions'' than to read ``now do a recursive call''.
                   1889: @end quotation
1.3       anton    1890: 
                   1891: For mutual recursion, use @code{defer}red words, like this:
                   1892: 
                   1893: @example
                   1894: defer foo
                   1895: 
                   1896: : bar ( ... -- ... )
                   1897:  ... foo ... ;
                   1898: 
                   1899: :noname ( ... -- ... )
                   1900:  ... bar ... ;
                   1901: IS foo
                   1902: @end example
                   1903: 
                   1904: When the end of the definition is reached, it returns. An earlier return
                   1905: can be forced using
1.1       anton    1906: 
                   1907: doc-exit
                   1908: 
                   1909: Don't forget to clean up the return stack and @code{UNLOOP} any
                   1910: outstanding @code{?DO}...@code{LOOP}s before @code{EXIT}ing. The
                   1911: primitive compiled by @code{EXIT} is
                   1912: 
                   1913: doc-;s
                   1914: 
                   1915: @node Exception Handling,  , Calls and returns, Control Structures
                   1916: @subsection Exception Handling
                   1917: @cindex Exceptions
                   1918: 
                   1919: doc-catch
                   1920: doc-throw
                   1921: 
                   1922: @node Locals, Defining Words, Control Structures, Words
                   1923: @section Locals
                   1924: @cindex locals
                   1925: 
                   1926: Local variables can make Forth programming more enjoyable and Forth
                   1927: programs easier to read. Unfortunately, the locals of ANS Forth are
                   1928: laden with restrictions. Therefore, we provide not only the ANS Forth
                   1929: locals wordset, but also our own, more powerful locals wordset (we
                   1930: implemented the ANS Forth locals wordset through our locals wordset).
                   1931: 
                   1932: The ideas in this section have also been published in the paper
                   1933: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
                   1934: at EuroForth '94; it is available at
                   1935: @*@url{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
                   1936: 
                   1937: @menu
                   1938: * Gforth locals::               
                   1939: * ANS Forth locals::            
                   1940: @end menu
                   1941: 
                   1942: @node Gforth locals, ANS Forth locals, Locals, Locals
                   1943: @subsection Gforth locals
                   1944: @cindex Gforth locals
                   1945: @cindex locals, Gforth style
                   1946: 
                   1947: Locals can be defined with
                   1948: 
                   1949: @example
                   1950: @{ local1 local2 ... -- comment @}
                   1951: @end example
                   1952: or
                   1953: @example
                   1954: @{ local1 local2 ... @}
                   1955: @end example
                   1956: 
                   1957: E.g.,
                   1958: @example
                   1959: : max @{ n1 n2 -- n3 @}
                   1960:  n1 n2 > if
                   1961:    n1
                   1962:  else
                   1963:    n2
                   1964:  endif ;
                   1965: @end example
                   1966: 
                   1967: The similarity of locals definitions with stack comments is intended. A
                   1968: locals definition often replaces the stack comment of a word. The order
                   1969: of the locals corresponds to the order in a stack comment and everything
                   1970: after the @code{--} is really a comment.
                   1971: 
                   1972: This similarity has one disadvantage: It is too easy to confuse locals
                   1973: declarations with stack comments, causing bugs and making them hard to
                   1974: find. However, this problem can be avoided by appropriate coding
                   1975: conventions: Do not use both notations in the same program. If you do,
                   1976: they should be distinguished using additional means, e.g. by position.
                   1977: 
                   1978: @cindex types of locals
                   1979: @cindex locals types
                   1980: The name of the local may be preceded by a type specifier, e.g.,
                   1981: @code{F:} for a floating point value:
                   1982: 
                   1983: @example
                   1984: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   1985: \ complex multiplication
                   1986:  Ar Br f* Ai Bi f* f-
                   1987:  Ar Bi f* Ai Br f* f+ ;
                   1988: @end example
                   1989: 
                   1990: @cindex flavours of locals
                   1991: @cindex locals flavours
                   1992: @cindex value-flavoured locals
                   1993: @cindex variable-flavoured locals
                   1994: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   1995: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   1996: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   1997: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   1998: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   1999: produces its address (which becomes invalid when the variable's scope is
                   2000: left). E.g., the standard word @code{emit} can be defined in terms of
                   2001: @code{type} like this:
                   2002: 
                   2003: @example
                   2004: : emit @{ C^ char* -- @}
                   2005:     char* 1 type ;
                   2006: @end example
                   2007: 
                   2008: @cindex default type of locals
                   2009: @cindex locals, default type
                   2010: A local without type specifier is a @code{W:} local. Both flavours of
                   2011: locals are initialized with values from the data or FP stack.
                   2012: 
                   2013: Currently there is no way to define locals with user-defined data
                   2014: structures, but we are working on it.
                   2015: 
                   2016: Gforth allows defining locals everywhere in a colon definition. This
                   2017: poses the following questions:
                   2018: 
                   2019: @menu
                   2020: * Where are locals visible by name?::  
                   2021: * How long do locals live?::    
                   2022: * Programming Style::           
                   2023: * Implementation::              
                   2024: @end menu
                   2025: 
                   2026: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   2027: @subsubsection Where are locals visible by name?
                   2028: @cindex locals visibility
                   2029: @cindex visibility of locals
                   2030: @cindex scope of locals
                   2031: 
                   2032: Basically, the answer is that locals are visible where you would expect
                   2033: it in block-structured languages, and sometimes a little longer. If you
                   2034: want to restrict the scope of a local, enclose its definition in
                   2035: @code{SCOPE}...@code{ENDSCOPE}.
                   2036: 
                   2037: doc-scope
                   2038: doc-endscope
                   2039: 
                   2040: These words behave like control structure words, so you can use them
                   2041: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   2042: arbitrary ways.
                   2043: 
                   2044: If you want a more exact answer to the visibility question, here's the
                   2045: basic principle: A local is visible in all places that can only be
                   2046: reached through the definition of the local@footnote{In compiler
                   2047: construction terminology, all places dominated by the definition of the
                   2048: local.}. In other words, it is not visible in places that can be reached
                   2049: without going through the definition of the local. E.g., locals defined
                   2050: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   2051: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   2052: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
                   2053: 
                   2054: The reasoning behind this solution is: We want to have the locals
                   2055: visible as long as it is meaningful. The user can always make the
                   2056: visibility shorter by using explicit scoping. In a place that can
                   2057: only be reached through the definition of a local, the meaning of a
                   2058: local name is clear. In other places it is not: How is the local
                   2059: initialized at the control flow path that does not contain the
                   2060: definition? Which local is meant, if the same name is defined twice in
                   2061: two independent control flow paths?
                   2062: 
                   2063: This should be enough detail for nearly all users, so you can skip the
                   2064: rest of this section. If you really must know all the gory details and
                   2065: options, read on.
                   2066: 
                   2067: In order to implement this rule, the compiler has to know which places
                   2068: are unreachable. It knows this automatically after @code{AHEAD},
                   2069: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   2070: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   2071: compiler that the control flow never reaches that place. If
                   2072: @code{UNREACHABLE} is not used where it could, the only consequence is
                   2073: that the visibility of some locals is more limited than the rule above
                   2074: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   2075: lie to the compiler), buggy code will be produced.
                   2076: 
                   2077: doc-unreachable
                   2078: 
                   2079: Another problem with this rule is that at @code{BEGIN}, the compiler
                   2080: does not know which locals will be visible on the incoming
                   2081: back-edge. All problems discussed in the following are due to this
                   2082: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   2083: loops as examples; the discussion also applies to @code{?DO} and other
                   2084: loops). Perhaps the most insidious example is:
                   2085: @example
                   2086: AHEAD
                   2087: BEGIN
                   2088:   x
                   2089: [ 1 CS-ROLL ] THEN
                   2090:   @{ x @}
                   2091:   ...
                   2092: UNTIL
                   2093: @end example
                   2094: 
                   2095: This should be legal according to the visibility rule. The use of
                   2096: @code{x} can only be reached through the definition; but that appears
                   2097: textually below the use.
                   2098: 
                   2099: From this example it is clear that the visibility rules cannot be fully
                   2100: implemented without major headaches. Our implementation treats common
                   2101: cases as advertised and the exceptions are treated in a safe way: The
                   2102: compiler makes a reasonable guess about the locals visible after a
                   2103: @code{BEGIN}; if it is too pessimistic, the
                   2104: user will get a spurious error about the local not being defined; if the
                   2105: compiler is too optimistic, it will notice this later and issue a
                   2106: warning. In the case above the compiler would complain about @code{x}
                   2107: being undefined at its use. You can see from the obscure examples in
                   2108: this section that it takes quite unusual control structures to get the
                   2109: compiler into trouble, and even then it will often do fine.
                   2110: 
                   2111: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   2112: is that all locals visible before the @code{BEGIN} will also be
                   2113: visible after the @code{BEGIN}. This guess is valid for all loops that
                   2114: are entered only through the @code{BEGIN}, in particular, for normal
                   2115: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   2116: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   2117: compiler. When the branch to the @code{BEGIN} is finally generated by
                   2118: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   2119: warns the user if it was too optimistic:
                   2120: @example
                   2121: IF
                   2122:   @{ x @}
                   2123: BEGIN
                   2124:   \ x ? 
                   2125: [ 1 cs-roll ] THEN
                   2126:   ...
                   2127: UNTIL
                   2128: @end example
                   2129: 
                   2130: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   2131: optimistically assumes that it lives until the @code{THEN}. It notices
                   2132: this difference when it compiles the @code{UNTIL} and issues a
                   2133: warning. The user can avoid the warning, and make sure that @code{x}
                   2134: is not used in the wrong area by using explicit scoping:
                   2135: @example
                   2136: IF
                   2137:   SCOPE
                   2138:   @{ x @}
                   2139:   ENDSCOPE
                   2140: BEGIN
                   2141: [ 1 cs-roll ] THEN
                   2142:   ...
                   2143: UNTIL
                   2144: @end example
                   2145: 
                   2146: Since the guess is optimistic, there will be no spurious error messages
                   2147: about undefined locals.
                   2148: 
                   2149: If the @code{BEGIN} is not reachable from above (e.g., after
                   2150: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   2151: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   2152: defined later. Therefore, the compiler assumes that no locals are
                   2153: visible after the @code{BEGIN}. However, the user can use
                   2154: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   2155: visible at the BEGIN as at the point where the top control-flow stack
                   2156: item was created.
                   2157: 
                   2158: doc-assume-live
                   2159: 
                   2160: E.g.,
                   2161: @example
                   2162: @{ x @}
                   2163: AHEAD
                   2164: ASSUME-LIVE
                   2165: BEGIN
                   2166:   x
                   2167: [ 1 CS-ROLL ] THEN
                   2168:   ...
                   2169: UNTIL
                   2170: @end example
                   2171: 
                   2172: Other cases where the locals are defined before the @code{BEGIN} can be
                   2173: handled by inserting an appropriate @code{CS-ROLL} before the
                   2174: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   2175: behind the @code{ASSUME-LIVE}).
                   2176: 
                   2177: Cases where locals are defined after the @code{BEGIN} (but should be
                   2178: visible immediately after the @code{BEGIN}) can only be handled by
                   2179: rearranging the loop. E.g., the ``most insidious'' example above can be
                   2180: arranged into:
                   2181: @example
                   2182: BEGIN
                   2183:   @{ x @}
                   2184:   ... 0=
                   2185: WHILE
                   2186:   x
                   2187: REPEAT
                   2188: @end example
                   2189: 
                   2190: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
                   2191: @subsubsection How long do locals live?
                   2192: @cindex locals lifetime
                   2193: @cindex lifetime of locals
                   2194: 
                   2195: The right answer for the lifetime question would be: A local lives at
                   2196: least as long as it can be accessed. For a value-flavoured local this
                   2197: means: until the end of its visibility. However, a variable-flavoured
                   2198: local could be accessed through its address far beyond its visibility
                   2199: scope. Ultimately, this would mean that such locals would have to be
                   2200: garbage collected. Since this entails un-Forth-like implementation
                   2201: complexities, I adopted the same cowardly solution as some other
                   2202: languages (e.g., C): The local lives only as long as it is visible;
                   2203: afterwards its address is invalid (and programs that access it
                   2204: afterwards are erroneous).
                   2205: 
                   2206: @node Programming Style, Implementation, How long do locals live?, Gforth locals
                   2207: @subsubsection Programming Style
                   2208: @cindex locals programming style
                   2209: @cindex programming style, locals
                   2210: 
                   2211: The freedom to define locals anywhere has the potential to change
                   2212: programming styles dramatically. In particular, the need to use the
                   2213: return stack for intermediate storage vanishes. Moreover, all stack
                   2214: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   2215: determined arguments) can be eliminated: If the stack items are in the
                   2216: wrong order, just write a locals definition for all of them; then
                   2217: write the items in the order you want.
                   2218: 
                   2219: This seems a little far-fetched and eliminating stack manipulations is
                   2220: unlikely to become a conscious programming objective. Still, the number
                   2221: of stack manipulations will be reduced dramatically if local variables
                   2222: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
                   2223: a traditional implementation of @code{max}).
                   2224: 
                   2225: This shows one potential benefit of locals: making Forth programs more
                   2226: readable. Of course, this benefit will only be realized if the
                   2227: programmers continue to honour the principle of factoring instead of
                   2228: using the added latitude to make the words longer.
                   2229: 
                   2230: @cindex single-assignment style for locals
                   2231: Using @code{TO} can and should be avoided.  Without @code{TO},
                   2232: every value-flavoured local has only a single assignment and many
                   2233: advantages of functional languages apply to Forth. I.e., programs are
                   2234: easier to analyse, to optimize and to read: It is clear from the
                   2235: definition what the local stands for, it does not turn into something
                   2236: different later.
                   2237: 
                   2238: E.g., a definition using @code{TO} might look like this:
                   2239: @example
                   2240: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   2241:  u1 u2 min 0
                   2242:  ?do
                   2243:    addr1 c@@ addr2 c@@ -
                   2244:    ?dup-if
                   2245:      unloop exit
                   2246:    then
                   2247:    addr1 char+ TO addr1
                   2248:    addr2 char+ TO addr2
                   2249:  loop
                   2250:  u1 u2 - ;
                   2251: @end example
                   2252: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   2253: every loop iteration. @code{strcmp} is a typical example of the
                   2254: readability problems of using @code{TO}. When you start reading
                   2255: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   2256: string. Only near the end of the loop you realize that it is something
                   2257: else.
                   2258: 
                   2259: This can be avoided by defining two locals at the start of the loop that
                   2260: are initialized with the right value for the current iteration.
                   2261: @example
                   2262: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   2263:  addr1 addr2
                   2264:  u1 u2 min 0 
                   2265:  ?do @{ s1 s2 @}
                   2266:    s1 c@@ s2 c@@ -
                   2267:    ?dup-if
                   2268:      unloop exit
                   2269:    then
                   2270:    s1 char+ s2 char+
                   2271:  loop
                   2272:  2drop
                   2273:  u1 u2 - ;
                   2274: @end example
                   2275: Here it is clear from the start that @code{s1} has a different value
                   2276: in every loop iteration.
                   2277: 
                   2278: @node Implementation,  , Programming Style, Gforth locals
                   2279: @subsubsection Implementation
                   2280: @cindex locals implementation
                   2281: @cindex implementation of locals
                   2282: 
                   2283: @cindex locals stack
                   2284: Gforth uses an extra locals stack. The most compelling reason for
                   2285: this is that the return stack is not float-aligned; using an extra stack
                   2286: also eliminates the problems and restrictions of using the return stack
                   2287: as locals stack. Like the other stacks, the locals stack grows toward
                   2288: lower addresses. A few primitives allow an efficient implementation:
                   2289: 
                   2290: doc-@local#
                   2291: doc-f@local#
                   2292: doc-laddr#
                   2293: doc-lp+!#
                   2294: doc-lp!
                   2295: doc->l
                   2296: doc-f>l
                   2297: 
                   2298: In addition to these primitives, some specializations of these
                   2299: primitives for commonly occurring inline arguments are provided for
                   2300: efficiency reasons, e.g., @code{@@local0} as specialization of
                   2301: @code{@@local#} for the inline argument 0. The following compiling words
                   2302: compile the right specialized version, or the general version, as
                   2303: appropriate:
                   2304: 
                   2305: doc-compile-@local
                   2306: doc-compile-f@local
                   2307: doc-compile-lp+!
                   2308: 
                   2309: Combinations of conditional branches and @code{lp+!#} like
                   2310: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   2311: is taken) are provided for efficiency and correctness in loops.
                   2312: 
                   2313: A special area in the dictionary space is reserved for keeping the
                   2314: local variable names. @code{@{} switches the dictionary pointer to this
                   2315: area and @code{@}} switches it back and generates the locals
                   2316: initializing code. @code{W:} etc.@ are normal defining words. This
                   2317: special area is cleared at the start of every colon definition.
                   2318: 
                   2319: @cindex wordlist for defining locals
                   2320: A special feature of Gforth's dictionary is used to implement the
                   2321: definition of locals without type specifiers: every wordlist (aka
                   2322: vocabulary) has its own methods for searching
                   2323: etc. (@pxref{Wordlists}). For the present purpose we defined a wordlist
                   2324: with a special search method: When it is searched for a word, it
                   2325: actually creates that word using @code{W:}. @code{@{} changes the search
                   2326: order to first search the wordlist containing @code{@}}, @code{W:} etc.,
                   2327: and then the wordlist for defining locals without type specifiers.
                   2328: 
                   2329: The lifetime rules support a stack discipline within a colon
                   2330: definition: The lifetime of a local is either nested with other locals
                   2331: lifetimes or it does not overlap them.
                   2332: 
                   2333: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   2334: pointer manipulation is generated. Between control structure words
                   2335: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   2336: is the simplest of the other three control flow words. It has to
                   2337: restore the locals stack depth of the corresponding @code{BEGIN}
                   2338: before branching. The code looks like this:
                   2339: @format
                   2340: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   2341: @code{branch} <begin>
                   2342: @end format
                   2343: 
                   2344: @code{UNTIL} is a little more complicated: If it branches back, it
                   2345: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   2346: the locals stack must not be changed. The compiler generates the
                   2347: following code:
                   2348: @format
                   2349: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   2350: @end format
                   2351: The locals stack pointer is only adjusted if the branch is taken.
                   2352: 
                   2353: @code{THEN} can produce somewhat inefficient code:
                   2354: @format
                   2355: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   2356: <orig target>:
                   2357: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   2358: @end format
                   2359: The second @code{lp+!#} adjusts the locals stack pointer from the
                   2360: level at the @var{orig} point to the level after the @code{THEN}. The
                   2361: first @code{lp+!#} adjusts the locals stack pointer from the current
                   2362: level to the level at the orig point, so the complete effect is an
                   2363: adjustment from the current level to the right level after the
                   2364: @code{THEN}.
                   2365: 
                   2366: @cindex locals information on the control-flow stack
                   2367: @cindex control-flow stack items, locals information
                   2368: In a conventional Forth implementation a dest control-flow stack entry
                   2369: is just the target address and an orig entry is just the address to be
                   2370: patched. Our locals implementation adds a wordlist to every orig or dest
                   2371: item. It is the list of locals visible (or assumed visible) at the point
                   2372: described by the entry. Our implementation also adds a tag to identify
                   2373: the kind of entry, in particular to differentiate between live and dead
                   2374: (reachable and unreachable) orig entries.
                   2375: 
                   2376: A few unusual operations have to be performed on locals wordlists:
                   2377: 
                   2378: doc-common-list
                   2379: doc-sub-list?
                   2380: doc-list-size
                   2381: 
                   2382: Several features of our locals wordlist implementation make these
                   2383: operations easy to implement: The locals wordlists are organised as
                   2384: linked lists; the tails of these lists are shared, if the lists
                   2385: contain some of the same locals; and the address of a name is greater
                   2386: than the address of the names behind it in the list.
                   2387: 
                   2388: Another important implementation detail is the variable
                   2389: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   2390: determine if they can be reached directly or only through the branch
                   2391: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   2392: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   2393: definition, by @code{BEGIN} and usually by @code{THEN}.
                   2394: 
                   2395: Counted loops are similar to other loops in most respects, but
                   2396: @code{LEAVE} requires special attention: It performs basically the same
                   2397: service as @code{AHEAD}, but it does not create a control-flow stack
                   2398: entry. Therefore the information has to be stored elsewhere;
                   2399: traditionally, the information was stored in the target fields of the
                   2400: branches created by the @code{LEAVE}s, by organizing these fields into a
                   2401: linked list. Unfortunately, this clever trick does not provide enough
                   2402: space for storing our extended control flow information. Therefore, we
                   2403: introduce another stack, the leave stack. It contains the control-flow
                   2404: stack entries for all unresolved @code{LEAVE}s.
                   2405: 
                   2406: Local names are kept until the end of the colon definition, even if
                   2407: they are no longer visible in any control-flow path. In a few cases
                   2408: this may lead to increased space needs for the locals name area, but
                   2409: usually less than reclaiming this space would cost in code size.
                   2410: 
                   2411: 
                   2412: @node ANS Forth locals,  , Gforth locals, Locals
                   2413: @subsection ANS Forth locals
                   2414: @cindex locals, ANS Forth style
                   2415: 
                   2416: The ANS Forth locals wordset does not define a syntax for locals, but
                   2417: words that make it possible to define various syntaxes. One of the
                   2418: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   2419: wordset, i.e.:
                   2420: 
                   2421: @example
                   2422: @{ local1 local2 ... -- comment @}
                   2423: @end example
                   2424: or
                   2425: @example
                   2426: @{ local1 local2 ... @}
                   2427: @end example
                   2428: 
                   2429: The order of the locals corresponds to the order in a stack comment. The
                   2430: restrictions are:
                   2431: 
                   2432: @itemize @bullet
                   2433: @item
                   2434: Locals can only be cell-sized values (no type specifiers are allowed).
                   2435: @item
                   2436: Locals can be defined only outside control structures.
                   2437: @item
                   2438: Locals can interfere with explicit usage of the return stack. For the
                   2439: exact (and long) rules, see the standard. If you don't use return stack
                   2440: accessing words in a definition using locals, you will be all right. The
                   2441: purpose of this rule is to make locals implementation on the return
                   2442: stack easier.
                   2443: @item
                   2444: The whole definition must be in one line.
                   2445: @end itemize
                   2446: 
                   2447: Locals defined in this way behave like @code{VALUE}s (@xref{Simple
                   2448: Defining Words}). I.e., they are initialized from the stack. Using their
                   2449: name produces their value. Their value can be changed using @code{TO}.
                   2450: 
                   2451: Since this syntax is supported by Gforth directly, you need not do
                   2452: anything to use it. If you want to port a program using this syntax to
                   2453: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   2454: syntax on the other system.
                   2455: 
                   2456: Note that a syntax shown in the standard, section A.13 looks
                   2457: similar, but is quite different in having the order of locals
                   2458: reversed. Beware!
                   2459: 
                   2460: The ANS Forth locals wordset itself consists of the following word
                   2461: 
                   2462: doc-(local)
                   2463: 
                   2464: The ANS Forth locals extension wordset defines a syntax, but it is so
                   2465: awful that we strongly recommend not to use it. We have implemented this
                   2466: syntax to make porting to Gforth easy, but do not document it here. The
                   2467: problem with this syntax is that the locals are defined in an order
                   2468: reversed with respect to the standard stack comment notation, making
                   2469: programs harder to read, and easier to misread and miswrite. The only
                   2470: merit of this syntax is that it is easy to implement using the ANS Forth
                   2471: locals wordset.
                   2472: 
1.5       anton    2473: @node Defining Words, Structures, Locals, Words
1.1       anton    2474: @section Defining Words
                   2475: @cindex defining words
                   2476: 
                   2477: @menu
                   2478: * Simple Defining Words::       
                   2479: * Colon Definitions::           
                   2480: * User-defined Defining Words::  
                   2481: * Supplying names::             
                   2482: * Interpretation and Compilation Semantics::  
                   2483: @end menu
                   2484: 
                   2485: @node Simple Defining Words, Colon Definitions, Defining Words, Defining Words
                   2486: @subsection Simple Defining Words
                   2487: @cindex simple defining words
                   2488: @cindex defining words, simple
                   2489: 
                   2490: doc-constant
                   2491: doc-2constant
                   2492: doc-fconstant
                   2493: doc-variable
                   2494: doc-2variable
                   2495: doc-fvariable
                   2496: doc-create
                   2497: doc-user
                   2498: doc-value
                   2499: doc-to
                   2500: doc-defer
                   2501: doc-is
                   2502: 
                   2503: @node Colon Definitions, User-defined Defining Words, Simple Defining Words, Defining Words
                   2504: @subsection Colon Definitions
                   2505: @cindex colon definitions
                   2506: 
                   2507: @example
                   2508: : name ( ... -- ... )
                   2509:     word1 word2 word3 ;
                   2510: @end example
                   2511: 
                   2512: creates a word called @code{name}, that, upon execution, executes
                   2513: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
                   2514: 
                   2515: The explanation above is somewhat superficial. @xref{Interpretation and
                   2516: Compilation Semantics} for an in-depth discussion of some of the issues
                   2517: involved.
                   2518: 
                   2519: doc-:
                   2520: doc-;
                   2521: 
                   2522: @node User-defined Defining Words, Supplying names, Colon Definitions, Defining Words
                   2523: @subsection User-defined Defining Words
                   2524: @cindex user-defined defining words
                   2525: @cindex defining words, user-defined
                   2526: 
                   2527: You can create new defining words simply by wrapping defining-time code
                   2528: around existing defining words and putting the sequence in a colon
                   2529: definition.
                   2530: 
                   2531: @cindex @code{CREATE} ... @code{DOES>}
                   2532: If you want the words defined with your defining words to behave
                   2533: differently from words defined with standard defining words, you can
                   2534: write your defining word like this:
                   2535: 
                   2536: @example
                   2537: : def-word ( "name" -- )
                   2538:     Create @var{code1}
                   2539: DOES> ( ... -- ... )
                   2540:     @var{code2} ;
                   2541: 
                   2542: def-word name
                   2543: @end example
                   2544: 
                   2545: Technically, this fragment defines a defining word @code{def-word}, and
                   2546: a word @code{name}; when you execute @code{name}, the address of the
                   2547: body of @code{name} is put on the data stack and @var{code2} is executed
                   2548: (the address of the body of @code{name} is the address @code{HERE}
                   2549: returns immediately after the @code{CREATE}).
                   2550: 
                   2551: In other words, if you make the following definitions:
                   2552: 
                   2553: @example
                   2554: : def-word1 ( "name" -- )
                   2555:     Create @var{code1} ;
                   2556: 
                   2557: : action1 ( ... -- ... )
                   2558:     @var{code2} ;
                   2559: 
                   2560: def-word name1
                   2561: @end example
                   2562: 
                   2563: Using @code{name1 action1} is equivalent to using @code{name}.
                   2564: 
                   2565: E.g., you can implement @code{Constant} in this way:
                   2566: 
                   2567: @example
                   2568: : constant ( w "name" -- )
                   2569:     create ,
                   2570: DOES> ( -- w )
                   2571:     @@ ;
                   2572: @end example
                   2573: 
                   2574: When you create a constant with @code{5 constant five}, first a new word
                   2575: @code{five} is created, then the value 5 is laid down in the body of
                   2576: @code{five} with @code{,}. When @code{five} is invoked, the address of
                   2577: the body is put on the stack, and @code{@@} retrieves the value 5.
                   2578: 
                   2579: @cindex stack effect of @code{DOES>}-parts
                   2580: @cindex @code{DOES>}-parts, stack effect
                   2581: In the example above the stack comment after the @code{DOES>} specifies
                   2582: the stack effect of the defined words, not the stack effect of the
                   2583: following code (the following code expects the address of the body on
                   2584: the top of stack, which is not reflected in the stack comment). This is
                   2585: the convention that I use and recommend (it clashes a bit with using
                   2586: locals declarations for stack effect specification, though).
                   2587: 
                   2588: @subsubsection Applications of @code{CREATE..DOES>}
                   2589: @cindex @code{CREATE} ... @code{DOES>}, applications
                   2590: 
                   2591: You may wonder how to use this feature. Here are some usage patterns:
                   2592: 
                   2593: @cindex factoring similar colon definitions
                   2594: When you see a sequence of code occurring several times, and you can
                   2595: identify a meaning, you will factor it out as a colon definition. When
                   2596: you see similar colon definitions, you can factor them using
                   2597: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   2598: that look very similar:
                   2599: @example
                   2600: : ori, ( reg-target reg-source n -- )
                   2601:     0 asm-reg-reg-imm ;
                   2602: : andi, ( reg-target reg-source n -- )
                   2603:     1 asm-reg-reg-imm ;
                   2604: @end example
                   2605: 
                   2606: This could be factored with:
                   2607: @example
                   2608: : reg-reg-imm ( op-code -- )
                   2609:     create ,
                   2610: DOES> ( reg-target reg-source n -- )
                   2611:     @@ asm-reg-reg-imm ;
                   2612: 
                   2613: 0 reg-reg-imm ori,
                   2614: 1 reg-reg-imm andi,
                   2615: @end example
                   2616: 
                   2617: @cindex currying
                   2618: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   2619: supply a part of the parameters for a word (known as @dfn{currying} in
                   2620: the functional language community). E.g., @code{+} needs two
                   2621: parameters. Creating versions of @code{+} with one parameter fixed can
                   2622: be done like this:
                   2623: @example
                   2624: : curry+ ( n1 -- )
                   2625:     create ,
                   2626: DOES> ( n2 -- n1+n2 )
                   2627:     @@ + ;
                   2628: 
                   2629:  3 curry+ 3+
                   2630: -2 curry+ 2-
                   2631: @end example
                   2632: 
                   2633: @subsubsection The gory details of @code{CREATE..DOES>}
                   2634: @cindex @code{CREATE} ... @code{DOES>}, details
                   2635: 
                   2636: doc-does>
                   2637: 
                   2638: @cindex @code{DOES>} in a separate definition
                   2639: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   2640: same definition; E.g., you can put the @code{DOES>}-part in a separate
                   2641: definition. This allows us to, e.g., select among different DOES>-parts:
                   2642: @example
                   2643: : does1 
                   2644: DOES> ( ... -- ... )
                   2645:     ... ;
                   2646: 
                   2647: : does2
                   2648: DOES> ( ... -- ... )
                   2649:     ... ;
                   2650: 
                   2651: : def-word ( ... -- ... )
                   2652:     create ...
                   2653:     IF
                   2654:        does1
                   2655:     ELSE
                   2656:        does2
                   2657:     ENDIF ;
                   2658: @end example
                   2659: 
                   2660: @cindex @code{DOES>} in interpretation state
                   2661: In a standard program you can apply a @code{DOES>}-part only if the last
                   2662: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   2663: will override the behaviour of the last word defined in any case. In a
                   2664: standard program, you can use @code{DOES>} only in a colon
                   2665: definition. In Gforth, you can also use it in interpretation state, in a
                   2666: kind of one-shot mode:
                   2667: @example
                   2668: CREATE name ( ... -- ... )
                   2669:   @var{initialization}
                   2670: DOES>
                   2671:   @var{code} ;
                   2672: @end example
                   2673: This is equivalent to the standard
                   2674: @example
                   2675: :noname
                   2676: DOES>
                   2677:     @var{code} ;
                   2678: CREATE name EXECUTE ( ... -- ... )
                   2679:     @var{initialization}
                   2680: @end example
                   2681: 
                   2682: You can get the address of the body of a word with
                   2683: 
                   2684: doc->body
                   2685: 
                   2686: @node Supplying names, Interpretation and Compilation Semantics, User-defined Defining Words, Defining Words
                   2687: @subsection Supplying names for the defined words
                   2688: @cindex names for defined words
                   2689: @cindex defining words, name parameter
                   2690: 
                   2691: @cindex defining words, name given in a string
                   2692: By default, defining words take the names for the defined words from the
                   2693: input stream. Sometimes you want to supply the name from a string. You
                   2694: can do this with
                   2695: 
                   2696: doc-nextname
                   2697: 
                   2698: E.g.,
                   2699: 
                   2700: @example
                   2701: s" foo" nextname create
                   2702: @end example
                   2703: is equivalent to
                   2704: @example
                   2705: create foo
                   2706: @end example
                   2707: 
                   2708: @cindex defining words without name
                   2709: Sometimes you want to define a word without a name. You can do this with
                   2710: 
                   2711: doc-noname
                   2712: 
                   2713: @cindex execution token of last defined word
                   2714: To make any use of the newly defined word, you need its execution
                   2715: token. You can get it with
                   2716: 
                   2717: doc-lastxt
                   2718: 
                   2719: E.g., you can initialize a deferred word with an anonymous colon
                   2720: definition:
                   2721: @example
                   2722: Defer deferred
                   2723: noname : ( ... -- ... )
                   2724:   ... ;
                   2725: lastxt IS deferred
                   2726: @end example
                   2727: 
                   2728: @code{lastxt} also works when the last word was not defined as
                   2729: @code{noname}. 
                   2730: 
                   2731: The standard has also recognized the need for anonymous words and
                   2732: provides
                   2733: 
                   2734: doc-:noname
                   2735: 
                   2736: This leaves the execution token for the word on the stack after the
                   2737: closing @code{;}. You can rewrite the last example with @code{:noname}:
                   2738: @example
                   2739: Defer deferred
                   2740: :noname ( ... -- ... )
                   2741:   ... ;
                   2742: IS deferred
                   2743: @end example
                   2744: 
                   2745: @node Interpretation and Compilation Semantics,  , Supplying names, Defining Words
                   2746: @subsection Interpretation and Compilation Semantics
                   2747: @cindex semantics, interpretation and compilation
                   2748: 
                   2749: @cindex interpretation semantics
                   2750: The @dfn{interpretation semantics} of a word are what the text
                   2751: interpreter does when it encounters the word in interpret state. It also
                   2752: appears in some other contexts, e.g., the execution token returned by
                   2753: @code{' @var{word}} identifies the interpretation semantics of
                   2754: @var{word} (in other words, @code{' @var{word} execute} is equivalent to
                   2755: interpret-state text interpretation of @code{@var{word}}).
                   2756: 
                   2757: @cindex compilation semantics
                   2758: The @dfn{compilation semantics} of a word are what the text interpreter
                   2759: does when it encounters the word in compile state. It also appears in
                   2760: other contexts, e.g, @code{POSTPONE @var{word}} compiles@footnote{In
                   2761: standard terminology, ``appends to the current definition''.} the
                   2762: compilation semantics of @var{word}.
                   2763: 
                   2764: @cindex execution semantics
                   2765: The standard also talks about @dfn{execution semantics}. They are used
                   2766: only for defining the interpretation and compilation semantics of many
                   2767: words. By default, the interpretation semantics of a word are to
                   2768: @code{execute} its execution semantics, and the compilation semantics of
                   2769: a word are to @code{compile,} its execution semantics.@footnote{In
                   2770: standard terminology: The default interpretation semantics are its
                   2771: execution semantics; the default compilation semantics are to append its
                   2772: execution semantics to the execution semantics of the current
                   2773: definition.}
                   2774: 
                   2775: @cindex immediate words
                   2776: You can change the compilation semantics into @code{execute}ing the
                   2777: execution semantics with
                   2778: 
                   2779: doc-immediate
                   2780: 
                   2781: @cindex compile-only words
                   2782: You can remove the interpretation semantics of a word with
                   2783: 
                   2784: doc-compile-only
                   2785: doc-restrict
                   2786: 
                   2787: Note that ticking (@code{'}) compile-only words gives an error
                   2788: (``Interpreting a compile-only word'').
                   2789: 
                   2790: Gforth also allows you to define words with arbitrary combinations of
                   2791: interpretation and compilation semantics.
                   2792: 
                   2793: doc-interpret/compile:
                   2794: 
                   2795: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   2796: recommend that you do not define such words, as cute as they may be:
                   2797: they make it hard to get at both parts of the word in some contexts.
                   2798: E.g., assume you want to get an execution token for the compilation
                   2799: part. Instead, define two words, one that embodies the interpretation
1.15      anton    2800: part, and one that embodies the compilation part.  Once you have done
                   2801: that, you can define a combined word with @code{interpret/compile:} for
                   2802: the convenience of your users.
1.1       anton    2803: 
1.15      anton    2804: You also might try to provide an optimizing implementation of the
                   2805: default compilation semantics with this feature, like this:
1.1       anton    2806: 
                   2807: @example
                   2808: :noname
                   2809:    foo bar ;
                   2810: :noname
                   2811:    POSTPONE foo POSTPONE bar ;
                   2812: interpret/compile: foobar
                   2813: @end example
                   2814: 
1.15      anton    2815: as an optimizing version of
                   2816: 
                   2817: @example
                   2818: : foobar
                   2819:     foo bar ;
                   2820: @end example
                   2821: 
                   2822: Unfortunately, this does not work correctly with @code{[compile]},
                   2823: because @code{[compile]} assumes that the compilation semantics of all
                   2824: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
                   2825: foobar} would compile the compilation semantics for the optimizing
                   2826: @code{foobar}, whereas it would compile the interpretation semantics for
                   2827: the non-optimizing @code{foobar}.
1.1       anton    2828: 
                   2829: @cindex state-smart words are a bad idea
                   2830: Some people try to use state-smart words to emulate the feature provided
                   2831: by @code{interpret/compile:} (words are state-smart if they check
                   2832: @code{STATE} during execution). E.g., they would try to code
                   2833: @code{foobar} like this:
                   2834: 
                   2835: @example
                   2836: : foobar
                   2837:   STATE @@
                   2838:   IF ( compilation state )
                   2839:     POSTPONE foo POSTPONE bar
                   2840:   ELSE
                   2841:     foo bar
                   2842:   ENDIF ; immediate
                   2843: @end example
                   2844: 
                   2845: While this works if @code{foobar} is processed only by the text
                   2846: interpreter, it does not work in other contexts (like @code{'} or
                   2847: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   2848: for a state-smart word, not for the interpretation semantics of the
                   2849: original @code{foobar}; when you execute this execution token (directly
                   2850: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   2851: state, the result will not be what you expected (i.e., it will not
                   2852: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   2853: write them!
                   2854: 
                   2855: @cindex defining words with arbitrary semantics combinations
                   2856: It is also possible to write defining words that define words with
1.15      anton    2857: arbitrary combinations of interpretation and compilation semantics. In
                   2858: general, this looks like:
1.1       anton    2859: 
                   2860: @example
                   2861: : def-word
                   2862:     create-interpret/compile
                   2863:     @var{code1}
                   2864: interpretation>
                   2865:     @var{code2}
                   2866: <interpretation
                   2867: compilation>
                   2868:     @var{code3}
                   2869: <compilation ;
                   2870: @end example
                   2871: 
                   2872: For a @var{word} defined with @code{def-word}, the interpretation
                   2873: semantics are to push the address of the body of @var{word} and perform
                   2874: @var{code2}, and the compilation semantics are to push the address of
                   2875: the body of @var{word} and perform @var{code3}. E.g., @code{constant}
1.15      anton    2876: can also be defined like this (except that the defined constants don't
                   2877: behave correctly when @code{[compile]}d):
1.1       anton    2878: 
                   2879: @example
                   2880: : constant ( n "name" -- )
                   2881:     create-interpret/compile
                   2882:     ,
                   2883: interpretation> ( -- n )
                   2884:     @@
                   2885: <interpretation
                   2886: compilation> ( compilation. -- ; run-time. -- n )
                   2887:     @@ postpone literal
                   2888: <compilation ;
                   2889: @end example
                   2890: 
                   2891: doc-create-interpret/compile
                   2892: doc-interpretation>
                   2893: doc-<interpretation
                   2894: doc-compilation>
                   2895: doc-<compilation
                   2896: 
                   2897: Note that words defined with @code{interpret/compile:} and
                   2898: @code{create-interpret/compile} have an extended header structure that
                   2899: differs from other words; however, unless you try to access them with
                   2900: plain address arithmetic, you should not notice this. Words for
                   2901: accessing the header structure usually know how to deal with this; e.g.,
                   2902: @code{' word >body} also gives you the body of a word created with
                   2903: @code{create-interpret/compile}.
                   2904: 
1.5       anton    2905: @c ----------------------------------------------------------
1.12      anton    2906: @node Structures, Object-oriented Forth, Defining Words, Words
1.5       anton    2907: @section  Structures
                   2908: @cindex structures
                   2909: @cindex records
                   2910: 
                   2911: This section presents the structure package that comes with Gforth. A
                   2912: version of the package implemented in plain ANS Forth is available in
                   2913: @file{compat/struct.fs}. This package was inspired by a posting on
                   2914: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   2915: possibly John Hayes). A version of this section has been published in
                   2916: ???. Marcel Hendrix provided helpful comments.
                   2917: 
                   2918: @menu
                   2919: * Why explicit structure support?::  
                   2920: * Structure Usage::             
                   2921: * Structure Naming Convention::  
                   2922: * Structure Implementation::    
                   2923: * Structure Glossary::          
                   2924: @end menu
                   2925: 
                   2926: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   2927: @subsection Why explicit structure support?
                   2928: 
                   2929: @cindex address arithmetic for structures
                   2930: @cindex structures using address arithmetic
                   2931: If we want to use a structure containing several fields, we could simply
                   2932: reserve memory for it, and access the fields using address arithmetic
                   2933: (@pxref{Address arithmetic}). As an example, consider a structure with
                   2934: the following fields
                   2935: 
                   2936: @table @code
                   2937: @item a
                   2938: is a float
                   2939: @item b
                   2940: is a cell
                   2941: @item c
                   2942: is a float
                   2943: @end table
                   2944: 
                   2945: Given the (float-aligned) base address of the structure we get the
                   2946: address of the field
                   2947: 
                   2948: @table @code
                   2949: @item a
                   2950: without doing anything further.
                   2951: @item b
                   2952: with @code{float+}
                   2953: @item c
                   2954: with @code{float+ cell+ faligned}
                   2955: @end table
                   2956: 
                   2957: It is easy to see that this can become quite tiring. 
                   2958: 
                   2959: Moreover, it is not very readable, because seeing a
                   2960: @code{cell+} tells us neither which kind of structure is
                   2961: accessed nor what field is accessed; we have to somehow infer the kind
                   2962: of structure, and then look up in the documentation, which field of
                   2963: that structure corresponds to that offset.
                   2964: 
                   2965: Finally, this kind of address arithmetic also causes maintenance
                   2966: troubles: If you add or delete a field somewhere in the middle of the
                   2967: structure, you have to find and change all computations for the fields
                   2968: afterwards.
                   2969: 
                   2970: So, instead of using @code{cell+} and friends directly, how
                   2971: about storing the offsets in constants:
                   2972: 
                   2973: @example
                   2974: 0 constant a-offset
                   2975: 0 float+ constant b-offset
                   2976: 0 float+ cell+ faligned c-offset
                   2977: @end example
                   2978: 
                   2979: Now we can get the address of field @code{x} with @code{x-offset
                   2980: +}. This is much better in all respects. Of course, you still
                   2981: have to change all later offset definitions if you add a field. You can
                   2982: fix this by declaring the offsets in the following way:
                   2983: 
                   2984: @example
                   2985: 0 constant a-offset
                   2986: a-offset float+ constant b-offset
                   2987: b-offset cell+ faligned constant c-offset
                   2988: @end example
                   2989: 
                   2990: Since we always use the offsets with @code{+}, using a defining
                   2991: word @code{cfield} that includes the @code{+} in the
                   2992: action of the defined word offers itself:
                   2993: 
                   2994: @example
                   2995: : cfield ( n "name" -- )
                   2996:     create ,
                   2997: does> ( name execution: addr1 -- addr2 )
                   2998:     @@ + ;
                   2999: 
                   3000: 0 cfield a
                   3001: 0 a float+ cfield b
                   3002: 0 b cell+ faligned cfield c
                   3003: @end example
                   3004: 
                   3005: Instead of @code{x-offset +}, we now simply write @code{x}.
                   3006: 
                   3007: The structure field words now can be used quite nicely. However,
                   3008: their definition is still a bit cumbersome: We have to repeat the
                   3009: name, the information about size and alignment is distributed before
                   3010: and after the field definitions etc.  The structure package presented
                   3011: here addresses these problems.
                   3012: 
                   3013: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   3014: @subsection Structure Usage
                   3015: @cindex structure usage
                   3016: 
                   3017: @cindex @code{field} usage
                   3018: @cindex @code{struct} usage
                   3019: @cindex @code{end-struct} usage
                   3020: You can define a structure for a (data-less) linked list with
                   3021: @example
                   3022: struct
                   3023:     cell% field list-next
                   3024: end-struct list%
                   3025: @end example
                   3026: 
                   3027: With the address of the list node on the stack, you can compute the
                   3028: address of the field that contains the address of the next node with
                   3029: @code{list-next}. E.g., you can determine the length of a list
                   3030: with:
                   3031: 
                   3032: @example
                   3033: : list-length ( list -- n )
                   3034: \ "list" is a pointer to the first element of a linked list
                   3035: \ "n" is the length of the list
                   3036:     0 begin ( list1 n1 )
                   3037:         over
                   3038:     while ( list1 n1 )
                   3039:         1+ swap list-next @@ swap
                   3040:     repeat
                   3041:     nip ;
                   3042: @end example
                   3043: 
                   3044: You can reserve memory for a list node in the dictionary with
                   3045: @code{list% %allot}, which leaves the address of the list node on the
                   3046: stack. For the equivalent allocation on the heap you can use @code{list%
                   3047: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   3048: use @code{list% %allocate}). You can also get the the size of a list
                   3049: node with @code{list% %size} and it's alignment with @code{list%
                   3050: %alignment}.
                   3051: 
                   3052: Note that in ANS Forth the body of a @code{create}d word is
                   3053: @code{aligned} but not necessarily @code{faligned};
                   3054: therefore, if you do a
                   3055: @example
                   3056: create @emph{name} foo% %allot
                   3057: @end example
                   3058: 
                   3059: then the memory alloted for @code{foo%} is
                   3060: guaranteed to start at the body of @code{@emph{name}} only if
                   3061: @code{foo%} contains only character, cell and double fields.
                   3062: 
                   3063: @cindex strcutures containing structures
                   3064: You can also include a structure @code{foo%} as field of
                   3065: another structure, with:
                   3066: @example
                   3067: struct
                   3068: ...
                   3069:     foo% field ...
                   3070: ...
                   3071: end-struct ...
                   3072: @end example
                   3073: 
                   3074: @cindex structure extension
                   3075: @cindex extended records
                   3076: Instead of starting with an empty structure, you can also extend an
                   3077: existing structure. E.g., a plain linked list without data, as defined
                   3078: above, is hardly useful; You can extend it to a linked list of integers,
                   3079: like this:@footnote{This feature is also known as @emph{extended
                   3080: records}. It is the main innovation in the Oberon language; in other
                   3081: words, adding this feature to Modula-2 led Wirth to create a new
                   3082: language, write a new compiler etc.  Adding this feature to Forth just
                   3083: requires a few lines of code.}
                   3084: 
                   3085: @example
                   3086: list%
                   3087:     cell% field intlist-int
                   3088: end-struct intlist%
                   3089: @end example
                   3090: 
                   3091: @code{intlist%} is a structure with two fields:
                   3092: @code{list-next} and @code{intlist-int}.
                   3093: 
                   3094: @cindex structures containing arrays
                   3095: You can specify an array type containing @emph{n} elements of
                   3096: type @code{foo%} like this:
                   3097: 
                   3098: @example
                   3099: foo% @emph{n} *
                   3100: @end example
                   3101: 
                   3102: You can use this array type in any place where you can use a normal
                   3103: type, e.g., when defining a @code{field}, or with
                   3104: @code{%allot}.
                   3105: 
                   3106: @cindex first field optimization
                   3107: The first field is at the base address of a structure and the word
                   3108: for this field (e.g., @code{list-next}) actually does not change
                   3109: the address on the stack. You may be tempted to leave it away in the
                   3110: interest of run-time and space efficiency. This is not necessary,
                   3111: because the structure package optimizes this case and compiling such
                   3112: words does not generate any code. So, in the interest of readability
                   3113: and maintainability you should include the word for the field when
                   3114: accessing the field.
                   3115: 
                   3116: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   3117: @subsection Structure Naming Convention
                   3118: @cindex structure naming conventions
                   3119: 
                   3120: The field names that come to (my) mind are often quite generic, and,
                   3121: if used, would cause frequent name clashes. E.g., many structures
                   3122: probably contain a @code{counter} field. The structure names
                   3123: that come to (my) mind are often also the logical choice for the names
                   3124: of words that create such a structure.
                   3125: 
                   3126: Therefore, I have adopted the following naming conventions: 
                   3127: 
                   3128: @itemize @bullet
                   3129: @cindex field naming convention
                   3130: @item
                   3131: The names of fields are of the form
                   3132: @code{@emph{struct}-@emph{field}}, where
                   3133: @code{@emph{struct}} is the basic name of the structure, and
                   3134: @code{@emph{field}} is the basic name of the field. You can
                   3135: think about field words as converting converts the (address of the)
                   3136: structure into the (address of the) field.
                   3137: 
                   3138: @cindex structure naming convention
                   3139: @item
                   3140: The names of structures are of the form
                   3141: @code{@emph{struct}%}, where
                   3142: @code{@emph{struct}} is the basic name of the structure.
                   3143: @end itemize
                   3144: 
                   3145: This naming convention does not work that well for fields of extended
                   3146: structures; e.g., the integer list structure has a field
                   3147: @code{intlist-int}, but has @code{list-next}, not
                   3148: @code{intlist-next}.
                   3149: 
                   3150: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   3151: @subsection Structure Implementation
                   3152: @cindex structure implementation
                   3153: @cindex implementation of structures
                   3154: 
                   3155: The central idea in the implementation is to pass the data about the
                   3156: structure being built on the stack, not in some global
                   3157: variable. Everything else falls into place naturally once this design
                   3158: decision is made.
                   3159: 
                   3160: The type description on the stack is of the form @emph{align
                   3161: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   3162: very simple.
                   3163: 
                   3164: @code{field} is a defining word that uses @code{create}
                   3165: and @code{does>}. The body of the field contains the offset
                   3166: of the field, and the normal @code{does>} action is
                   3167: 
                   3168: @example
                   3169: @ +
                   3170: @end example
                   3171: 
                   3172: i.e., add the offset to the address, giving the stack effect
                   3173: @code{addr1 -- addr2} for a field.
                   3174: 
                   3175: @cindex first field optimization, implementation
                   3176: This simple structure is slightly complicated by the optimization
                   3177: for fields with offset 0, which requires a different
                   3178: @code{does>}-part (because we cannot rely on there being
                   3179: something on the stack if such a field is invoked during
                   3180: compilation). Therefore, we put the different @code{does>}-parts
                   3181: in separate words, and decide which one to invoke based on the
                   3182: offset. For a zero offset, the field is basically a noop; it is
                   3183: immediate, and therefore no code is generated when it is compiled.
                   3184: 
                   3185: @node Structure Glossary,  , Structure Implementation, Structures
                   3186: @subsection Structure Glossary
                   3187: @cindex structure glossary
                   3188: 
                   3189: doc-%align
                   3190: doc-%alignment
                   3191: doc-%alloc
                   3192: doc-%allocate
                   3193: doc-%allot
                   3194: doc-cell%
                   3195: doc-char%
                   3196: doc-dfloat%
                   3197: doc-double%
                   3198: doc-end-struct
                   3199: doc-field
                   3200: doc-float%
                   3201: doc-nalign
                   3202: doc-sfloat%
                   3203: doc-%size
                   3204: doc-struct
                   3205: 
                   3206: @c -------------------------------------------------------------
1.12      anton    3207: @node Object-oriented Forth, Tokens for Words, Structures, Words
                   3208: @section Object-oriented Forth
                   3209: 
                   3210: Gforth comes with three packets for object-oriented programming,
                   3211: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   3212: is preloaded, so you have to @code{include} them before use. The most
                   3213: important differences between these packets (and others) are discussed
                   3214: in @ref{Comparison with other object models}. All packets are written
                   3215: in ANS Forth and can be used with any other ANS Forth.
                   3216: 
                   3217: @menu
                   3218: * Objects::                     
                   3219: * OOF::                         
                   3220: * Mini-OOF::                    
                   3221: @end menu
                   3222: 
                   3223: @node Objects, OOF, Object-oriented Forth, Object-oriented Forth
                   3224: @subsection Objects
1.5       anton    3225: @cindex objects
                   3226: @cindex object-oriented programming
                   3227: 
                   3228: @cindex @file{objects.fs}
                   3229: @cindex @file{oof.fs}
1.12      anton    3230: 
                   3231: This section describes the @file{objects.fs} packet. This material also has been published in @cite{Yet Another Forth Objects Package} by Anton Ertl and appeared in Forth Dimensions 19(2), pages 37--43 (@url{http://www.complang.tuwien.ac.at/forth/objects/objects.html}).
1.5       anton    3232: @c McKewan's and Zsoter's packages
                   3233: 
                   3234: This section assumes (in some places) that you have read @ref{Structures}.
                   3235: 
                   3236: @menu
                   3237: * Properties of the Objects model::  
                   3238: * Why object-oriented programming?::  
                   3239: * Object-Oriented Terminology::  
                   3240: * Basic Objects Usage::         
                   3241: * The class Object::            
                   3242: * Creating objects::            
                   3243: * Object-Oriented Programming Style::  
                   3244: * Class Binding::               
                   3245: * Method conveniences::         
                   3246: * Classes and Scoping::         
                   3247: * Object Interfaces::           
                   3248: * Objects Implementation::      
                   3249: * Comparison with other object models::  
                   3250: * Objects Glossary::            
                   3251: @end menu
                   3252: 
                   3253: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
                   3254: and Bernd Paysan helped me with the related works section.
                   3255: 
                   3256: @node Properties of the Objects model, Why object-oriented programming?, Objects, Objects
1.12      anton    3257: @subsubsection Properties of the @file{objects.fs} model
1.5       anton    3258: @cindex @file{objects.fs} properties
                   3259: 
                   3260: @itemize @bullet
                   3261: @item
                   3262: It is straightforward to pass objects on the stack. Passing
                   3263: selectors on the stack is a little less convenient, but possible.
                   3264: 
                   3265: @item
                   3266: Objects are just data structures in memory, and are referenced by
                   3267: their address. You can create words for objects with normal defining
                   3268: words like @code{constant}. Likewise, there is no difference
                   3269: between instance variables that contain objects and those
                   3270: that contain other data.
                   3271: 
                   3272: @item
                   3273: Late binding is efficient and easy to use.
                   3274: 
                   3275: @item
                   3276: It avoids parsing, and thus avoids problems with state-smartness
                   3277: and reduced extensibility; for convenience there are a few parsing
                   3278: words, but they have non-parsing counterparts. There are also a few
                   3279: defining words that parse. This is hard to avoid, because all standard
                   3280: defining words parse (except @code{:noname}); however, such
                   3281: words are not as bad as many other parsing words, because they are not
                   3282: state-smart.
                   3283: 
                   3284: @item
                   3285: It does not try to incorporate everything. It does a few things
                   3286: and does them well (IMO). In particular, I did not intend to support
                   3287: information hiding with this model (although it has features that may
                   3288: help); you can use a separate package for achieving this.
                   3289: 
                   3290: @item
                   3291: It is layered; you don't have to learn and use all features to use this
                   3292: model. Only a few features are necessary (@xref{Basic Objects Usage},
                   3293: @xref{The class Object}, @xref{Creating objects}.), the others
                   3294: are optional and independent of each other.
                   3295: 
                   3296: @item
                   3297: An implementation in ANS Forth is available.
                   3298: 
                   3299: @end itemize
                   3300: 
                   3301: I have used the technique, on which this model is based, for
                   3302: implementing the parser generator Gray; we have also used this technique
                   3303: in Gforth for implementing the various flavours of wordlists (hashed or
                   3304: not, case-sensitive or not, special-purpose wordlists for locals etc.).
                   3305: 
                   3306: @node Why object-oriented programming?, Object-Oriented Terminology, Properties of the Objects model, Objects
1.12      anton    3307: @subsubsection Why object-oriented programming?
1.5       anton    3308: @cindex object-oriented programming motivation
                   3309: @cindex motivation for object-oriented programming
                   3310: 
                   3311: Often we have to deal with several data structures (@emph{objects}),
                   3312: that have to be treated similarly in some respects, but differ in
                   3313: others. Graphical objects are the textbook example: circles,
                   3314: triangles, dinosaurs, icons, and others, and we may want to add more
                   3315: during program development. We want to apply some operations to any
                   3316: graphical object, e.g., @code{draw} for displaying it on the
                   3317: screen. However, @code{draw} has to do something different for
                   3318: every kind of object.
                   3319: 
                   3320: We could implement @code{draw} as a big @code{CASE}
                   3321: control structure that executes the appropriate code depending on the
                   3322: kind of object to be drawn. This would be not be very elegant, and,
                   3323: moreover, we would have to change @code{draw} every time we add
                   3324: a new kind of graphical object (say, a spaceship).
                   3325: 
                   3326: What we would rather do is: When defining spaceships, we would tell
                   3327: the system: "Here's how you @code{draw} a spaceship; you figure
                   3328: out the rest."
                   3329: 
                   3330: This is the problem that all systems solve that (rightfully) call
                   3331: themselves object-oriented, and the object-oriented package I present
                   3332: here also solves this problem (and not much else).
                   3333: 
                   3334: @node Object-Oriented Terminology, Basic Objects Usage, Why object-oriented programming?, Objects
1.12      anton    3335: @subsubsection Object-Oriented Terminology
1.5       anton    3336: @cindex object-oriented terminology
                   3337: @cindex terminology for object-oriented programming
                   3338: 
                   3339: This section is mainly for reference, so you don't have to understand
                   3340: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   3341: short:
                   3342: 
                   3343: @table @emph
                   3344: @cindex class
                   3345: @item class
                   3346: a data structure definition with some extras.
                   3347: 
                   3348: @cindex object
                   3349: @item object
                   3350: an instance of the data structure described by the class definition.
                   3351: 
                   3352: @cindex instance variables
                   3353: @item instance variables
                   3354: fields of the data structure.
                   3355: 
                   3356: @cindex selector
                   3357: @cindex method selector
                   3358: @cindex virtual function
                   3359: @item selector
                   3360: (or @emph{method selector}) a word (e.g.,
                   3361: @code{draw}) for performing an operation on a variety of data
                   3362: structures (classes). A selector describes @emph{what} operation to
                   3363: perform. In C++ terminology: a (pure) virtual function.
                   3364: 
                   3365: @cindex method
                   3366: @item method
                   3367: the concrete definition that performs the operation
                   3368: described by the selector for a specific class. A method specifies
                   3369: @emph{how} the operation is performed for a specific class.
                   3370: 
                   3371: @cindex selector invocation
                   3372: @cindex message send
                   3373: @cindex invoking a selector
                   3374: @item selector invocation
                   3375: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   3376: is used for determining which method is used. In Smalltalk terminology:
                   3377: a message (consisting of the selector and the other arguments) is sent
                   3378: to the object.
                   3379: 
                   3380: @cindex receiving object
                   3381: @item receiving object
                   3382: the object used for determining the method executed by a selector
                   3383: invocation. In our model it is the object that is on the TOS when the
                   3384: selector is invoked. (@emph{Receiving} comes from Smalltalks
                   3385: @emph{message} terminology.)
                   3386: 
                   3387: @cindex child class
                   3388: @cindex parent class
                   3389: @cindex inheritance
                   3390: @item child class
                   3391: a class that has (@emph{inherits}) all properties (instance variables,
                   3392: selectors, methods) from a @emph{parent class}. In Smalltalk
                   3393: terminology: The subclass inherits from the superclass. In C++
                   3394: terminology: The derived class inherits from the base class.
                   3395: 
                   3396: @end table
                   3397: 
                   3398: @c If you wonder about the message sending terminology, it comes from
                   3399: @c a time when each object had it's own task and objects communicated via
                   3400: @c message passing; eventually the Smalltalk developers realized that
                   3401: @c they can do most things through simple (indirect) calls. They kept the
                   3402: @c terminology.
                   3403: 
                   3404: @node Basic Objects Usage, The class Object, Object-Oriented Terminology, Objects
1.12      anton    3405: @subsubsection Basic Objects Usage
1.5       anton    3406: @cindex basic objects usage
                   3407: @cindex objects, basic usage
                   3408: 
                   3409: You can define a class for graphical objects like this:
                   3410: 
                   3411: @cindex @code{class} usage
                   3412: @cindex @code{end-class} usage
                   3413: @cindex @code{selector} usage
                   3414: @example
                   3415: object class \ "object" is the parent class
                   3416:   selector draw ( x y graphical -- )
                   3417: end-class graphical
                   3418: @end example
                   3419: 
                   3420: This code defines a class @code{graphical} with an
                   3421: operation @code{draw}.  We can perform the operation
                   3422: @code{draw} on any @code{graphical} object, e.g.:
                   3423: 
                   3424: @example
                   3425: 100 100 t-rex draw
                   3426: @end example
                   3427: 
                   3428: where @code{t-rex} is a word (say, a constant) that produces a
                   3429: graphical object.
                   3430: 
                   3431: @cindex abstract class
                   3432: How do we create a graphical object? With the present definitions,
                   3433: we cannot create a useful graphical object. The class
                   3434: @code{graphical} describes graphical objects in general, but not
                   3435: any concrete graphical object type (C++ users would call it an
                   3436: @emph{abstract class}); e.g., there is no method for the selector
                   3437: @code{draw} in the class @code{graphical}.
                   3438: 
                   3439: For concrete graphical objects, we define child classes of the
                   3440: class @code{graphical}, e.g.:
                   3441: 
                   3442: @cindex @code{overrides} usage
                   3443: @cindex @code{field} usage in class definition
                   3444: @example
                   3445: graphical class \ "graphical" is the parent class
                   3446:   cell% field circle-radius
                   3447: 
                   3448: :noname ( x y circle -- )
                   3449:   circle-radius @@ draw-circle ;
                   3450: overrides draw
                   3451: 
                   3452: :noname ( n-radius circle -- )
                   3453:   circle-radius ! ;
                   3454: overrides construct
                   3455: 
                   3456: end-class circle
                   3457: @end example
                   3458: 
                   3459: Here we define a class @code{circle} as a child of @code{graphical},
                   3460: with a field @code{circle-radius} (which behaves just like a field in
                   3461: @pxref{Structures}); it defines new methods for the selectors
                   3462: @code{draw} and @code{construct} (@code{construct} is defined in
                   3463: @code{object}, the parent class of @code{graphical}).
                   3464: 
                   3465: Now we can create a circle on the heap (i.e.,
                   3466: @code{allocate}d memory) with
                   3467: 
                   3468: @cindex @code{heap-new} usage
                   3469: @example
                   3470: 50 circle heap-new constant my-circle
                   3471: @end example
                   3472: 
                   3473: @code{heap-new} invokes @code{construct}, thus
                   3474: initializing the field @code{circle-radius} with 50. We can draw
                   3475: this new circle at (100,100) with
                   3476: 
                   3477: @example
                   3478: 100 100 my-circle draw
                   3479: @end example
                   3480: 
                   3481: @cindex selector invocation, restrictions
                   3482: @cindex class definition, restrictions
                   3483: Note: You can invoke a selector only if the object on the TOS
                   3484: (the receiving object) belongs to the class where the selector was
                   3485: defined or one of its descendents; e.g., you can invoke
                   3486: @code{draw} only for objects belonging to @code{graphical}
                   3487: or its descendents (e.g., @code{circle}).  Immediately before
                   3488: @code{end-class}, the search order has to be the same as
                   3489: immediately after @code{class}.
                   3490: 
                   3491: @node The class Object, Creating objects, Basic Objects Usage, Objects
1.12      anton    3492: @subsubsection The class @code{object}
1.5       anton    3493: @cindex @code{object} class
                   3494: 
                   3495: When you define a class, you have to specify a parent class.  So how do
                   3496: you start defining classes? There is one class available from the start:
                   3497: @code{object}. You can use it as ancestor for all classes. It is the
                   3498: only class that has no parent. It has two selectors: @code{construct}
                   3499: and @code{print}.
                   3500: 
                   3501: @node Creating objects, Object-Oriented Programming Style, The class Object, Objects
1.12      anton    3502: @subsubsection Creating objects
1.5       anton    3503: @cindex creating objects
                   3504: @cindex object creation
                   3505: @cindex object allocation options
                   3506: 
                   3507: @cindex @code{heap-new} discussion
                   3508: @cindex @code{dict-new} discussion
                   3509: @cindex @code{construct} discussion
                   3510: You can create and initialize an object of a class on the heap with
                   3511: @code{heap-new} ( ... class -- object ) and in the dictionary
                   3512: (allocation with @code{allot}) with @code{dict-new} (
                   3513: ... class -- object ). Both words invoke @code{construct}, which
                   3514: consumes the stack items indicated by "..." above.
                   3515: 
                   3516: @cindex @code{init-object} discussion
                   3517: @cindex @code{class-inst-size} discussion
                   3518: If you want to allocate memory for an object yourself, you can get its
                   3519: alignment and size with @code{class-inst-size 2@@} ( class --
                   3520: align size ). Once you have memory for an object, you can initialize
                   3521: it with @code{init-object} ( ... class object -- );
                   3522: @code{construct} does only a part of the necessary work.
                   3523: 
                   3524: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
1.12      anton    3525: @subsubsection Object-Oriented Programming Style
1.5       anton    3526: @cindex object-oriented programming style
                   3527: 
                   3528: This section is not exhaustive.
                   3529: 
                   3530: @cindex stack effects of selectors
                   3531: @cindex selectors and stack effects
                   3532: In general, it is a good idea to ensure that all methods for the
                   3533: same selector have the same stack effect: when you invoke a selector,
                   3534: you often have no idea which method will be invoked, so, unless all
                   3535: methods have the same stack effect, you will not know the stack effect
                   3536: of the selector invocation.
                   3537: 
                   3538: One exception to this rule is methods for the selector
                   3539: @code{construct}. We know which method is invoked, because we
                   3540: specify the class to be constructed at the same place. Actually, I
                   3541: defined @code{construct} as a selector only to give the users a
                   3542: convenient way to specify initialization. The way it is used, a
                   3543: mechanism different from selector invocation would be more natural
                   3544: (but probably would take more code and more space to explain).
                   3545: 
                   3546: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
1.12      anton    3547: @subsubsection Class Binding
1.5       anton    3548: @cindex class binding
                   3549: @cindex early binding
                   3550: 
                   3551: @cindex late binding
                   3552: Normal selector invocations determine the method at run-time depending
                   3553: on the class of the receiving object (late binding).
                   3554: 
                   3555: Sometimes we want to invoke a different method. E.g., assume that
                   3556: you want to use the simple method for @code{print}ing
                   3557: @code{object}s instead of the possibly long-winded
                   3558: @code{print} method of the receiver class. You can achieve this
                   3559: by replacing the invocation of @code{print} with
                   3560: 
                   3561: @cindex @code{[bind]} usage
                   3562: @example
                   3563: [bind] object print
                   3564: @end example
                   3565: 
                   3566: in compiled code or
                   3567: 
                   3568: @cindex @code{bind} usage
                   3569: @example
                   3570: bind object print
                   3571: @end example
                   3572: 
                   3573: @cindex class binding, alternative to
                   3574: in interpreted code. Alternatively, you can define the method with a
                   3575: name (e.g., @code{print-object}), and then invoke it through the
                   3576: name. Class binding is just a (often more convenient) way to achieve
                   3577: the same effect; it avoids name clutter and allows you to invoke
                   3578: methods directly without naming them first.
                   3579: 
                   3580: @cindex superclass binding
                   3581: @cindex parent class binding
                   3582: A frequent use of class binding is this: When we define a method
                   3583: for a selector, we often want the method to do what the selector does
                   3584: in the parent class, and a little more. There is a special word for
                   3585: this purpose: @code{[parent]}; @code{[parent]
                   3586: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   3587: selector}}, where @code{@emph{parent}} is the parent
                   3588: class of the current class. E.g., a method definition might look like:
                   3589: 
                   3590: @cindex @code{[parent]} usage
                   3591: @example
                   3592: :noname
                   3593:   dup [parent] foo \ do parent's foo on the receiving object
                   3594:   ... \ do some more
                   3595: ; overrides foo
                   3596: @end example
                   3597: 
                   3598: @cindex class binding as optimization
                   3599: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   3600: March 1997), Andrew McKewan presents class binding as an optimization
                   3601: technique. I recommend not using it for this purpose unless you are in
                   3602: an emergency. Late binding is pretty fast with this model anyway, so the
                   3603: benefit of using class binding is small; the cost of using class binding
                   3604: where it is not appropriate is reduced maintainability.
                   3605: 
                   3606: While we are at programming style questions: You should bind
                   3607: selectors only to ancestor classes of the receiving object. E.g., say,
                   3608: you know that the receiving object is of class @code{foo} or its
                   3609: descendents; then you should bind only to @code{foo} and its
                   3610: ancestors.
                   3611: 
                   3612: @node Method conveniences, Classes and Scoping, Class Binding, Objects
1.12      anton    3613: @subsubsection Method conveniences
1.5       anton    3614: @cindex method conveniences
                   3615: 
                   3616: In a method you usually access the receiving object pretty often.  If
                   3617: you define the method as a plain colon definition (e.g., with
                   3618: @code{:noname}), you may have to do a lot of stack
                   3619: gymnastics. To avoid this, you can define the method with @code{m:
                   3620: ... ;m}. E.g., you could define the method for
                   3621: @code{draw}ing a @code{circle} with
                   3622: 
                   3623: @cindex @code{this} usage
                   3624: @cindex @code{m:} usage
                   3625: @cindex @code{;m} usage
                   3626: @example
                   3627: m: ( x y circle -- )
                   3628:   ( x y ) this circle-radius @@ draw-circle ;m
                   3629: @end example
                   3630: 
                   3631: @cindex @code{exit} in @code{m: ... ;m}
                   3632: @cindex @code{exitm} discussion
                   3633: @cindex @code{catch} in @code{m: ... ;m}
                   3634: When this method is executed, the receiver object is removed from the
                   3635: stack; you can access it with @code{this} (admittedly, in this
                   3636: example the use of @code{m: ... ;m} offers no advantage). Note
                   3637: that I specify the stack effect for the whole method (i.e. including
                   3638: the receiver object), not just for the code between @code{m:}
                   3639: and @code{;m}. You cannot use @code{exit} in
                   3640: @code{m:...;m}; instead, use
                   3641: @code{exitm}.@footnote{Moreover, for any word that calls
                   3642: @code{catch} and was defined before loading
                   3643: @code{objects.fs}, you have to redefine it like I redefined
                   3644: @code{catch}: @code{: catch this >r catch r> to-this ;}}
                   3645: 
                   3646: @cindex @code{inst-var} usage
                   3647: You will frequently use sequences of the form @code{this
                   3648: @emph{field}} (in the example above: @code{this
                   3649: circle-radius}). If you use the field only in this way, you can
                   3650: define it with @code{inst-var} and eliminate the
                   3651: @code{this} before the field name. E.g., the @code{circle}
                   3652: class above could also be defined with:
                   3653: 
                   3654: @example
                   3655: graphical class
                   3656:   cell% inst-var radius
                   3657: 
                   3658: m: ( x y circle -- )
                   3659:   radius @@ draw-circle ;m
                   3660: overrides draw
                   3661: 
                   3662: m: ( n-radius circle -- )
                   3663:   radius ! ;m
                   3664: overrides construct
                   3665: 
                   3666: end-class circle
                   3667: @end example
                   3668: 
                   3669: @code{radius} can only be used in @code{circle} and its
                   3670: descendent classes and inside @code{m:...;m}.
                   3671: 
                   3672: @cindex @code{inst-value} usage
                   3673: You can also define fields with @code{inst-value}, which is
                   3674: to @code{inst-var} what @code{value} is to
                   3675: @code{variable}.  You can change the value of such a field with
                   3676: @code{[to-inst]}.  E.g., we could also define the class
                   3677: @code{circle} like this:
                   3678: 
                   3679: @example
                   3680: graphical class
                   3681:   inst-value radius
                   3682: 
                   3683: m: ( x y circle -- )
                   3684:   radius draw-circle ;m
                   3685: overrides draw
                   3686: 
                   3687: m: ( n-radius circle -- )
                   3688:   [to-inst] radius ;m
                   3689: overrides construct
                   3690: 
                   3691: end-class circle
                   3692: @end example
                   3693: 
                   3694: 
                   3695: @node Classes and Scoping, Object Interfaces, Method conveniences, Objects
1.12      anton    3696: @subsubsection Classes and Scoping
1.5       anton    3697: @cindex classes and scoping
                   3698: @cindex scoping and classes
                   3699: 
                   3700: Inheritance is frequent, unlike structure extension. This exacerbates
                   3701: the problem with the field name convention (@pxref{Structure Naming
                   3702: Convention}): One always has to remember in which class the field was
                   3703: originally defined; changing a part of the class structure would require
                   3704: changes for renaming in otherwise unaffected code.
                   3705: 
                   3706: @cindex @code{inst-var} visibility
                   3707: @cindex @code{inst-value} visibility
                   3708: To solve this problem, I added a scoping mechanism (which was not in my
                   3709: original charter): A field defined with @code{inst-var} (or
                   3710: @code{inst-value}) is visible only in the class where it is defined and in
                   3711: the descendent classes of this class.  Using such fields only makes
                   3712: sense in @code{m:}-defined methods in these classes anyway.
                   3713: 
                   3714: This scoping mechanism allows us to use the unadorned field name,
                   3715: because name clashes with unrelated words become much less likely.
                   3716: 
                   3717: @cindex @code{protected} discussion
                   3718: @cindex @code{private} discussion
                   3719: Once we have this mechanism, we can also use it for controlling the
                   3720: visibility of other words: All words defined after
                   3721: @code{protected} are visible only in the current class and its
                   3722: descendents. @code{public} restores the compilation
                   3723: (i.e. @code{current}) wordlist that was in effect before. If you
                   3724: have several @code{protected}s without an intervening
                   3725: @code{public} or @code{set-current}, @code{public}
                   3726: will restore the compilation wordlist in effect before the first of
                   3727: these @code{protected}s.
                   3728: 
                   3729: @node Object Interfaces, Objects Implementation, Classes and Scoping, Objects
1.12      anton    3730: @subsubsection Object Interfaces
1.5       anton    3731: @cindex object interfaces
                   3732: @cindex interfaces for objects
                   3733: 
                   3734: In this model you can only call selectors defined in the class of the
                   3735: receiving objects or in one of its ancestors. If you call a selector
                   3736: with a receiving object that is not in one of these classes, the
                   3737: result is undefined; if you are lucky, the program crashes
                   3738: immediately.
                   3739: 
                   3740: @cindex selectors common to hardly-related classes
                   3741: Now consider the case when you want to have a selector (or several)
                   3742: available in two classes: You would have to add the selector to a
                   3743: common ancestor class, in the worst case to @code{object}. You
                   3744: may not want to do this, e.g., because someone else is responsible for
                   3745: this ancestor class.
                   3746: 
                   3747: The solution for this problem is interfaces. An interface is a
                   3748: collection of selectors. If a class implements an interface, the
                   3749: selectors become available to the class and its descendents. A class
                   3750: can implement an unlimited number of interfaces. For the problem
                   3751: discussed above, we would define an interface for the selector(s), and
                   3752: both classes would implement the interface.
                   3753: 
                   3754: As an example, consider an interface @code{storage} for
                   3755: writing objects to disk and getting them back, and a class
                   3756: @code{foo} foo that implements it. The code for this would look
                   3757: like this:
                   3758: 
                   3759: @cindex @code{interface} usage
                   3760: @cindex @code{end-interface} usage
                   3761: @cindex @code{implementation} usage
                   3762: @example
                   3763: interface
                   3764:   selector write ( file object -- )
                   3765:   selector read1 ( file object -- )
                   3766: end-interface storage
                   3767: 
                   3768: bar class
                   3769:   storage implementation
                   3770: 
                   3771: ... overrides write
                   3772: ... overrides read
                   3773: ...
                   3774: end-class foo
                   3775: @end example
                   3776: 
                   3777: (I would add a word @code{read} ( file -- object ) that uses
                   3778: @code{read1} internally, but that's beyond the point illustrated
                   3779: here.)
                   3780: 
                   3781: Note that you cannot use @code{protected} in an interface; and
                   3782: of course you cannot define fields.
                   3783: 
                   3784: In the Neon model, all selectors are available for all classes;
                   3785: therefore it does not need interfaces. The price you pay in this model
                   3786: is slower late binding, and therefore, added complexity to avoid late
                   3787: binding.
                   3788: 
                   3789: @node Objects Implementation, Comparison with other object models, Object Interfaces, Objects
1.12      anton    3790: @subsubsection @file{objects.fs} Implementation
1.5       anton    3791: @cindex @file{objects.fs} implementation
                   3792: 
                   3793: @cindex @code{object-map} discussion
                   3794: An object is a piece of memory, like one of the data structures
                   3795: described with @code{struct...end-struct}. It has a field
                   3796: @code{object-map} that points to the method map for the object's
                   3797: class.
                   3798: 
                   3799: @cindex method map
                   3800: @cindex virtual function table
                   3801: The @emph{method map}@footnote{This is Self terminology; in C++
                   3802: terminology: virtual function table.} is an array that contains the
                   3803: execution tokens (XTs) of the methods for the object's class. Each
                   3804: selector contains an offset into the method maps.
                   3805: 
                   3806: @cindex @code{selector} implementation, class
                   3807: @code{selector} is a defining word that uses
                   3808: @code{create} and @code{does>}. The body of the
                   3809: selector contains the offset; the @code{does>} action for a
                   3810: class selector is, basically:
                   3811: 
                   3812: @example
                   3813: ( object addr ) @@ over object-map @@ + @@ execute
                   3814: @end example
                   3815: 
                   3816: Since @code{object-map} is the first field of the object, it
                   3817: does not generate any code. As you can see, calling a selector has a
                   3818: small, constant cost.
                   3819: 
                   3820: @cindex @code{current-interface} discussion
                   3821: @cindex class implementation and representation
                   3822: A class is basically a @code{struct} combined with a method
                   3823: map. During the class definition the alignment and size of the class
                   3824: are passed on the stack, just as with @code{struct}s, so
                   3825: @code{field} can also be used for defining class
                   3826: fields. However, passing more items on the stack would be
                   3827: inconvenient, so @code{class} builds a data structure in memory,
                   3828: which is accessed through the variable
                   3829: @code{current-interface}. After its definition is complete, the
                   3830: class is represented on the stack by a pointer (e.g., as parameter for
                   3831: a child class definition).
                   3832: 
                   3833: At the start, a new class has the alignment and size of its parent,
                   3834: and a copy of the parent's method map. Defining new fields extends the
                   3835: size and alignment; likewise, defining new selectors extends the
                   3836: method map. @code{overrides} just stores a new XT in the method
                   3837: map at the offset given by the selector.
                   3838: 
                   3839: @cindex class binding, implementation
                   3840: Class binding just gets the XT at the offset given by the selector
                   3841: from the class's method map and @code{compile,}s (in the case of
                   3842: @code{[bind]}) it.
                   3843: 
                   3844: @cindex @code{this} implementation
                   3845: @cindex @code{catch} and @code{this}
                   3846: @cindex @code{this} and @code{catch}
                   3847: I implemented @code{this} as a @code{value}. At the
                   3848: start of an @code{m:...;m} method the old @code{this} is
                   3849: stored to the return stack and restored at the end; and the object on
                   3850: the TOS is stored @code{TO this}. This technique has one
                   3851: disadvantage: If the user does not leave the method via
                   3852: @code{;m}, but via @code{throw} or @code{exit},
                   3853: @code{this} is not restored (and @code{exit} may
                   3854: crash). To deal with the @code{throw} problem, I have redefined
                   3855: @code{catch} to save and restore @code{this}; the same
                   3856: should be done with any word that can catch an exception. As for
                   3857: @code{exit}, I simply forbid it (as a replacement, there is
                   3858: @code{exitm}).
                   3859: 
                   3860: @cindex @code{inst-var} implementation
                   3861: @code{inst-var} is just the same as @code{field}, with
                   3862: a different @code{does>} action:
                   3863: @example
                   3864: @@ this +
                   3865: @end example
                   3866: Similar for @code{inst-value}.
                   3867: 
                   3868: @cindex class scoping implementation
                   3869: Each class also has a wordlist that contains the words defined with
                   3870: @code{inst-var} and @code{inst-value}, and its protected
                   3871: words. It also has a pointer to its parent. @code{class} pushes
                   3872: the wordlists of the class an all its ancestors on the search order,
                   3873: and @code{end-class} drops them.
                   3874: 
                   3875: @cindex interface implementation
                   3876: An interface is like a class without fields, parent and protected
                   3877: words; i.e., it just has a method map. If a class implements an
                   3878: interface, its method map contains a pointer to the method map of the
                   3879: interface. The positive offsets in the map are reserved for class
                   3880: methods, therefore interface map pointers have negative
                   3881: offsets. Interfaces have offsets that are unique throughout the
                   3882: system, unlike class selectors, whose offsets are only unique for the
                   3883: classes where the selector is available (invokable).
                   3884: 
                   3885: This structure means that interface selectors have to perform one
                   3886: indirection more than class selectors to find their method. Their body
                   3887: contains the interface map pointer offset in the class method map, and
                   3888: the method offset in the interface method map. The
                   3889: @code{does>} action for an interface selector is, basically:
                   3890: 
                   3891: @example
                   3892: ( object selector-body )
                   3893: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   3894: swap object-map @@ + @@ ( object selector-body map )
                   3895: swap selector-offset @@ + @@ execute
                   3896: @end example
                   3897: 
                   3898: where @code{object-map} and @code{selector-offset} are
                   3899: first fields and generate no code.
                   3900: 
                   3901: As a concrete example, consider the following code:
                   3902: 
                   3903: @example
                   3904: interface
                   3905:   selector if1sel1
                   3906:   selector if1sel2
                   3907: end-interface if1
                   3908: 
                   3909: object class
                   3910:   if1 implementation
                   3911:   selector cl1sel1
                   3912:   cell% inst-var cl1iv1
                   3913: 
                   3914: ' m1 overrides construct
                   3915: ' m2 overrides if1sel1
                   3916: ' m3 overrides if1sel2
                   3917: ' m4 overrides cl1sel2
                   3918: end-class cl1
                   3919: 
                   3920: create obj1 object dict-new drop
                   3921: create obj2 cl1    dict-new drop
                   3922: @end example
                   3923: 
                   3924: The data structure created by this code (including the data structure
                   3925: for @code{object}) is shown in the <a
                   3926: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
                   3927: 
                   3928: @node Comparison with other object models, Objects Glossary, Objects Implementation, Objects
1.12      anton    3929: @subsubsection Comparison with other object models
1.5       anton    3930: @cindex comparison of object models
                   3931: @cindex object models, comparison
                   3932: 
                   3933: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   3934: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   3935: J. Rodriguez and W. F. S. Poehlman lists 17). Here I'll discuss the
                   3936: relation of @file{objects.fs} to two well-known and two closely-related
                   3937: (by the use of method maps) models.
                   3938: 
                   3939: @cindex Neon model
                   3940: The most popular model currently seems to be the Neon model (see
                   3941: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   3942: 1997) by Andrew McKewan). The Neon model uses a @code{@emph{selector
                   3943: object}} syntax, which makes it unnatural to pass objects on the
                   3944: stack. It also requires that the selector parses the input stream (at
                   3945: compile time); this leads to reduced extensibility and to bugs that are
                   3946: hard to find. Finally, it allows using every selector to every object;
                   3947: this eliminates the need for classes, but makes it harder to create
                   3948: efficient implementations. A longer version of this critique can be
                   3949: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   3950: Dimensions, May 1997) by Anton Ertl.
                   3951: 
                   3952: @cindex Pountain's object-oriented model
                   3953: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   3954: Press, London, 1987) by Dick Pountain. However, it is not really about
                   3955: object-oriented programming, because it hardly deals with late
                   3956: binding. Instead, it focuses on features like information hiding and
                   3957: overloading that are characteristic of modular languages like Ada (83).
                   3958: 
                   3959: @cindex Zsoter's object-oriented model
                   3960: In @cite{Does late binding have to be slow?} (Forth Dimensions ??? 1996)
                   3961: Andras Zsoter describes a model that makes heavy use of an active object
                   3962: (like @code{this} in @file{objects.fs}): The active object is not only
                   3963: used for accessing all fields, but also specifies the receiving object
                   3964: of every selector invocation; you have to change the active object
                   3965: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
                   3966: changes more or less implicitly at @code{m: ... ;m}. Such a change at
                   3967: the method entry point is unnecessary with the Zsoter's model, because
                   3968: the receiving object is the active object already; OTOH, the explicit
                   3969: change is absolutely necessary in that model, because otherwise no one
                   3970: could ever change the active object. An ANS Forth implementation of this
                   3971: model is available at @url{http://www.forth.org/fig/oopf.html}.
                   3972: 
1.12      anton    3973: @cindex @file{oof.fs}, differences to other models
1.5       anton    3974: The @file{oof.fs} model combines information hiding and overloading
                   3975: resolution (by keeping names in various wordlists) with object-oriented
                   3976: programming. It sets the active object implicitly on method entry, but
                   3977: also allows explicit changing (with @code{>o...o>} or with
                   3978: @code{with...endwith}). It uses parsing and state-smart objects and
                   3979: classes for resolving overloading and for early binding: the object or
                   3980: class parses the selector and determines the method from this. If the
                   3981: selector is not parsed by an object or class, it performs a call to the
                   3982: selector for the active object (late binding), like Zsoter's model.
                   3983: Fields are always accessed through the active object. The big
                   3984: disadvantage of this model is the parsing and the state-smartness, which
                   3985: reduces extensibility and increases the opportunities for subtle bugs;
                   3986: essentially, you are only safe if you never tick or @code{postpone} an
1.12      anton    3987: object or class (Bernd disagrees, but I (Anton) am not convinced).
                   3988: 
                   3989: @cindex @file{mini-oof.fs}, differences to other models
                   3990: The Mini-OOF model is quite similar to a very stripped-down version of
                   3991: the Objects model, but syntactically it is a mixture of the Objects and
                   3992: the OOF model.
                   3993: 
1.5       anton    3994: 
                   3995: @node Objects Glossary,  , Comparison with other object models, Objects
1.12      anton    3996: @subsubsection @file{objects.fs} Glossary
1.5       anton    3997: @cindex @file{objects.fs} Glossary
                   3998: 
1.19    ! anton    3999: doc---objects-bind
        !          4000: doc---objects-<bind>
        !          4001: doc---objects-bind'
        !          4002: doc---objects-[bind]
        !          4003: doc---objects-class
        !          4004: doc---objects-class->map
        !          4005: doc---objects-class-inst-size
        !          4006: doc---objects-class-override!
        !          4007: doc---objects-construct
        !          4008: doc---objects-current'
        !          4009: doc---objects-[current]
        !          4010: doc---objects-current-interface
        !          4011: doc---objects-dict-new
        !          4012: doc---objects-drop-order
        !          4013: doc---objects-end-class
        !          4014: doc---objects-end-class-noname
        !          4015: doc---objects-end-interface
        !          4016: doc---objects-end-interface-noname
        !          4017: doc---objects-exitm
        !          4018: doc---objects-heap-new
        !          4019: doc---objects-implementation
        !          4020: doc---objects-init-object
        !          4021: doc---objects-inst-value
        !          4022: doc---objects-inst-var
        !          4023: doc---objects-interface
        !          4024: doc---objects-;m
        !          4025: doc---objects-m:
        !          4026: doc---objects-method
        !          4027: doc---objects-object
        !          4028: doc---objects-overrides
        !          4029: doc---objects-[parent]
        !          4030: doc---objects-print
        !          4031: doc---objects-protected
        !          4032: doc---objects-public
        !          4033: doc---objects-push-order
        !          4034: doc---objects-selector
        !          4035: doc---objects-this
        !          4036: doc---objects-<to-inst>
        !          4037: doc---objects-[to-inst]
        !          4038: doc---objects-to-this
        !          4039: doc---objects-xt-new
1.5       anton    4040: 
                   4041: @c -------------------------------------------------------------
1.12      anton    4042: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   4043: @subsection OOF
1.6       pazsan   4044: @cindex oof
                   4045: @cindex object-oriented programming
                   4046: 
                   4047: @cindex @file{objects.fs}
                   4048: @cindex @file{oof.fs}
1.12      anton    4049: 
                   4050: This section describes the @file{oof.fs} packet. This section uses the
                   4051: same rationale why using object-oriented programming, and the same
1.6       pazsan   4052: terminology.
                   4053: 
                   4054: The packet described in this section is used in bigFORTH since 1991, and
                   4055: used for two large applications: a chromatographic system used to
                   4056: create new medicaments, and a graphic user interface library (MINOS).
                   4057: 
1.12      anton    4058: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   4059: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   4060: 10(2), 1994.
                   4061: 
1.6       pazsan   4062: @menu
                   4063: * Properties of the OOF model::
                   4064: * Basic OOF Usage::
                   4065: * The base class object::
1.7       pazsan   4066: * Class Declaration::
                   4067: * Class Implementation::
1.6       pazsan   4068: @end menu
                   4069: 
1.12      anton    4070: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   4071: @subsubsection Properties of the OOF model
1.6       pazsan   4072: @cindex @file{oof.fs} properties
                   4073: 
                   4074: @itemize @bullet
                   4075: @item
                   4076: This model combines object oriented programming with information
                   4077: hiding. It helps you writing large application, where scoping is
                   4078: necessary, because it provides class-oriented scoping.
                   4079: 
                   4080: @item
                   4081: Named objects, object pointers, and object arrays can be created,
                   4082: selector invocation uses the "object selector" syntax. Selector invocation
                   4083: to objects and/or selectors on the stack is a bit less convenient, but
                   4084: possible.
                   4085: 
                   4086: @item
                   4087: Selector invocation and instance variable usage of the active object is
                   4088: straight forward, since both make use of the active object.
                   4089: 
                   4090: @item
                   4091: Late binding is efficient and easy to use.
                   4092: 
                   4093: @item
                   4094: State-smart objects parse selectors. However, extensibility is provided
                   4095: using a (parsing) selector @code{postpone} and a selector @code{'}.
                   4096: 
                   4097: @item
                   4098: An implementation in ANS Forth is available.
                   4099: 
                   4100: @end itemize
                   4101: 
                   4102: 
1.12      anton    4103: @node Basic OOF Usage, The base class object, Properties of the OOF model, OOF
                   4104: @subsubsection Basic OOF Usage
1.6       pazsan   4105: @cindex @file{oof.fs} usage
                   4106: 
                   4107: Here, I use the same example as for @code{objects} (@pxref{Basic Objects Usage}).
                   4108: 
                   4109: You can define a class for graphical objects like this:
                   4110: 
                   4111: @cindex @code{class} usage
                   4112: @cindex @code{class;} usage
                   4113: @cindex @code{method} usage
                   4114: @example
                   4115: object class graphical \ "object" is the parent class
                   4116:   method draw ( x y graphical -- )
                   4117: class;
                   4118: @end example
                   4119: 
                   4120: This code defines a class @code{graphical} with an
                   4121: operation @code{draw}.  We can perform the operation
                   4122: @code{draw} on any @code{graphical} object, e.g.:
                   4123: 
                   4124: @example
                   4125: 100 100 t-rex draw
                   4126: @end example
                   4127: 
                   4128: where @code{t-rex} is an object or object pointer, created with e.g.
1.13      pazsan   4129: @code{graphical : t-rex}.
1.6       pazsan   4130: 
                   4131: @cindex abstract class
                   4132: How do we create a graphical object? With the present definitions,
                   4133: we cannot create a useful graphical object. The class
                   4134: @code{graphical} describes graphical objects in general, but not
                   4135: any concrete graphical object type (C++ users would call it an
                   4136: @emph{abstract class}); e.g., there is no method for the selector
                   4137: @code{draw} in the class @code{graphical}.
                   4138: 
                   4139: For concrete graphical objects, we define child classes of the
                   4140: class @code{graphical}, e.g.:
                   4141: 
                   4142: @example
                   4143: graphical class circle \ "graphical" is the parent class
                   4144:   cell var circle-radius
                   4145: how:
                   4146:   : draw ( x y -- )
                   4147:     circle-radius @@ draw-circle ;
                   4148: 
                   4149:   : init ( n-radius -- (
                   4150:     circle-radius ! ;
                   4151: class;
                   4152: @end example
                   4153: 
                   4154: Here we define a class @code{circle} as a child of @code{graphical},
                   4155: with a field @code{circle-radius}; it defines new methods for the
                   4156: selectors @code{draw} and @code{init} (@code{init} is defined in
                   4157: @code{object}, the parent class of @code{graphical}).
                   4158: 
                   4159: Now we can create a circle in the dictionary with
                   4160: 
                   4161: @example
                   4162: 50 circle : my-circle
                   4163: @end example
                   4164: 
                   4165: @code{:} invokes @code{init}, thus initializing the field
                   4166: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   4167: with
                   4168: 
                   4169: @example
                   4170: 100 100 my-circle draw
                   4171: @end example
                   4172: 
                   4173: @cindex selector invocation, restrictions
                   4174: @cindex class definition, restrictions
                   4175: Note: You can invoke a selector only if the receiving object belongs to
                   4176: the class where the selector was defined or one of its descendents;
                   4177: e.g., you can invoke @code{draw} only for objects belonging to
                   4178: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
1.7       pazsan   4179: mechanism will check if you try to invoke a selector that is not
1.6       pazsan   4180: defined in this class hierarchy, so you'll get an error at compilation
                   4181: time.
                   4182: 
                   4183: 
1.12      anton    4184: @node The base class object, Class Declaration, Basic OOF Usage, OOF
                   4185: @subsubsection The base class @file{object}
1.6       pazsan   4186: @cindex @file{oof.fs} base class
                   4187: 
                   4188: When you define a class, you have to specify a parent class.  So how do
                   4189: you start defining classes? There is one class available from the start:
                   4190: @code{object}. You have to use it as ancestor for all classes. It is the
                   4191: only class that has no parent. Classes are also objects, except that
                   4192: they don't have instance variables; class manipulation such as
                   4193: inheritance or changing definitions of a class is handled through
                   4194: selectors of the class @code{object}.
                   4195: 
                   4196: @code{object} provides a number of selectors:
                   4197: 
                   4198: @itemize @bullet
                   4199: @item
                   4200: @code{class} for subclassing, @code{definitions} to add definitions
                   4201: later on, and @code{class?} to get type informations (is the class a
                   4202: subclass of the class passed on the stack?).
1.7       pazsan   4203: doc---object-class
                   4204: doc---object-definitions
                   4205: doc---object-class?
1.6       pazsan   4206: 
                   4207: @item
                   4208: @code{init} and @code{dispose} as constructor and destroctor of the
                   4209: object. @code{init} is invocated after the object's memory is allocated,
                   4210: while @code{dispose} also handles deallocation. Thus if you redefine
                   4211: @code{dispose}, you have to call the parent's dispose with @code{super
                   4212: dispose}, too.
1.7       pazsan   4213: doc---object-init
                   4214: doc---object-dispose
1.6       pazsan   4215: 
                   4216: @item
1.7       pazsan   4217: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   4218: @code{[]} to create named and unnamed objects and object arrays or
                   4219: object pointers.
                   4220: doc---object-new
                   4221: doc---object-new[]
                   4222: doc---object-:
                   4223: doc---object-ptr
                   4224: doc---object-asptr
                   4225: doc---object-[]
1.6       pazsan   4226: 
                   4227: @item
                   4228: @code{::} and @code{super} for expicit scoping. You should use expicit
                   4229: scoping only for super classes or classes with the same set of instance
                   4230: variables. Explicit scoped selectors use early binding.
1.7       pazsan   4231: doc---object-::
                   4232: doc---object-super
1.6       pazsan   4233: 
                   4234: @item
                   4235: @code{self} to get the address of the object
1.7       pazsan   4236: doc---object-self
1.6       pazsan   4237: 
                   4238: @item
                   4239: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   4240: pointers and instance defers.
1.7       pazsan   4241: doc---object-bind
                   4242: doc---object-bound
                   4243: doc---object-link
                   4244: doc---object-is
1.6       pazsan   4245: 
                   4246: @item
                   4247: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   4248: form the stack, and @code{postpone} to generate selector invocation code.
1.7       pazsan   4249: doc---object-'
                   4250: doc---object-postpone
1.6       pazsan   4251: 
                   4252: @item
                   4253: @code{with} and @code{endwith} to select the active object from the
                   4254: stack, and enabling it's scope. Using @code{with} and @code{endwith}
                   4255: also allows to create code using selector @code{postpone} without being
                   4256: trapped bye the state-smart objects.
1.7       pazsan   4257: doc---object-with
                   4258: doc---object-endwith
1.6       pazsan   4259: 
                   4260: @end itemize
                   4261: 
1.12      anton    4262: @node Class Declaration, Class Implementation, The base class object, OOF
                   4263: @subsubsection Class Declaration
1.7       pazsan   4264: @cindex class declaration
                   4265: 
                   4266: @itemize @bullet
                   4267: @item
                   4268: Instance variables
                   4269: doc---oof-var
                   4270: 
                   4271: @item
                   4272: Object pointers
                   4273: doc---oof-ptr
                   4274: doc---oof-asptr
                   4275: 
                   4276: @item
                   4277: Instance defers
                   4278: doc---oof-defer
                   4279: 
                   4280: @item
                   4281: Method selectors
                   4282: doc---oof-early
                   4283: doc---oof-method
                   4284: 
                   4285: @item
                   4286: Class wide variables
                   4287: doc---oof-static
                   4288: 
                   4289: @item
                   4290: End declaration
                   4291: doc---oof-how:
                   4292: doc---oof-class;
                   4293: 
                   4294: @end itemize
                   4295: 
1.13      pazsan   4296: @c -------------------------------------------------------------
1.12      anton    4297: @node Class Implementation,  , Class Declaration, OOF
                   4298: @subsubsection Class Implementation
1.7       pazsan   4299: @cindex class implementation
                   4300: 
1.13      pazsan   4301: @c -------------------------------------------------------------
                   4302: @node Mini-OOF, , OOF, Object-oriented Forth
1.12      anton    4303: @subsection Mini-OOF
1.8       pazsan   4304: @cindex mini-oof
                   4305: 
                   4306: Gforth's third object oriented Forth package is a 12-liner. It uses a
                   4307: bit of a mixture of the @file{object.fs} and the @file{oof.fs} syntax,
1.13      pazsan   4308: and reduces to the bare minimum of features. This is based on a posting
                   4309: of Bernd Paysan in comp.arch.
                   4310: 
                   4311: @menu
                   4312: * Mini-OOF Usage::
                   4313: * Mini-OOF Example::
                   4314: @end menu
                   4315: 
                   4316: @c -------------------------------------------------------------
                   4317: @node Mini-OOF Usage, Mini-OOF Example, , Mini-OOF
                   4318: @subsubsection Usage
                   4319: @cindex mini-oof usage
                   4320: 
                   4321: Basically, there are seven words, to define a method, a variable, a
                   4322: class; to end a class, to define a method, to allocate an object, to
                   4323: resolve binding, and the base class (which allocates one cell for the
                   4324: object pointer).
                   4325: 
                   4326: doc-method
                   4327: 
                   4328: Defines a method
                   4329: 
                   4330: doc-var
                   4331: 
                   4332: Defines a variable with size bytes
                   4333: 
                   4334: doc-class
                   4335: 
                   4336: Starts the definition of a sub-class
                   4337: 
                   4338: doc-end-class
                   4339: 
                   4340: Ends the definition of a class
                   4341: 
                   4342: doc-defines
                   4343: 
                   4344: Binds the xt to the method name in the class
                   4345: 
                   4346: doc-new
                   4347: 
                   4348: Creates a new incarnation of the class
                   4349: 
                   4350: doc-::
                   4351: 
                   4352: Compiles the method name of the class (not immediate!)
                   4353: 
                   4354: doc-object
                   4355: 
                   4356: Is the base class of all objects
                   4357: 
                   4358: @c -------------------------------------------------------------
                   4359: @node Mini-OOF Example, , Mini-OOF Usage, Mini-OOF
                   4360: @subsubsection Mini-OOF Example
                   4361: @cindex mini-oof example
                   4362: 
                   4363: A short example shows how to use this package.
                   4364: 
                   4365: @example
                   4366: object class
                   4367:   method init
                   4368:   method draw
                   4369: end-class graphical
                   4370: @end example
                   4371: 
                   4372: This code defines a class @code{graphical} with an
                   4373: operation @code{draw}.  We can perform the operation
                   4374: @code{draw} on any @code{graphical} object, e.g.:
                   4375: 
                   4376: @example
                   4377: 100 100 t-rex draw
                   4378: @end example
                   4379: 
                   4380: where @code{t-rex} is an object or object pointer, created with e.g.
                   4381: @code{graphical new Constant t-rex}.
                   4382: 
                   4383: For concrete graphical objects, we define child classes of the
                   4384: class @code{graphical}, e.g.:
1.8       pazsan   4385: 
                   4386: @example
1.13      pazsan   4387: graphical class
                   4388:   cell var circle-radius
                   4389: end-class circle \ "graphical" is the parent class
                   4390: 
                   4391: :noname ( x y -- )
                   4392:   circle-radius @@ draw-circle ; circle defines draw
                   4393: :noname ( r -- )
                   4394:   circle-radius ! ; circle defines init
                   4395: @end example
                   4396: 
                   4397: There is no implicit init method, so we have to define one. The creation
                   4398: code of the object now has to call init explicitely.
                   4399: 
                   4400: @example
                   4401: circle new Constant my-circle
                   4402: 50 my-circle init
                   4403: @end example
                   4404: 
                   4405: It is also possible to add a function to create named objects with
                   4406: automatic call of @code{init}, given that all objects have @code{init}
                   4407: on the same place
                   4408: 
                   4409: @example
                   4410: : new: ( .. o "name" -- )
                   4411:     new dup Constant init ;
                   4412: 80 circle new: large-circle
                   4413: @end example
                   4414: 
                   4415: We can draw this new circle at (100,100)
                   4416: with
                   4417: 
                   4418: @example
                   4419: 100 100 my-circle draw
1.8       pazsan   4420: @end example
                   4421: 
1.6       pazsan   4422: @c -------------------------------------------------------------
1.12      anton    4423: @node Tokens for Words, Wordlists, Object-oriented Forth, Words
1.1       anton    4424: @section Tokens for Words
                   4425: @cindex tokens for words
                   4426: 
                   4427: This chapter describes the creation and use of tokens that represent
                   4428: words on the stack (and in data space).
                   4429: 
                   4430: Named words have interpretation and compilation semantics. Unnamed words
                   4431: just have execution semantics.
                   4432: 
                   4433: @cindex execution token
                   4434: An @dfn{execution token} represents the execution semantics of an
                   4435: unnamed word. An execution token occupies one cell. As explained in
                   4436: section @ref{Supplying names}, the execution token of the last words
                   4437: defined can be produced with
                   4438: 
                   4439: short-lastxt
                   4440: 
                   4441: You can perform the semantics represented by an execution token with
                   4442: doc-execute
                   4443: You can compile the word with
                   4444: doc-compile,
                   4445: 
                   4446: @cindex code field address
                   4447: @cindex CFA
                   4448: In Gforth, the abstract data type @emph{execution token} is implemented
                   4449: as CFA (code field address).
                   4450: 
                   4451: The interpretation semantics of a named word are also represented by an
                   4452: execution token. You can get it with
                   4453: 
                   4454: doc-[']
                   4455: doc-'
                   4456: 
                   4457: For literals, you use @code{'} in interpreted code and @code{[']} in
                   4458: compiled code. Gforth's @code{'} and @code{[']} behave somewhat unusual
                   4459: by complaining about compile-only words. To get an execution token for a
                   4460: compiling word @var{X}, use @code{COMP' @var{X} drop} or @code{[COMP']
                   4461: @var{X} drop}.
                   4462: 
                   4463: @cindex compilation token
                   4464: The compilation semantics are represented by a @dfn{compilation token}
                   4465: consisting of two cells: @var{w xt}. The top cell @var{xt} is an
                   4466: execution token. The compilation semantics represented by the
                   4467: compilation token can be performed with @code{execute}, which consumes
                   4468: the whole compilation token, with an additional stack effect determined
                   4469: by the represented compilation semantics.
                   4470: 
                   4471: doc-[comp']
                   4472: doc-comp'
                   4473: 
                   4474: You can compile the compilation semantics with @code{postpone,}. I.e.,
                   4475: @code{COMP' @var{word} POSTPONE,} is equivalent to @code{POSTPONE
                   4476: @var{word}}.
                   4477: 
                   4478: doc-postpone,
                   4479: 
                   4480: At present, the @var{w} part of a compilation token is an execution
                   4481: token, and the @var{xt} part represents either @code{execute} or
                   4482: @code{compile,}. However, don't rely on that knowledge, unless necessary;
                   4483: we may introduce unusual compilation tokens in the future (e.g.,
                   4484: compilation tokens representing the compilation semantics of literals).
                   4485: 
                   4486: @cindex name token
                   4487: @cindex name field address
                   4488: @cindex NFA
                   4489: Named words are also represented by the @dfn{name token}. The abstract
                   4490: data type @emph{name token} is implemented as NFA (name field address).
                   4491: 
                   4492: doc-find-name
                   4493: doc-name>int
                   4494: doc-name?int
                   4495: doc-name>comp
                   4496: doc-name>string
                   4497: 
                   4498: @node Wordlists, Files, Tokens for Words, Words
                   4499: @section Wordlists
                   4500: 
1.12      anton    4501: @node Files, Including Files, Wordlists, Words
1.1       anton    4502: @section Files
                   4503: 
1.12      anton    4504: @node Including Files, Blocks, Files, Words
                   4505: @section Including Files
                   4506: @cindex including files
                   4507: 
                   4508: @menu
                   4509: * Words for Including::         
                   4510: * Search Path::                 
                   4511: * Changing the Search Path::    
                   4512: * General Search Paths::        
                   4513: @end menu
                   4514: 
                   4515: @node Words for Including, Search Path, Including Files, Including Files
                   4516: @subsection Words for Including
                   4517: 
                   4518: doc-include-file
                   4519: doc-included
                   4520: doc-include
                   4521: 
                   4522: Usually you want to include a file only if it is not included already
                   4523: (by, say, another source file):
                   4524: 
                   4525: doc-required
                   4526: doc-require
                   4527: doc-needs
                   4528: 
                   4529: @cindex stack effect of included files
                   4530: @cindex including files, stack effect
                   4531: I recommend that you write your source files such that interpreting them
                   4532: does not change the stack. This allows using these files with
                   4533: @code{required} and friends without complications. E.g.,
                   4534: 
                   4535: @example
                   4536: 1 require foo.fs drop
                   4537: @end example
                   4538: 
                   4539: @node Search Path, Changing the Search Path, Words for Including, Including Files
                   4540: @subsection Search Path
                   4541: @cindex path for @code{included}
                   4542: @cindex file search path
                   4543: @cindex include search path
                   4544: @cindex search path for files
                   4545: 
                   4546: If you specify an absolute filename (i.e., a filename starting with
                   4547: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   4548: @samp{C:...})) for @code{included} and friends, that file is included
                   4549: just as you would expect.
                   4550: 
                   4551: For relative filenames, Gforth uses a search path similar to Forth's
                   4552: search order (@pxref{Wordlists}). It tries to find the given filename in
                   4553: the directories present in the path, and includes the first one it
                   4554: finds.
                   4555: 
                   4556: If the search path contains the directory @file{.} (as it should), this
                   4557: refers to the directory that the present file was @code{included}
                   4558: from. This allows files to include other files relative to their own
                   4559: position (irrespective of the current working directory or the absolute
                   4560: position).  This feature is essential for libraries consisting of
                   4561: several files, where a file may include other files from the library.
                   4562: It corresponds to @code{#include "..."} in C. If the current input
                   4563: source is not a file, @file{.} refers to the directory of the innermost
                   4564: file being included, or, if there is no file being included, to the
                   4565: current working directory.
                   4566: 
                   4567: Use @file{~+} to refer to the current working directory (as in the
                   4568: @code{bash}).
                   4569: 
                   4570: If the filename starts with @file{./}, the search path is not searched
                   4571: (just as with absolute filenames), and the @file{.} has the same meaning
                   4572: as described above.
                   4573: 
                   4574: @node Changing the Search Path, General Search Paths, Search Path, Including Files
                   4575: @subsection Changing the Search Path
                   4576: @cindex search path, changes
                   4577: 
                   4578: The search path is initialized when you start Gforth (@pxref{Invoking
                   4579: Gforth}). You can display it with
                   4580: 
                   4581: doc-.fpath
                   4582: 
                   4583: You can change it later with the following words:
                   4584: 
                   4585: doc-fpath+
                   4586: doc-fpath=
                   4587: 
                   4588: Using fpath and require would look like:
                   4589: 
                   4590: @example
                   4591: fpath= /usr/lib/forth/|./
                   4592: 
                   4593: require timer.fs
                   4594: @end example
                   4595: 
                   4596: If you have the need to look for a file in the Forth search path, you could
                   4597: use this Gforth feature in your application.
                   4598: 
                   4599: doc-open-fpath-file
                   4600: 
                   4601: 
                   4602: @node General Search Paths,  , Changing the Search Path, Including Files
                   4603: @subsection General Search Paths
                   4604: @cindex search paths for user applications
                   4605: 
                   4606: Your application may need to search files in sevaral directories, like
                   4607: @code{included} does. For this purpose you can define and use your own
                   4608: search paths. Create a search path like this:
                   4609: 
                   4610: @example
                   4611: 
                   4612: Make a buffer for the path:
                   4613: create mypath   100 chars ,     \ maximum length (is checked)
                   4614:                 0 ,             \ real len
                   4615:                 100 chars allot \ space for path
                   4616: @end example
                   4617: 
                   4618: You have the same functions for the forth search path in a generic version
                   4619: for different paths.
                   4620: 
                   4621: doc-path+
                   4622: doc-path=
                   4623: doc-.path
                   4624: doc-open-path-file
                   4625: 
                   4626: 
                   4627: @node Blocks, Other I/O, Including Files, Words
1.1       anton    4628: @section Blocks
                   4629: 
                   4630: @node Other I/O, Programming Tools, Blocks, Words
                   4631: @section Other I/O
                   4632: 
1.7       pazsan   4633: @node Programming Tools, Assembler and Code Words, Other I/O, Words
1.1       anton    4634: @section Programming Tools
                   4635: @cindex programming tools
                   4636: 
                   4637: @menu
                   4638: * Debugging::                   Simple and quick.
                   4639: * Assertions::                  Making your programs self-checking.
1.6       pazsan   4640: * Singlestep Debugger::                Executing your program word by word.
1.1       anton    4641: @end menu
                   4642: 
                   4643: @node Debugging, Assertions, Programming Tools, Programming Tools
                   4644: @subsection Debugging
                   4645: @cindex debugging
                   4646: 
1.2       jwilke   4647: The simple debugging aids provided in @file{debugs.fs}
1.1       anton    4648: are meant to support a different style of debugging than the
                   4649: tracing/stepping debuggers used in languages with long turn-around
                   4650: times.
                   4651: 
                   4652: A much better (faster) way in fast-compiling languages is to add
                   4653: printing code at well-selected places, let the program run, look at
                   4654: the output, see where things went wrong, add more printing code, etc.,
                   4655: until the bug is found.
                   4656: 
                   4657: The word @code{~~} is easy to insert. It just prints debugging
                   4658: information (by default the source location and the stack contents). It
                   4659: is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   4660: query-replace them with nothing). The deferred words
                   4661: @code{printdebugdata} and @code{printdebugline} control the output of
                   4662: @code{~~}. The default source location output format works well with
                   4663: Emacs' compilation mode, so you can step through the program at the
                   4664: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   4665: is that you can step in any direction and you know where the crash has
                   4666: happened or where the strange data has occurred).
                   4667: 
                   4668: Note that the default actions clobber the contents of the pictured
                   4669: numeric output string, so you should not use @code{~~}, e.g., between
                   4670: @code{<#} and @code{#>}.
                   4671: 
                   4672: doc-~~
                   4673: doc-printdebugdata
                   4674: doc-printdebugline
                   4675: 
1.2       jwilke   4676: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
1.1       anton    4677: @subsection Assertions
                   4678: @cindex assertions
                   4679: 
                   4680: It is a good idea to make your programs self-checking, in particular, if
                   4681: you use an assumption (e.g., that a certain field of a data structure is
                   4682: never zero) that may become wrong during maintenance. Gforth supports
                   4683: assertions for this purpose. They are used like this:
                   4684: 
                   4685: @example
                   4686: assert( @var{flag} )
                   4687: @end example
                   4688: 
                   4689: The code between @code{assert(} and @code{)} should compute a flag, that
                   4690: should be true if everything is alright and false otherwise. It should
                   4691: not change anything else on the stack. The overall stack effect of the
                   4692: assertion is @code{( -- )}. E.g.
                   4693: 
                   4694: @example
                   4695: assert( 1 1 + 2 = ) \ what we learn in school
                   4696: assert( dup 0<> ) \ assert that the top of stack is not zero
                   4697: assert( false ) \ this code should not be reached
                   4698: @end example
                   4699: 
                   4700: The need for assertions is different at different times. During
                   4701: debugging, we want more checking, in production we sometimes care more
                   4702: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   4703: becomes a comment. Depending on the importance of an assertion and the
                   4704: time it takes to check it, you may want to turn off some assertions and
                   4705: keep others turned on. Gforth provides several levels of assertions for
                   4706: this purpose:
                   4707: 
                   4708: doc-assert0(
                   4709: doc-assert1(
                   4710: doc-assert2(
                   4711: doc-assert3(
                   4712: doc-assert(
                   4713: doc-)
                   4714: 
                   4715: @code{Assert(} is the same as @code{assert1(}. The variable
                   4716: @code{assert-level} specifies the highest assertions that are turned
                   4717: on. I.e., at the default @code{assert-level} of one, @code{assert0(} and
                   4718: @code{assert1(} assertions perform checking, while @code{assert2(} and
                   4719: @code{assert3(} assertions are treated as comments.
                   4720: 
                   4721: Note that the @code{assert-level} is evaluated at compile-time, not at
                   4722: run-time. I.e., you cannot turn assertions on or off at run-time, you
                   4723: have to set the @code{assert-level} appropriately before compiling a
                   4724: piece of code. You can compile several pieces of code at several
                   4725: @code{assert-level}s (e.g., a trusted library at level 1 and newly
                   4726: written code at level 3).
                   4727: 
                   4728: doc-assert-level
                   4729: 
                   4730: If an assertion fails, a message compatible with Emacs' compilation mode
                   4731: is produced and the execution is aborted (currently with @code{ABORT"}.
                   4732: If there is interest, we will introduce a special throw code. But if you
                   4733: intend to @code{catch} a specific condition, using @code{throw} is
                   4734: probably more appropriate than an assertion).
                   4735: 
1.2       jwilke   4736: @node Singlestep Debugger, , Assertions, Programming Tools
                   4737: @subsection Singlestep Debugger
                   4738: @cindex singlestep Debugger
                   4739: @cindex debugging Singlestep
                   4740: @cindex @code{dbg}
                   4741: @cindex @code{BREAK:}
                   4742: @cindex @code{BREAK"}
                   4743: 
                   4744: When a new word is created there's often the need to check whether it behaves
1.5       anton    4745: correctly or not. You can do this by typing @code{dbg badword}. This might
1.2       jwilke   4746: look like:
                   4747: @example
                   4748: : badword 0 DO i . LOOP ;  ok
                   4749: 2 dbg badword 
                   4750: : badword  
                   4751: Scanning code...
                   4752: 
                   4753: Nesting debugger ready!
                   4754: 
                   4755: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   4756: 400D4740  8049F68 DO             -> [ 0 ] 
                   4757: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   4758: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   4759: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   4760: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   4761: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   4762: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   4763: 400D4758  804B384 ;              ->  ok
                   4764: @end example
                   4765: 
1.5       anton    4766: Each line displayed is one step. You always have to hit return to
                   4767: execute the next word that is displayed. If you don't want to execute
                   4768: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   4769: an overview what keys are available:
1.2       jwilke   4770: 
                   4771: @table @i
                   4772: 
1.4       anton    4773: @item <return>
1.5       anton    4774: Next; Execute the next word.
1.2       jwilke   4775: 
                   4776: @item n
1.5       anton    4777: Nest; Single step through next word.
1.2       jwilke   4778: 
                   4779: @item u
1.5       anton    4780: Unnest; Stop debugging and execute rest of word. If we got to this word
                   4781: with nest, continue debugging with the calling word.
1.2       jwilke   4782: 
                   4783: @item d
1.5       anton    4784: Done; Stop debugging and execute rest.
1.2       jwilke   4785: 
                   4786: @item s
1.5       anton    4787: Stopp; Abort immediately.
1.2       jwilke   4788: 
                   4789: @end table
                   4790: 
                   4791: Debugging large application with this mechanism is very difficult, because
                   4792: you have to nest very deep into the program before the interesting part
                   4793: begins. This takes a lot of time. 
                   4794: 
                   4795: To do it more directly put a @code{BREAK:} command into your source code.
                   4796: When program execution reaches @code{BREAK:} the single step debugger is
                   4797: invoked and you have all the features described above.
                   4798: 
                   4799: If you have more than one part to debug it is useful to know where the
                   4800: program has stopped at the moment. You can do this by the 
                   4801: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   4802: string is typed out when the ``breakpoint'' is reached.
                   4803: 
1.7       pazsan   4804: @node Assembler and Code Words, Threading Words, Programming Tools, Words
                   4805: @section Assembler and Code Words
1.1       anton    4806: @cindex assembler
                   4807: @cindex code words
                   4808: 
                   4809: Gforth provides some words for defining primitives (words written in
                   4810: machine code), and for defining the the machine-code equivalent of
                   4811: @code{DOES>}-based defining words. However, the machine-independent
                   4812: nature of Gforth poses a few problems: First of all, Gforth runs on
                   4813: several architectures, so it can provide no standard assembler. What's
                   4814: worse is that the register allocation not only depends on the processor,
                   4815: but also on the @code{gcc} version and options used.
                   4816: 
                   4817: The words that Gforth offers encapsulate some system dependences (e.g., the
                   4818: header structure), so a system-independent assembler may be used in
                   4819: Gforth. If you do not have an assembler, you can compile machine code
                   4820: directly with @code{,} and @code{c,}.
                   4821: 
                   4822: doc-assembler
                   4823: doc-code
                   4824: doc-end-code
                   4825: doc-;code
                   4826: doc-flush-icache
                   4827: 
                   4828: If @code{flush-icache} does not work correctly, @code{code} words
                   4829: etc. will not work (reliably), either.
                   4830: 
                   4831: These words are rarely used. Therefore they reside in @code{code.fs},
                   4832: which is usually not loaded (except @code{flush-icache}, which is always
                   4833: present). You can load them with @code{require code.fs}.
                   4834: 
                   4835: @cindex registers of the inner interpreter
                   4836: In the assembly code you will want to refer to the inner interpreter's
                   4837: registers (e.g., the data stack pointer) and you may want to use other
                   4838: registers for temporary storage. Unfortunately, the register allocation
                   4839: is installation-dependent.
                   4840: 
                   4841: The easiest solution is to use explicit register declarations
                   4842: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
                   4843: GNU C Manual}) for all of the inner interpreter's registers: You have to
                   4844: compile Gforth with @code{-DFORCE_REG} (configure option
                   4845: @code{--enable-force-reg}) and the appropriate declarations must be
                   4846: present in the @code{machine.h} file (see @code{mips.h} for an example;
                   4847: you can find a full list of all declarable register symbols with
                   4848: @code{grep register engine.c}). If you give explicit registers to all
                   4849: variables that are declared at the beginning of @code{engine()}, you
                   4850: should be able to use the other caller-saved registers for temporary
                   4851: storage. Alternatively, you can use the @code{gcc} option
                   4852: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
                   4853: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
                   4854: (however, this restriction on register allocation may slow Gforth
                   4855: significantly).
                   4856: 
                   4857: If this solution is not viable (e.g., because @code{gcc} does not allow
                   4858: you to explicitly declare all the registers you need), you have to find
                   4859: out by looking at the code where the inner interpreter's registers
                   4860: reside and which registers can be used for temporary storage. You can
                   4861: get an assembly listing of the engine's code with @code{make engine.s}.
                   4862: 
                   4863: In any case, it is good practice to abstract your assembly code from the
                   4864: actual register allocation. E.g., if the data stack pointer resides in
                   4865: register @code{$17}, create an alias for this register called @code{sp},
                   4866: and use that in your assembly code.
                   4867: 
                   4868: @cindex code words, portable
                   4869: Another option for implementing normal and defining words efficiently
                   4870: is: adding the wanted functionality to the source of Gforth. For normal
                   4871: words you just have to edit @file{primitives} (@pxref{Automatic
                   4872: Generation}), defining words (equivalent to @code{;CODE} words, for fast
                   4873: defined words) may require changes in @file{engine.c}, @file{kernal.fs},
                   4874: @file{prims2x.fs}, and possibly @file{cross.fs}.
                   4875: 
                   4876: 
1.12      anton    4877: @node Threading Words,  , Assembler and Code Words, Words
1.1       anton    4878: @section Threading Words
                   4879: @cindex threading words
                   4880: 
                   4881: @cindex code address
                   4882: These words provide access to code addresses and other threading stuff
                   4883: in Gforth (and, possibly, other interpretive Forths). It more or less
                   4884: abstracts away the differences between direct and indirect threading
                   4885: (and, for direct threading, the machine dependences). However, at
                   4886: present this wordset is still incomplete. It is also pretty low-level;
                   4887: some day it will hopefully be made unnecessary by an internals wordset
                   4888: that abstracts implementation details away completely.
                   4889: 
                   4890: doc->code-address
                   4891: doc->does-code
                   4892: doc-code-address!
                   4893: doc-does-code!
                   4894: doc-does-handler!
                   4895: doc-/does-handler
                   4896: 
                   4897: The code addresses produced by various defining words are produced by
                   4898: the following words:
                   4899: 
                   4900: doc-docol:
                   4901: doc-docon:
                   4902: doc-dovar:
                   4903: doc-douser:
                   4904: doc-dodefer:
                   4905: doc-dofield:
                   4906: 
                   4907: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
                   4908: with @code{>DOES-CODE}. If the word was defined in that way, the value
                   4909: returned is different from 0 and identifies the @code{DOES>} used by the
                   4910: defining word.
1.2       jwilke   4911: 
1.5       anton    4912: @c ******************************************************************
1.1       anton    4913: @node Tools, ANS conformance, Words, Top
                   4914: @chapter Tools
                   4915: 
                   4916: @menu
                   4917: * ANS Report::                  Report the words used, sorted by wordset.
                   4918: @end menu
                   4919: 
                   4920: See also @ref{Emacs and Gforth}.
                   4921: 
                   4922: @node ANS Report,  , Tools, Tools
                   4923: @section @file{ans-report.fs}: Report the words used, sorted by wordset
                   4924: @cindex @file{ans-report.fs}
                   4925: @cindex report the words used in your program
                   4926: @cindex words used in your program
                   4927: 
                   4928: If you want to label a Forth program as ANS Forth Program, you must
                   4929: document which wordsets the program uses; for extension wordsets, it is
                   4930: helpful to list the words the program requires from these wordsets
                   4931: (because Forth systems are allowed to provide only some words of them).
                   4932: 
                   4933: The @file{ans-report.fs} tool makes it easy for you to determine which
                   4934: words from which wordset and which non-ANS words your application
                   4935: uses. You simply have to include @file{ans-report.fs} before loading the
                   4936: program you want to check. After loading your program, you can get the
                   4937: report with @code{print-ans-report}. A typical use is to run this as
                   4938: batch job like this:
                   4939: @example
                   4940: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
                   4941: @end example
                   4942: 
                   4943: The output looks like this (for @file{compat/control.fs}):
                   4944: @example
                   4945: The program uses the following words
                   4946: from CORE :
                   4947: : POSTPONE THEN ; immediate ?dup IF 0= 
                   4948: from BLOCK-EXT :
                   4949: \ 
                   4950: from FILE :
                   4951: ( 
                   4952: @end example
                   4953: 
                   4954: @subsection Caveats
                   4955: 
                   4956: Note that @file{ans-report.fs} just checks which words are used, not whether
                   4957: they are used in an ANS Forth conforming way!
                   4958: 
                   4959: Some words are defined in several wordsets in the
                   4960: standard. @file{ans-report.fs} reports them for only one of the
                   4961: wordsets, and not necessarily the one you expect. It depends on usage
                   4962: which wordset is the right one to specify. E.g., if you only use the
                   4963: compilation semantics of @code{S"}, it is a Core word; if you also use
                   4964: its interpretation semantics, it is a File word.
                   4965: 
                   4966: @c ******************************************************************
                   4967: @node ANS conformance, Model, Tools, Top
                   4968: @chapter ANS conformance
                   4969: @cindex ANS conformance of Gforth
                   4970: 
                   4971: To the best of our knowledge, Gforth is an
                   4972: 
                   4973: ANS Forth System
                   4974: @itemize @bullet
                   4975: @item providing the Core Extensions word set
                   4976: @item providing the Block word set
                   4977: @item providing the Block Extensions word set
                   4978: @item providing the Double-Number word set
                   4979: @item providing the Double-Number Extensions word set
                   4980: @item providing the Exception word set
                   4981: @item providing the Exception Extensions word set
                   4982: @item providing the Facility word set
                   4983: @item providing @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
                   4984: @item providing the File Access word set
                   4985: @item providing the File Access Extensions word set
                   4986: @item providing the Floating-Point word set
                   4987: @item providing the Floating-Point Extensions word set
                   4988: @item providing the Locals word set
                   4989: @item providing the Locals Extensions word set
                   4990: @item providing the Memory-Allocation word set
                   4991: @item providing the Memory-Allocation Extensions word set (that one's easy)
                   4992: @item providing the Programming-Tools word set
                   4993: @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
                   4994: @item providing the Search-Order word set
                   4995: @item providing the Search-Order Extensions word set
                   4996: @item providing the String word set
                   4997: @item providing the String Extensions word set (another easy one)
                   4998: @end itemize
                   4999: 
                   5000: @cindex system documentation
                   5001: In addition, ANS Forth systems are required to document certain
                   5002: implementation choices. This chapter tries to meet these
                   5003: requirements. In many cases it gives a way to ask the system for the
                   5004: information instead of providing the information directly, in
                   5005: particular, if the information depends on the processor, the operating
                   5006: system or the installation options chosen, or if they are likely to
                   5007: change during the maintenance of Gforth.
                   5008: 
                   5009: @comment The framework for the rest has been taken from pfe.
                   5010: 
                   5011: @menu
                   5012: * The Core Words::              
                   5013: * The optional Block word set::  
                   5014: * The optional Double Number word set::  
                   5015: * The optional Exception word set::  
                   5016: * The optional Facility word set::  
                   5017: * The optional File-Access word set::  
                   5018: * The optional Floating-Point word set::  
                   5019: * The optional Locals word set::  
                   5020: * The optional Memory-Allocation word set::  
                   5021: * The optional Programming-Tools word set::  
                   5022: * The optional Search-Order word set::  
                   5023: @end menu
                   5024: 
                   5025: 
                   5026: @c =====================================================================
                   5027: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
                   5028: @comment  node-name,  next,  previous,  up
                   5029: @section The Core Words
                   5030: @c =====================================================================
                   5031: @cindex core words, system documentation
                   5032: @cindex system documentation, core words
                   5033: 
                   5034: @menu
                   5035: * core-idef::                   Implementation Defined Options                   
                   5036: * core-ambcond::                Ambiguous Conditions                
                   5037: * core-other::                  Other System Documentation                  
                   5038: @end menu
                   5039: 
                   5040: @c ---------------------------------------------------------------------
                   5041: @node core-idef, core-ambcond, The Core Words, The Core Words
                   5042: @subsection Implementation Defined Options
                   5043: @c ---------------------------------------------------------------------
                   5044: @cindex core words, implementation-defined options
                   5045: @cindex implementation-defined options, core words
                   5046: 
                   5047: 
                   5048: @table @i
                   5049: @item (Cell) aligned addresses:
                   5050: @cindex cell-aligned addresses
                   5051: @cindex aligned addresses
                   5052: processor-dependent. Gforth's alignment words perform natural alignment
                   5053: (e.g., an address aligned for a datum of size 8 is divisible by
                   5054: 8). Unaligned accesses usually result in a @code{-23 THROW}.
                   5055: 
                   5056: @item @code{EMIT} and non-graphic characters:
                   5057: @cindex @code{EMIT} and non-graphic characters
                   5058: @cindex non-graphic characters and @code{EMIT}
                   5059: The character is output using the C library function (actually, macro)
                   5060: @code{putc}.
                   5061: 
                   5062: @item character editing of @code{ACCEPT} and @code{EXPECT}:
                   5063: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
                   5064: @cindex editing in @code{ACCEPT} and @code{EXPECT}
                   5065: @cindex @code{ACCEPT}, editing
                   5066: @cindex @code{EXPECT}, editing
                   5067: This is modeled on the GNU readline library (@pxref{Readline
                   5068: Interaction, , Command Line Editing, readline, The GNU Readline
                   5069: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
                   5070: producing a full word completion every time you type it (instead of
                   5071: producing the common prefix of all completions).
                   5072: 
                   5073: @item character set:
                   5074: @cindex character set
                   5075: The character set of your computer and display device. Gforth is
                   5076: 8-bit-clean (but some other component in your system may make trouble).
                   5077: 
                   5078: @item Character-aligned address requirements:
                   5079: @cindex character-aligned address requirements
                   5080: installation-dependent. Currently a character is represented by a C
                   5081: @code{unsigned char}; in the future we might switch to @code{wchar_t}
                   5082: (Comments on that requested).
                   5083: 
                   5084: @item character-set extensions and matching of names:
                   5085: @cindex character-set extensions and matching of names
                   5086: @cindex case sensitivity for name lookup
                   5087: @cindex name lookup, case sensitivity
                   5088: @cindex locale and case sensitivity
                   5089: Any character except the ASCII NUL charcter can be used in a
                   5090: name. Matching is case-insensitive (except in @code{TABLE}s). The
                   5091: matching is performed using the C function @code{strncasecmp}, whose
                   5092: function is probably influenced by the locale. E.g., the @code{C} locale
                   5093: does not know about accents and umlauts, so they are matched
                   5094: case-sensitively in that locale. For portability reasons it is best to
                   5095: write programs such that they work in the @code{C} locale. Then one can
                   5096: use libraries written by a Polish programmer (who might use words
                   5097: containing ISO Latin-2 encoded characters) and by a French programmer
                   5098: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
                   5099: funny results for some of the words (which ones, depends on the font you
                   5100: are using)). Also, the locale you prefer may not be available in other
                   5101: operating systems. Hopefully, Unicode will solve these problems one day.
                   5102: 
                   5103: @item conditions under which control characters match a space delimiter:
                   5104: @cindex space delimiters
                   5105: @cindex control characters as delimiters
                   5106: If @code{WORD} is called with the space character as a delimiter, all
                   5107: white-space characters (as identified by the C macro @code{isspace()})
                   5108: are delimiters. @code{PARSE}, on the other hand, treats space like other
                   5109: delimiters. @code{PARSE-WORD} treats space like @code{WORD}, but behaves
                   5110: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
                   5111: interpreter (aka text interpreter) by default, treats all white-space
                   5112: characters as delimiters.
                   5113: 
                   5114: @item format of the control flow stack:
                   5115: @cindex control flow stack, format
                   5116: The data stack is used as control flow stack. The size of a control flow
                   5117: stack item in cells is given by the constant @code{cs-item-size}. At the
                   5118: time of this writing, an item consists of a (pointer to a) locals list
                   5119: (third), an address in the code (second), and a tag for identifying the
                   5120: item (TOS). The following tags are used: @code{defstart},
                   5121: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
                   5122: @code{scopestart}.
                   5123: 
                   5124: @item conversion of digits > 35
                   5125: @cindex digits > 35
                   5126: The characters @code{[\]^_'} are the digits with the decimal value
                   5127: 36@minus{}41. There is no way to input many of the larger digits.
                   5128: 
                   5129: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
                   5130: @cindex @code{EXPECT}, display after end of input
                   5131: @cindex @code{ACCEPT}, display after end of input
                   5132: The cursor is moved to the end of the entered string. If the input is
                   5133: terminated using the @kbd{Return} key, a space is typed.
                   5134: 
                   5135: @item exception abort sequence of @code{ABORT"}:
                   5136: @cindex exception abort sequence of @code{ABORT"}
                   5137: @cindex @code{ABORT"}, exception abort sequence
                   5138: The error string is stored into the variable @code{"error} and a
                   5139: @code{-2 throw} is performed.
                   5140: 
                   5141: @item input line terminator:
                   5142: @cindex input line terminator
                   5143: @cindex line terminator on input
                   5144: @cindex newline charcter on input
                   5145: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
                   5146: lines. One of these characters is typically produced when you type the
                   5147: @kbd{Enter} or @kbd{Return} key.
                   5148: 
                   5149: @item maximum size of a counted string:
                   5150: @cindex maximum size of a counted string
                   5151: @cindex counted string, maximum size
                   5152: @code{s" /counted-string" environment? drop .}. Currently 255 characters
                   5153: on all ports, but this may change.
                   5154: 
                   5155: @item maximum size of a parsed string:
                   5156: @cindex maximum size of a parsed string
                   5157: @cindex parsed string, maximum size
                   5158: Given by the constant @code{/line}. Currently 255 characters.
                   5159: 
                   5160: @item maximum size of a definition name, in characters:
                   5161: @cindex maximum size of a definition name, in characters
                   5162: @cindex name, maximum length
                   5163: 31
                   5164: 
                   5165: @item maximum string length for @code{ENVIRONMENT?}, in characters:
                   5166: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
                   5167: @cindex @code{ENVIRONMENT?} string length, maximum
                   5168: 31
                   5169: 
                   5170: @item method of selecting the user input device:
                   5171: @cindex user input device, method of selecting
                   5172: The user input device is the standard input. There is currently no way to
                   5173: change it from within Gforth. However, the input can typically be
                   5174: redirected in the command line that starts Gforth.
                   5175: 
                   5176: @item method of selecting the user output device:
                   5177: @cindex user output device, method of selecting
                   5178: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10      anton    5179: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
                   5180: output when the user output device is a terminal, otherwise the output
                   5181: is buffered.
1.1       anton    5182: 
                   5183: @item methods of dictionary compilation:
                   5184: What are we expected to document here?
                   5185: 
                   5186: @item number of bits in one address unit:
                   5187: @cindex number of bits in one address unit
                   5188: @cindex address unit, size in bits
                   5189: @code{s" address-units-bits" environment? drop .}. 8 in all current
                   5190: ports.
                   5191: 
                   5192: @item number representation and arithmetic:
                   5193: @cindex number representation and arithmetic
                   5194: Processor-dependent. Binary two's complement on all current ports.
                   5195: 
                   5196: @item ranges for integer types:
                   5197: @cindex ranges for integer types
                   5198: @cindex integer types, ranges
                   5199: Installation-dependent. Make environmental queries for @code{MAX-N},
                   5200: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
                   5201: unsigned (and positive) types is 0. The lower bound for signed types on
                   5202: two's complement and one's complement machines machines can be computed
                   5203: by adding 1 to the upper bound.
                   5204: 
                   5205: @item read-only data space regions:
                   5206: @cindex read-only data space regions
                   5207: @cindex data-space, read-only regions
                   5208: The whole Forth data space is writable.
                   5209: 
                   5210: @item size of buffer at @code{WORD}:
                   5211: @cindex size of buffer at @code{WORD}
                   5212: @cindex @code{WORD} buffer size
                   5213: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   5214: shared with the pictured numeric output string. If overwriting
                   5215: @code{PAD} is acceptable, it is as large as the remaining dictionary
                   5216: space, although only as much can be sensibly used as fits in a counted
                   5217: string.
                   5218: 
                   5219: @item size of one cell in address units:
                   5220: @cindex cell size
                   5221: @code{1 cells .}.
                   5222: 
                   5223: @item size of one character in address units:
                   5224: @cindex char size
                   5225: @code{1 chars .}. 1 on all current ports.
                   5226: 
                   5227: @item size of the keyboard terminal buffer:
                   5228: @cindex size of the keyboard terminal buffer
                   5229: @cindex terminal buffer, size
                   5230: Varies. You can determine the size at a specific time using @code{lp@@
                   5231: tib - .}. It is shared with the locals stack and TIBs of files that
                   5232: include the current file. You can change the amount of space for TIBs
                   5233: and locals stack at Gforth startup with the command line option
                   5234: @code{-l}.
                   5235: 
                   5236: @item size of the pictured numeric output buffer:
                   5237: @cindex size of the pictured numeric output buffer
                   5238: @cindex pictured numeric output buffer, size
                   5239: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   5240: shared with @code{WORD}.
                   5241: 
                   5242: @item size of the scratch area returned by @code{PAD}:
                   5243: @cindex size of the scratch area returned by @code{PAD}
                   5244: @cindex @code{PAD} size
                   5245: The remainder of dictionary space. @code{unused pad here - - .}.
                   5246: 
                   5247: @item system case-sensitivity characteristics:
                   5248: @cindex case-sensitivity characteristics
                   5249: Dictionary searches are case insensitive (except in
                   5250: @code{TABLE}s). However, as explained above under @i{character-set
                   5251: extensions}, the matching for non-ASCII characters is determined by the
                   5252: locale you are using. In the default @code{C} locale all non-ASCII
                   5253: characters are matched case-sensitively.
                   5254: 
                   5255: @item system prompt:
                   5256: @cindex system prompt
                   5257: @cindex prompt
                   5258: @code{ ok} in interpret state, @code{ compiled} in compile state.
                   5259: 
                   5260: @item division rounding:
                   5261: @cindex division rounding
                   5262: installation dependent. @code{s" floored" environment? drop .}. We leave
                   5263: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
                   5264: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
                   5265: 
                   5266: @item values of @code{STATE} when true:
                   5267: @cindex @code{STATE} values
                   5268: -1.
                   5269: 
                   5270: @item values returned after arithmetic overflow:
                   5271: On two's complement machines, arithmetic is performed modulo
                   5272: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   5273: arithmetic (with appropriate mapping for signed types). Division by zero
                   5274: typically results in a @code{-55 throw} (Floating-point unidentified
                   5275: fault), although a @code{-10 throw} (divide by zero) would be more
                   5276: appropriate.
                   5277: 
                   5278: @item whether the current definition can be found after @t{DOES>}:
                   5279: @cindex @t{DOES>}, visibility of current definition
                   5280: No.
                   5281: 
                   5282: @end table
                   5283: 
                   5284: @c ---------------------------------------------------------------------
                   5285: @node core-ambcond, core-other, core-idef, The Core Words
                   5286: @subsection Ambiguous conditions
                   5287: @c ---------------------------------------------------------------------
                   5288: @cindex core words, ambiguous conditions
                   5289: @cindex ambiguous conditions, core words
                   5290: 
                   5291: @table @i
                   5292: 
                   5293: @item a name is neither a word nor a number:
                   5294: @cindex name not found
                   5295: @cindex Undefined word
                   5296: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
                   5297: preserves the data and FP stack, so you don't lose more work than
                   5298: necessary.
                   5299: 
                   5300: @item a definition name exceeds the maximum length allowed:
                   5301: @cindex Word name too long
                   5302: @code{-19 throw} (Word name too long)
                   5303: 
                   5304: @item addressing a region not inside the various data spaces of the forth system:
                   5305: @cindex Invalid memory address
                   5306: The stacks, code space and name space are accessible. Machine code space is
                   5307: typically readable. Accessing other addresses gives results dependent on
                   5308: the operating system. On decent systems: @code{-9 throw} (Invalid memory
                   5309: address).
                   5310: 
                   5311: @item argument type incompatible with parameter:
                   5312: @cindex Argument type mismatch
                   5313: This is usually not caught. Some words perform checks, e.g., the control
                   5314: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
                   5315: mismatch).
                   5316: 
                   5317: @item attempting to obtain the execution token of a word with undefined execution semantics:
                   5318: @cindex Interpreting a compile-only word, for @code{'} etc.
                   5319: @cindex execution token of words with undefined execution semantics
                   5320: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
                   5321: get an execution token for @code{compile-only-error} (which performs a
                   5322: @code{-14 throw} when executed).
                   5323: 
                   5324: @item dividing by zero:
                   5325: @cindex dividing by zero
                   5326: @cindex floating point unidentified fault, integer division
                   5327: @cindex divide by zero
                   5328: typically results in a @code{-55 throw} (floating point unidentified
                   5329: fault), although a @code{-10 throw} (divide by zero) would be more
                   5330: appropriate.
                   5331: 
                   5332: @item insufficient data stack or return stack space:
                   5333: @cindex insufficient data stack or return stack space
                   5334: @cindex stack overflow
                   5335: @cindex Address alignment exception, stack overflow
                   5336: @cindex Invalid memory address, stack overflow
                   5337: Depending on the operating system, the installation, and the invocation
                   5338: of Gforth, this is either checked by the memory management hardware, or
                   5339: it is not checked. If it is checked, you typically get a @code{-9 throw}
                   5340: (Invalid memory address) as soon as the overflow happens. If it is not
                   5341: check, overflows typically result in mysterious illegal memory accesses,
                   5342: producing @code{-9 throw} (Invalid memory address) or @code{-23 throw}
                   5343: (Address alignment exception); they might also destroy the internal data
                   5344: structure of @code{ALLOCATE} and friends, resulting in various errors in
                   5345: these words.
                   5346: 
                   5347: @item insufficient space for loop control parameters:
                   5348: @cindex insufficient space for loop control parameters
                   5349: like other return stack overflows.
                   5350: 
                   5351: @item insufficient space in the dictionary:
                   5352: @cindex insufficient space in the dictionary
                   5353: @cindex dictionary overflow
1.12      anton    5354: If you try to allot (either directly with @code{allot}, or indirectly
                   5355: with @code{,}, @code{create} etc.) more memory than available in the
                   5356: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
                   5357: to access memory beyond the end of the dictionary, the results are
                   5358: similar to stack overflows.
1.1       anton    5359: 
                   5360: @item interpreting a word with undefined interpretation semantics:
                   5361: @cindex interpreting a word with undefined interpretation semantics
                   5362: @cindex Interpreting a compile-only word
                   5363: For some words, we have defined interpretation semantics. For the
                   5364: others: @code{-14 throw} (Interpreting a compile-only word).
                   5365: 
                   5366: @item modifying the contents of the input buffer or a string literal:
                   5367: @cindex modifying the contents of the input buffer or a string literal
                   5368: These are located in writable memory and can be modified.
                   5369: 
                   5370: @item overflow of the pictured numeric output string:
                   5371: @cindex overflow of the pictured numeric output string
                   5372: @cindex pictured numeric output string, overflow
                   5373: Not checked. Runs into the dictionary and destroys it (at least,
                   5374: partially).
                   5375: 
                   5376: @item parsed string overflow:
                   5377: @cindex parsed string overflow
                   5378: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
                   5379: 
                   5380: @item producing a result out of range:
                   5381: @cindex result out of range
                   5382: On two's complement machines, arithmetic is performed modulo
                   5383: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   5384: arithmetic (with appropriate mapping for signed types). Division by zero
                   5385: typically results in a @code{-55 throw} (floatingpoint unidentified
                   5386: fault), although a @code{-10 throw} (divide by zero) would be more
                   5387: appropriate. @code{convert} and @code{>number} currently overflow
                   5388: silently.
                   5389: 
                   5390: @item reading from an empty data or return stack:
                   5391: @cindex stack empty
                   5392: @cindex stack underflow
                   5393: The data stack is checked by the outer (aka text) interpreter after
                   5394: every word executed. If it has underflowed, a @code{-4 throw} (Stack
                   5395: underflow) is performed. Apart from that, stacks may be checked or not,
                   5396: depending on operating system, installation, and invocation. The
                   5397: consequences of stack underflows are similar to the consequences of
                   5398: stack overflows. Note that even if the system uses checking (through the
                   5399: MMU), your program may have to underflow by a significant number of
                   5400: stack items to trigger the reaction (the reason for this is that the
                   5401: MMU, and therefore the checking, works with a page-size granularity).
                   5402: 
                   5403: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
                   5404: @cindex unexpected end of the input buffer
                   5405: @cindex zero-length string as a name
                   5406: @cindex Attempt to use zero-length string as a name
                   5407: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
                   5408: use zero-length string as a name). Words like @code{'} probably will not
                   5409: find what they search. Note that it is possible to create zero-length
                   5410: names with @code{nextname} (should it not?).
                   5411: 
                   5412: @item @code{>IN} greater than input buffer:
                   5413: @cindex @code{>IN} greater than input buffer
                   5414: The next invocation of a parsing word returns a string with length 0.
                   5415: 
                   5416: @item @code{RECURSE} appears after @code{DOES>}:
                   5417: @cindex @code{RECURSE} appears after @code{DOES>}
                   5418: Compiles a recursive call to the defining word, not to the defined word.
                   5419: 
                   5420: @item argument input source different than current input source for @code{RESTORE-INPUT}:
                   5421: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
                   5422: @cindex Argument type mismatch, @code{RESTORE-INPUT}
                   5423: @cindex @code{RESTORE-INPUT}, Argument type mismatch
                   5424: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
                   5425: the end of the file was reached), its source-id may be
                   5426: reused. Therefore, restoring an input source specification referencing a
                   5427: closed file may lead to unpredictable results instead of a @code{-12
                   5428: THROW}.
                   5429: 
                   5430: In the future, Gforth may be able to restore input source specifications
                   5431: from other than the current input source.
                   5432: 
                   5433: @item data space containing definitions gets de-allocated:
                   5434: @cindex data space containing definitions gets de-allocated
                   5435: Deallocation with @code{allot} is not checked. This typically results in
                   5436: memory access faults or execution of illegal instructions.
                   5437: 
                   5438: @item data space read/write with incorrect alignment:
                   5439: @cindex data space read/write with incorrect alignment
                   5440: @cindex alignment faults
                   5441: @cindex Address alignment exception
                   5442: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12      anton    5443: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1       anton    5444: alignment turned on, incorrect alignment results in a @code{-9 throw}
                   5445: (Invalid memory address). There are reportedly some processors with
1.12      anton    5446: alignment restrictions that do not report violations.
1.1       anton    5447: 
                   5448: @item data space pointer not properly aligned, @code{,}, @code{C,}:
                   5449: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
                   5450: Like other alignment errors.
                   5451: 
                   5452: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
                   5453: Like other stack underflows.
                   5454: 
                   5455: @item loop control parameters not available:
                   5456: @cindex loop control parameters not available
                   5457: Not checked. The counted loop words simply assume that the top of return
                   5458: stack items are loop control parameters and behave accordingly.
                   5459: 
                   5460: @item most recent definition does not have a name (@code{IMMEDIATE}):
                   5461: @cindex most recent definition does not have a name (@code{IMMEDIATE})
                   5462: @cindex last word was headerless
                   5463: @code{abort" last word was headerless"}.
                   5464: 
                   5465: @item name not defined by @code{VALUE} used by @code{TO}:
                   5466: @cindex name not defined by @code{VALUE} used by @code{TO}
                   5467: @cindex @code{TO} on non-@code{VALUE}s
                   5468: @cindex Invalid name argument, @code{TO}
                   5469: @code{-32 throw} (Invalid name argument) (unless name is a local or was
                   5470: defined by @code{CONSTANT}; in the latter case it just changes the constant).
                   5471: 
                   5472: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
                   5473: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
                   5474: @cindex Undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
                   5475: @code{-13 throw} (Undefined word)
                   5476: 
                   5477: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
                   5478: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
                   5479: Gforth behaves as if they were of the same type. I.e., you can predict
                   5480: the behaviour by interpreting all parameters as, e.g., signed.
                   5481: 
                   5482: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
                   5483: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
                   5484: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
                   5485: compilation semantics of @code{TO}.
                   5486: 
                   5487: @item String longer than a counted string returned by @code{WORD}:
                   5488: @cindex String longer than a counted string returned by @code{WORD}
                   5489: @cindex @code{WORD}, string overflow
                   5490: Not checked. The string will be ok, but the count will, of course,
                   5491: contain only the least significant bits of the length.
                   5492: 
                   5493: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
                   5494: @cindex @code{LSHIFT}, large shift counts
                   5495: @cindex @code{RSHIFT}, large shift counts
                   5496: Processor-dependent. Typical behaviours are returning 0 and using only
                   5497: the low bits of the shift count.
                   5498: 
                   5499: @item word not defined via @code{CREATE}:
                   5500: @cindex @code{>BODY} of non-@code{CREATE}d words
                   5501: @code{>BODY} produces the PFA of the word no matter how it was defined.
                   5502: 
                   5503: @cindex @code{DOES>} of non-@code{CREATE}d words
                   5504: @code{DOES>} changes the execution semantics of the last defined word no
                   5505: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
                   5506: @code{CREATE , DOES>}.
                   5507: 
                   5508: @item words improperly used outside @code{<#} and @code{#>}:
                   5509: Not checked. As usual, you can expect memory faults.
                   5510: 
                   5511: @end table
                   5512: 
                   5513: 
                   5514: @c ---------------------------------------------------------------------
                   5515: @node core-other,  , core-ambcond, The Core Words
                   5516: @subsection Other system documentation
                   5517: @c ---------------------------------------------------------------------
                   5518: @cindex other system documentation, core words
                   5519: @cindex core words, other system documentation
                   5520: 
                   5521: @table @i
                   5522: @item nonstandard words using @code{PAD}:
                   5523: @cindex @code{PAD} use by nonstandard words
                   5524: None.
                   5525: 
                   5526: @item operator's terminal facilities available:
                   5527: @cindex operator's terminal facilities available
                   5528: After processing the command line, Gforth goes into interactive mode,
                   5529: and you can give commands to Gforth interactively. The actual facilities
                   5530: available depend on how you invoke Gforth.
                   5531: 
                   5532: @item program data space available:
                   5533: @cindex program data space available
                   5534: @cindex data space available
                   5535: @code{UNUSED .} gives the remaining dictionary space. The total
                   5536: dictionary space can be specified with the @code{-m} switch
                   5537: (@pxref{Invoking Gforth}) when Gforth starts up.
                   5538: 
                   5539: @item return stack space available:
                   5540: @cindex return stack space available
                   5541: You can compute the total return stack space in cells with
                   5542: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
                   5543: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
                   5544: 
                   5545: @item stack space available:
                   5546: @cindex stack space available
                   5547: You can compute the total data stack space in cells with
                   5548: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
                   5549: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
                   5550: 
                   5551: @item system dictionary space required, in address units:
                   5552: @cindex system dictionary space required, in address units
                   5553: Type @code{here forthstart - .} after startup. At the time of this
                   5554: writing, this gives 80080 (bytes) on a 32-bit system.
                   5555: @end table
                   5556: 
                   5557: 
                   5558: @c =====================================================================
                   5559: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
                   5560: @section The optional Block word set
                   5561: @c =====================================================================
                   5562: @cindex system documentation, block words
                   5563: @cindex block words, system documentation
                   5564: 
                   5565: @menu
                   5566: * block-idef::                  Implementation Defined Options
                   5567: * block-ambcond::               Ambiguous Conditions               
                   5568: * block-other::                 Other System Documentation                 
                   5569: @end menu
                   5570: 
                   5571: 
                   5572: @c ---------------------------------------------------------------------
                   5573: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
                   5574: @subsection Implementation Defined Options
                   5575: @c ---------------------------------------------------------------------
                   5576: @cindex implementation-defined options, block words
                   5577: @cindex block words, implementation-defined options
                   5578: 
                   5579: @table @i
                   5580: @item the format for display by @code{LIST}:
                   5581: @cindex @code{LIST} display format
                   5582: First the screen number is displayed, then 16 lines of 64 characters,
                   5583: each line preceded by the line number.
                   5584: 
                   5585: @item the length of a line affected by @code{\}:
                   5586: @cindex length of a line affected by @code{\}
                   5587: @cindex @code{\}, line length in blocks
                   5588: 64 characters.
                   5589: @end table
                   5590: 
                   5591: 
                   5592: @c ---------------------------------------------------------------------
                   5593: @node block-ambcond, block-other, block-idef, The optional Block word set
                   5594: @subsection Ambiguous conditions
                   5595: @c ---------------------------------------------------------------------
                   5596: @cindex block words, ambiguous conditions
                   5597: @cindex ambiguous conditions, block words
                   5598: 
                   5599: @table @i
                   5600: @item correct block read was not possible:
                   5601: @cindex block read not possible
                   5602: Typically results in a @code{throw} of some OS-derived value (between
                   5603: -512 and -2048). If the blocks file was just not long enough, blanks are
                   5604: supplied for the missing portion.
                   5605: 
                   5606: @item I/O exception in block transfer:
                   5607: @cindex I/O exception in block transfer
                   5608: @cindex block transfer, I/O exception
                   5609: Typically results in a @code{throw} of some OS-derived value (between
                   5610: -512 and -2048).
                   5611: 
                   5612: @item invalid block number:
                   5613: @cindex invalid block number
                   5614: @cindex block number invalid
                   5615: @code{-35 throw} (Invalid block number)
                   5616: 
                   5617: @item a program directly alters the contents of @code{BLK}:
                   5618: @cindex @code{BLK}, altering @code{BLK}
                   5619: The input stream is switched to that other block, at the same
                   5620: position. If the storing to @code{BLK} happens when interpreting
                   5621: non-block input, the system will get quite confused when the block ends.
                   5622: 
                   5623: @item no current block buffer for @code{UPDATE}:
                   5624: @cindex @code{UPDATE}, no current block buffer
                   5625: @code{UPDATE} has no effect.
                   5626: 
                   5627: @end table
                   5628: 
                   5629: @c ---------------------------------------------------------------------
                   5630: @node block-other,  , block-ambcond, The optional Block word set
                   5631: @subsection Other system documentation
                   5632: @c ---------------------------------------------------------------------
                   5633: @cindex other system documentation, block words
                   5634: @cindex block words, other system documentation
                   5635: 
                   5636: @table @i
                   5637: @item any restrictions a multiprogramming system places on the use of buffer addresses:
                   5638: No restrictions (yet).
                   5639: 
                   5640: @item the number of blocks available for source and data:
                   5641: depends on your disk space.
                   5642: 
                   5643: @end table
                   5644: 
                   5645: 
                   5646: @c =====================================================================
                   5647: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
                   5648: @section The optional Double Number word set
                   5649: @c =====================================================================
                   5650: @cindex system documentation, double words
                   5651: @cindex double words, system documentation
                   5652: 
                   5653: @menu
                   5654: * double-ambcond::              Ambiguous Conditions              
                   5655: @end menu
                   5656: 
                   5657: 
                   5658: @c ---------------------------------------------------------------------
                   5659: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
                   5660: @subsection Ambiguous conditions
                   5661: @c ---------------------------------------------------------------------
                   5662: @cindex double words, ambiguous conditions
                   5663: @cindex ambiguous conditions, double words
                   5664: 
                   5665: @table @i
                   5666: @item @var{d} outside of range of @var{n} in @code{D>S}:
                   5667: @cindex @code{D>S}, @var{d} out of range of @var{n} 
                   5668: The least significant cell of @var{d} is produced.
                   5669: 
                   5670: @end table
                   5671: 
                   5672: 
                   5673: @c =====================================================================
                   5674: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
                   5675: @section The optional Exception word set
                   5676: @c =====================================================================
                   5677: @cindex system documentation, exception words
                   5678: @cindex exception words, system documentation
                   5679: 
                   5680: @menu
                   5681: * exception-idef::              Implementation Defined Options              
                   5682: @end menu
                   5683: 
                   5684: 
                   5685: @c ---------------------------------------------------------------------
                   5686: @node exception-idef,  , The optional Exception word set, The optional Exception word set
                   5687: @subsection Implementation Defined Options
                   5688: @c ---------------------------------------------------------------------
                   5689: @cindex implementation-defined options, exception words
                   5690: @cindex exception words, implementation-defined options
                   5691: 
                   5692: @table @i
                   5693: @item @code{THROW}-codes used in the system:
                   5694: @cindex @code{THROW}-codes used in the system
                   5695: The codes -256@minus{}-511 are used for reporting signals. The mapping
                   5696: from OS signal numbers to throw codes is -256@minus{}@var{signal}. The
                   5697: codes -512@minus{}-2047 are used for OS errors (for file and memory
                   5698: allocation operations). The mapping from OS error numbers to throw codes
                   5699: is -512@minus{}@code{errno}. One side effect of this mapping is that
                   5700: undefined OS errors produce a message with a strange number; e.g.,
                   5701: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
                   5702: @end table
                   5703: 
                   5704: @c =====================================================================
                   5705: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
                   5706: @section The optional Facility word set
                   5707: @c =====================================================================
                   5708: @cindex system documentation, facility words
                   5709: @cindex facility words, system documentation
                   5710: 
                   5711: @menu
                   5712: * facility-idef::               Implementation Defined Options               
                   5713: * facility-ambcond::            Ambiguous Conditions            
                   5714: @end menu
                   5715: 
                   5716: 
                   5717: @c ---------------------------------------------------------------------
                   5718: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
                   5719: @subsection Implementation Defined Options
                   5720: @c ---------------------------------------------------------------------
                   5721: @cindex implementation-defined options, facility words
                   5722: @cindex facility words, implementation-defined options
                   5723: 
                   5724: @table @i
                   5725: @item encoding of keyboard events (@code{EKEY}):
                   5726: @cindex keyboard events, encoding in @code{EKEY}
                   5727: @cindex @code{EKEY}, encoding of keyboard events
                   5728: Not yet implemented.
                   5729: 
                   5730: @item duration of a system clock tick:
                   5731: @cindex duration of a system clock tick
                   5732: @cindex clock tick duration
                   5733: System dependent. With respect to @code{MS}, the time is specified in
                   5734: microseconds. How well the OS and the hardware implement this, is
                   5735: another question.
                   5736: 
                   5737: @item repeatability to be expected from the execution of @code{MS}:
                   5738: @cindex repeatability to be expected from the execution of @code{MS}
                   5739: @cindex @code{MS}, repeatability to be expected
                   5740: System dependent. On Unix, a lot depends on load. If the system is
                   5741: lightly loaded, and the delay is short enough that Gforth does not get
                   5742: swapped out, the performance should be acceptable. Under MS-DOS and
                   5743: other single-tasking systems, it should be good.
                   5744: 
                   5745: @end table
                   5746: 
                   5747: 
                   5748: @c ---------------------------------------------------------------------
                   5749: @node facility-ambcond,  , facility-idef, The optional Facility word set
                   5750: @subsection Ambiguous conditions
                   5751: @c ---------------------------------------------------------------------
                   5752: @cindex facility words, ambiguous conditions
                   5753: @cindex ambiguous conditions, facility words
                   5754: 
                   5755: @table @i
                   5756: @item @code{AT-XY} can't be performed on user output device:
                   5757: @cindex @code{AT-XY} can't be performed on user output device
                   5758: Largely terminal dependent. No range checks are done on the arguments.
                   5759: No errors are reported. You may see some garbage appearing, you may see
                   5760: simply nothing happen.
                   5761: 
                   5762: @end table
                   5763: 
                   5764: 
                   5765: @c =====================================================================
                   5766: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
                   5767: @section The optional File-Access word set
                   5768: @c =====================================================================
                   5769: @cindex system documentation, file words
                   5770: @cindex file words, system documentation
                   5771: 
                   5772: @menu
                   5773: * file-idef::                   Implementation Defined Options
                   5774: * file-ambcond::                Ambiguous Conditions                
                   5775: @end menu
                   5776: 
                   5777: @c ---------------------------------------------------------------------
                   5778: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
                   5779: @subsection Implementation Defined Options
                   5780: @c ---------------------------------------------------------------------
                   5781: @cindex implementation-defined options, file words
                   5782: @cindex file words, implementation-defined options
                   5783: 
                   5784: @table @i
                   5785: @item file access methods used:
                   5786: @cindex file access methods used
                   5787: @code{R/O}, @code{R/W} and @code{BIN} work as you would
                   5788: expect. @code{W/O} translates into the C file opening mode @code{w} (or
                   5789: @code{wb}): The file is cleared, if it exists, and created, if it does
                   5790: not (with both @code{open-file} and @code{create-file}).  Under Unix
                   5791: @code{create-file} creates a file with 666 permissions modified by your
                   5792: umask.
                   5793: 
                   5794: @item file exceptions:
                   5795: @cindex file exceptions
                   5796: The file words do not raise exceptions (except, perhaps, memory access
                   5797: faults when you pass illegal addresses or file-ids).
                   5798: 
                   5799: @item file line terminator:
                   5800: @cindex file line terminator
                   5801: System-dependent. Gforth uses C's newline character as line
                   5802: terminator. What the actual character code(s) of this are is
                   5803: system-dependent.
                   5804: 
                   5805: @item file name format:
                   5806: @cindex file name format
                   5807: System dependent. Gforth just uses the file name format of your OS.
                   5808: 
                   5809: @item information returned by @code{FILE-STATUS}:
                   5810: @cindex @code{FILE-STATUS}, returned information
                   5811: @code{FILE-STATUS} returns the most powerful file access mode allowed
                   5812: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
                   5813: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
                   5814: along with the returned mode.
                   5815: 
                   5816: @item input file state after an exception when including source:
                   5817: @cindex exception when including source
                   5818: All files that are left via the exception are closed.
                   5819: 
                   5820: @item @var{ior} values and meaning:
                   5821: @cindex @var{ior} values and meaning
                   5822: The @var{ior}s returned by the file and memory allocation words are
                   5823: intended as throw codes. They typically are in the range
                   5824: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
                   5825: @var{ior}s is -512@minus{}@var{errno}.
                   5826: 
                   5827: @item maximum depth of file input nesting:
                   5828: @cindex maximum depth of file input nesting
                   5829: @cindex file input nesting, maximum depth
                   5830: limited by the amount of return stack, locals/TIB stack, and the number
                   5831: of open files available. This should not give you troubles.
                   5832: 
                   5833: @item maximum size of input line:
                   5834: @cindex maximum size of input line
                   5835: @cindex input line size, maximum
                   5836: @code{/line}. Currently 255.
                   5837: 
                   5838: @item methods of mapping block ranges to files:
                   5839: @cindex mapping block ranges to files
                   5840: @cindex files containing blocks
                   5841: @cindex blocks in files
                   5842: By default, blocks are accessed in the file @file{blocks.fb} in the
                   5843: current working directory. The file can be switched with @code{USE}.
                   5844: 
                   5845: @item number of string buffers provided by @code{S"}:
                   5846: @cindex @code{S"}, number of string buffers
                   5847: 1
                   5848: 
                   5849: @item size of string buffer used by @code{S"}:
                   5850: @cindex @code{S"}, size of string buffer
                   5851: @code{/line}. currently 255.
                   5852: 
                   5853: @end table
                   5854: 
                   5855: @c ---------------------------------------------------------------------
                   5856: @node file-ambcond,  , file-idef, The optional File-Access word set
                   5857: @subsection Ambiguous conditions
                   5858: @c ---------------------------------------------------------------------
                   5859: @cindex file words, ambiguous conditions
                   5860: @cindex ambiguous conditions, file words
                   5861: 
                   5862: @table @i
                   5863: @item attempting to position a file outside its boundaries:
                   5864: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
                   5865: @code{REPOSITION-FILE} is performed as usual: Afterwards,
                   5866: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
                   5867: 
                   5868: @item attempting to read from file positions not yet written:
                   5869: @cindex reading from file positions not yet written
                   5870: End-of-file, i.e., zero characters are read and no error is reported.
                   5871: 
                   5872: @item @var{file-id} is invalid (@code{INCLUDE-FILE}):
                   5873: @cindex @code{INCLUDE-FILE}, @var{file-id} is invalid 
                   5874: An appropriate exception may be thrown, but a memory fault or other
                   5875: problem is more probable.
                   5876: 
                   5877: @item I/O exception reading or closing @var{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
                   5878: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @var{file-id}
                   5879: @cindex @code{INCLUDED}, I/O exception reading or closing @var{file-id}
                   5880: The @var{ior} produced by the operation, that discovered the problem, is
                   5881: thrown.
                   5882: 
                   5883: @item named file cannot be opened (@code{INCLUDED}):
                   5884: @cindex @code{INCLUDED}, named file cannot be opened
                   5885: The @var{ior} produced by @code{open-file} is thrown.
                   5886: 
                   5887: @item requesting an unmapped block number:
                   5888: @cindex unmapped block numbers
                   5889: There are no unmapped legal block numbers. On some operating systems,
                   5890: writing a block with a large number may overflow the file system and
                   5891: have an error message as consequence.
                   5892: 
                   5893: @item using @code{source-id} when @code{blk} is non-zero:
                   5894: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
                   5895: @code{source-id} performs its function. Typically it will give the id of
                   5896: the source which loaded the block. (Better ideas?)
                   5897: 
                   5898: @end table
                   5899: 
                   5900: 
                   5901: @c =====================================================================
                   5902: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
                   5903: @section The optional Floating-Point word set
                   5904: @c =====================================================================
                   5905: @cindex system documentation, floating-point words
                   5906: @cindex floating-point words, system documentation
                   5907: 
                   5908: @menu
                   5909: * floating-idef::               Implementation Defined Options
                   5910: * floating-ambcond::            Ambiguous Conditions            
                   5911: @end menu
                   5912: 
                   5913: 
                   5914: @c ---------------------------------------------------------------------
                   5915: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
                   5916: @subsection Implementation Defined Options
                   5917: @c ---------------------------------------------------------------------
                   5918: @cindex implementation-defined options, floating-point words
                   5919: @cindex floating-point words, implementation-defined options
                   5920: 
                   5921: @table @i
                   5922: @item format and range of floating point numbers:
                   5923: @cindex format and range of floating point numbers
                   5924: @cindex floating point numbers, format and range
                   5925: System-dependent; the @code{double} type of C.
                   5926: 
                   5927: @item results of @code{REPRESENT} when @var{float} is out of range:
                   5928: @cindex  @code{REPRESENT}, results when @var{float} is out of range
                   5929: System dependent; @code{REPRESENT} is implemented using the C library
                   5930: function @code{ecvt()} and inherits its behaviour in this respect.
                   5931: 
                   5932: @item rounding or truncation of floating-point numbers:
                   5933: @cindex rounding of floating-point numbers
                   5934: @cindex truncation of floating-point numbers
                   5935: @cindex floating-point numbers, rounding or truncation
                   5936: System dependent; the rounding behaviour is inherited from the hosting C
                   5937: compiler. IEEE-FP-based (i.e., most) systems by default round to
                   5938: nearest, and break ties by rounding to even (i.e., such that the last
                   5939: bit of the mantissa is 0).
                   5940: 
                   5941: @item size of floating-point stack:
                   5942: @cindex floating-point stack size
                   5943: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
                   5944: the floating-point stack (in floats). You can specify this on startup
                   5945: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
                   5946: 
                   5947: @item width of floating-point stack:
                   5948: @cindex floating-point stack width 
                   5949: @code{1 floats}.
                   5950: 
                   5951: @end table
                   5952: 
                   5953: 
                   5954: @c ---------------------------------------------------------------------
                   5955: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
                   5956: @subsection Ambiguous conditions
                   5957: @c ---------------------------------------------------------------------
                   5958: @cindex floating-point words, ambiguous conditions
                   5959: @cindex ambiguous conditions, floating-point words
                   5960: 
                   5961: @table @i
                   5962: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
                   5963: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
                   5964: System-dependent. Typically results in a @code{-23 THROW} like other
                   5965: alignment violations.
                   5966: 
                   5967: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
                   5968: @cindex @code{f@@} used with an address that is not float aligned
                   5969: @cindex @code{f!} used with an address that is not float aligned
                   5970: System-dependent. Typically results in a @code{-23 THROW} like other
                   5971: alignment violations.
                   5972: 
                   5973: @item floating-point result out of range:
                   5974: @cindex floating-point result out of range
                   5975: System-dependent. Can result in a @code{-55 THROW} (Floating-point
                   5976: unidentified fault), or can produce a special value representing, e.g.,
                   5977: Infinity.
                   5978: 
                   5979: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
                   5980: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
                   5981: System-dependent. Typically results in an alignment fault like other
                   5982: alignment violations.
                   5983: 
                   5984: @item @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
                   5985: @cindex @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
                   5986: The floating-point number is converted into decimal nonetheless.
                   5987: 
                   5988: @item Both arguments are equal to zero (@code{FATAN2}):
                   5989: @cindex @code{FATAN2}, both arguments are equal to zero
                   5990: System-dependent. @code{FATAN2} is implemented using the C library
                   5991: function @code{atan2()}.
                   5992: 
                   5993: @item Using @code{FTAN} on an argument @var{r1} where cos(@var{r1}) is zero:
                   5994: @cindex @code{FTAN} on an argument @var{r1} where cos(@var{r1}) is zero
                   5995: System-dependent. Anyway, typically the cos of @var{r1} will not be zero
                   5996: because of small errors and the tan will be a very large (or very small)
                   5997: but finite number.
                   5998: 
                   5999: @item @var{d} cannot be presented precisely as a float in @code{D>F}:
                   6000: @cindex @code{D>F}, @var{d} cannot be presented precisely as a float
                   6001: The result is rounded to the nearest float.
                   6002: 
                   6003: @item dividing by zero:
                   6004: @cindex dividing by zero, floating-point
                   6005: @cindex floating-point dividing by zero
                   6006: @cindex floating-point unidentified fault, FP divide-by-zero
                   6007: @code{-55 throw} (Floating-point unidentified fault)
                   6008: 
                   6009: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
                   6010: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
                   6011: System dependent. On IEEE-FP based systems the number is converted into
                   6012: an infinity.
                   6013: 
                   6014: @item @var{float}<1 (@code{FACOSH}):
                   6015: @cindex @code{FACOSH}, @var{float}<1
                   6016: @cindex floating-point unidentified fault, @code{FACOSH}
                   6017: @code{-55 throw} (Floating-point unidentified fault)
                   6018: 
                   6019: @item @var{float}=<-1 (@code{FLNP1}):
                   6020: @cindex @code{FLNP1}, @var{float}=<-1
                   6021: @cindex floating-point unidentified fault, @code{FLNP1}
                   6022: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
                   6023: negative infinity is typically produced for @var{float}=-1.
                   6024: 
                   6025: @item @var{float}=<0 (@code{FLN}, @code{FLOG}):
                   6026: @cindex @code{FLN}, @var{float}=<0
                   6027: @cindex @code{FLOG}, @var{float}=<0
                   6028: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
                   6029: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
                   6030: negative infinity is typically produced for @var{float}=0.
                   6031: 
                   6032: @item @var{float}<0 (@code{FASINH}, @code{FSQRT}):
                   6033: @cindex @code{FASINH}, @var{float}<0
                   6034: @cindex @code{FSQRT}, @var{float}<0
                   6035: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
                   6036: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
                   6037: produces values for these inputs on my Linux box (Bug in the C library?)
                   6038: 
                   6039: @item |@var{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
                   6040: @cindex @code{FACOS}, |@var{float}|>1
                   6041: @cindex @code{FASIN}, |@var{float}|>1
                   6042: @cindex @code{FATANH}, |@var{float}|>1
                   6043: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
                   6044: @code{-55 throw} (Floating-point unidentified fault).
                   6045: 
                   6046: @item integer part of float cannot be represented by @var{d} in @code{F>D}:
                   6047: @cindex @code{F>D}, integer part of float cannot be represented by @var{d}
                   6048: @cindex floating-point unidentified fault, @code{F>D}
                   6049: @code{-55 throw} (Floating-point unidentified fault).
                   6050: 
                   6051: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
                   6052: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
                   6053: This does not happen.
                   6054: @end table
                   6055: 
                   6056: @c =====================================================================
                   6057: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
                   6058: @section The optional Locals word set
                   6059: @c =====================================================================
                   6060: @cindex system documentation, locals words
                   6061: @cindex locals words, system documentation
                   6062: 
                   6063: @menu
                   6064: * locals-idef::                 Implementation Defined Options                 
                   6065: * locals-ambcond::              Ambiguous Conditions              
                   6066: @end menu
                   6067: 
                   6068: 
                   6069: @c ---------------------------------------------------------------------
                   6070: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
                   6071: @subsection Implementation Defined Options
                   6072: @c ---------------------------------------------------------------------
                   6073: @cindex implementation-defined options, locals words
                   6074: @cindex locals words, implementation-defined options
                   6075: 
                   6076: @table @i
                   6077: @item maximum number of locals in a definition:
                   6078: @cindex maximum number of locals in a definition
                   6079: @cindex locals, maximum number in a definition
                   6080: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
                   6081: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
                   6082: characters. The number of locals in a definition is bounded by the size
                   6083: of locals-buffer, which contains the names of the locals.
                   6084: 
                   6085: @end table
                   6086: 
                   6087: 
                   6088: @c ---------------------------------------------------------------------
                   6089: @node locals-ambcond,  , locals-idef, The optional Locals word set
                   6090: @subsection Ambiguous conditions
                   6091: @c ---------------------------------------------------------------------
                   6092: @cindex locals words, ambiguous conditions
                   6093: @cindex ambiguous conditions, locals words
                   6094: 
                   6095: @table @i
                   6096: @item executing a named local in interpretation state:
                   6097: @cindex local in interpretation state
                   6098: @cindex Interpreting a compile-only word, for a local
                   6099: Locals have no interpretation semantics. If you try to perform the
                   6100: interpretation semantics, you will get a @code{-14 throw} somewhere
                   6101: (Interpreting a compile-only word). If you perform the compilation
                   6102: semantics, the locals access will be compiled (irrespective of state).
                   6103: 
                   6104: @item @var{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
                   6105: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
                   6106: @cindex @code{TO} on non-@code{VALUE}s and non-locals
                   6107: @cindex Invalid name argument, @code{TO}
                   6108: @code{-32 throw} (Invalid name argument)
                   6109: 
                   6110: @end table
                   6111: 
                   6112: 
                   6113: @c =====================================================================
                   6114: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
                   6115: @section The optional Memory-Allocation word set
                   6116: @c =====================================================================
                   6117: @cindex system documentation, memory-allocation words
                   6118: @cindex memory-allocation words, system documentation
                   6119: 
                   6120: @menu
                   6121: * memory-idef::                 Implementation Defined Options                 
                   6122: @end menu
                   6123: 
                   6124: 
                   6125: @c ---------------------------------------------------------------------
                   6126: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
                   6127: @subsection Implementation Defined Options
                   6128: @c ---------------------------------------------------------------------
                   6129: @cindex implementation-defined options, memory-allocation words
                   6130: @cindex memory-allocation words, implementation-defined options
                   6131: 
                   6132: @table @i
                   6133: @item values and meaning of @var{ior}:
                   6134: @cindex  @var{ior} values and meaning
                   6135: The @var{ior}s returned by the file and memory allocation words are
                   6136: intended as throw codes. They typically are in the range
                   6137: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
                   6138: @var{ior}s is -512@minus{}@var{errno}.
                   6139: 
                   6140: @end table
                   6141: 
                   6142: @c =====================================================================
                   6143: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
                   6144: @section The optional Programming-Tools word set
                   6145: @c =====================================================================
                   6146: @cindex system documentation, programming-tools words
                   6147: @cindex programming-tools words, system documentation
                   6148: 
                   6149: @menu
                   6150: * programming-idef::            Implementation Defined Options            
                   6151: * programming-ambcond::         Ambiguous Conditions         
                   6152: @end menu
                   6153: 
                   6154: 
                   6155: @c ---------------------------------------------------------------------
                   6156: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
                   6157: @subsection Implementation Defined Options
                   6158: @c ---------------------------------------------------------------------
                   6159: @cindex implementation-defined options, programming-tools words
                   6160: @cindex programming-tools words, implementation-defined options
                   6161: 
                   6162: @table @i
                   6163: @item ending sequence for input following @code{;CODE} and @code{CODE}:
                   6164: @cindex @code{;CODE} ending sequence
                   6165: @cindex @code{CODE} ending sequence
                   6166: @code{END-CODE}
                   6167: 
                   6168: @item manner of processing input following @code{;CODE} and @code{CODE}:
                   6169: @cindex @code{;CODE}, processing input
                   6170: @cindex @code{CODE}, processing input
                   6171: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
                   6172: the input is processed by the text interpreter, (starting) in interpret
                   6173: state.
                   6174: 
                   6175: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
                   6176: @cindex @code{ASSEMBLER}, search order capability
                   6177: The ANS Forth search order word set.
                   6178: 
                   6179: @item source and format of display by @code{SEE}:
                   6180: @cindex @code{SEE}, source and format of output
                   6181: The source for @code{see} is the intermediate code used by the inner
                   6182: interpreter.  The current @code{see} tries to output Forth source code
                   6183: as well as possible.
                   6184: 
                   6185: @end table
                   6186: 
                   6187: @c ---------------------------------------------------------------------
                   6188: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
                   6189: @subsection Ambiguous conditions
                   6190: @c ---------------------------------------------------------------------
                   6191: @cindex programming-tools words, ambiguous conditions
                   6192: @cindex ambiguous conditions, programming-tools words
                   6193: 
                   6194: @table @i
                   6195: 
                   6196: @item deleting the compilation wordlist (@code{FORGET}):
                   6197: @cindex @code{FORGET}, deleting the compilation wordlist
                   6198: Not implemented (yet).
                   6199: 
                   6200: @item fewer than @var{u}+1 items on the control flow stack (@code{CS-PICK}, @code{CS-ROLL}):
                   6201: @cindex @code{CS-PICK}, fewer than @var{u}+1 items on the control flow stack
                   6202: @cindex @code{CS-ROLL}, fewer than @var{u}+1 items on the control flow stack
                   6203: @cindex control-flow stack underflow
                   6204: This typically results in an @code{abort"} with a descriptive error
                   6205: message (may change into a @code{-22 throw} (Control structure mismatch)
                   6206: in the future). You may also get a memory access error. If you are
                   6207: unlucky, this ambiguous condition is not caught.
                   6208: 
                   6209: @item @var{name} can't be found (@code{FORGET}):
                   6210: @cindex @code{FORGET}, @var{name} can't be found
                   6211: Not implemented (yet).
                   6212: 
                   6213: @item @var{name} not defined via @code{CREATE}:
                   6214: @cindex @code{;CODE}, @var{name} not defined via @code{CREATE}
                   6215: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
                   6216: the execution semantics of the last defined word no matter how it was
                   6217: defined.
                   6218: 
                   6219: @item @code{POSTPONE} applied to @code{[IF]}:
                   6220: @cindex @code{POSTPONE} applied to @code{[IF]}
                   6221: @cindex @code{[IF]} and @code{POSTPONE}
                   6222: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
                   6223: equivalent to @code{[IF]}.
                   6224: 
                   6225: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
                   6226: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
                   6227: Continue in the same state of conditional compilation in the next outer
                   6228: input source. Currently there is no warning to the user about this.
                   6229: 
                   6230: @item removing a needed definition (@code{FORGET}):
                   6231: @cindex @code{FORGET}, removing a needed definition
                   6232: Not implemented (yet).
                   6233: 
                   6234: @end table
                   6235: 
                   6236: 
                   6237: @c =====================================================================
                   6238: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
                   6239: @section The optional Search-Order word set
                   6240: @c =====================================================================
                   6241: @cindex system documentation, search-order words
                   6242: @cindex search-order words, system documentation
                   6243: 
                   6244: @menu
                   6245: * search-idef::                 Implementation Defined Options                 
                   6246: * search-ambcond::              Ambiguous Conditions              
                   6247: @end menu
                   6248: 
                   6249: 
                   6250: @c ---------------------------------------------------------------------
                   6251: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
                   6252: @subsection Implementation Defined Options
                   6253: @c ---------------------------------------------------------------------
                   6254: @cindex implementation-defined options, search-order words
                   6255: @cindex search-order words, implementation-defined options
                   6256: 
                   6257: @table @i
                   6258: @item maximum number of word lists in search order:
                   6259: @cindex maximum number of word lists in search order
                   6260: @cindex search order, maximum depth
                   6261: @code{s" wordlists" environment? drop .}. Currently 16.
                   6262: 
                   6263: @item minimum search order:
                   6264: @cindex minimum search order
                   6265: @cindex search order, minimum
                   6266: @code{root root}.
                   6267: 
                   6268: @end table
                   6269: 
                   6270: @c ---------------------------------------------------------------------
                   6271: @node search-ambcond,  , search-idef, The optional Search-Order word set
                   6272: @subsection Ambiguous conditions
                   6273: @c ---------------------------------------------------------------------
                   6274: @cindex search-order words, ambiguous conditions
                   6275: @cindex ambiguous conditions, search-order words
                   6276: 
                   6277: @table @i
                   6278: @item changing the compilation wordlist (during compilation):
                   6279: @cindex changing the compilation wordlist (during compilation)
                   6280: @cindex compilation wordlist, change before definition ends
                   6281: The word is entered into the wordlist that was the compilation wordlist
                   6282: at the start of the definition. Any changes to the name field (e.g.,
                   6283: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
                   6284: are applied to the latest defined word (as reported by @code{last} or
                   6285: @code{lastxt}), if possible, irrespective of the compilation wordlist.
                   6286: 
                   6287: @item search order empty (@code{previous}):
                   6288: @cindex @code{previous}, search order empty
                   6289: @cindex Vocstack empty, @code{previous}
                   6290: @code{abort" Vocstack empty"}.
                   6291: 
                   6292: @item too many word lists in search order (@code{also}):
                   6293: @cindex @code{also}, too many word lists in search order
                   6294: @cindex Vocstack full, @code{also}
                   6295: @code{abort" Vocstack full"}.
                   6296: 
                   6297: @end table
                   6298: 
                   6299: @c ***************************************************************
                   6300: @node Model, Integrating Gforth, ANS conformance, Top
                   6301: @chapter Model
                   6302: 
                   6303: This chapter has yet to be written. It will contain information, on
                   6304: which internal structures you can rely.
                   6305: 
                   6306: @c ***************************************************************
                   6307: @node Integrating Gforth, Emacs and Gforth, Model, Top
                   6308: @chapter Integrating Gforth into C programs
                   6309: 
                   6310: This is not yet implemented.
                   6311: 
                   6312: Several people like to use Forth as scripting language for applications
                   6313: that are otherwise written in C, C++, or some other language.
                   6314: 
                   6315: The Forth system ATLAST provides facilities for embedding it into
                   6316: applications; unfortunately it has several disadvantages: most
                   6317: importantly, it is not based on ANS Forth, and it is apparently dead
                   6318: (i.e., not developed further and not supported). The facilities
                   6319: provided by Gforth in this area are inspired by ATLASTs facilities, so
                   6320: making the switch should not be hard.
                   6321: 
                   6322: We also tried to design the interface such that it can easily be
                   6323: implemented by other Forth systems, so that we may one day arrive at a
                   6324: standardized interface. Such a standard interface would allow you to
                   6325: replace the Forth system without having to rewrite C code.
                   6326: 
                   6327: You embed the Gforth interpreter by linking with the library
                   6328: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
                   6329: global symbols in this library that belong to the interface, have the
                   6330: prefix @code{forth_}. (Global symbols that are used internally have the
                   6331: prefix @code{gforth_}).
                   6332: 
                   6333: You can include the declarations of Forth types and the functions and
                   6334: variables of the interface with @code{#include <forth.h>}.
                   6335: 
                   6336: Types.
                   6337: 
                   6338: Variables.
                   6339: 
                   6340: Data and FP Stack pointer. Area sizes.
                   6341: 
                   6342: functions.
                   6343: 
                   6344: forth_init(imagefile)
                   6345: forth_evaluate(string) exceptions?
                   6346: forth_goto(address) (or forth_execute(xt)?)
                   6347: forth_continue() (a corountining mechanism)
                   6348: 
                   6349: Adding primitives.
                   6350: 
                   6351: No checking.
                   6352: 
                   6353: Signals?
                   6354: 
                   6355: Accessing the Stacks
                   6356: 
                   6357: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
                   6358: @chapter Emacs and Gforth
                   6359: @cindex Emacs and Gforth
                   6360: 
                   6361: @cindex @file{gforth.el}
                   6362: @cindex @file{forth.el}
                   6363: @cindex Rydqvist, Goran
                   6364: @cindex comment editing commands
                   6365: @cindex @code{\}, editing with Emacs
                   6366: @cindex debug tracer editing commands
                   6367: @cindex @code{~~}, removal with Emacs
                   6368: @cindex Forth mode in Emacs
                   6369: Gforth comes with @file{gforth.el}, an improved version of
                   6370: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
                   6371: improvements are a better (but still not perfect) handling of
                   6372: indentation. I have also added comment paragraph filling (@kbd{M-q}),
                   6373: commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) regions and
                   6374: removing debugging tracers (@kbd{C-x ~}, @pxref{Debugging}). I left the
                   6375: stuff I do not use alone, even though some of it only makes sense for
                   6376: TILE. To get a description of these features, enter Forth mode and type
                   6377: @kbd{C-h m}.
                   6378: 
                   6379: @cindex source location of error or debugging output in Emacs
                   6380: @cindex error output, finding the source location in Emacs
                   6381: @cindex debugging output, finding the source location in Emacs
                   6382: In addition, Gforth supports Emacs quite well: The source code locations
                   6383: given in error messages, debugging output (from @code{~~}) and failed
                   6384: assertion messages are in the right format for Emacs' compilation mode
                   6385: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
                   6386: Manual}) so the source location corresponding to an error or other
                   6387: message is only a few keystrokes away (@kbd{C-x `} for the next error,
                   6388: @kbd{C-c C-c} for the error under the cursor).
                   6389: 
                   6390: @cindex @file{TAGS} file
                   6391: @cindex @file{etags.fs}
                   6392: @cindex viewing the source of a word in Emacs
                   6393: Also, if you @code{include} @file{etags.fs}, a new @file{TAGS} file
                   6394: (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) will be produced that
                   6395: contains the definitions of all words defined afterwards. You can then
                   6396: find the source for a word using @kbd{M-.}. Note that emacs can use
                   6397: several tags files at the same time (e.g., one for the Gforth sources
                   6398: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
                   6399: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
                   6400: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
                   6401: @file{/usr/local/share/gforth/0.2.0/TAGS}).
                   6402: 
                   6403: @cindex @file{.emacs}
                   6404: To get all these benefits, add the following lines to your @file{.emacs}
                   6405: file:
                   6406: 
                   6407: @example
                   6408: (autoload 'forth-mode "gforth.el")
                   6409: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
                   6410: @end example
                   6411: 
                   6412: @node Image Files, Engine, Emacs and Gforth, Top
                   6413: @chapter Image Files
                   6414: @cindex image files
                   6415: @cindex @code{.fi} files
                   6416: @cindex precompiled Forth code
                   6417: @cindex dictionary in persistent form
                   6418: @cindex persistent form of dictionary
                   6419: 
                   6420: An image file is a file containing an image of the Forth dictionary,
                   6421: i.e., compiled Forth code and data residing in the dictionary.  By
                   6422: convention, we use the extension @code{.fi} for image files.
                   6423: 
                   6424: @menu
1.18      anton    6425: * Image Licensing Issues::      Distribution terms for images.
                   6426: * Image File Background::       Why have image files?
                   6427: * Non-Relocatable Image Files::  don't always work.
                   6428: * Data-Relocatable Image Files::  are better.
1.1       anton    6429: * Fully Relocatable Image Files::  better yet.
1.18      anton    6430: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
                   6431: * Running Image Files::         @code{gforth -i @var{file}} or @var{file}.
                   6432: * Modifying the Startup Sequence::  and turnkey applications.
1.1       anton    6433: @end menu
                   6434: 
1.18      anton    6435: @node Image Licensing Issues, Image File Background, Image Files, Image Files
                   6436: @section Image Licensing Issues
                   6437: @cindex license for images
                   6438: @cindex image license
                   6439: 
                   6440: An image created with @code{gforthmi} (@pxref{gforthmi}) or
                   6441: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
                   6442: original image; i.e., according to copyright law it is a derived work of
                   6443: the original image.
                   6444: 
                   6445: Since Gforth is distributed under the GNU GPL, the newly created image
                   6446: falls under the GNU GPL, too. In particular, this means that if you
                   6447: distribute the image, you have to make all of the sources for the image
                   6448: available, including those you wrote.  For details see @ref{License, ,
                   6449: GNU General Public License (Section 3)}.
                   6450: 
                   6451: If you create an image with @code{cross} (@pxref{cross.fs}), the image
                   6452: contains only code compiled from the sources you gave it; if none of
                   6453: these sources is under the GPL, the terms discussed above do not apply
                   6454: to the image. However, if your image needs an engine (a gforth binary)
                   6455: that is under the GPL, you should make sure that you distribute both in
                   6456: a way that is at most a @emph{mere aggregation}, if you don't want the
                   6457: terms of the GPL to apply to the image.
                   6458: 
                   6459: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1       anton    6460: @section Image File Background
                   6461: @cindex image file background
                   6462: 
                   6463: Our Forth system consists not only of primitives, but also of
                   6464: definitions written in Forth. Since the Forth compiler itself belongs to
                   6465: those definitions, it is not possible to start the system with the
                   6466: primitives and the Forth source alone. Therefore we provide the Forth
                   6467: code as an image file in nearly executable form. At the start of the
                   6468: system a C routine loads the image file into memory, optionally
                   6469: relocates the addresses, then sets up the memory (stacks etc.) according
                   6470: to information in the image file, and starts executing Forth code.
                   6471: 
                   6472: The image file variants represent different compromises between the
                   6473: goals of making it easy to generate image files and making them
                   6474: portable.
                   6475: 
                   6476: @cindex relocation at run-time
                   6477: Win32Forth 3.4 and Mitch Bradleys @code{cforth} use relocation at
                   6478: run-time. This avoids many of the complications discussed below (image
                   6479: files are data relocatable without further ado), but costs performance
                   6480: (one addition per memory access).
                   6481: 
                   6482: @cindex relocation at load-time
                   6483: By contrast, our loader performs relocation at image load time. The
                   6484: loader also has to replace tokens standing for primitive calls with the
                   6485: appropriate code-field addresses (or code addresses in the case of
                   6486: direct threading).
                   6487: 
                   6488: There are three kinds of image files, with different degrees of
                   6489: relocatability: non-relocatable, data-relocatable, and fully relocatable
                   6490: image files.
                   6491: 
                   6492: @cindex image file loader
                   6493: @cindex relocating loader
                   6494: @cindex loader for image files
                   6495: These image file variants have several restrictions in common; they are
                   6496: caused by the design of the image file loader:
                   6497: 
                   6498: @itemize @bullet
                   6499: @item
                   6500: There is only one segment; in particular, this means, that an image file
                   6501: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
                   6502: them). And the contents of the stacks are not represented, either.
                   6503: 
                   6504: @item
                   6505: The only kinds of relocation supported are: adding the same offset to
                   6506: all cells that represent data addresses; and replacing special tokens
                   6507: with code addresses or with pieces of machine code.
                   6508: 
                   6509: If any complex computations involving addresses are performed, the
                   6510: results cannot be represented in the image file. Several applications that
                   6511: use such computations come to mind:
                   6512: @itemize @minus
                   6513: @item
                   6514: Hashing addresses (or data structures which contain addresses) for table
                   6515: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
                   6516: purpose, you will have no problem, because the hash tables are
                   6517: recomputed automatically when the system is started. If you use your own
                   6518: hash tables, you will have to do something similar.
                   6519: 
                   6520: @item
                   6521: There's a cute implementation of doubly-linked lists that uses
                   6522: @code{XOR}ed addresses. You could represent such lists as singly-linked
                   6523: in the image file, and restore the doubly-linked representation on
                   6524: startup.@footnote{In my opinion, though, you should think thrice before
                   6525: using a doubly-linked list (whatever implementation).}
                   6526: 
                   6527: @item
                   6528: The code addresses of run-time routines like @code{docol:} cannot be
                   6529: represented in the image file (because their tokens would be replaced by
                   6530: machine code in direct threaded implementations). As a workaround,
                   6531: compute these addresses at run-time with @code{>code-address} from the
                   6532: executions tokens of appropriate words (see the definitions of
                   6533: @code{docol:} and friends in @file{kernel.fs}).
                   6534: 
                   6535: @item
                   6536: On many architectures addresses are represented in machine code in some
                   6537: shifted or mangled form. You cannot put @code{CODE} words that contain
                   6538: absolute addresses in this form in a relocatable image file. Workarounds
                   6539: are representing the address in some relative form (e.g., relative to
                   6540: the CFA, which is present in some register), or loading the address from
                   6541: a place where it is stored in a non-mangled form.
                   6542: @end itemize
                   6543: @end itemize
                   6544: 
                   6545: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
                   6546: @section Non-Relocatable Image Files
                   6547: @cindex non-relocatable image files
                   6548: @cindex image files, non-relocatable
                   6549: 
                   6550: These files are simple memory dumps of the dictionary. They are specific
                   6551: to the executable (i.e., @file{gforth} file) they were created
                   6552: with. What's worse, they are specific to the place on which the
                   6553: dictionary resided when the image was created. Now, there is no
                   6554: guarantee that the dictionary will reside at the same place the next
                   6555: time you start Gforth, so there's no guarantee that a non-relocatable
                   6556: image will work the next time (Gforth will complain instead of crashing,
                   6557: though).
                   6558: 
                   6559: You can create a non-relocatable image file with
                   6560: 
                   6561: doc-savesystem
                   6562: 
                   6563: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
                   6564: @section Data-Relocatable Image Files
                   6565: @cindex data-relocatable image files
                   6566: @cindex image files, data-relocatable
                   6567: 
                   6568: These files contain relocatable data addresses, but fixed code addresses
                   6569: (instead of tokens). They are specific to the executable (i.e.,
                   6570: @file{gforth} file) they were created with. For direct threading on some
                   6571: architectures (e.g., the i386), data-relocatable images do not work. You
                   6572: get a data-relocatable image, if you use @file{gforthmi} with a
                   6573: Gforth binary that is not doubly indirect threaded (@pxref{Fully
                   6574: Relocatable Image Files}).
                   6575: 
                   6576: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
                   6577: @section Fully Relocatable Image Files
                   6578: @cindex fully relocatable image files
                   6579: @cindex image files, fully relocatable
                   6580: 
                   6581: @cindex @file{kern*.fi}, relocatability
                   6582: @cindex @file{gforth.fi}, relocatability
                   6583: These image files have relocatable data addresses, and tokens for code
                   6584: addresses. They can be used with different binaries (e.g., with and
                   6585: without debugging) on the same machine, and even across machines with
                   6586: the same data formats (byte order, cell size, floating point
                   6587: format). However, they are usually specific to the version of Gforth
                   6588: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
                   6589: are fully relocatable.
                   6590: 
                   6591: There are two ways to create a fully relocatable image file:
                   6592: 
                   6593: @menu
                   6594: * gforthmi::            The normal way
                   6595: * cross.fs::                    The hard way
                   6596: @end menu
                   6597: 
                   6598: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
                   6599: @subsection @file{gforthmi}
                   6600: @cindex @file{comp-i.fs}
                   6601: @cindex @file{gforthmi}
                   6602: 
                   6603: You will usually use @file{gforthmi}. If you want to create an
                   6604: image @var{file} that contains everything you would load by invoking
                   6605: Gforth with @code{gforth @var{options}}, you simply say
                   6606: @example
                   6607: gforthmi @var{file} @var{options}
                   6608: @end example
                   6609: 
                   6610: E.g., if you want to create an image @file{asm.fi} that has the file
                   6611: @file{asm.fs} loaded in addition to the usual stuff, you could do it
                   6612: like this:
                   6613: 
                   6614: @example
                   6615: gforthmi asm.fi asm.fs
                   6616: @end example
                   6617: 
                   6618: @file{gforthmi} works like this: It produces two non-relocatable
                   6619: images for different addresses and then compares them. Its output
                   6620: reflects this: first you see the output (if any) of the two Gforth
                   6621: invocations that produce the nonrelocatable image files, then you see
                   6622: the output of the comparing program: It displays the offset used for
                   6623: data addresses and the offset used for code addresses;
                   6624: moreover, for each cell that cannot be represented correctly in the
                   6625: image files, it displays a line like the following one:
                   6626: 
                   6627: @example
                   6628:      78DC         BFFFFA50         BFFFFA40
                   6629: @end example
                   6630: 
                   6631: This means that at offset $78dc from @code{forthstart}, one input image
                   6632: contains $bffffa50, and the other contains $bffffa40. Since these cells
                   6633: cannot be represented correctly in the output image, you should examine
                   6634: these places in the dictionary and verify that these cells are dead
                   6635: (i.e., not read before they are written).
                   6636: 
                   6637: @cindex @code{savesystem} during @file{gforthmi}
                   6638: @cindex @code{bye} during @file{gforthmi}
                   6639: @cindex doubly indirect threaded code
                   6640: @cindex environment variable @code{GFORTHD}
                   6641: @cindex @code{GFORTHD} environment variable
                   6642: @cindex @code{gforth-ditc}
                   6643: There are a few wrinkles: After processing the passed @var{options}, the
                   6644: words @code{savesystem} and @code{bye} must be visible. A special doubly
                   6645: indirect threaded version of the @file{gforth} executable is used for
                   6646: creating the nonrelocatable images; you can pass the exact filename of
                   6647: this executable through the environment variable @code{GFORTHD}
                   6648: (default: @file{gforth-ditc}); if you pass a version that is not doubly
                   6649: indirect threaded, you will not get a fully relocatable image, but a
                   6650: data-relocatable image (because there is no code address offset).
                   6651: 
                   6652: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
                   6653: @subsection @file{cross.fs}
                   6654: @cindex @file{cross.fs}
                   6655: @cindex cross-compiler
                   6656: @cindex metacompiler
                   6657: 
                   6658: You can also use @code{cross}, a batch compiler that accepts a Forth-like
                   6659: programming language. This @code{cross} language has to be documented
                   6660: yet.
                   6661: 
                   6662: @cindex target compiler
                   6663: @code{cross} also allows you to create image files for machines with
                   6664: different data sizes and data formats than the one used for generating
                   6665: the image file. You can also use it to create an application image that
                   6666: does not contain a Forth compiler. These features are bought with
                   6667: restrictions and inconveniences in programming. E.g., addresses have to
                   6668: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
                   6669: order to make the code relocatable.
                   6670: 
                   6671: 
                   6672: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
                   6673: @section Stack and Dictionary Sizes
                   6674: @cindex image file, stack and dictionary sizes
                   6675: @cindex dictionary size default
                   6676: @cindex stack size default
                   6677: 
                   6678: If you invoke Gforth with a command line flag for the size
                   6679: (@pxref{Invoking Gforth}), the size you specify is stored in the
                   6680: dictionary. If you save the dictionary with @code{savesystem} or create
                   6681: an image with @file{gforthmi}, this size will become the default
                   6682: for the resulting image file. E.g., the following will create a
                   6683: fully relocatable version of gforth.fi with a 1MB dictionary:
                   6684: 
                   6685: @example
                   6686: gforthmi gforth.fi -m 1M
                   6687: @end example
                   6688: 
                   6689: In other words, if you want to set the default size for the dictionary
                   6690: and the stacks of an image, just invoke @file{gforthmi} with the
                   6691: appropriate options when creating the image.
                   6692: 
                   6693: @cindex stack size, cache-friendly
                   6694: Note: For cache-friendly behaviour (i.e., good performance), you should
                   6695: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
                   6696: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
                   6697: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
                   6698: 
                   6699: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
                   6700: @section Running Image Files
                   6701: @cindex running image files
                   6702: @cindex invoking image files
                   6703: @cindex image file invocation
                   6704: 
                   6705: @cindex -i, invoke image file
                   6706: @cindex --image file, invoke image file
                   6707: You can invoke Gforth with an image file @var{image} instead of the
                   6708: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
                   6709: @example
                   6710: gforth -i @var{image}
                   6711: @end example
                   6712: 
                   6713: @cindex executable image file
                   6714: @cindex image files, executable
                   6715: If your operating system supports starting scripts with a line of the
                   6716: form @code{#! ...}, you just have to type the image file name to start
                   6717: Gforth with this image file (note that the file extension @code{.fi} is
                   6718: just a convention). I.e., to run Gforth with the image file @var{image},
                   6719: you can just type @var{image} instead of @code{gforth -i @var{image}}.
                   6720: 
                   6721: doc-#!
                   6722: 
                   6723: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
                   6724: @section Modifying the Startup Sequence
                   6725: @cindex startup sequence for image file
                   6726: @cindex image file initialization sequence
                   6727: @cindex initialization sequence of image file
                   6728: 
                   6729: You can add your own initialization to the startup sequence through the
                   6730: deferred word
                   6731: 
                   6732: doc-'cold
                   6733: 
                   6734: @code{'cold} is invoked just before the image-specific command line
                   6735: processing (by default, loading files and evaluating (@code{-e}) strings)
                   6736: starts.
                   6737: 
                   6738: A sequence for adding your initialization usually looks like this:
                   6739: 
                   6740: @example
                   6741: :noname
                   6742:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
                   6743:     ... \ your stuff
                   6744: ; IS 'cold
                   6745: @end example
                   6746: 
                   6747: @cindex turnkey image files
                   6748: @cindex image files, turnkey applications
                   6749: You can make a turnkey image by letting @code{'cold} execute a word
                   6750: (your turnkey application) that never returns; instead, it exits Gforth
                   6751: via @code{bye} or @code{throw}.
                   6752: 
                   6753: @cindex command-line arguments, access
                   6754: @cindex arguments on the command line, access
                   6755: You can access the (image-specific) command-line arguments through the
                   6756: variables @code{argc} and @code{argv}. @code{arg} provides conventient
                   6757: access to @code{argv}.
                   6758: 
                   6759: doc-argc
                   6760: doc-argv
                   6761: doc-arg
                   6762: 
                   6763: If @code{'cold} exits normally, Gforth processes the command-line
                   6764: arguments as files to be loaded and strings to be evaluated.  Therefore,
                   6765: @code{'cold} should remove the arguments it has used in this case.
                   6766: 
                   6767: @c ******************************************************************
1.13      pazsan   6768: @node Engine, Binding to System Library, Image Files, Top
1.1       anton    6769: @chapter Engine
                   6770: @cindex engine
                   6771: @cindex virtual machine
                   6772: 
                   6773: Reading this section is not necessary for programming with Gforth. It
                   6774: may be helpful for finding your way in the Gforth sources.
                   6775: 
                   6776: The ideas in this section have also been published in the papers
                   6777: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
                   6778: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
                   6779: Ertl, presented at EuroForth '93; the latter is available at
                   6780: @*@url{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
                   6781: 
                   6782: @menu
                   6783: * Portability::                 
                   6784: * Threading::                   
                   6785: * Primitives::                  
                   6786: * Performance::                 
                   6787: @end menu
                   6788: 
                   6789: @node Portability, Threading, Engine, Engine
                   6790: @section Portability
                   6791: @cindex engine portability
                   6792: 
                   6793: One of the main goals of the effort is availability across a wide range
                   6794: of personal machines. fig-Forth, and, to a lesser extent, F83, achieved
                   6795: this goal by manually coding the engine in assembly language for several
                   6796: then-popular processors. This approach is very labor-intensive and the
                   6797: results are short-lived due to progress in computer architecture.
                   6798: 
                   6799: @cindex C, using C for the engine
                   6800: Others have avoided this problem by coding in C, e.g., Mitch Bradley
                   6801: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
                   6802: particularly popular for UNIX-based Forths due to the large variety of
                   6803: architectures of UNIX machines. Unfortunately an implementation in C
                   6804: does not mix well with the goals of efficiency and with using
                   6805: traditional techniques: Indirect or direct threading cannot be expressed
                   6806: in C, and switch threading, the fastest technique available in C, is
                   6807: significantly slower. Another problem with C is that it is very
                   6808: cumbersome to express double integer arithmetic.
                   6809: 
                   6810: @cindex GNU C for the engine
                   6811: @cindex long long
                   6812: Fortunately, there is a portable language that does not have these
                   6813: limitations: GNU C, the version of C processed by the GNU C compiler
                   6814: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
                   6815: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
                   6816: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
                   6817: threading possible, its @code{long long} type (@pxref{Long Long, ,
                   6818: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
                   6819: double numbers@footnote{Unfortunately, long longs are not implemented
                   6820: properly on all machines (e.g., on alpha-osf1, long longs are only 64
                   6821: bits, the same size as longs (and pointers), but they should be twice as
1.4       anton    6822: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1       anton    6823: C Manual}). So, we had to implement doubles in C after all. Still, on
                   6824: most machines we can use long longs and achieve better performance than
                   6825: with the emulation package.}. GNU C is available for free on all
                   6826: important (and many unimportant) UNIX machines, VMS, 80386s running
                   6827: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
                   6828: on all these machines.
                   6829: 
                   6830: Writing in a portable language has the reputation of producing code that
                   6831: is slower than assembly. For our Forth engine we repeatedly looked at
                   6832: the code produced by the compiler and eliminated most compiler-induced
                   6833: inefficiencies by appropriate changes in the source code.
                   6834: 
                   6835: @cindex explicit register declarations
                   6836: @cindex --enable-force-reg, configuration flag
                   6837: @cindex -DFORCE_REG
                   6838: However, register allocation cannot be portably influenced by the
                   6839: programmer, leading to some inefficiencies on register-starved
                   6840: machines. We use explicit register declarations (@pxref{Explicit Reg
                   6841: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
                   6842: improve the speed on some machines. They are turned on by using the
                   6843: configuration flag @code{--enable-force-reg} (@code{gcc} switch
                   6844: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
                   6845: machine, but also on the compiler version: On some machines some
                   6846: compiler versions produce incorrect code when certain explicit register
                   6847: declarations are used. So by default @code{-DFORCE_REG} is not used.
                   6848: 
                   6849: @node Threading, Primitives, Portability, Engine
                   6850: @section Threading
                   6851: @cindex inner interpreter implementation
                   6852: @cindex threaded code implementation
                   6853: 
                   6854: @cindex labels as values
                   6855: GNU C's labels as values extension (available since @code{gcc-2.0},
                   6856: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
                   6857: makes it possible to take the address of @var{label} by writing
                   6858: @code{&&@var{label}}.  This address can then be used in a statement like
                   6859: @code{goto *@var{address}}. I.e., @code{goto *&&x} is the same as
                   6860: @code{goto x}.
                   6861: 
                   6862: @cindex NEXT, indirect threaded
                   6863: @cindex indirect threaded inner interpreter
                   6864: @cindex inner interpreter, indirect threaded
                   6865: With this feature an indirect threaded NEXT looks like:
                   6866: @example
                   6867: cfa = *ip++;
                   6868: ca = *cfa;
                   6869: goto *ca;
                   6870: @end example
                   6871: @cindex instruction pointer
                   6872: For those unfamiliar with the names: @code{ip} is the Forth instruction
                   6873: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
                   6874: execution token and points to the code field of the next word to be
                   6875: executed; The @code{ca} (code address) fetched from there points to some
                   6876: executable code, e.g., a primitive or the colon definition handler
                   6877: @code{docol}.
                   6878: 
                   6879: @cindex NEXT, direct threaded
                   6880: @cindex direct threaded inner interpreter
                   6881: @cindex inner interpreter, direct threaded
                   6882: Direct threading is even simpler:
                   6883: @example
                   6884: ca = *ip++;
                   6885: goto *ca;
                   6886: @end example
                   6887: 
                   6888: Of course we have packaged the whole thing neatly in macros called
                   6889: @code{NEXT} and @code{NEXT1} (the part of NEXT after fetching the cfa).
                   6890: 
                   6891: @menu
                   6892: * Scheduling::                  
                   6893: * Direct or Indirect Threaded?::  
                   6894: * DOES>::                       
                   6895: @end menu
                   6896: 
                   6897: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
                   6898: @subsection Scheduling
                   6899: @cindex inner interpreter optimization
                   6900: 
                   6901: There is a little complication: Pipelined and superscalar processors,
                   6902: i.e., RISC and some modern CISC machines can process independent
                   6903: instructions while waiting for the results of an instruction. The
                   6904: compiler usually reorders (schedules) the instructions in a way that
                   6905: achieves good usage of these delay slots. However, on our first tries
                   6906: the compiler did not do well on scheduling primitives. E.g., for
                   6907: @code{+} implemented as
                   6908: @example
                   6909: n=sp[0]+sp[1];
                   6910: sp++;
                   6911: sp[0]=n;
                   6912: NEXT;
                   6913: @end example
                   6914: the NEXT comes strictly after the other code, i.e., there is nearly no
                   6915: scheduling. After a little thought the problem becomes clear: The
                   6916: compiler cannot know that sp and ip point to different addresses (and
                   6917: the version of @code{gcc} we used would not know it even if it was
                   6918: possible), so it could not move the load of the cfa above the store to
                   6919: the TOS. Indeed the pointers could be the same, if code on or very near
                   6920: the top of stack were executed. In the interest of speed we chose to
                   6921: forbid this probably unused ``feature'' and helped the compiler in
                   6922: scheduling: NEXT is divided into the loading part (@code{NEXT_P1}) and
                   6923: the goto part (@code{NEXT_P2}). @code{+} now looks like:
                   6924: @example
                   6925: n=sp[0]+sp[1];
                   6926: sp++;
                   6927: NEXT_P1;
                   6928: sp[0]=n;
                   6929: NEXT_P2;
                   6930: @end example
                   6931: This can be scheduled optimally by the compiler.
                   6932: 
                   6933: This division can be turned off with the switch @code{-DCISC_NEXT}. This
                   6934: switch is on by default on machines that do not profit from scheduling
                   6935: (e.g., the 80386), in order to preserve registers.
                   6936: 
                   6937: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
                   6938: @subsection Direct or Indirect Threaded?
                   6939: @cindex threading, direct or indirect?
                   6940: 
                   6941: @cindex -DDIRECT_THREADED
                   6942: Both! After packaging the nasty details in macro definitions we
                   6943: realized that we could switch between direct and indirect threading by
                   6944: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
                   6945: defining a few machine-specific macros for the direct-threading case.
                   6946: On the Forth level we also offer access words that hide the
                   6947: differences between the threading methods (@pxref{Threading Words}).
                   6948: 
                   6949: Indirect threading is implemented completely machine-independently.
                   6950: Direct threading needs routines for creating jumps to the executable
                   6951: code (e.g. to docol or dodoes). These routines are inherently
                   6952: machine-dependent, but they do not amount to many source lines. I.e.,
                   6953: even porting direct threading to a new machine is a small effort.
                   6954: 
                   6955: @cindex --enable-indirect-threaded, configuration flag
                   6956: @cindex --enable-direct-threaded, configuration flag
                   6957: The default threading method is machine-dependent. You can enforce a
                   6958: specific threading method when building Gforth with the configuration
                   6959: flag @code{--enable-direct-threaded} or
                   6960: @code{--enable-indirect-threaded}. Note that direct threading is not
                   6961: supported on all machines.
                   6962: 
                   6963: @node DOES>,  , Direct or Indirect Threaded?, Threading
                   6964: @subsection DOES>
                   6965: @cindex @code{DOES>} implementation
                   6966: 
                   6967: @cindex dodoes routine
                   6968: @cindex DOES-code
                   6969: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
                   6970: the chunk of code executed by every word defined by a
                   6971: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
                   6972: the Forth code to be executed, i.e. the code after the
                   6973: @code{DOES>} (the DOES-code)? There are two solutions:
                   6974: 
                   6975: In fig-Forth the code field points directly to the dodoes and the
                   6976: DOES-code address is stored in the cell after the code address (i.e. at
                   6977: @code{@var{cfa} cell+}). It may seem that this solution is illegal in
                   6978: the Forth-79 and all later standards, because in fig-Forth this address
                   6979: lies in the body (which is illegal in these standards). However, by
                   6980: making the code field larger for all words this solution becomes legal
                   6981: again. We use this approach for the indirect threaded version and for
                   6982: direct threading on some machines. Leaving a cell unused in most words
                   6983: is a bit wasteful, but on the machines we are targeting this is hardly a
                   6984: problem. The other reason for having a code field size of two cells is
                   6985: to avoid having different image files for direct and indirect threaded
                   6986: systems (direct threaded systems require two-cell code fields on many
                   6987: machines).
                   6988: 
                   6989: @cindex DOES-handler
                   6990: The other approach is that the code field points or jumps to the cell
                   6991: after @code{DOES}. In this variant there is a jump to @code{dodoes} at
                   6992: this address (the DOES-handler). @code{dodoes} can then get the
                   6993: DOES-code address by computing the code address, i.e., the address of
                   6994: the jump to dodoes, and add the length of that jump field. A variant of
                   6995: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
                   6996: return address (which can be found in the return register on RISCs) is
                   6997: the DOES-code address. Since the two cells available in the code field
                   6998: are used up by the jump to the code address in direct threading on many
                   6999: architectures, we use this approach for direct threading on these
                   7000: architectures. We did not want to add another cell to the code field.
                   7001: 
                   7002: @node Primitives, Performance, Threading, Engine
                   7003: @section Primitives
                   7004: @cindex primitives, implementation
                   7005: @cindex virtual machine instructions, implementation
                   7006: 
                   7007: @menu
                   7008: * Automatic Generation::        
                   7009: * TOS Optimization::            
                   7010: * Produced code::               
                   7011: @end menu
                   7012: 
                   7013: @node Automatic Generation, TOS Optimization, Primitives, Primitives
                   7014: @subsection Automatic Generation
                   7015: @cindex primitives, automatic generation
                   7016: 
                   7017: @cindex @file{prims2x.fs}
                   7018: Since the primitives are implemented in a portable language, there is no
                   7019: longer any need to minimize the number of primitives. On the contrary,
                   7020: having many primitives has an advantage: speed. In order to reduce the
                   7021: number of errors in primitives and to make programming them easier, we
                   7022: provide a tool, the primitive generator (@file{prims2x.fs}), that
                   7023: automatically generates most (and sometimes all) of the C code for a
                   7024: primitive from the stack effect notation.  The source for a primitive
                   7025: has the following form:
                   7026: 
                   7027: @cindex primitive source format
                   7028: @format
                   7029: @var{Forth-name}       @var{stack-effect}      @var{category}  [@var{pronounc.}]
                   7030: [@code{""}@var{glossary entry}@code{""}]
                   7031: @var{C code}
                   7032: [@code{:}
                   7033: @var{Forth code}]
                   7034: @end format
                   7035: 
                   7036: The items in brackets are optional. The category and glossary fields
                   7037: are there for generating the documentation, the Forth code is there
                   7038: for manual implementations on machines without GNU C. E.g., the source
                   7039: for the primitive @code{+} is:
                   7040: @example
                   7041: +    n1 n2 -- n    core    plus
                   7042: n = n1+n2;
                   7043: @end example
                   7044: 
                   7045: This looks like a specification, but in fact @code{n = n1+n2} is C
                   7046: code. Our primitive generation tool extracts a lot of information from
                   7047: the stack effect notations@footnote{We use a one-stack notation, even
                   7048: though we have separate data and floating-point stacks; The separate
                   7049: notation can be generated easily from the unified notation.}: The number
                   7050: of items popped from and pushed on the stack, their type, and by what
                   7051: name they are referred to in the C code. It then generates a C code
                   7052: prelude and postlude for each primitive. The final C code for @code{+}
                   7053: looks like this:
                   7054: 
                   7055: @example
                   7056: I_plus:        /* + ( n1 n2 -- n ) */  /* label, stack effect */
                   7057: /*  */                          /* documentation */
                   7058: @{
                   7059: DEF_CA                          /* definition of variable ca (indirect threading) */
                   7060: Cell n1;                        /* definitions of variables */
                   7061: Cell n2;
                   7062: Cell n;
                   7063: n1 = (Cell) sp[1];              /* input */
                   7064: n2 = (Cell) TOS;
                   7065: sp += 1;                        /* stack adjustment */
                   7066: NAME("+")                       /* debugging output (with -DDEBUG) */
                   7067: @{
                   7068: n = n1+n2;                      /* C code taken from the source */
                   7069: @}
                   7070: NEXT_P1;                        /* NEXT part 1 */
                   7071: TOS = (Cell)n;                  /* output */
                   7072: NEXT_P2;                        /* NEXT part 2 */
                   7073: @}
                   7074: @end example
                   7075: 
                   7076: This looks long and inefficient, but the GNU C compiler optimizes quite
                   7077: well and produces optimal code for @code{+} on, e.g., the R3000 and the
                   7078: HP RISC machines: Defining the @code{n}s does not produce any code, and
                   7079: using them as intermediate storage also adds no cost.
                   7080: 
                   7081: There are also other optimizations, that are not illustrated by this
                   7082: example: Assignments between simple variables are usually for free (copy
                   7083: propagation). If one of the stack items is not used by the primitive
                   7084: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
                   7085: (dead code elimination). On the other hand, there are some things that
                   7086: the compiler does not do, therefore they are performed by
                   7087: @file{prims2x.fs}: The compiler does not optimize code away that stores
                   7088: a stack item to the place where it just came from (e.g., @code{over}).
                   7089: 
                   7090: While programming a primitive is usually easy, there are a few cases
                   7091: where the programmer has to take the actions of the generator into
                   7092: account, most notably @code{?dup}, but also words that do not (always)
                   7093: fall through to NEXT.
                   7094: 
                   7095: @node TOS Optimization, Produced code, Automatic Generation, Primitives
                   7096: @subsection TOS Optimization
                   7097: @cindex TOS optimization for primitives
                   7098: @cindex primitives, keeping the TOS in a register
                   7099: 
                   7100: An important optimization for stack machine emulators, e.g., Forth
                   7101: engines, is keeping  one or more of the top stack items in
                   7102: registers.  If a word has the stack effect @var{in1}...@var{inx} @code{--}
                   7103: @var{out1}...@var{outy}, keeping the top @var{n} items in registers
                   7104: @itemize @bullet
                   7105: @item
                   7106: is better than keeping @var{n-1} items, if @var{x>=n} and @var{y>=n},
                   7107: due to fewer loads from and stores to the stack.
                   7108: @item is slower than keeping @var{n-1} items, if @var{x<>y} and @var{x<n} and
                   7109: @var{y<n}, due to additional moves between registers.
                   7110: @end itemize
                   7111: 
                   7112: @cindex -DUSE_TOS
                   7113: @cindex -DUSE_NO_TOS
                   7114: In particular, keeping one item in a register is never a disadvantage,
                   7115: if there are enough registers. Keeping two items in registers is a
                   7116: disadvantage for frequent words like @code{?branch}, constants,
                   7117: variables, literals and @code{i}. Therefore our generator only produces
                   7118: code that keeps zero or one items in registers. The generated C code
                   7119: covers both cases; the selection between these alternatives is made at
                   7120: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
                   7121: code for @code{+} is just a simple variable name in the one-item case,
                   7122: otherwise it is a macro that expands into @code{sp[0]}. Note that the
                   7123: GNU C compiler tries to keep simple variables like @code{TOS} in
                   7124: registers, and it usually succeeds, if there are enough registers.
                   7125: 
                   7126: @cindex -DUSE_FTOS
                   7127: @cindex -DUSE_NO_FTOS
                   7128: The primitive generator performs the TOS optimization for the
                   7129: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
                   7130: operations the benefit of this optimization is even larger:
                   7131: floating-point operations take quite long on most processors, but can be
                   7132: performed in parallel with other operations as long as their results are
                   7133: not used. If the FP-TOS is kept in a register, this works. If
                   7134: it is kept on the stack, i.e., in memory, the store into memory has to
                   7135: wait for the result of the floating-point operation, lengthening the
                   7136: execution time of the primitive considerably.
                   7137: 
                   7138: The TOS optimization makes the automatic generation of primitives a
                   7139: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
                   7140: @code{TOS} is not sufficient. There are some special cases to
                   7141: consider:
                   7142: @itemize @bullet
                   7143: @item In the case of @code{dup ( w -- w w )} the generator must not
                   7144: eliminate the store to the original location of the item on the stack,
                   7145: if the TOS optimization is turned on.
                   7146: @item Primitives with stack effects of the form @code{--}
                   7147: @var{out1}...@var{outy} must store the TOS to the stack at the start.
                   7148: Likewise, primitives with the stack effect @var{in1}...@var{inx} @code{--}
                   7149: must load the TOS from the stack at the end. But for the null stack
                   7150: effect @code{--} no stores or loads should be generated.
                   7151: @end itemize
                   7152: 
                   7153: @node Produced code,  , TOS Optimization, Primitives
                   7154: @subsection Produced code
                   7155: @cindex primitives, assembly code listing
                   7156: 
                   7157: @cindex @file{engine.s}
                   7158: To see what assembly code is produced for the primitives on your machine
                   7159: with your compiler and your flag settings, type @code{make engine.s} and
                   7160: look at the resulting file @file{engine.s}.
                   7161: 
                   7162: @node  Performance,  , Primitives, Engine
                   7163: @section Performance
                   7164: @cindex performance of some Forth interpreters
                   7165: @cindex engine performance
                   7166: @cindex benchmarking Forth systems
                   7167: @cindex Gforth performance
                   7168: 
                   7169: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
                   7170: impossible to write a significantly faster engine.
                   7171: 
                   7172: On register-starved machines like the 386 architecture processors
                   7173: improvements are possible, because @code{gcc} does not utilize the
                   7174: registers as well as a human, even with explicit register declarations;
                   7175: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
                   7176: and hand-tuned it for the 486; this system is 1.19 times faster on the
                   7177: Sieve benchmark on a 486DX2/66 than Gforth compiled with
                   7178: @code{gcc-2.6.3} with @code{-DFORCE_REG}.
                   7179: 
                   7180: @cindex Win32Forth performance
                   7181: @cindex NT Forth performance
                   7182: @cindex eforth performance
                   7183: @cindex ThisForth performance
                   7184: @cindex PFE performance
                   7185: @cindex TILE performance
                   7186: However, this potential advantage of assembly language implementations
                   7187: is not necessarily realized in complete Forth systems: We compared
                   7188: Gforth (direct threaded, compiled with @code{gcc-2.6.3} and
                   7189: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
                   7190: 1994) and Eforth (with and without peephole (aka pinhole) optimization
                   7191: of the threaded code); all these systems were written in assembly
                   7192: language. We also compared Gforth with three systems written in C:
                   7193: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
                   7194: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
                   7195: -DUNROLL_NEXT}), ThisForth Beta (compiled with gcc-2.6.3 -O3
                   7196: -fomit-frame-pointer; ThisForth employs peephole optimization of the
                   7197: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
                   7198: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
                   7199: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
                   7200: 486DX2/66 with similar memory performance under Windows NT. Marcel
                   7201: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
                   7202: added the peephole optimizer, ran the benchmarks and reported the
                   7203: results.
                   7204:  
                   7205: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
                   7206: matrix multiplication come from the Stanford integer benchmarks and have
                   7207: been translated into Forth by Martin Fraeman; we used the versions
                   7208: included in the TILE Forth package, but with bigger data set sizes; and
                   7209: a recursive Fibonacci number computation for benchmarking calling
                   7210: performance. The following table shows the time taken for the benchmarks
                   7211: scaled by the time taken by Gforth (in other words, it shows the speedup
                   7212: factor that Gforth achieved over the other systems).
                   7213: 
                   7214: @example
                   7215: relative      Win32-    NT       eforth       This-
                   7216:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
                   7217: sieve     1.00  1.39  1.14   1.39  0.85  1.58  3.18  8.58
                   7218: bubble    1.00  1.31  1.41   1.48  0.88  1.50        3.88
                   7219: matmul    1.00  1.47  1.35   1.46  0.74  1.58        4.09
                   7220: fib       1.00  1.52  1.34   1.22  0.86  1.74  2.99  4.30
                   7221: @end example
                   7222: 
                   7223: You may find the good performance of Gforth compared with the systems
                   7224: written in assembly language quite surprising. One important reason for
                   7225: the disappointing performance of these systems is probably that they are
                   7226: not written optimally for the 486 (e.g., they use the @code{lods}
                   7227: instruction). In addition, Win32Forth uses a comfortable, but costly
                   7228: method for relocating the Forth image: like @code{cforth}, it computes
                   7229: the actual addresses at run time, resulting in two address computations
                   7230: per NEXT (@pxref{Image File Background}).
                   7231: 
                   7232: Only Eforth with the peephole optimizer performs comparable to
                   7233: Gforth. The speedups achieved with peephole optimization of threaded
                   7234: code are quite remarkable. Adding a peephole optimizer to Gforth should
                   7235: cause similar speedups.
                   7236: 
                   7237: The speedup of Gforth over PFE, ThisForth and TILE can be easily
                   7238: explained with the self-imposed restriction of the latter systems to
                   7239: standard C, which makes efficient threading impossible (however, the
1.4       anton    7240: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1       anton    7241: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
                   7242: Moreover, current C compilers have a hard time optimizing other aspects
                   7243: of the ThisForth and the TILE source.
                   7244: 
                   7245: Note that the performance of Gforth on 386 architecture processors
                   7246: varies widely with the version of @code{gcc} used. E.g., @code{gcc-2.5.8}
                   7247: failed to allocate any of the virtual machine registers into real
                   7248: machine registers by itself and would not work correctly with explicit
                   7249: register declarations, giving a 1.3 times slower engine (on a 486DX2/66
                   7250: running the Sieve) than the one measured above.
                   7251: 
                   7252: Note also that there have been several releases of Win32Forth since the
                   7253: release presented here, so the results presented here may have little
                   7254: predictive value for the performance of Win32Forth today.
                   7255: 
                   7256: @cindex @file{Benchres}
                   7257: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
                   7258: Maierhofer (presented at EuroForth '95), an indirect threaded version of
                   7259: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
                   7260: version of Gforth is 2%@minus{}8% slower on a 486 than the direct
                   7261: threaded version used here. The paper available at
                   7262: @*@url{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
                   7263: it also contains numbers for some native code systems. You can find a
                   7264: newer version of these measurements at
                   7265: @url{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
                   7266: find numbers for Gforth on various machines in @file{Benchres}.
                   7267: 
1.13      pazsan   7268: @node Binding to System Library, Cross Compiler, Engine, Top
1.14      pazsan   7269: @chapter Binding to System Library
1.13      pazsan   7270: 
                   7271: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14      pazsan   7272: @chapter Cross Compiler
1.13      pazsan   7273: 
                   7274: Cross Compiler
                   7275: 
                   7276: @menu
                   7277: * Using the Cross Compiler::
                   7278: * How the Cross Compiler Works::
                   7279: @end menu
                   7280: 
                   7281: @node Using the Cross Compiler, , How the Cross Compiler Works, Cross Compiler
1.14      pazsan   7282: @section Using the Cross Compiler
1.13      pazsan   7283: 
                   7284: @node How the Cross Compiler Works, Using the Cross Compiler, , Cross Compiler
1.14      pazsan   7285: @section How the Cross Compiler Works
1.13      pazsan   7286: 
                   7287: @node Bugs, Origin, Cross Compiler, Top
1.1       anton    7288: @chapter Bugs
                   7289: @cindex bug reporting
                   7290: 
                   7291: Known bugs are described in the file BUGS in the Gforth distribution.
                   7292: 
                   7293: If you find a bug, please send a bug report to
                   7294: @email{bug-gforth@@gnu.ai.mit.edu}. A bug report should
                   7295: describe the Gforth version used (it is announced at the start of an
                   7296: interactive Gforth session), the machine and operating system (on Unix
                   7297: systems you can use @code{uname -a} to produce this information), the
                   7298: installation options (send the @file{config.status} file), and a
                   7299: complete list of changes you (or your installer) have made to the Gforth
                   7300: sources (if any); it should contain a program (or a sequence of keyboard
                   7301: commands) that reproduces the bug and a description of what you think
                   7302: constitutes the buggy behaviour.
                   7303: 
                   7304: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
                   7305: to Report Bugs, gcc.info, GNU C Manual}.
                   7306: 
                   7307: 
                   7308: @node Origin, Word Index, Bugs, Top
                   7309: @chapter Authors and Ancestors of Gforth
                   7310: 
                   7311: @section Authors and Contributors
                   7312: @cindex authors of Gforth
                   7313: @cindex contributors to Gforth
                   7314: 
                   7315: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
                   7316: Ertl. The third major author was Jens Wilke.  Lennart Benschop (who was
                   7317: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
                   7318: with their continuous feedback. Lennart Benshop contributed
                   7319: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
                   7320: support for calling C libraries. Helpful comments also came from Paul
                   7321: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.12      anton    7322: Wavrik, Barrie Stott, Marc de Groot, and Jorge Acerada. Since the
                   7323: release of Gforth-0.2.1 there were also helpful comments from many
                   7324: others; thank you all, sorry for not listing you here (but digging
                   7325: through my mailbox to extract your names is on my to-do list).
1.1       anton    7326: 
                   7327: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
                   7328: and autoconf, among others), and to the creators of the Internet: Gforth
                   7329: was developed across the Internet, and its authors have not met
                   7330: physically yet.
                   7331: 
                   7332: @section Pedigree
                   7333: @cindex Pedigree of Gforth
                   7334: 
                   7335: Gforth descends from BigForth (1993) and fig-Forth. Gforth and PFE (by
                   7336: Dirk Zoller) will cross-fertilize each other. Of course, a significant
                   7337: part of the design of Gforth was prescribed by ANS Forth.
                   7338: 
                   7339: Bernd Paysan wrote BigForth, a descendent from TurboForth, an unreleased
                   7340: 32 bit native code version of VolksForth for the Atari ST, written
                   7341: mostly by Dietrich Weineck.
                   7342: 
                   7343: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
                   7344: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
                   7345: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
                   7346: 
                   7347: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
                   7348: Forth-83 standard. !! Pedigree? When?
                   7349: 
                   7350: A team led by Bill Ragsdale implemented fig-Forth on many processors in
                   7351: 1979. Robert Selzer and Bill Ragsdale developed the original
                   7352: implementation of fig-Forth for the 6502 based on microForth.
                   7353: 
                   7354: The principal architect of microForth was Dean Sanderson. microForth was
                   7355: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
                   7356: the 1802, and subsequently implemented on the 8080, the 6800 and the
                   7357: Z80.
                   7358: 
                   7359: All earlier Forth systems were custom-made, usually by Charles Moore,
                   7360: who discovered (as he puts it) Forth during the late 60s. The first full
                   7361: Forth existed in 1971.
                   7362: 
                   7363: A part of the information in this section comes from @cite{The Evolution
                   7364: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
                   7365: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
                   7366: Notices 28(3), 1993.  You can find more historical and genealogical
                   7367: information about Forth there.
                   7368: 
                   7369: @node Word Index, Concept Index, Origin, Top
                   7370: @unnumbered Word Index
                   7371: 
                   7372: This index is as incomplete as the manual. Each word is listed with
                   7373: stack effect and wordset.
                   7374: 
                   7375: @printindex fn
                   7376: 
                   7377: @node Concept Index,  , Word Index, Top
                   7378: @unnumbered Concept and Word Index
                   7379: 
                   7380: This index is as incomplete as the manual. Not all entries listed are
                   7381: present verbatim in the text. Only the names are listed for the words
                   7382: here.
                   7383: 
                   7384: @printindex cp
                   7385: 
                   7386: @contents
                   7387: @bye
                   7388: 

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