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

1.1       anton       1: \input texinfo   @c -*-texinfo-*-
                      2: @comment The source is gforth.ds, from which gforth.texi is generated
1.28      crook       3: 
1.21      crook       4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
1.28      crook       5: @comment 1. x-ref all ambiguous or implementation-defined features?
                      6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
                      7: @comment 3. words in miscellaneous section need a home.
                      8: @comment 4. search for TODO for other minor and major works required.
                      9: @comment 5. [rats] change all @var to @i in Forth source so that info
                     10: @comment    file looks decent.
1.29    ! crook      11: @comment .. would be useful to have a word that identified all deferred words
        !            12: @comment should semantics stuff in intro be moved to another section
        !            13: 
1.28      crook      14: 
1.1       anton      15: @comment %**start of header (This is for running Texinfo on a region.)
                     16: @setfilename gforth.info
                     17: @settitle Gforth Manual
                     18: @dircategory GNU programming tools
                     19: @direntry
                     20: * Gforth: (gforth).             A fast interpreter for the Forth language.
                     21: @end direntry
                     22: @comment @setchapternewpage odd
1.29    ! crook      23: @comment TODO this gets left in by HTML converter
1.12      anton      24: @macro progstyle {}
                     25: Programming style note:
1.3       anton      26: @end macro
1.1       anton      27: @comment %**end of header (This is for running Texinfo on a region.)
                     28: 
1.29    ! crook      29: 
        !            30: @comment ----------------------------------------------------------
        !            31: @comment macros for beautifying glossary entries
        !            32: @comment if these are used, need to strip them out for HTML converter
        !            33: @comment else they get repeated verbatim in HTML output.
        !            34: @comment .. not working yet.
        !            35: 
        !            36: @macro GLOSS-START {}
        !            37: @iftex
        !            38: @ninerm
        !            39: @end iftex
        !            40: @end macro
        !            41: 
        !            42: @macro GLOSS-END {}
        !            43: @iftex
        !            44: @rm
        !            45: @end iftex
        !            46: @end macro
        !            47: 
        !            48: @comment ----------------------------------------------------------
        !            49: 
        !            50: 
1.10      anton      51: @include version.texi
                     52: 
1.1       anton      53: @ifinfo
1.11      anton      54: This file documents Gforth @value{VERSION}
1.1       anton      55: 
1.26      crook      56: Copyright @copyright{} 1995-1999 Free Software Foundation, Inc.
1.1       anton      57: 
                     58:      Permission is granted to make and distribute verbatim copies of
                     59:      this manual provided the copyright notice and this permission notice
                     60:      are preserved on all copies.
                     61:      
                     62: @ignore
                     63:      Permission is granted to process this file through TeX and print the
                     64:      results, provided the printed document carries a copying permission
                     65:      notice identical to this one except for the removal of this paragraph
                     66:      (this paragraph not being relevant to the printed manual).
                     67:      
                     68: @end ignore
                     69:      Permission is granted to copy and distribute modified versions of this
                     70:      manual under the conditions for verbatim copying, provided also that the
                     71:      sections entitled "Distribution" and "General Public License" are
                     72:      included exactly as in the original, and provided that the entire
                     73:      resulting derived work is distributed under the terms of a permission
                     74:      notice identical to this one.
                     75:      
                     76:      Permission is granted to copy and distribute translations of this manual
                     77:      into another language, under the above conditions for modified versions,
                     78:      except that the sections entitled "Distribution" and "General Public
                     79:      License" may be included in a translation approved by the author instead
                     80:      of in the original English.
                     81: @end ifinfo
                     82: 
                     83: @finalout
                     84: @titlepage
                     85: @sp 10
                     86: @center @titlefont{Gforth Manual}
                     87: @sp 2
1.11      anton      88: @center for version @value{VERSION}
1.1       anton      89: @sp 2
                     90: @center Anton Ertl
1.6       pazsan     91: @center Bernd Paysan
1.5       anton      92: @center Jens Wilke
1.23      crook      93: @center Neal Crook
1.1       anton      94: @sp 3
1.29    ! crook      95: @center This manual is permanently under construction and was last updated on 04-May-1999
1.1       anton      96: 
                     97: @comment  The following two commands start the copyright page.
                     98: @page
                     99: @vskip 0pt plus 1filll
1.29    ! crook     100: Copyright @copyright{} 1995--1999 Free Software Foundation, Inc.
1.1       anton     101: 
                    102: @comment !! Published by ... or You can get a copy of this manual ...
                    103: 
                    104:      Permission is granted to make and distribute verbatim copies of
                    105:      this manual provided the copyright notice and this permission notice
                    106:      are preserved on all copies.
                    107:      
                    108:      Permission is granted to copy and distribute modified versions of this
                    109:      manual under the conditions for verbatim copying, provided also that the
                    110:      sections entitled "Distribution" and "General Public License" are
                    111:      included exactly as in the original, and provided that the entire
                    112:      resulting derived work is distributed under the terms of a permission
                    113:      notice identical to this one.
                    114:      
                    115:      Permission is granted to copy and distribute translations of this manual
                    116:      into another language, under the above conditions for modified versions,
                    117:      except that the sections entitled "Distribution" and "General Public
                    118:      License" may be included in a translation approved by the author instead
                    119:      of in the original English.
                    120: @end titlepage
                    121: 
                    122: 
                    123: @node Top, License, (dir), (dir)
                    124: @ifinfo
                    125: Gforth is a free implementation of ANS Forth available on many
1.11      anton     126: personal machines. This manual corresponds to version @value{VERSION}.
1.1       anton     127: @end ifinfo
                    128: 
                    129: @menu
1.21      crook     130: * License::                     The GPL
1.26      crook     131: * Goals::                       About the Gforth Project
1.29    ! crook     132: * Gforth Environment::          Starting (and exiting) Gforth
1.21      crook     133: * Introduction::                An introduction to ANS Forth
1.1       anton     134: * Words::                       Forth words available in Gforth
1.24      anton     135: * Error messages::              How to interpret them
1.1       anton     136: * Tools::                       Programming tools
                    137: * ANS conformance::             Implementation-defined options etc.
                    138: * Model::                       The abstract machine of Gforth
                    139: * Integrating Gforth::          Forth as scripting language for applications
                    140: * Emacs and Gforth::            The Gforth Mode
                    141: * Image Files::                 @code{.fi} files contain compiled code
                    142: * Engine::                      The inner interpreter and the primitives
1.24      anton     143: * Binding to System Library::   
1.13      pazsan    144: * Cross Compiler::              The Cross Compiler
1.1       anton     145: * Bugs::                        How to report them
                    146: * Origin::                      Authors and ancestors of Gforth
1.21      crook     147: * Forth-related information::   Books and places to look on the WWW
1.1       anton     148: * Word Index::                  An item for each Forth word
                    149: * Concept Index::               A menu covering many topics
1.12      anton     150: 
1.24      anton     151: @detailmenu --- The Detailed Node Listing ---
1.12      anton     152: 
1.26      crook     153: Goals of Gforth
                    154: 
                    155: * Gforth Extensions Sinful?::
                    156: 
1.29    ! crook     157: Gforth Environment
        !           158: 
        !           159: * Invoking Gforth::
        !           160: * Leaving Gforth::
        !           161: * Command-line editing::
        !           162: * Upper and lower case::
        !           163: * Environment variables::
        !           164: * Gforth Files::
        !           165: 
1.24      anton     166: An Introduction to ANS Forth
                    167: 
                    168: * Introducing the Text Interpreter::
                    169: * Stacks and Postfix notation::
                    170: * Your first definition::
                    171: * How does that work?::
                    172: * Forth is written in Forth::
                    173: * Review - elements of a Forth system::
1.29    ! crook     174: * Where to go next::
1.24      anton     175: * Exercises::
                    176: 
1.12      anton     177: Forth Words
                    178: 
                    179: * Notation::                    
1.21      crook     180: * Comments::
                    181: * Boolean Flags::
1.12      anton     182: * Arithmetic::                  
                    183: * Stack Manipulation::          
                    184: * Memory::                      
                    185: * Control Structures::          
                    186: * Defining Words::              
1.21      crook     187: * The Text Interpreter::
1.12      anton     188: * Tokens for Words::            
1.21      crook     189: * Word Lists::                   
                    190: * Environmental Queries::
1.12      anton     191: * Files::                       
                    192: * Blocks::                      
                    193: * Other I/O::                   
                    194: * Programming Tools::           
                    195: * Assembler and Code Words::    
                    196: * Threading Words::             
1.26      crook     197: * Locals::                      
                    198: * Structures::                  
                    199: * Object-oriented Forth::       
1.21      crook     200: * Passing Commands to the OS::
                    201: * Miscellaneous Words::
1.12      anton     202: 
                    203: Arithmetic
                    204: 
                    205: * Single precision::            
                    206: * Bitwise operations::          
1.21      crook     207: * Double precision::            Double-cell integer arithmetic
                    208: * Numeric comparison::
1.12      anton     209: * Mixed precision::             operations with single and double-cell integers
                    210: * Floating Point::              
                    211: 
                    212: Stack Manipulation
                    213: 
                    214: * Data stack::                  
                    215: * Floating point stack::        
                    216: * Return stack::                
                    217: * Locals stack::                
                    218: * Stack pointer manipulation::  
                    219: 
                    220: Memory
                    221: 
1.27      crook     222: * Reserving Data Space::
1.12      anton     223: * Memory Access::      
1.27      crook     224: * Address Arithmetic::          
                    225: * Memory Blocks::
                    226: * Dynamic Allocation::        
1.12      anton     227: 
                    228: Control Structures
                    229: 
                    230: * Selection::                   
                    231: * Simple Loops::                
                    232: * Counted Loops::               
                    233: * Arbitrary control structures::  
                    234: * Calls and returns::           
                    235: * Exception Handling::          
                    236: 
                    237: Defining Words
                    238: 
                    239: * Simple Defining Words::       
                    240: * Colon Definitions::           
                    241: * User-defined Defining Words::  
                    242: * Supplying names::             
                    243: * Interpretation and Compilation Semantics::  
                    244: 
1.21      crook     245: The Text Interpreter
                    246: 
1.29    ! crook     247: * Input Sources::
1.21      crook     248: * Number Conversion::
                    249: * Interpret/Compile states::
                    250: * Literals::
                    251: * Interpreter Directives::
                    252: 
1.26      crook     253: Word Lists
                    254: 
                    255: * Why use word lists?::
                    256: * Word list examples::
                    257: 
                    258: Files
                    259: 
                    260: * Forth source files::
                    261: * General files::         
                    262: * Search Paths::                 
                    263: * Forth Search Paths::    
                    264: * General Search Paths::        
                    265: 
                    266: Other I/O
                    267: 
                    268: * Simple numeric output::
                    269: * Formatted numeric output::
                    270: * String Formats::
                    271: * Displaying characters and strings::
                    272: * Input::
                    273: 
                    274: Programming Tools
                    275: 
                    276: * Debugging::                   Simple and quick.
                    277: * Assertions::                  Making your programs self-checking.
                    278: * Singlestep Debugger::                Executing your program word by word.
                    279: 
                    280: Locals
                    281: 
                    282: * Gforth locals::               
                    283: * ANS Forth locals::            
                    284: 
                    285: Gforth locals
                    286: 
                    287: * Where are locals visible by name?::  
                    288: * How long do locals live?::    
                    289: * Programming Style::           
                    290: * Implementation::              
                    291: 
1.12      anton     292: Structures
                    293: 
                    294: * Why explicit structure support?::  
                    295: * Structure Usage::             
                    296: * Structure Naming Convention::  
                    297: * Structure Implementation::    
                    298: * Structure Glossary::          
                    299: 
                    300: Object-oriented Forth
                    301: 
1.24      anton     302: * Why object-oriented programming?::
                    303: * Object-Oriented Terminology::
                    304: * Objects::
                    305: * OOF::
                    306: * Mini-OOF::
1.23      crook     307: * Comparison with other object models::  
1.12      anton     308: 
1.24      anton     309: The @file{objects.fs} model
1.12      anton     310: 
                    311: * Properties of the Objects model::  
                    312: * Basic Objects Usage::         
1.23      crook     313: * The Objects base class::            
1.12      anton     314: * Creating objects::            
                    315: * Object-Oriented Programming Style::  
                    316: * Class Binding::               
                    317: * Method conveniences::         
                    318: * Classes and Scoping::         
                    319: * Object Interfaces::           
                    320: * Objects Implementation::      
                    321: * Objects Glossary::            
                    322: 
1.24      anton     323: The @file{oof.fs} model
1.12      anton     324: 
                    325: * Properties of the OOF model::
                    326: * Basic OOF Usage::
1.23      crook     327: * The OOF base class::
1.12      anton     328: * Class Declaration::
                    329: * Class Implementation::
                    330: 
1.24      anton     331: The @file{mini-oof.fs} model
1.23      crook     332: 
                    333: * Basic Mini-OOF Usage::
                    334: * Mini-OOF Example::
                    335: * Mini-OOF Implementation::
                    336: 
1.12      anton     337: Tools
                    338: 
                    339: * ANS Report::                  Report the words used, sorted by wordset.
                    340: 
                    341: ANS conformance
                    342: 
                    343: * The Core Words::              
                    344: * The optional Block word set::  
                    345: * The optional Double Number word set::  
                    346: * The optional Exception word set::  
                    347: * The optional Facility word set::  
                    348: * The optional File-Access word set::  
                    349: * The optional Floating-Point word set::  
                    350: * The optional Locals word set::  
                    351: * The optional Memory-Allocation word set::  
                    352: * The optional Programming-Tools word set::  
                    353: * The optional Search-Order word set::  
                    354: 
                    355: The Core Words
                    356: 
                    357: * core-idef::                   Implementation Defined Options                   
                    358: * core-ambcond::                Ambiguous Conditions                
                    359: * core-other::                  Other System Documentation                  
                    360: 
                    361: The optional Block word set
                    362: 
                    363: * block-idef::                  Implementation Defined Options
                    364: * block-ambcond::               Ambiguous Conditions               
                    365: * block-other::                 Other System Documentation                 
                    366: 
                    367: The optional Double Number word set
                    368: 
                    369: * double-ambcond::              Ambiguous Conditions              
                    370: 
                    371: The optional Exception word set
                    372: 
                    373: * exception-idef::              Implementation Defined Options              
                    374: 
                    375: The optional Facility word set
                    376: 
                    377: * facility-idef::               Implementation Defined Options               
                    378: * facility-ambcond::            Ambiguous Conditions            
                    379: 
                    380: The optional File-Access word set
                    381: 
                    382: * file-idef::                   Implementation Defined Options
                    383: * file-ambcond::                Ambiguous Conditions                
                    384: 
                    385: The optional Floating-Point word set
                    386: 
                    387: * floating-idef::               Implementation Defined Options
                    388: * floating-ambcond::            Ambiguous Conditions            
                    389: 
                    390: The optional Locals word set
                    391: 
                    392: * locals-idef::                 Implementation Defined Options                 
                    393: * locals-ambcond::              Ambiguous Conditions              
                    394: 
                    395: The optional Memory-Allocation word set
                    396: 
                    397: * memory-idef::                 Implementation Defined Options                 
                    398: 
                    399: The optional Programming-Tools word set
                    400: 
                    401: * programming-idef::            Implementation Defined Options            
                    402: * programming-ambcond::         Ambiguous Conditions         
                    403: 
                    404: The optional Search-Order word set
                    405: 
                    406: * search-idef::                 Implementation Defined Options                 
                    407: * search-ambcond::              Ambiguous Conditions              
                    408: 
                    409: Image Files
                    410: 
1.24      anton     411: * Image Licensing Issues::      Distribution terms for images.
                    412: * Image File Background::       Why have image files?
                    413: * Non-Relocatable Image Files::  don't always work.
                    414: * Data-Relocatable Image Files::  are better.
1.12      anton     415: * Fully Relocatable Image Files::  better yet.
1.24      anton     416: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
                    417: * Running Image Files::         @code{gforth -i @var{file}} or @var{file}.
                    418: * Modifying the Startup Sequence::  and turnkey applications.
1.12      anton     419: 
                    420: Fully Relocatable Image Files
                    421: 
1.27      crook     422: * gforthmi::                    The normal way
1.12      anton     423: * cross.fs::                    The hard way
                    424: 
                    425: Engine
                    426: 
                    427: * Portability::                 
                    428: * Threading::                   
                    429: * Primitives::                  
                    430: * Performance::                 
                    431: 
                    432: Threading
                    433: 
                    434: * Scheduling::                  
                    435: * Direct or Indirect Threaded?::  
                    436: * DOES>::                       
                    437: 
                    438: Primitives
                    439: 
                    440: * Automatic Generation::        
                    441: * TOS Optimization::            
                    442: * Produced code::               
1.13      pazsan    443: 
                    444: Cross Compiler
                    445: 
                    446: * Using the Cross Compiler::
                    447: * How the Cross Compiler Works::
                    448: 
1.24      anton     449: Other Forth-related information
1.21      crook     450: 
                    451: * Internet resources::
                    452: * Books::
                    453: * The Forth Interest Group::
                    454: * Conferences::
                    455: 
1.24      anton     456: @end detailmenu
1.1       anton     457: @end menu
                    458: 
1.26      crook     459: @node License, Goals, Top, Top
1.1       anton     460: @unnumbered GNU GENERAL PUBLIC LICENSE
                    461: @center Version 2, June 1991
                    462: 
                    463: @display
                    464: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
                    465: 675 Mass Ave, Cambridge, MA 02139, USA
                    466: 
                    467: Everyone is permitted to copy and distribute verbatim copies
                    468: of this license document, but changing it is not allowed.
                    469: @end display
                    470: 
                    471: @unnumberedsec Preamble
                    472: 
                    473:   The licenses for most software are designed to take away your
                    474: freedom to share and change it.  By contrast, the GNU General Public
                    475: License is intended to guarantee your freedom to share and change free
                    476: software---to make sure the software is free for all its users.  This
                    477: General Public License applies to most of the Free Software
                    478: Foundation's software and to any other program whose authors commit to
                    479: using it.  (Some other Free Software Foundation software is covered by
                    480: the GNU Library General Public License instead.)  You can apply it to
                    481: your programs, too.
                    482: 
                    483:   When we speak of free software, we are referring to freedom, not
                    484: price.  Our General Public Licenses are designed to make sure that you
                    485: have the freedom to distribute copies of free software (and charge for
                    486: this service if you wish), that you receive source code or can get it
                    487: if you want it, that you can change the software or use pieces of it
                    488: in new free programs; and that you know you can do these things.
                    489: 
                    490:   To protect your rights, we need to make restrictions that forbid
                    491: anyone to deny you these rights or to ask you to surrender the rights.
                    492: These restrictions translate to certain responsibilities for you if you
                    493: distribute copies of the software, or if you modify it.
                    494: 
                    495:   For example, if you distribute copies of such a program, whether
                    496: gratis or for a fee, you must give the recipients all the rights that
                    497: you have.  You must make sure that they, too, receive or can get the
                    498: source code.  And you must show them these terms so they know their
                    499: rights.
                    500: 
                    501:   We protect your rights with two steps: (1) copyright the software, and
                    502: (2) offer you this license which gives you legal permission to copy,
                    503: distribute and/or modify the software.
                    504: 
                    505:   Also, for each author's protection and ours, we want to make certain
                    506: that everyone understands that there is no warranty for this free
                    507: software.  If the software is modified by someone else and passed on, we
                    508: want its recipients to know that what they have is not the original, so
                    509: that any problems introduced by others will not reflect on the original
                    510: authors' reputations.
                    511: 
                    512:   Finally, any free program is threatened constantly by software
                    513: patents.  We wish to avoid the danger that redistributors of a free
                    514: program will individually obtain patent licenses, in effect making the
                    515: program proprietary.  To prevent this, we have made it clear that any
                    516: patent must be licensed for everyone's free use or not licensed at all.
                    517: 
                    518:   The precise terms and conditions for copying, distribution and
                    519: modification follow.
                    520: 
                    521: @iftex
                    522: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
                    523: @end iftex
                    524: @ifinfo
                    525: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
                    526: @end ifinfo
                    527: 
                    528: @enumerate 0
                    529: @item
                    530: This License applies to any program or other work which contains
                    531: a notice placed by the copyright holder saying it may be distributed
                    532: under the terms of this General Public License.  The ``Program'', below,
                    533: refers to any such program or work, and a ``work based on the Program''
                    534: means either the Program or any derivative work under copyright law:
                    535: that is to say, a work containing the Program or a portion of it,
                    536: either verbatim or with modifications and/or translated into another
                    537: language.  (Hereinafter, translation is included without limitation in
                    538: the term ``modification''.)  Each licensee is addressed as ``you''.
                    539: 
                    540: Activities other than copying, distribution and modification are not
                    541: covered by this License; they are outside its scope.  The act of
                    542: running the Program is not restricted, and the output from the Program
                    543: is covered only if its contents constitute a work based on the
                    544: Program (independent of having been made by running the Program).
                    545: Whether that is true depends on what the Program does.
                    546: 
                    547: @item
                    548: You may copy and distribute verbatim copies of the Program's
                    549: source code as you receive it, in any medium, provided that you
                    550: conspicuously and appropriately publish on each copy an appropriate
                    551: copyright notice and disclaimer of warranty; keep intact all the
                    552: notices that refer to this License and to the absence of any warranty;
                    553: and give any other recipients of the Program a copy of this License
                    554: along with the Program.
                    555: 
                    556: You may charge a fee for the physical act of transferring a copy, and
                    557: you may at your option offer warranty protection in exchange for a fee.
                    558: 
                    559: @item
                    560: You may modify your copy or copies of the Program or any portion
                    561: of it, thus forming a work based on the Program, and copy and
                    562: distribute such modifications or work under the terms of Section 1
                    563: above, provided that you also meet all of these conditions:
                    564: 
                    565: @enumerate a
                    566: @item
                    567: You must cause the modified files to carry prominent notices
                    568: stating that you changed the files and the date of any change.
                    569: 
                    570: @item
                    571: You must cause any work that you distribute or publish, that in
                    572: whole or in part contains or is derived from the Program or any
                    573: part thereof, to be licensed as a whole at no charge to all third
                    574: parties under the terms of this License.
                    575: 
                    576: @item
                    577: If the modified program normally reads commands interactively
                    578: when run, you must cause it, when started running for such
                    579: interactive use in the most ordinary way, to print or display an
                    580: announcement including an appropriate copyright notice and a
                    581: notice that there is no warranty (or else, saying that you provide
                    582: a warranty) and that users may redistribute the program under
                    583: these conditions, and telling the user how to view a copy of this
                    584: License.  (Exception: if the Program itself is interactive but
                    585: does not normally print such an announcement, your work based on
                    586: the Program is not required to print an announcement.)
                    587: @end enumerate
                    588: 
                    589: These requirements apply to the modified work as a whole.  If
                    590: identifiable sections of that work are not derived from the Program,
                    591: and can be reasonably considered independent and separate works in
                    592: themselves, then this License, and its terms, do not apply to those
                    593: sections when you distribute them as separate works.  But when you
                    594: distribute the same sections as part of a whole which is a work based
                    595: on the Program, the distribution of the whole must be on the terms of
                    596: this License, whose permissions for other licensees extend to the
                    597: entire whole, and thus to each and every part regardless of who wrote it.
                    598: 
                    599: Thus, it is not the intent of this section to claim rights or contest
                    600: your rights to work written entirely by you; rather, the intent is to
                    601: exercise the right to control the distribution of derivative or
                    602: collective works based on the Program.
                    603: 
                    604: In addition, mere aggregation of another work not based on the Program
                    605: with the Program (or with a work based on the Program) on a volume of
                    606: a storage or distribution medium does not bring the other work under
                    607: the scope of this License.
                    608: 
                    609: @item
                    610: You may copy and distribute the Program (or a work based on it,
                    611: under Section 2) in object code or executable form under the terms of
                    612: Sections 1 and 2 above provided that you also do one of the following:
                    613: 
                    614: @enumerate a
                    615: @item
                    616: Accompany it with the complete corresponding machine-readable
                    617: source code, which must be distributed under the terms of Sections
                    618: 1 and 2 above on a medium customarily used for software interchange; or,
                    619: 
                    620: @item
                    621: Accompany it with a written offer, valid for at least three
                    622: years, to give any third party, for a charge no more than your
                    623: cost of physically performing source distribution, a complete
                    624: machine-readable copy of the corresponding source code, to be
                    625: distributed under the terms of Sections 1 and 2 above on a medium
                    626: customarily used for software interchange; or,
                    627: 
                    628: @item
                    629: Accompany it with the information you received as to the offer
                    630: to distribute corresponding source code.  (This alternative is
                    631: allowed only for noncommercial distribution and only if you
                    632: received the program in object code or executable form with such
                    633: an offer, in accord with Subsection b above.)
                    634: @end enumerate
                    635: 
                    636: The source code for a work means the preferred form of the work for
                    637: making modifications to it.  For an executable work, complete source
                    638: code means all the source code for all modules it contains, plus any
                    639: associated interface definition files, plus the scripts used to
                    640: control compilation and installation of the executable.  However, as a
                    641: special exception, the source code distributed need not include
                    642: anything that is normally distributed (in either source or binary
                    643: form) with the major components (compiler, kernel, and so on) of the
                    644: operating system on which the executable runs, unless that component
                    645: itself accompanies the executable.
                    646: 
                    647: If distribution of executable or object code is made by offering
                    648: access to copy from a designated place, then offering equivalent
                    649: access to copy the source code from the same place counts as
                    650: distribution of the source code, even though third parties are not
                    651: compelled to copy the source along with the object code.
                    652: 
                    653: @item
                    654: You may not copy, modify, sublicense, or distribute the Program
                    655: except as expressly provided under this License.  Any attempt
                    656: otherwise to copy, modify, sublicense or distribute the Program is
                    657: void, and will automatically terminate your rights under this License.
                    658: However, parties who have received copies, or rights, from you under
                    659: this License will not have their licenses terminated so long as such
                    660: parties remain in full compliance.
                    661: 
                    662: @item
                    663: You are not required to accept this License, since you have not
                    664: signed it.  However, nothing else grants you permission to modify or
                    665: distribute the Program or its derivative works.  These actions are
                    666: prohibited by law if you do not accept this License.  Therefore, by
                    667: modifying or distributing the Program (or any work based on the
                    668: Program), you indicate your acceptance of this License to do so, and
                    669: all its terms and conditions for copying, distributing or modifying
                    670: the Program or works based on it.
                    671: 
                    672: @item
                    673: Each time you redistribute the Program (or any work based on the
                    674: Program), the recipient automatically receives a license from the
                    675: original licensor to copy, distribute or modify the Program subject to
                    676: these terms and conditions.  You may not impose any further
                    677: restrictions on the recipients' exercise of the rights granted herein.
                    678: You are not responsible for enforcing compliance by third parties to
                    679: this License.
                    680: 
                    681: @item
                    682: If, as a consequence of a court judgment or allegation of patent
                    683: infringement or for any other reason (not limited to patent issues),
                    684: conditions are imposed on you (whether by court order, agreement or
                    685: otherwise) that contradict the conditions of this License, they do not
                    686: excuse you from the conditions of this License.  If you cannot
                    687: distribute so as to satisfy simultaneously your obligations under this
                    688: License and any other pertinent obligations, then as a consequence you
                    689: may not distribute the Program at all.  For example, if a patent
                    690: license would not permit royalty-free redistribution of the Program by
                    691: all those who receive copies directly or indirectly through you, then
                    692: the only way you could satisfy both it and this License would be to
                    693: refrain entirely from distribution of the Program.
                    694: 
                    695: If any portion of this section is held invalid or unenforceable under
                    696: any particular circumstance, the balance of the section is intended to
                    697: apply and the section as a whole is intended to apply in other
                    698: circumstances.
                    699: 
                    700: It is not the purpose of this section to induce you to infringe any
                    701: patents or other property right claims or to contest validity of any
                    702: such claims; this section has the sole purpose of protecting the
                    703: integrity of the free software distribution system, which is
                    704: implemented by public license practices.  Many people have made
                    705: generous contributions to the wide range of software distributed
                    706: through that system in reliance on consistent application of that
                    707: system; it is up to the author/donor to decide if he or she is willing
                    708: to distribute software through any other system and a licensee cannot
                    709: impose that choice.
                    710: 
                    711: This section is intended to make thoroughly clear what is believed to
                    712: be a consequence of the rest of this License.
                    713: 
                    714: @item
                    715: If the distribution and/or use of the Program is restricted in
                    716: certain countries either by patents or by copyrighted interfaces, the
                    717: original copyright holder who places the Program under this License
                    718: may add an explicit geographical distribution limitation excluding
                    719: those countries, so that distribution is permitted only in or among
                    720: countries not thus excluded.  In such case, this License incorporates
                    721: the limitation as if written in the body of this License.
                    722: 
                    723: @item
                    724: The Free Software Foundation may publish revised and/or new versions
                    725: of the General Public License from time to time.  Such new versions will
                    726: be similar in spirit to the present version, but may differ in detail to
                    727: address new problems or concerns.
                    728: 
                    729: Each version is given a distinguishing version number.  If the Program
                    730: specifies a version number of this License which applies to it and ``any
                    731: later version'', you have the option of following the terms and conditions
                    732: either of that version or of any later version published by the Free
                    733: Software Foundation.  If the Program does not specify a version number of
                    734: this License, you may choose any version ever published by the Free Software
                    735: Foundation.
                    736: 
                    737: @item
                    738: If you wish to incorporate parts of the Program into other free
                    739: programs whose distribution conditions are different, write to the author
                    740: to ask for permission.  For software which is copyrighted by the Free
                    741: Software Foundation, write to the Free Software Foundation; we sometimes
                    742: make exceptions for this.  Our decision will be guided by the two goals
                    743: of preserving the free status of all derivatives of our free software and
                    744: of promoting the sharing and reuse of software generally.
                    745: 
                    746: @iftex
                    747: @heading NO WARRANTY
                    748: @end iftex
                    749: @ifinfo
                    750: @center NO WARRANTY
                    751: @end ifinfo
                    752: 
                    753: @item
                    754: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
                    755: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
                    756: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
                    757: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
                    758: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
                    759: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
                    760: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
                    761: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
                    762: REPAIR OR CORRECTION.
                    763: 
                    764: @item
                    765: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
                    766: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
                    767: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
                    768: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
                    769: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
                    770: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
                    771: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
                    772: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
                    773: POSSIBILITY OF SUCH DAMAGES.
                    774: @end enumerate
                    775: 
                    776: @iftex
                    777: @heading END OF TERMS AND CONDITIONS
                    778: @end iftex
                    779: @ifinfo
                    780: @center END OF TERMS AND CONDITIONS
                    781: @end ifinfo
                    782: 
                    783: @page
                    784: @unnumberedsec How to Apply These Terms to Your New Programs
                    785: 
                    786:   If you develop a new program, and you want it to be of the greatest
                    787: possible use to the public, the best way to achieve this is to make it
                    788: free software which everyone can redistribute and change under these terms.
                    789: 
                    790:   To do so, attach the following notices to the program.  It is safest
                    791: to attach them to the start of each source file to most effectively
                    792: convey the exclusion of warranty; and each file should have at least
                    793: the ``copyright'' line and a pointer to where the full notice is found.
                    794: 
                    795: @smallexample
                    796: @var{one line to give the program's name and a brief idea of what it does.}
                    797: Copyright (C) 19@var{yy}  @var{name of author}
                    798: 
                    799: This program is free software; you can redistribute it and/or modify 
                    800: it under the terms of the GNU General Public License as published by 
                    801: the Free Software Foundation; either version 2 of the License, or 
                    802: (at your option) any later version.
                    803: 
                    804: This program is distributed in the hope that it will be useful,
                    805: but WITHOUT ANY WARRANTY; without even the implied warranty of
                    806: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                    807: GNU General Public License for more details.
                    808: 
                    809: You should have received a copy of the GNU General Public License
                    810: along with this program; if not, write to the Free Software
                    811: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
                    812: @end smallexample
                    813: 
                    814: Also add information on how to contact you by electronic and paper mail.
                    815: 
                    816: If the program is interactive, make it output a short notice like this
                    817: when it starts in an interactive mode:
                    818: 
                    819: @smallexample
                    820: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
                    821: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
                    822: type `show w'.  
                    823: This is free software, and you are welcome to redistribute it 
                    824: under certain conditions; type `show c' for details.
                    825: @end smallexample
                    826: 
                    827: The hypothetical commands @samp{show w} and @samp{show c} should show
                    828: the appropriate parts of the General Public License.  Of course, the
                    829: commands you use may be called something other than @samp{show w} and
                    830: @samp{show c}; they could even be mouse-clicks or menu items---whatever
                    831: suits your program.
                    832: 
                    833: You should also get your employer (if you work as a programmer) or your
                    834: school, if any, to sign a ``copyright disclaimer'' for the program, if
                    835: necessary.  Here is a sample; alter the names:
                    836: 
                    837: @smallexample
                    838: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
                    839: `Gnomovision' (which makes passes at compilers) written by James Hacker.
                    840: 
                    841: @var{signature of Ty Coon}, 1 April 1989
                    842: Ty Coon, President of Vice
                    843: @end smallexample
                    844: 
                    845: This General Public License does not permit incorporating your program into
                    846: proprietary programs.  If your program is a subroutine library, you may
                    847: consider it more useful to permit linking proprietary applications with the
                    848: library.  If this is what you want to do, use the GNU Library General
                    849: Public License instead of this License.
                    850: 
                    851: @iftex
                    852: @unnumbered Preface
                    853: @cindex Preface
1.21      crook     854: This manual documents Gforth. Some introductory material is provided for
                    855: readers who are unfamiliar with Forth or who are migrating to Gforth
                    856: from other Forth compilers. However, this manual is primarily a
                    857: reference manual.
1.1       anton     858: @end iftex
                    859: 
1.28      crook     860: @comment TODO much more blurb here.
1.26      crook     861: 
                    862: @c ******************************************************************
1.29    ! crook     863: @node Goals, Gforth Environment, License, Top
1.26      crook     864: @comment node-name,     next,           previous, up
                    865: @chapter Goals of Gforth
                    866: @cindex goals of the Gforth project
                    867: The goal of the Gforth Project is to develop a standard model for
                    868: ANS Forth. This can be split into several subgoals:
                    869: 
                    870: @itemize @bullet
                    871: @item
                    872: Gforth should conform to the ANS Forth Standard.
                    873: @item
                    874: It should be a model, i.e. it should define all the
                    875: implementation-dependent things.
                    876: @item
                    877: It should become standard, i.e. widely accepted and used. This goal
                    878: is the most difficult one.
                    879: @end itemize
                    880: 
                    881: To achieve these goals Gforth should be
                    882: @itemize @bullet
                    883: @item
                    884: Similar to previous models (fig-Forth, F83)
                    885: @item
                    886: Powerful. It should provide for all the things that are considered
                    887: necessary today and even some that are not yet considered necessary.
                    888: @item
                    889: Efficient. It should not get the reputation of being exceptionally
                    890: slow.
                    891: @item
                    892: Free.
                    893: @item
                    894: Available on many machines/easy to port.
                    895: @end itemize
                    896: 
                    897: Have we achieved these goals? Gforth conforms to the ANS Forth
                    898: standard. It may be considered a model, but we have not yet documented
                    899: which parts of the model are stable and which parts we are likely to
                    900: change. It certainly has not yet become a de facto standard, but it
                    901: appears to be quite popular. It has some similarities to and some
                    902: differences from previous models. It has some powerful features, but not
                    903: yet everything that we envisioned. We certainly have achieved our
                    904: execution speed goals (@pxref{Performance}).  It is free and available
                    905: on many machines.
                    906: 
                    907: @menu
                    908: * Gforth Extensions Sinful?::
                    909: @end menu
                    910: 
                    911: @node Gforth Extensions Sinful?, , Goals, Goals
                    912: @comment node-name,     next,           previous, up
                    913: @section Is it a Sin to use Gforth Extensions?
                    914: @cindex Gforth extensions
                    915: 
                    916: If you've been paying attention, you will have realised that there is an
                    917: ANS (American National Standard) for Forth. As you read through the rest
1.29    ! crook     918: of this manual, you will see documentation for @i{Standard} words, and
        !           919: documentation for some appealing Gforth @i{extensions}. You might ask
        !           920: yourself the question: @i{``Given that there is a standard, would I be
1.26      crook     921: committing a sin to use (non-Standard) Gforth extensions?''}
                    922: 
                    923: The answer to that question is somewhat pragmatic and somewhat
                    924: philosophical. Consider these points:
                    925: 
                    926: @itemize @bullet
                    927: @item
                    928: A number of the Gforth extensions can be implemented in ANS Forth using
                    929: files provided in the @file{compat/} directory. These are mentioned in
                    930: the text in passing.
                    931: @item
                    932: Forth has a rich historical precedent for programmers taking advantage
                    933: of implementation-dependent features of their tools (for example,
                    934: relying on a knowledge of the dictionary structure). Sometimes these
                    935: techniques are necessary to extract every last bit of performance from
                    936: the hardware, sometimes they are just a programming shorthand.
                    937: @item
                    938: The best way to break the rules is to know what the rules are. To learn
                    939: the rules, there is no substitute for studying the text of the Standard
                    940: itself. In particular, Appendix A of the Standard (@var{Rationale})
                    941: provides a valuable insight into the thought processes of the technical
                    942: committee.
                    943: @item
                    944: The best reason to break a rule is because you have to; because it's
                    945: more productive to do that, because it makes your code run fast enough
                    946: or because you can see no Standard way to achieve what you want to
                    947: achieve.
                    948: @end itemize
                    949: 
                    950: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
                    951: analyse your program and determine what non-Standard definitions it
                    952: relies upon.
                    953: 
1.29    ! crook     954: 
1.26      crook     955: @c ******************************************************************
1.29    ! crook     956: @node Gforth Environment, Introduction, Goals, Top
        !           957: @chapter Gforth Environment
        !           958: @cindex Gforth environment
1.21      crook     959: 
1.29    ! crook     960: Note: ultimately, the gforth man page will be auto-generated from the
        !           961: material in this chapter.
1.21      crook     962: 
                    963: @menu
1.29    ! crook     964: * Invoking Gforth::             Getting in
        !           965: * Leaving Gforth::              Getting out
        !           966: * Command-line editing::        
        !           967: * Upper and lower case::
        !           968: * Environment variables::       ..that affect how Gforth starts up
        !           969: * Gforth Files::                What gets installed and where
1.21      crook     970: @end menu
                    971: 
1.29    ! crook     972: 
1.21      crook     973: @comment ----------------------------------------------
1.29    ! crook     974: @node Invoking Gforth, Leaving Gforth, ,Gforth Environment
        !           975: @section Invoking Gforth
        !           976: @cindex invoking Gforth
        !           977: @cindex running Gforth
        !           978: @cindex command-line options
        !           979: @cindex options on the command line
        !           980: @cindex flags on the command line
1.21      crook     981: 
1.29    ! crook     982: Gforth is made up of two parts; an executable ``engine'' (named gforth)
        !           983: and an image file. To start it, you will usually just say @code{gforth}
        !           984: -- this automatically loads the default image file. In many other cases
        !           985: the default Gforth image will be invoked like this:
1.21      crook     986: @example
1.29    ! crook     987: gforth [files] [-e forth-code]
1.21      crook     988: @end example
1.29    ! crook     989: @noindent
        !           990: This interprets the contents of the files and the Forth code in the order they
        !           991: are given.
1.21      crook     992: 
1.29    ! crook     993: In general, the command line looks like this:
1.21      crook     994: 
                    995: @example
1.29    ! crook     996: gforth [initialization options] [image-specific options]
1.21      crook     997: @end example
                    998: 
1.29    ! crook     999: The initialization options must come before the rest of the command
        !          1000: line. They are:
1.26      crook    1001: 
1.29    ! crook    1002: @table @code
        !          1003: @cindex -i, command-line option
        !          1004: @cindex --image-file, command-line option
        !          1005: @item --image-file @i{file}
        !          1006: @itemx -i @i{file}
        !          1007: Loads the Forth image @i{file} instead of the default
        !          1008: @file{gforth.fi} (@pxref{Image Files}).
1.21      crook    1009: 
1.29    ! crook    1010: @cindex --path, command-line option
        !          1011: @cindex -p, command-line option
        !          1012: @item --path @i{path}
        !          1013: @itemx -p @i{path}
        !          1014: Uses @i{path} for searching the image file and Forth source code files
        !          1015: instead of the default in the environment variable @code{GFORTHPATH} or
        !          1016: the path specified at installation time (e.g.,
        !          1017: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
        !          1018: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21      crook    1019: 
1.29    ! crook    1020: @cindex --dictionary-size, command-line option
        !          1021: @cindex -m, command-line option
        !          1022: @cindex @i{size} parameters for command-line options
        !          1023: @cindex size of the dictionary and the stacks
        !          1024: @item --dictionary-size @i{size}
        !          1025: @itemx -m @i{size}
        !          1026: Allocate @i{size} space for the Forth dictionary space instead of
        !          1027: using the default specified in the image (typically 256K). The
        !          1028: @i{size} specification for this and subsequent options consists of
        !          1029: an integer and a unit (e.g.,
        !          1030: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
        !          1031: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
        !          1032: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
        !          1033: @code{e} is used.
1.21      crook    1034: 
1.29    ! crook    1035: @cindex --data-stack-size, command-line option
        !          1036: @cindex -d, command-line option
        !          1037: @item --data-stack-size @i{size}
        !          1038: @itemx -d @i{size}
        !          1039: Allocate @i{size} space for the data stack instead of using the
        !          1040: default specified in the image (typically 16K).
1.21      crook    1041: 
1.29    ! crook    1042: @cindex --return-stack-size, command-line option
        !          1043: @cindex -r, command-line option
        !          1044: @item --return-stack-size @i{size}
        !          1045: @itemx -r @i{size}
        !          1046: Allocate @i{size} space for the return stack instead of using the
        !          1047: default specified in the image (typically 15K).
1.21      crook    1048: 
1.29    ! crook    1049: @cindex --fp-stack-size, command-line option
        !          1050: @cindex -f, command-line option
        !          1051: @item --fp-stack-size @i{size}
        !          1052: @itemx -f @i{size}
        !          1053: Allocate @i{size} space for the floating point stack instead of
        !          1054: using the default specified in the image (typically 15.5K). In this case
        !          1055: the unit specifier @code{e} refers to floating point numbers.
1.21      crook    1056: 
1.29    ! crook    1057: @cindex --locals-stack-size, command-line option
        !          1058: @cindex -l, command-line option
        !          1059: @item --locals-stack-size @i{size}
        !          1060: @itemx -l @i{size}
        !          1061: Allocate @i{size} space for the locals stack instead of using the
        !          1062: default specified in the image (typically 14.5K).
1.21      crook    1063: 
1.29    ! crook    1064: @cindex -h, command-line option
        !          1065: @cindex --help, command-line option
        !          1066: @item --help
        !          1067: @itemx -h
        !          1068: Print a message about the command-line options
1.21      crook    1069: 
1.29    ! crook    1070: @cindex -v, command-line option
        !          1071: @cindex --version, command-line option
        !          1072: @item --version
        !          1073: @itemx -v
        !          1074: Print version and exit
1.21      crook    1075: 
1.29    ! crook    1076: @cindex --debug, command-line option
        !          1077: @item --debug
        !          1078: Print some information useful for debugging on startup.
1.21      crook    1079: 
1.29    ! crook    1080: @cindex --offset-image, command-line option
        !          1081: @item --offset-image
        !          1082: Start the dictionary at a slightly different position than would be used
        !          1083: otherwise (useful for creating data-relocatable images,
        !          1084: @pxref{Data-Relocatable Image Files}).
1.21      crook    1085: 
1.29    ! crook    1086: @cindex --no-offset-im, command-line option
        !          1087: @item --no-offset-im
        !          1088: Start the dictionary at the normal position.
1.21      crook    1089: 
1.29    ! crook    1090: @cindex --clear-dictionary, command-line option
        !          1091: @item --clear-dictionary
        !          1092: Initialize all bytes in the dictionary to 0 before loading the image
        !          1093: (@pxref{Data-Relocatable Image Files}).
        !          1094: 
        !          1095: @cindex --die-on-signal, command-line-option
        !          1096: @item --die-on-signal
        !          1097: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
        !          1098: or the segmentation violation SIGSEGV) by translating it into a Forth
        !          1099: @code{THROW}. With this option, Gforth exits if it receives such a
        !          1100: signal. This option is useful when the engine and/or the image might be
        !          1101: severely broken (such that it causes another signal before recovering
        !          1102: from the first); this option avoids endless loops in such cases.
        !          1103: @end table
        !          1104: 
        !          1105: @cindex loading files at startup
        !          1106: @cindex executing code on startup
        !          1107: @cindex batch processing with Gforth
        !          1108: As explained above, the image-specific command-line arguments for the
        !          1109: default image @file{gforth.fi} consist of a sequence of filenames and
        !          1110: @code{-e @var{forth-code}} options that are interpreted in the sequence
        !          1111: in which they are given. The @code{-e @var{forth-code}} or
        !          1112: @code{--evaluate @var{forth-code}} option evaluates the Forth
        !          1113: code. This option takes only one argument; if you want to evaluate more
        !          1114: Forth words, you have to quote them or use @code{-e} several times. To exit
        !          1115: after processing the command line (instead of entering interactive mode)
        !          1116: append @code{-e bye} to the command line.
        !          1117: 
        !          1118: @cindex versions, invoking other versions of Gforth
        !          1119: If you have several versions of Gforth installed, @code{gforth} will
        !          1120: invoke the version that was installed last. @code{gforth-@i{version}}
        !          1121: invokes a specific version. You may want to use the option
        !          1122: @code{--path}, if your environment contains the variable
        !          1123: @code{GFORTHPATH}.
        !          1124: 
        !          1125: Not yet implemented:
        !          1126: On startup the system first executes the system initialization file
        !          1127: (unless the option @code{--no-init-file} is given; note that the system
        !          1128: resulting from using this option may not be ANS Forth conformant). Then
        !          1129: the user initialization file @file{.gforth.fs} is executed, unless the
        !          1130: option @code{--no-rc} is given; this file is first searched in @file{.},
        !          1131: then in @file{~}, then in the normal path (see above).
1.21      crook    1132: 
                   1133: 
                   1134: 
1.29    ! crook    1135: @comment ----------------------------------------------
        !          1136: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
        !          1137: @section Leaving Gforth
        !          1138: @cindex Gforth - leaving
        !          1139: @cindex leaving Gforth
1.21      crook    1140: 
1.29    ! crook    1141: You can leave Gforth by typing @code{bye} or Ctrl-D or (if you invoked
        !          1142: Gforth with the @code{--die-on-signal} option) Ctrl-C. When you leave
        !          1143: Gforth, all of your definitions and data are discarded. @xref{Image
        !          1144: Files} for ways of saving the state of the system before leaving Gforth.
1.21      crook    1145: 
1.29    ! crook    1146: doc-bye
1.21      crook    1147: 
1.29    ! crook    1148: @comment ----------------------------------------------
        !          1149: @node Command-line editing, Upper and lower case,Leaving Gforth,Gforth Environment
        !          1150: @section Command-line editing
        !          1151: @cindex command-line editing
1.21      crook    1152: 
1.29    ! crook    1153: Gforth maintains a history file that records every line that you type to
        !          1154: the text interpreter. This file is preserved between sessions, and is
        !          1155: used to provide a command-line recall facility; if you type ctrl-P
        !          1156: repeatedly you can recall successively older commands from this (or
        !          1157: previous) session(s). The full list of command-line editing facilities is:
1.21      crook    1158: 
                   1159: @itemize @bullet
                   1160: @item
1.29    ! crook    1161: ctrl-P (``previous'') (or up-arrow) to recall successively older
        !          1162: commands from the history buffer.
        !          1163: @item
        !          1164: ctrl-N (``next'') (or down-arrow) to recall successively newer commands
        !          1165: from the history buffer.
        !          1166: @item
        !          1167: ctrl-F (or right-arrow) to move the cursor right, non-destructively.
        !          1168: @item
        !          1169: ctrl-B (or left-arrow) to move the cursor left, non-destructively.
        !          1170: @item
        !          1171: ctrl-H (backspace) to delete the character to the left of the cursor,
        !          1172: closing up the line.
        !          1173: @item
        !          1174: ctrl-K to delete (``kill'') from the cursor to the end of the line.
        !          1175: @item
        !          1176: ctrl-A to move the cursor to the start of the line.
1.21      crook    1177: @item
1.29    ! crook    1178: ctrl-E to move the cursor to the end of the line.
1.21      crook    1179: @item
1.29    ! crook    1180: carriage-return or line-feed (ctrl-J, ctrl-M) to submit the current
        !          1181: line.
1.21      crook    1182: @item
1.29    ! crook    1183: tab to step through all possible full-word completions of the word
        !          1184: currently being typed.
1.21      crook    1185: @item
1.29    ! crook    1186: ctrl-D to terminate Gforth (gracefully, using @code{bye}).
1.21      crook    1187: @end itemize
                   1188: 
1.29    ! crook    1189: When editing, displayable characters are inserted to the left of the
        !          1190: cursor position; the line is always in ``insert'' (as opposed to
        !          1191: ``overstrike'') mode.
        !          1192: 
        !          1193: @cindex history file
        !          1194: @cindex @file{.gforth-history}
        !          1195: On Unix systems, the history file is @file{~/.gforth-history} by
        !          1196: default@footnote{i.e. it is stored in the user's home directory.}. You
        !          1197: can find out the name and location of your history file using:
        !          1198: 
        !          1199: @example 
        !          1200: history-file type \ Unix-class systems
1.21      crook    1201: 
1.29    ! crook    1202: history-file type \ Other systems
        !          1203: history-dir  type
1.21      crook    1204: @end example
                   1205: 
1.29    ! crook    1206: If you enter long definitions by hand, you can use a text editor to
        !          1207: paste them out of the history file into a Forth source file for reuse at
        !          1208: a later time.
        !          1209: 
        !          1210: Gforth never trims the size of the history file, so you should do this
        !          1211: periodically, if necessary.
        !          1212: 
        !          1213: @comment this is all defined in history.fs
        !          1214: @comment TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
        !          1215: @comment chosen?
        !          1216: 
        !          1217: 
        !          1218: 
        !          1219: @comment ----------------------------------------------
        !          1220: @node Upper and lower case, Environment variables,Command-line editing,Gforth Environment
        !          1221: @section Upper and lower case
        !          1222: @cindex case-sensitivity
        !          1223: @cindex upper and lower case
        !          1224: 
        !          1225: Gforth is case-insensitive, so you can enter definitions and invoke
        !          1226: Standard words using upper, lower or mixed case (however,
        !          1227: @pxref{core-idef, Implementation-defined options, Implementation-defined
        !          1228: options}).
        !          1229: 
        !          1230: ANS Forth only @i{requires} implementations to recognise Standard words when
        !          1231: they are typed entirely in upper case. Therefore, a Standard program
        !          1232: must use upper case for all Standard words@footnote{You can use whatever
        !          1233: case you like for words that you define.}.
        !          1234: 
        !          1235: 
        !          1236: @comment ----------------------------------------------
        !          1237: @node Environment variables, Gforth Files, Upper and lower case,Gforth Environment
        !          1238: @section Environment variables
        !          1239: @cindex environment variables
1.21      crook    1240: 
1.29    ! crook    1241: Gforth uses these environment variables:
1.21      crook    1242: 
1.29    ! crook    1243: @itemize @bullet
        !          1244: @item
        !          1245: @cindex GFORTHHIST - environment variable
        !          1246: GFORTHHIST - (Unix systems only) specifies the directory in which to
        !          1247: open/create the history file, @file{.gforth-history}. Default:
        !          1248: @code{$HOME}.
1.21      crook    1249: 
1.29    ! crook    1250: @item
        !          1251: @cindex GFORTHPATH - environment variable
        !          1252: GFORTHPATH - specifies the path used when searching for the gforth image file and
        !          1253: for Forth source-code files.
1.21      crook    1254: 
1.29    ! crook    1255: @item
        !          1256: @cindex GFORTH - environment variable
        !          1257: GFORTH - used by @file{gforthmi} @xref{gforthmi}.
1.26      crook    1258: 
1.29    ! crook    1259: @item
        !          1260: @cindex GFORTHD - environment variable
        !          1261: GFORTHD - used by @file{gforthmi} @xref{gforthmi}.
1.21      crook    1262: 
1.29    ! crook    1263: @item
        !          1264: @cindex TMP, TEMP - environment variable
        !          1265: TMP, TEMP - (non-Unix systems only) used as a potential location for the
        !          1266: history file.
        !          1267: @end itemize
1.21      crook    1268: 
1.29    ! crook    1269: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
        !          1270: @comment mentioning these.
1.21      crook    1271: 
1.29    ! crook    1272: All the Gforth environment variables default to sensible values if they
        !          1273: are not set.
1.21      crook    1274: 
                   1275: 
1.29    ! crook    1276: @comment ----------------------------------------------
        !          1277: @node Gforth Files, ,Environment variables,Gforth Environment
        !          1278: @section Gforth files
        !          1279: @cindex Gforth files
1.21      crook    1280: 
1.29    ! crook    1281: When Gforth is installed on a Unix system it leaves files in these
        !          1282: locations:
1.21      crook    1283: 
1.26      crook    1284: @itemize @bullet
                   1285: @item
1.29    ! crook    1286: @file{/usr/local/bin/gforth}
        !          1287: @item
        !          1288: @file{/usr/local/bin/gforthmi}
        !          1289: @item
        !          1290: @file{/usr/local/man/man1/gforth.1} - man page.
        !          1291: @item
        !          1292: @file{/usr/local/info} - the Info version of this manual.
        !          1293: @item
        !          1294: @file{/usr/local/lib/gforth/<version>/..} - Gforth @file{.fi} files.
        !          1295: @item
        !          1296: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1.26      crook    1297: @item
1.29    ! crook    1298: @file{/usr/local/share/gforth/<version>/..} - Gforth source files.
1.26      crook    1299: @item
1.29    ! crook    1300: @file{../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1.26      crook    1301: @end itemize
1.21      crook    1302: 
                   1303: 
1.29    ! crook    1304: @c ******************************************************************
        !          1305: @node Introduction, Words, Gforth Environment, Top
        !          1306: @comment node-name,     next,           previous, up
        !          1307: @chapter An Introduction to ANS Forth
        !          1308: @cindex Forth - an introduction
1.21      crook    1309: 
1.29    ! crook    1310: The primary purpose of this manual is to document Gforth. However, since
        !          1311: Forth is not a widely-known language and there is a lack of up-to-date
        !          1312: teaching material, it seems worthwhile to provide some introductory
        !          1313: material. @xref{Forth-related information} for other sources of Forth-related
        !          1314: information.
1.21      crook    1315: 
1.29    ! crook    1316: The examples in this section should work on any ANS Forth; the
        !          1317: output shown was produced using Gforth. Each example attempts to
        !          1318: reproduce the exact output that Gforth produces. If you try out the
        !          1319: examples (and you should), what you should type is shown @kbd{like this}
        !          1320: and Gforth's response is shown @code{like this}. The single exception is
        !          1321: that, where the example shows @kbd{<return>} it means that you should
        !          1322: press the ``carriage return'' key. Unfortunately, some output formats for
        !          1323: this manual cannot show the difference between @kbd{this} and
        !          1324: @code{this} which will make trying out the examples harder (but not
        !          1325: impossible).
1.21      crook    1326: 
1.29    ! crook    1327: Forth is an unusual language. It provides an interactive development
        !          1328: environment which includes both an interpreter and compiler. Forth
        !          1329: programming style encourages you to break a problem down into many
        !          1330: @cindex factoring
        !          1331: small fragments (@dfn{factoring}), and then to develop and test each
        !          1332: fragment interactively. Forth advocates assert that breaking the
        !          1333: edit-compile-test cycle used by conventional programming languages can
        !          1334: lead to great productivity improvements.
1.21      crook    1335: 
1.29    ! crook    1336: @menu
        !          1337: * Introducing the Text Interpreter::
        !          1338: * Stacks and Postfix notation::
        !          1339: * Your first definition::
        !          1340: * How does that work?::
        !          1341: * Forth is written in Forth::
        !          1342: * Review - elements of a Forth system::
        !          1343: * Where to go next::
        !          1344: * Exercises::
        !          1345: @end menu
1.21      crook    1346: 
1.29    ! crook    1347: @comment ----------------------------------------------
        !          1348: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
        !          1349: @section Introducing the Text Interpreter
        !          1350: @cindex text interpreter
        !          1351: @cindex outer interpreter
1.21      crook    1352: 
1.29    ! crook    1353: When you invoke the Forth image, you will see a startup banner printed
        !          1354: and nothing else (if you have Gforth installed on your system, try
        !          1355: invoking it now, by typing @kbd{gforth<return>}). Forth is now running
        !          1356: its command line interpreter, which is called the @dfn{Text Interpreter}
        !          1357: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
        !          1358: about the text interpreter as you read through this chapter,
        !          1359: but @pxref{The Text Interpreter} for more detail).
1.21      crook    1360: 
1.29    ! crook    1361: Although it's not obvious, Forth is actually waiting for your
        !          1362: input. Type a number and press the <return> key:
1.21      crook    1363: 
1.26      crook    1364: @example
1.29    ! crook    1365: @kbd{45<return>}  ok
1.26      crook    1366: @end example
1.21      crook    1367: 
1.29    ! crook    1368: Rather than give you a prompt to invite you to input something, the text
        !          1369: interpreter prints a status message @i{after} it has processed a line
        !          1370: of input. The status message in this case (``@code{ ok}'' followed by
        !          1371: carriage-return) indicates that the text interpreter was able to process
        !          1372: all of your input successfully. Now type something illegal:
        !          1373: 
        !          1374: @example
        !          1375: @kbd{qwer341<return>}
        !          1376: :1: Undefined word
        !          1377: qwer341
        !          1378: ^^^^^^^
        !          1379: $400D2BA8 Bounce
        !          1380: $400DBDA8 no.extensions
        !          1381: @end example
1.23      crook    1382: 
1.29    ! crook    1383: The exact text, other than the ``Undefined word'' may differ slightly on
        !          1384: your system, but the effect is the same; when the text interpreter
        !          1385: detects an error, it discards any remaining text on a line, resets
        !          1386: certain internal state and prints an error message.
1.23      crook    1387: 
1.29    ! crook    1388: The text interpreter waits for you to press carriage-return, and then
        !          1389: processes your input line. Starting at the beginning of the line, it
        !          1390: breaks the line into groups of characters separated by spaces. For each
        !          1391: group of characters in turn, it makes two attempts to do something:
1.23      crook    1392: 
1.29    ! crook    1393: @itemize @bullet
        !          1394: @item
        !          1395: It tries to treat it as a command. It does this by searching a @dfn{name
        !          1396: dictionary}. If the group of characters matches an entry in the name
        !          1397: dictionary, the name dictionary provides the text interpreter with
        !          1398: information that allows the text interpreter perform some actions. In
        !          1399: Forth jargon, we say that the group
        !          1400: @cindex word
        !          1401: @cindex definition
        !          1402: @cindex execution token
        !          1403: @cindex xt
        !          1404: of characters names a @dfn{word}, that the dictionary search returns an
        !          1405: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
        !          1406: word, and that the text interpreter executes the xt. Often, the terms
        !          1407: @dfn{word} and @dfn{definition} are used interchangeably.
        !          1408: @item
        !          1409: If the text interpreter fails to find a match in the name dictionary, it
        !          1410: tries to treat the group of characters as a number in the current number
        !          1411: base (when you start up Forth, the current number base is base 10). If
        !          1412: the group of characters legitimately represents a number, the text
        !          1413: interpreter pushes the number onto a stack (we'll learn more about that
        !          1414: in the next section).
        !          1415: @end itemize
1.23      crook    1416: 
1.29    ! crook    1417: If the text interpreter is unable to do either of these things with any
        !          1418: group of characters, it discards the group of characters and the rest of
        !          1419: the line, then prints an error message. If the text interpreter reaches
        !          1420: the end of the line without error, it prints the status message ``@code{ ok}''
        !          1421: followed by carriage-return.
1.21      crook    1422: 
1.29    ! crook    1423: This is the simplest command we can give to the text interpreter:
1.23      crook    1424: 
                   1425: @example
1.29    ! crook    1426: @kbd{<return>}  ok
1.23      crook    1427: @end example
1.21      crook    1428: 
1.29    ! crook    1429: The text interpreter did everything we asked it to do (nothing) without
        !          1430: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
        !          1431: command:
1.21      crook    1432: 
1.23      crook    1433: @example
1.29    ! crook    1434: @kbd{12 dup fred dup<return>}
        !          1435: :1: Undefined word
        !          1436: 12 dup fred dup
        !          1437:        ^^^^
        !          1438: $400D2BA8 Bounce
        !          1439: $400DBDA8 no.extensions
1.23      crook    1440: @end example
1.21      crook    1441: 
1.29    ! crook    1442: When you press the carriage-return key, the text interpreter starts to
        !          1443: work its way along the line:
1.21      crook    1444: 
1.29    ! crook    1445: @itemize @bullet
        !          1446: @item
        !          1447: When it gets to the space after the @code{2}, it takes the group of
        !          1448: characters @code{12} and looks them up in the name
        !          1449: dictionary@footnote{We can't tell if it found them or not, but assume
        !          1450: for now that it did not}. There is no match for this group of characters
        !          1451: in the name dictionary, so it tries to treat them as a number. It is
        !          1452: able to do this successfully, so it puts the number, 12, ``on the stack''
        !          1453: (whatever that means).
        !          1454: @item
        !          1455: The text interpreter resumes scanning the line and gets the next group
        !          1456: of characters, @code{dup}. It looks it up in the name dictionary and
        !          1457: (you'll have to take my word for this) finds it, and executes the word
        !          1458: @code{dup} (whatever that means).
        !          1459: @item
        !          1460: Once again, the text interpreter resumes scanning the line and gets the
        !          1461: group of characters @code{fred}. It looks them up in the name
        !          1462: dictionary, but can't find them. It tries to treat them as a number, but
        !          1463: they don't represent any legal number.
        !          1464: @end itemize
1.21      crook    1465: 
1.29    ! crook    1466: At this point, the text interpreter gives up and prints an error
        !          1467: message. The error message shows exactly how far the text interpreter
        !          1468: got in processing the line. In particular, it shows that the text
        !          1469: interpreter made no attempt to do anything with the final character
        !          1470: group, @code{dup}, even though we have good reason to believe that the
        !          1471: text interpreter would have no problem looking that word up and
        !          1472: executing it a second time.
1.21      crook    1473: 
                   1474: 
1.29    ! crook    1475: @comment ----------------------------------------------
        !          1476: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
        !          1477: @section Stacks, postfix notation and parameter passing
        !          1478: @cindex text interpreter
        !          1479: @cindex outer interpreter
1.21      crook    1480: 
1.29    ! crook    1481: In procedural programming languages (like C and Pascal), the
        !          1482: building-block of programs is the @dfn{function} or @dfn{procedure}. These
        !          1483: functions or procedures are called with @dfn{explicit parameters}. For
        !          1484: example, in C we might write:
1.21      crook    1485: 
1.23      crook    1486: @example
1.29    ! crook    1487: total = total + new_volume(length,height,depth);
1.23      crook    1488: @end example
1.21      crook    1489: 
1.23      crook    1490: @noindent
1.29    ! crook    1491: where new_volume is a function-call to another piece of code, and total,
        !          1492: length, height and depth are all variables. length, height and depth are
        !          1493: parameters to the function-call.
1.21      crook    1494: 
1.29    ! crook    1495: In Forth, the equivalent of the function or procedure is the
        !          1496: @dfn{definition} and parameters are implicitly passed between
        !          1497: definitions using a shared stack that is visible to the
        !          1498: programmer. Although Forth does support variables, the existence of the
        !          1499: stack means that they are used far less often than in most other
        !          1500: programming languages. When the text interpreter encounters a number, it
        !          1501: will place (@dfn{push}) it on the stack. There are several stacks (the
        !          1502: actual number is implementation-dependent ..) and the particular stack
        !          1503: used for any operation is implied unambiguously by the operation being
        !          1504: performed. The stack used for all integer operations is called the @dfn{data
        !          1505: stack} and, since this is the stack used most commonly, references to
        !          1506: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    1507: 
1.29    ! crook    1508: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    1509: 
1.23      crook    1510: @example
1.29    ! crook    1511: @kbd{1 2 3<return>}  ok
1.23      crook    1512: @end example
1.21      crook    1513: 
1.29    ! crook    1514: Then this instructs the text interpreter to placed three numbers on the
        !          1515: (data) stack. An analogy for the behaviour of the stack is to take a
        !          1516: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
        !          1517: the table. The 3 was the last card onto the pile (``last-in'') and if
        !          1518: you take a card off the pile then, unless you're prepared to fiddle a
        !          1519: bit, the card that you take off will be the 3 (``first-out''). The
        !          1520: number that will be first-out of the stack is called the @dfn{top of
        !          1521: stack}, which
        !          1522: @cindex TOS definition
        !          1523: is often abbreviated to @dfn{TOS}.
1.21      crook    1524: 
1.29    ! crook    1525: To understand how parameters are passed in Forth, consider the
        !          1526: behaviour of the definition @code{+} (pronounced ``plus''). You will not
        !          1527: be surprised to learn that this definition performs addition. More
        !          1528: precisely, it adds two number together and produces a result. Where does
        !          1529: it get the two numbers from? It takes the top two numbers off the
        !          1530: stack. Where does it place the result? On the stack. You can act-out the
        !          1531: behaviour of @code{+} with your playing cards like this:
1.21      crook    1532: 
                   1533: @itemize @bullet
                   1534: @item
1.29    ! crook    1535: Pick up two cards from the stack on the table
1.21      crook    1536: @item
1.29    ! crook    1537: Stare at them intently and ask yourself ``what @i{is} the sum of these two
        !          1538: numbers''
1.21      crook    1539: @item
1.29    ! crook    1540: Decide that the answer is 5
1.21      crook    1541: @item
1.29    ! crook    1542: Shuffle the two cards back into the pack and find a 5
1.21      crook    1543: @item
1.29    ! crook    1544: Put a 5 on the remaining ace that's on the table.
1.21      crook    1545: @end itemize
                   1546: 
1.29    ! crook    1547: If you don't have a pack of cards handy but you do have Forth running,
        !          1548: you can use the definition @code{.s} to show the current state of the stack,
        !          1549: without affecting the stack. Type:
1.21      crook    1550: 
                   1551: @example
1.29    ! crook    1552: @kbd{clearstack 1 2 3<return>} ok
        !          1553: @kbd{.s<return>} <3> 1 2 3  ok
1.23      crook    1554: @end example
                   1555: 
1.29    ! crook    1556: The text interpreter looks up the word @code{clearstack} and executes
        !          1557: it; it tidies up the stack and removes any entries that may have been
        !          1558: left on it by earlier examples. The text interpreter pushes each of the
        !          1559: three numbers in turn onto the stack. Finally, the text interpreter
        !          1560: looks up the word @code{.s} and executes it. The effect of executing
        !          1561: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
        !          1562: followed by a list of all the items on the stack; the item on the far
        !          1563: right-hand side is the TOS.
1.21      crook    1564: 
1.29    ! crook    1565: You can now type:
1.21      crook    1566: 
1.29    ! crook    1567: @example
        !          1568: @kbd{+ .s<return>} <2> 1 5  ok
        !          1569: @end example
1.21      crook    1570: 
1.29    ! crook    1571: @noindent
        !          1572: which is correct; there are now 2 items on the stack and the result of
        !          1573: the addition is 5.
1.23      crook    1574: 
1.29    ! crook    1575: If you're playing with cards, try doing a second addition: pick up the
        !          1576: two cards, work out that their sum is 6, shuffle them into the pack,
        !          1577: look for a 6 and place that on the table. You now have just one item on
        !          1578: the stack. What happens if you try to do a third addition? Pick up the
        !          1579: first card, pick up the second card -- ah! There is no second card. This
        !          1580: is called a @dfn{stack underflow} and consitutes an error. If you try to
        !          1581: do the same thing with Forth it will report an error (probably a Stack
        !          1582: Underflow or an Invalid Memory Address error).
1.23      crook    1583: 
1.29    ! crook    1584: The opposite situation to a stack underflow is a @dfn{stack overflow},
        !          1585: which simply accepts that there is a finite amount of storage space
        !          1586: reserved for the stack. To stretch the playing card analogy, if you had
        !          1587: enough packs of cards and you piled the cards up on the table, you would
        !          1588: eventually be unable to add another card; you'd hit the ceiling. Gforth
        !          1589: allows you to set the maximum size of the stacks. In general, the only
        !          1590: time that you will get a stack overflow is because a definition has a
        !          1591: bug in it and is generating data on the stack uncontrollably.
1.23      crook    1592: 
1.29    ! crook    1593: There's one final use for the playing card analogy. If you model your
        !          1594: stack using a pack of playing cards, the maximum number of items on
        !          1595: your stack will be 52 (I assume you didn't use the Joker). The maximum
        !          1596: @i{value} of any item on the stack is 13 (the King). In fact, the only
        !          1597: possible numbers are positive integer numbers 1 through 13; you can't
        !          1598: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
        !          1599: think about some of the cards, you can accommodate different
        !          1600: numbers. For example, you could think of the Jack as representing 0,
        !          1601: the Queen as representing -1 and the King as representing -2. Your
        !          1602: *range* remains unchanged (you can still only represent a total of 13
        !          1603: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    1604: 
1.29    ! crook    1605: In that analogy, the limit was the amount of information that a single
        !          1606: stack entry could hold, and Forth has a similar limit. In Forth, the
        !          1607: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
        !          1608: implementation dependent and affects the maximum value that a stack
        !          1609: entry can hold. A Standard Forth provides a cell size of at least
        !          1610: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    1611: 
1.29    ! crook    1612: Forth does not do any type checking for you, so you are free to
        !          1613: manipulate and combine stack items in any way you wish. A convenient way
        !          1614: of treating stack items is as 2's complement signed integers, and that
        !          1615: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    1616: 
1.29    ! crook    1617: @example
        !          1618: @kbd{-5 12 + .s<return>} <1> 7  ok
        !          1619: @end example
1.21      crook    1620: 
1.29    ! crook    1621: If you use numbers and definitions like @code{+} in order to turn Forth
        !          1622: into a great big pocket calculator, you will realise that it's rather
        !          1623: different from a normal calculator. Rather than typing 2 + 3 = you had
        !          1624: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
        !          1625: result). The terminology used to describe this difference is to say that
        !          1626: your calculator uses @dfn{Infix Notation} (parameters and operators are
        !          1627: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
        !          1628: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    1629: 
1.29    ! crook    1630: Whilst postfix notation might look confusing to begin with, it has
        !          1631: several important advantages:
1.21      crook    1632: 
1.23      crook    1633: @itemize @bullet
                   1634: @item
1.29    ! crook    1635: it is unambiguous
1.23      crook    1636: @item
1.29    ! crook    1637: it is more concise
1.23      crook    1638: @item
1.29    ! crook    1639: it fits naturally with a stack-based system
1.23      crook    1640: @end itemize
1.21      crook    1641: 
1.29    ! crook    1642: To examine these claims in more detail, consider these sums:
1.21      crook    1643: 
1.29    ! crook    1644: @example
        !          1645: 6 + 5 * 4 =
        !          1646: 4 * 5 + 6 =
        !          1647: @end example
1.21      crook    1648: 
1.29    ! crook    1649: If you're just learning maths or your maths is very rusty, you will
        !          1650: probably come up with the answer 44 for the first and 26 for the
        !          1651: second. If you are a bit of a whizz at maths you will remember the
        !          1652: @i{convention} that multiplication takes precendence over addition, and
        !          1653: you'd come up with the answer 26 both times. To explain the answer 26
        !          1654: to someone who got the answer 44, you'd probably rewrite the first sum
        !          1655: like this:
1.21      crook    1656: 
1.29    ! crook    1657: @example
        !          1658: 6 + (5 * 4) =
        !          1659: @end example
1.21      crook    1660: 
1.29    ! crook    1661: If what you really wanted was to perform the addition before the
        !          1662: multiplication, you would have to use parentheses to force it.
1.21      crook    1663: 
1.29    ! crook    1664: If you did the first two sums on a pocket calculator you would probably
        !          1665: get the right answers, unless you were very cautious and entered them using
        !          1666: these keystroke sequences:
1.21      crook    1667: 
1.29    ! crook    1668: 6 + 5 = * 4 =
        !          1669: 4 * 5 = + 6 =
1.21      crook    1670: 
1.29    ! crook    1671: Postfix notation is unambiguous because the order that the operators
        !          1672: are applied is always explicit; that also means that parentheses are
        !          1673: never required. The operators are @i{active} (the act of quoting the
        !          1674: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    1675: 
1.29    ! crook    1676: The sum 6 + 5 * 4 can be written (in postfix notation) in two
        !          1677: equivalent ways:
1.26      crook    1678: 
                   1679: @example
1.29    ! crook    1680: 6 5 4 * +      or:
        !          1681: 5 4 * 6 +
1.26      crook    1682: @end example
1.23      crook    1683: 
1.29    ! crook    1684: An important thing that you should notice about this notation is that
        !          1685: the @i{order} of the numbers does not change; if you want to subtract
        !          1686: 2 from 10 you type @code{10 2 -}.
1.1       anton    1687: 
1.29    ! crook    1688: The reason that Forth uses postfix notation is very simple to explain: it
        !          1689: makes the implementation extremely simple, and it follows naturally from
        !          1690: using the stack as a mechanism for passing parameters. Another way of
        !          1691: thinking about this is to realise that all Forth definitions are
        !          1692: @i{active}; they execute as they are encountered by the text
        !          1693: interpreter. The result of this is that the syntax of Forth is trivially
        !          1694: simple.
1.1       anton    1695: 
                   1696: 
                   1697: 
1.29    ! crook    1698: @comment ----------------------------------------------
        !          1699: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
        !          1700: @section Your first Forth definition
        !          1701: @cindex first definition
1.1       anton    1702: 
1.29    ! crook    1703: Until now, the examples we've seen have been trivial; we've just been
        !          1704: using Forth as a bigger-than-pocket calculator. Also, each calculation
        !          1705: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
        !          1706: again@footnote{That's not quite true. If you press the up-arrow key on
        !          1707: your keyboard you should be able to scroll back to any earlier command,
        !          1708: edit it and re-enter it.} In this section we'll see how to add new
        !          1709: words to Forth's vocabulary.
1.1       anton    1710: 
1.29    ! crook    1711: The easiest way to create a new word is to use a @dfn{colon
        !          1712: definition}. We'll define a few and try them out before worrying too
        !          1713: much about how they work. Try typing in these examples; be careful to
        !          1714: copy the spaces accurately:
1.1       anton    1715: 
1.29    ! crook    1716: @example
        !          1717: : add-two 2 + . ;
        !          1718: : greet ." Hello and welcome" ;
        !          1719: : demo 5 add-two ;
        !          1720: @end example
1.1       anton    1721: 
1.29    ! crook    1722: @noindent
        !          1723: Now try them out:
1.1       anton    1724: 
1.29    ! crook    1725: @example
        !          1726: @kbd{greet<return>} Hello and welcome  ok
        !          1727: @kbd{greet greet<return>} Hello and welcomeHello and welcome  ok
        !          1728: @kbd{4 add-two<return>} 6  ok
        !          1729: @kbd{demo<return>} 7  ok
        !          1730: @kbd{9 greet demo add-two<return>} Hello and welcome7 11  ok
        !          1731: @end example
1.1       anton    1732: 
1.29    ! crook    1733: The first new thing that we've introduced here is the pair of words
        !          1734: @code{:} and @code{;}. These are used to start and terminate a new
        !          1735: definition, respectively. The first word after the @code{:} is the name
        !          1736: for the new definition.
1.1       anton    1737: 
1.29    ! crook    1738: As you can see from the examples, a definition is built up of words that
        !          1739: have already been defined; Forth makes no distinction between
        !          1740: definitions that existed when you started the system up, and those that
        !          1741: you define yourself.
1.1       anton    1742: 
1.29    ! crook    1743: The examples also introduce the words @code{.} (dot), @code{."}
        !          1744: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
        !          1745: the stack and displays it. It's like @code{.s} except that it only
        !          1746: displays the top item of the stack and it is destructive; after it has
        !          1747: executed, the number is no longer on the stack. There is always one
        !          1748: space printed after the number, and no spaces before it. Dot-quote
        !          1749: defines a string (a sequence of characters) that will be printed when
        !          1750: the word is executed. The string can contain any printable characters
        !          1751: except @code{"}. A @code{"} has a special function; it is not a Forth
        !          1752: word but it acts as a delimiter (the way that delimiters work is
        !          1753: described in the next section). Finally, @code{dup} duplicates the value
        !          1754: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    1755: 
1.29    ! crook    1756: We already know that the text interpreter searches through the
        !          1757: dictionary to locate names. If you've followed the examples earlier, you
        !          1758: will already have a definition called @code{add-two}. Lets try modifying
        !          1759: it by typing in a new definition:
1.1       anton    1760: 
1.29    ! crook    1761: @example
        !          1762: @kbd{: add-two dup . ." + 2 =" 2 + . ;<return>} redefined add-two  ok
        !          1763: @end example
1.5       anton    1764: 
1.29    ! crook    1765: Forth recognised that we were defining a word that already exists, and
        !          1766: printed a message to warn us of that fact. Let's try out the new
        !          1767: definition:
1.5       anton    1768: 
1.29    ! crook    1769: @example
        !          1770: @kbd{9 add-two<return>} 9 + 2 =11  ok
        !          1771: @end example
1.1       anton    1772: 
1.29    ! crook    1773: @noindent
        !          1774: All that we've actually done here, though, is to create a new
        !          1775: definition, with a particular name. The fact that there was already a
        !          1776: definition with the same name did not make any difference to the way
        !          1777: that the new definition was created (except that Forth printed a warning
        !          1778: message). The old definition of add-two still exists (try @code{demo}
        !          1779: again to see that this is true). Any new definition will use the new
        !          1780: definition of @code{add-two}, but old definitions continue to use the
        !          1781: version that already existed at the time that they were @code{compiled}.
1.1       anton    1782: 
1.29    ! crook    1783: Before you go on to the next section, try defining and redefining some
        !          1784: words of your own.
1.1       anton    1785: 
1.29    ! crook    1786: @comment ----------------------------------------------
        !          1787: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
        !          1788: @section How does that work?
        !          1789: @cindex parsing words
1.1       anton    1790: 
1.29    ! crook    1791: Now we're going to take another look at the definition of @code{add-two}
        !          1792: from the previous section. From our knowledge of the way that the text
        !          1793: interpreter works, we would have expected this result when we tried to
        !          1794: define @code{add-two}:
1.21      crook    1795: 
1.29    ! crook    1796: @example
        !          1797: @kbd{: add-two 2 + . " ;<return>}
        !          1798:   ^^^^^^^
        !          1799: Error: Undefined word
        !          1800: @end example
1.28      crook    1801: 
1.29    ! crook    1802: The reason that this didn't happen is bound up in the way that @code{:}
        !          1803: works. The word @code{:} does two special things. The first special
        !          1804: thing that it does prevents the text interpreter from ever seeing the
        !          1805: characters @code{add-two}. The text interpreter uses a variable called
        !          1806: @cindex modifying >IN
        !          1807: @code{>IN} (pronounced ''to-in'') to keep track of where it is in the
        !          1808: input line. When it encounters the word @code{:} it behaves in exactly
        !          1809: the same way as it does for any other word; it looks it up in the name
        !          1810: dictionary, finds its xt and executes it. When @code{:} executes, it
        !          1811: looks at the input buffer, finds the word @code{add-two} and advances the
        !          1812: value of @code{>IN} to point past it. It then does some other stuff
        !          1813: associated with creating the new definition (including creating an entry
        !          1814: for @code{add-two} in the name dictionary). When the execution of @code{:}
        !          1815: completes, control returns to the text interpreter, which is oblivious
        !          1816: to the fact that it has been tricked into ignoring part of the input
        !          1817: line.
1.21      crook    1818: 
1.29    ! crook    1819: @cindex parsing words
        !          1820: Words like @code{:} -- words that advance the value of @code{>IN} and so
        !          1821: prevent the text interpreter from acting on the whole of the input line
        !          1822: -- are called @dfn{parsing words}.
1.21      crook    1823: 
1.29    ! crook    1824: @cindex @code{state} - effect on the text interpreter
        !          1825: @cindex text interpreter - effect of state
        !          1826: The second special thing that @code{:} does is change the value of a
        !          1827: variable called @code{state}, which affects the way that the text
        !          1828: interpreter behaves. When Gforth starts up, @code{state} has the value
        !          1829: 0, and the text interpreter is said to be @dfn{interpreting}. During a
        !          1830: colon definition (started with @code{:}), @code{state} is set to -1 and
        !          1831: the text interpreter is said to be @dfn{compiling}. The word @code{;}
        !          1832: ends the definition -- one of the things that it does is to change the
        !          1833: value of @code{state} back to 0.
1.21      crook    1834: 
1.29    ! crook    1835: We have already seen how the text interpreter behaves when it is
        !          1836: interpreting; it looks for each character sequence in the dictionary,
        !          1837: finds its xt and executes it, or it converts it to a number and pushes
        !          1838: it onto the stack, or it fails to do either and generates an error.
1.21      crook    1839: 
1.29    ! crook    1840: When the text interpreter is compiling, its behaviour is slightly
        !          1841: different; it still looks for each character sequence in the dictionary
        !          1842: and finds its xt, or converts it to a number, or fails to do either and
        !          1843: generates an error. However, instead of executing the xt or pushing the
        !          1844: number onto the stack it lays down (@dfn{compiles}) some magic to make
        !          1845: that xt or number get executed or pushed at a later time; at the time
        !          1846: that @code{add-two} is @dfn{executed}. Therefore, when you execute
        !          1847: @code{add-two} its @dfn{run-time effect} is exactly the same as if you
        !          1848: had typed @code{2 + .} outside of a definition, and pressed
        !          1849: carriage-return.
1.28      crook    1850: 
1.29    ! crook    1851: In Forth, every word or number can be described in terms of three
        !          1852: properties:
1.28      crook    1853: 
                   1854: @itemize @bullet
                   1855: @item
1.29    ! crook    1856: Its behaviour at @dfn{compile} time
1.28      crook    1857: @item
1.29    ! crook    1858: Its behaviour at @dfn{interpret} time
1.28      crook    1859: @item
1.29    ! crook    1860: Its behaviour at @dfn{execution} time.
        !          1861: @end itemize
        !          1862: 
        !          1863: These behaviours are called the @dfn{semantics} of the word or
        !          1864: number. The value of @code{state} determines whether the text
        !          1865: interpreter will use the compilation or interpretation semantics of a
        !          1866: word or number that it encounters.
        !          1867: 
        !          1868: @itemize @bullet
1.28      crook    1869: @item
1.29    ! crook    1870: @cindex interpretation semantics
        !          1871: When the text interpreter encounters a word or number in @dfn{interpret}
        !          1872: state, it performs the @dfn{interpretation semantics} of the word or
        !          1873: number.
1.28      crook    1874: @item
1.29    ! crook    1875: @cindex compilation semantics
        !          1876: When the text interpreter encounters a word or number in @dfn{compile}
        !          1877: state, it performs the @dfn{compilation semantics} of the word or
        !          1878: number.
        !          1879: @end itemize
        !          1880: 
        !          1881: @noindent
        !          1882: Numbers are always treated in a fixed way:
        !          1883: 
        !          1884: @itemize @bullet
1.28      crook    1885: @item
1.29    ! crook    1886: When the number is @dfn{compiled}, it is appended to the current
        !          1887: definition so that its run-time behaviour is to execute. (In other
        !          1888: words, the compilation semantics of a number are to postpone its
        !          1889: execution semantics until the run-time of the definition that it is
        !          1890: being compiled into.)
1.28      crook    1891: @item
1.29    ! crook    1892: When the number is @dfn{interpreted}, its behaviour is to execute. (In
        !          1893: other words, the interpretation semantics of a number are to perform its
        !          1894: execution semantics.)
1.28      crook    1895: @item
1.29    ! crook    1896: @cindex execution semantics
        !          1897: When the number is @dfn{executed}, its behaviour is to push its value
        !          1898: onto the stack. (In other words, the execution semantics of a number are
        !          1899: to push its value onto the stack.)
        !          1900: @end itemize
        !          1901: 
        !          1902: 
        !          1903: The behaviour of a word is not so regular, but most have @i{default
        !          1904: semantics} which means that they behave like this:
        !          1905: 
        !          1906: @itemize @bullet
1.28      crook    1907: @item
1.29    ! crook    1908: The @dfn{compilation semantics} of the word are to append its
        !          1909: @dfn{execution semantics} to the current definition (so that its
        !          1910: run-time behaviour is to execute).
1.28      crook    1911: @item
1.29    ! crook    1912: The @dfn{interpretation semantics} of the word are to execute.
1.28      crook    1913: @item
1.29    ! crook    1914: The @dfn{execution semantics} of the word are to do something useful.
1.28      crook    1915: @end itemize
                   1916: 
                   1917: 
1.29    ! crook    1918: The actual behaviour of any particular word depends upon the way in
        !          1919: which it was defined. When the text interpreter finds the word in the
        !          1920: name dictionary, it not only retrieves the xt for the word, it also
        !          1921: retrieves some flags: the @dfn{compile-only} flag and the @dfn{immediate
        !          1922: flag}. The compile-only flag indicates that the word has no
        !          1923: interpretation semantics; any attempt to interpret a word that has the
        !          1924: compile-only flag set will generate an error (for example, @code{IF} has
        !          1925: no interpretation semantics). The immediate flag changes the compilation
        !          1926: semantics of the word; if it is set, the text interpreter will
        !          1927: @dfn{execute} the word rather than @dfn{compiling}
        !          1928: @cindex immediate words
        !          1929: it. In other words, these so-called @dfn{immediate} words behave like
        !          1930: this:
        !          1931: 
        !          1932: @itemize @bullet
        !          1933: @item
        !          1934: The @dfn{compilation semantics} of the word are to perform its
        !          1935: @dfn{execution semantics} (so that its compile-time behaviour is to
        !          1936: execute).
        !          1937: @item
        !          1938: The @dfn{interpretation semantics} of the word are to execute.
        !          1939: @item
        !          1940: The @dfn{execution semantics} of the word are to do something useful.
        !          1941: @end itemize
1.28      crook    1942: 
1.29    ! crook    1943: This example shows the difference between an immediate and a
        !          1944: non-immediate word:
1.28      crook    1945: 
1.29    ! crook    1946: @example
        !          1947: : show-state state @@ . ;
        !          1948: : show-state-now show-state ; immediate
        !          1949: : word1 show-state ;
        !          1950: : word2 show-state-now ;
1.28      crook    1951: @end example
1.23      crook    1952: 
1.29    ! crook    1953: The word @code{immediate} after the definition of @code{show-state-now}
        !          1954: makes that word an immediate word. These definitions introduce a new
        !          1955: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
        !          1956: variable, and leaves it on the stack. Therefore, the behaviour of
        !          1957: @code{show-state} is to print a number that represents the current value
        !          1958: of @code{state}.
1.28      crook    1959: 
1.29    ! crook    1960: When you execute @code{word1}, it prints the number 0, indicating that
        !          1961: the system is interpreting. When the text interpreter compiled the
        !          1962: definition of @code{word1}, it encountered @code{show-state} whose
        !          1963: compilation semantics are to append its execution semantics to the
        !          1964: current definition. When you execute @code{word1}, it performs the
        !          1965: execution semantics of @code{show-state}.  At the time that @code{word1}
        !          1966: (and therefore @code{show-state}) are executed, the system is
        !          1967: interpreting.
1.28      crook    1968: 
1.29    ! crook    1969: When you pressed <return> after entering the definition of @code{word2},
        !          1970: you should have seen the number -1 printed, followed by ``@code{
        !          1971: ok}''. When the text interpreter compiled the definition of
        !          1972: @code{word2}, it encountered @code{show-state-now}, an immediate word,
        !          1973: whose compilation semantics are therefore to perform its execution
        !          1974: semantics. It is executed straight away (even before the text
        !          1975: interpreter has moved on to process another group of characters; the
        !          1976: @code{;} in this example). The effect of executing it are to display the
        !          1977: value of @code{state} @i{at the time that the definition of}
        !          1978: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
        !          1979: system is compiling at this time. If you execute @code{word2} it does
        !          1980: nothing at all.
1.28      crook    1981: 
1.29    ! crook    1982: @cindex @code{."}, how it works
        !          1983: Before leaving the subject of immediate words, consider the behaviour of
        !          1984: @code{."} in the definition of @code{greet}, in the previous
        !          1985: section. This word is both a parsing word and an immediate word. Notice
        !          1986: that there is a space between @code{."} and the start of the text
        !          1987: @code{Hello and welcome}, but that there is no space between the last
        !          1988: letter of @code{welcome} and the @code{"} character. The reason for this
        !          1989: is that @code{."} is a Forth word; it must have a space after it so that
        !          1990: the text interpreter can identify it. The @code{"} is not a Forth word;
        !          1991: it is a @dfn{delimiter}. The examples earlier show that, when the string
        !          1992: is displayed, there is neither a space before the @code{H} nor after the
        !          1993: @code{e}. Since @code{."} is an immediate word, it executes at the time
        !          1994: that @code{greet} is defined. When it executes, its behaviour is to
        !          1995: search forward in the input line looking for the delimiter. When it
        !          1996: finds the delimiter, it updates @code{>IN} to point past the
        !          1997: delimiter. It also compiles some magic code into the definition of
        !          1998: @code{greet}; the xt of a run-time routine that prints a text string. It
        !          1999: compiles the string @code{Hello and welcome} into memory so that it is
        !          2000: available to be printed later. When the text interpreter gains control,
        !          2001: the next word it finds in the input stream is @code{;} and so it
        !          2002: terminates the definition of @code{greet}.
1.28      crook    2003: 
                   2004: 
                   2005: @comment ----------------------------------------------
1.29    ! crook    2006: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
        !          2007: @section Forth is written in Forth
        !          2008: @cindex structure of Forth programs
        !          2009: 
        !          2010: When you start up a Forth compiler, a large number of definitions
        !          2011: already exist. In Forth, you develop a new application using bottom-up
        !          2012: programming techniques to create new definitions that are defined in
        !          2013: terms of existing definitions. As you create each definition you can
        !          2014: test and debug it interactively.
        !          2015: 
        !          2016: If you have tried out the examples in this section, you will probably
        !          2017: have typed them in by hand; when you leave Gforth, your definitions will
        !          2018: be lost. You can avoid this by using a text editor to enter Forth source
        !          2019: code into a file, and then loading code from the file using
        !          2020: @code{include} (@xref{Forth source files}). A Forth source file is
        !          2021: processed by the text interpreter, just as though you had typed it in by
        !          2022: hand@footnote{Actually, there are some subtle differences -- see
        !          2023: @ref{The Text Interpreter}.}.
        !          2024: 
        !          2025: Gforth also supports the traditional Forth alternative to using text
        !          2026: files for program entry (@xref{Blocks}).
1.28      crook    2027: 
1.29    ! crook    2028: In common with many, if not most, Forth compilers, most of Gforth is
        !          2029: actually written in Forth. All of the @file{.fs} files in the
        !          2030: installation directory@footnote{For example,
        !          2031: @file{/usr/local/share/gforth..}} are Forth source files, which you can
        !          2032: study to see examples of Forth programming.
1.28      crook    2033: 
1.29    ! crook    2034: Gforth maintains a history file that records every line that you type to
        !          2035: the text interpreter. This file is preserved between sessions, and is
        !          2036: used to provide a command-line recall facility. If you enter long
        !          2037: definitions by hand, you can use a text editor to paste them out of the
        !          2038: history file into a Forth source file for reuse at a later time
        !          2039: (@pxref{Command-line editing} for more information).
1.28      crook    2040: 
                   2041: 
                   2042: @comment ----------------------------------------------
1.29    ! crook    2043: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
        !          2044: @section Review - elements of a Forth system
        !          2045: @cindex elements of a Forth system
1.28      crook    2046: 
1.29    ! crook    2047: To summarise this chapter:
1.28      crook    2048: 
                   2049: @itemize @bullet
                   2050: @item
1.29    ! crook    2051: Forth programs use @dfn{factoring} to break a problem down into small
        !          2052: fragments called @dfn{words} or @dfn{definitions}.
        !          2053: @item
        !          2054: Forth program development is an interactive process.
        !          2055: @item
        !          2056: The main command loop that accepts input, and controls both
        !          2057: interpretation and compilation, is called the @dfn{text interpreter}
        !          2058: (also known as the @dfn{outer interpreter}).
        !          2059: @item
        !          2060: Forth has a very simple syntax, consisting of words and numbers
        !          2061: separated by spaces or carriage-return characters. Any additional syntax
        !          2062: is imposed by @dfn{parsing words}.
        !          2063: @item
        !          2064: Forth uses a stack to pass parameters between words. As a result, it
        !          2065: uses postfix notation.
        !          2066: @item
        !          2067: To use a word that has previously been defined, the text interpreter
        !          2068: searches for the word in the @dfn{name dictionary}.
        !          2069: @item
        !          2070: Words have @dfn{interpretation semantics}, @dfn{compilation semantics}
        !          2071: and @dfn{execution semantics}.
1.28      crook    2072: @item
1.29    ! crook    2073: The text interpreter uses the value of @code{state} to select between
        !          2074: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
        !          2075: semantics} of a word that it encounters.
1.28      crook    2076: @item
1.29    ! crook    2077: The relationship between the @dfn{interpretation semantics},
        !          2078: @dfn{compilation semantics} and @dfn{execution semantics} for a word
        !          2079: depend upon the way in which the word was defined (for example, whether
        !          2080: it is an @dfn{immediate} word).
1.28      crook    2081: @item
1.29    ! crook    2082: Forth definitions can be implemented in Forth (called @dfn{high-level
        !          2083: definitions}) or in some other way (usually a lower-level language and
        !          2084: as a result often called @dfn{low-level definitions}, @dfn{code
        !          2085: definitions} or @dfn{primitives}).
1.28      crook    2086: @item
1.29    ! crook    2087: Many Forth systems are implemented mainly in Forth.
1.28      crook    2088: @end itemize
                   2089: 
                   2090: 
1.29    ! crook    2091: @comment ----------------------------------------------
        !          2092: @node Where to go next,Exercises,Review - elements of a Forth system, Introduction
        !          2093: @section Where To Go Next
        !          2094: @cindex where to go next
1.28      crook    2095: 
1.29    ! crook    2096: Amazing as it may seem, if you have read (and understood) this far, you
        !          2097: know almost all the fundamentals about the inner workings of a Forth
        !          2098: system. You certainly know enough to be able to read and understand the
        !          2099: rest of this manual and the ANS Forth document, to learn more about the
        !          2100: facilities that Forth in general and Gforth in particular provide. Even
        !          2101: scarier, you know almost enough to implement your own Forth system.
        !          2102: However, that's not a good idea just yet.. better to try writing some
        !          2103: programs in Gforth.
1.28      crook    2104: 
1.29    ! crook    2105: Forth has such a rich vocabulary that it can be hard to know where to
        !          2106: start in learning it. This section suggests a few sets of words that are
        !          2107: enough to write small but useful programs. Use the word index in this
        !          2108: document to learn more about each word, then try it out and try to write
        !          2109: small definitions using it. Start by experimenting with these words:
1.28      crook    2110: 
                   2111: @itemize @bullet
                   2112: @item
1.29    ! crook    2113: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
        !          2114: @item
        !          2115: Comparison: @code{MIN MAX =}
        !          2116: @item
        !          2117: Logic: @code{AND OR XOR NOT}
        !          2118: @item
        !          2119: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    2120: @item
1.29    ! crook    2121: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    2122: @item
1.29    ! crook    2123: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    2124: @item
1.29    ! crook    2125: Defining words: @code{: ; CREATE}
1.28      crook    2126: @item
1.29    ! crook    2127: Memory allocation words: @code{ALLOT ,}
1.28      crook    2128: @item
1.29    ! crook    2129: Tools: @code{SEE WORDS .S MARKER}
        !          2130: @end itemize
        !          2131: 
        !          2132: When you have mastered those, go on to:
        !          2133: 
        !          2134: @itemize @bullet
1.28      crook    2135: @item
1.29    ! crook    2136: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    2137: @item
1.29    ! crook    2138: Memory access: @code{@@ !}
1.28      crook    2139: @end itemize
1.23      crook    2140: 
1.29    ! crook    2141: When you have mastered these, there's nothing for it but to read through
        !          2142: the whole of this manual and find out what you've missed.
        !          2143: 
        !          2144: @comment ----------------------------------------------
        !          2145: @node Exercises, ,Where to go next, Introduction
        !          2146: @section Exercises
        !          2147: @cindex exercises
        !          2148: 
        !          2149: TODO: provide a set of programming excercises linked into the stuff done
        !          2150: already and into other sections of the manual. Provide solutions to all
        !          2151: the exercises in a .fs file in the distribution.
        !          2152: 
        !          2153: @c Get some inspiration from Starting Forth and Kelly&Spies.
        !          2154: 
        !          2155: @c excercises:
        !          2156: @c 1. take inches and convert to feet and inches.
        !          2157: @c 2. take temperature and convert from fahrenheight to celcius;
        !          2158: @c    may need to care about symmetric vs floored??
        !          2159: @c 3. take input line and do character substitution
        !          2160: @c    to encipher or decipher
        !          2161: @c 4. as above but work on a file for in and out
        !          2162: @c 5. take input line and convert to pig-latin 
        !          2163: @c
        !          2164: @c thing of sets of things to exercise then come up with
        !          2165: @c problems that need those things.
        !          2166: 
        !          2167: 
1.26      crook    2168: @c ******************************************************************
1.29    ! crook    2169: @node Words, Error messages, Introduction, Top
1.1       anton    2170: @chapter Forth Words
1.26      crook    2171: @cindex words
1.1       anton    2172: 
                   2173: @menu
                   2174: * Notation::                    
1.21      crook    2175: * Comments::
                   2176: * Boolean Flags::
1.1       anton    2177: * Arithmetic::                  
                   2178: * Stack Manipulation::          
1.5       anton    2179: * Memory::                      
1.1       anton    2180: * Control Structures::          
                   2181: * Defining Words::              
1.21      crook    2182: * The Text Interpreter::
1.12      anton    2183: * Tokens for Words::            
1.21      crook    2184: * Word Lists::                   
                   2185: * Environmental Queries::
1.12      anton    2186: * Files::                       
                   2187: * Blocks::                      
                   2188: * Other I/O::                   
                   2189: * Programming Tools::           
                   2190: * Assembler and Code Words::    
                   2191: * Threading Words::             
1.26      crook    2192: * Locals::                      
                   2193: * Structures::                  
                   2194: * Object-oriented Forth::       
1.21      crook    2195: * Passing Commands to the OS::
                   2196: * Miscellaneous Words::
1.1       anton    2197: @end menu
                   2198: 
1.21      crook    2199: @node Notation, Comments, Words, Words
1.1       anton    2200: @section Notation
                   2201: @cindex notation of glossary entries
                   2202: @cindex format of glossary entries
                   2203: @cindex glossary notation format
                   2204: @cindex word glossary entry format
                   2205: 
                   2206: The Forth words are described in this section in the glossary notation
                   2207: that has become a de-facto standard for Forth texts, i.e.,
                   2208: 
                   2209: @format
1.29    ! crook    2210: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    2211: @end format
1.29    ! crook    2212: @i{Description}
1.1       anton    2213: 
                   2214: @table @var
                   2215: @item word
1.28      crook    2216: The name of the word.
1.1       anton    2217: 
                   2218: @item Stack effect
                   2219: @cindex stack effect
1.29    ! crook    2220: The stack effect is written in the notation @code{@i{before} --
        !          2221: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    2222: stack entries before and after the execution of the word. The rest of
                   2223: the stack is not touched by the word. The top of stack is rightmost,
                   2224: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   2225: uses a separate floating point stack, but a unified stack
1.29    ! crook    2226: notation. Also, return stack effects are not shown in @i{stack
        !          2227: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    2228: the type and/or the function of the item. See below for a discussion of
                   2229: the types.
                   2230: 
                   2231: All words have two stack effects: A compile-time stack effect and a
                   2232: run-time stack effect. The compile-time stack-effect of most words is
1.29    ! crook    2233: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    2234: this standard behaviour, or the word does other unusual things at
                   2235: compile time, both stack effects are shown; otherwise only the run-time
                   2236: stack effect is shown.
                   2237: 
                   2238: @cindex pronounciation of words
                   2239: @item pronunciation
                   2240: How the word is pronounced.
                   2241: 
                   2242: @cindex wordset
                   2243: @item wordset
1.21      crook    2244: The ANS Forth standard is divided into several word sets. A standard
                   2245: system need not support all of them. Therefore, in theory, the fewer
                   2246: word sets your program uses the more portable it will be. However, we
                   2247: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    2248: all word sets. Words that are not defined in ANS Forth have
1.21      crook    2249: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    2250: describes words that will work in future releases of Gforth;
                   2251: @code{gforth-internal} words are more volatile. Environmental query
                   2252: strings are also displayed like words; you can recognize them by the
1.21      crook    2253: @code{environment} in the word set field.
1.1       anton    2254: 
                   2255: @item Description
                   2256: A description of the behaviour of the word.
                   2257: @end table
                   2258: 
                   2259: @cindex types of stack items
                   2260: @cindex stack item types
                   2261: The type of a stack item is specified by the character(s) the name
                   2262: starts with:
                   2263: 
                   2264: @table @code
                   2265: @item f
                   2266: @cindex @code{f}, stack item type
                   2267: Boolean flags, i.e. @code{false} or @code{true}.
                   2268: @item c
                   2269: @cindex @code{c}, stack item type
                   2270: Char
                   2271: @item w
                   2272: @cindex @code{w}, stack item type
                   2273: Cell, can contain an integer or an address
                   2274: @item n
                   2275: @cindex @code{n}, stack item type
                   2276: signed integer
                   2277: @item u
                   2278: @cindex @code{u}, stack item type
                   2279: unsigned integer
                   2280: @item d
                   2281: @cindex @code{d}, stack item type
                   2282: double sized signed integer
                   2283: @item ud
                   2284: @cindex @code{ud}, stack item type
                   2285: double sized unsigned integer
                   2286: @item r
                   2287: @cindex @code{r}, stack item type
                   2288: Float (on the FP stack)
1.21      crook    2289: @item a-
1.1       anton    2290: @cindex @code{a_}, stack item type
                   2291: Cell-aligned address
1.21      crook    2292: @item c-
1.1       anton    2293: @cindex @code{c_}, stack item type
                   2294: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    2295: @item f-
1.1       anton    2296: @cindex @code{f_}, stack item type
                   2297: Float-aligned address
1.21      crook    2298: @item df-
1.1       anton    2299: @cindex @code{df_}, stack item type
                   2300: Address aligned for IEEE double precision float
1.21      crook    2301: @item sf-
1.1       anton    2302: @cindex @code{sf_}, stack item type
                   2303: Address aligned for IEEE single precision float
                   2304: @item xt
                   2305: @cindex @code{xt}, stack item type
                   2306: Execution token, same size as Cell
                   2307: @item wid
                   2308: @cindex @code{wid}, stack item type
1.21      crook    2309: Word list ID, same size as Cell
1.1       anton    2310: @item f83name
                   2311: @cindex @code{f83name}, stack item type
                   2312: Pointer to a name structure
                   2313: @item "
                   2314: @cindex @code{"}, stack item type
1.12      anton    2315: string in the input stream (not on the stack). The terminating character
                   2316: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    2317: quotes.
                   2318: @end table
                   2319: 
1.21      crook    2320: @node Comments, Boolean Flags, Notation, Words
                   2321: @section Comments
1.26      crook    2322: @cindex comments
1.21      crook    2323: 
1.29    ! crook    2324: Forth supports two styles of comment; the traditional @i{in-line} comment,
        !          2325: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    2326: 
1.23      crook    2327: doc-(
1.21      crook    2328: doc-\
1.23      crook    2329: doc-\G
1.21      crook    2330: 
                   2331: @node Boolean Flags, Arithmetic, Comments, Words
                   2332: @section Boolean Flags
1.26      crook    2333: @cindex Boolean flags
1.21      crook    2334: 
                   2335: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   2336: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    2337: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29    ! crook    2338: a cell that has @i{any} bit set as @code{true}.
1.21      crook    2339: 
                   2340: doc-true
                   2341: doc-false
1.29    ! crook    2342: doc-on
        !          2343: doc-off
1.21      crook    2344: 
                   2345: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    2346: @section Arithmetic
                   2347: @cindex arithmetic words
                   2348: 
                   2349: @cindex division with potentially negative operands
                   2350: Forth arithmetic is not checked, i.e., you will not hear about integer
                   2351: overflow on addition or multiplication, you may hear about division by
                   2352: zero if you are lucky. The operator is written after the operands, but
                   2353: the operands are still in the original order. I.e., the infix @code{2-1}
                   2354: corresponds to @code{2 1 -}. Forth offers a variety of division
                   2355: operators. If you perform division with potentially negative operands,
                   2356: you do not want to use @code{/} or @code{/mod} with its undefined
                   2357: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   2358: former, @pxref{Mixed precision}).
1.26      crook    2359: @comment TODO discuss the different division forms and the std approach
1.1       anton    2360: 
                   2361: @menu
                   2362: * Single precision::            
                   2363: * Bitwise operations::          
1.21      crook    2364: * Double precision::            Double-cell integer arithmetic
                   2365: * Numeric comparison::
1.29    ! crook    2366: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    2367: * Floating Point::              
                   2368: @end menu
                   2369: 
                   2370: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
                   2371: @subsection Single precision
                   2372: @cindex single precision arithmetic words
                   2373: 
1.21      crook    2374: By default, numbers in Forth are single-precision integers that are 1
1.26      crook    2375: cell in size. They can be signed or unsigned, depending upon how you
1.21      crook    2376: treat them. @xref{Number Conversion} for the rules used by the text
                   2377: interpreter for recognising single-precision integers.
                   2378: 
1.1       anton    2379: doc-+
1.21      crook    2380: doc-1+
1.1       anton    2381: doc--
1.21      crook    2382: doc-1-
1.1       anton    2383: doc-*
                   2384: doc-/
                   2385: doc-mod
                   2386: doc-/mod
                   2387: doc-negate
                   2388: doc-abs
                   2389: doc-min
                   2390: doc-max
1.21      crook    2391: doc-d>s
1.27      crook    2392: doc-floored
1.1       anton    2393: 
1.21      crook    2394: @node Bitwise operations, Double precision, Single precision, Arithmetic
1.1       anton    2395: @subsection Bitwise operations
                   2396: @cindex bitwise operation words
                   2397: 
                   2398: doc-and
                   2399: doc-or
                   2400: doc-xor
                   2401: doc-invert
1.21      crook    2402: doc-lshift
                   2403: doc-rshift
1.1       anton    2404: doc-2*
1.21      crook    2405: doc-d2*
1.1       anton    2406: doc-2/
1.21      crook    2407: doc-d2/
                   2408: 
                   2409: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
                   2410: @subsection Double precision
                   2411: @cindex double precision arithmetic words
                   2412: 
                   2413: @xref{Number Conversion} for the rules used by the text interpreter for
                   2414: recognising double-precision integers.
                   2415: 
                   2416: A double precision number is represented by a cell pair, with the most
1.26      crook    2417: significant digit at the TOS. It is trivial to convert an unsigned
                   2418: single to an (unsigned) double; simply push a @code{0} onto the
                   2419: TOS. Since numbers are represented by Gforth using 2's complement
                   2420: arithmetic, converting a signed single to a (signed) double requires
                   2421: sign-extension across the most significant digit. This can be achieved
                   2422: using @code{s>d}. The moral of the story is that you cannot convert a
                   2423: number without knowing whether it represents an unsigned or a
                   2424: signed number.
1.21      crook    2425: 
                   2426: doc-s>d
                   2427: doc-d+
                   2428: doc-d-
                   2429: doc-dnegate
                   2430: doc-dabs
                   2431: doc-dmin
                   2432: doc-dmax
                   2433: 
                   2434: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
                   2435: @subsection Numeric comparison
                   2436: @cindex numeric comparison words
                   2437: 
1.28      crook    2438: doc-<
                   2439: doc-<=
                   2440: doc-<>
                   2441: doc-=
                   2442: doc->
                   2443: doc->=
                   2444: 
1.21      crook    2445: doc-0<
1.23      crook    2446: doc-0<=
1.21      crook    2447: doc-0<>
                   2448: doc-0=
1.23      crook    2449: doc-0>
                   2450: doc-0>=
1.28      crook    2451: 
                   2452: doc-u<
                   2453: doc-u<=
                   2454: @comment TODO why u<> and u= .. they are the same as <> and =
                   2455: doc-u<>
                   2456: doc-u=
                   2457: doc-u>
                   2458: doc-u>=
                   2459: 
                   2460: doc-within
                   2461: 
                   2462: doc-d<
                   2463: doc-d<=
                   2464: doc-d<>
                   2465: doc-d=
                   2466: doc-d>
                   2467: doc-d>=
1.23      crook    2468: 
1.21      crook    2469: doc-d0<
1.23      crook    2470: doc-d0<=
                   2471: doc-d0<>
1.21      crook    2472: doc-d0=
1.23      crook    2473: doc-d0>
                   2474: doc-d0>=
                   2475: 
1.21      crook    2476: doc-du<
1.28      crook    2477: doc-du<=
                   2478: doc-du<>
                   2479: doc-du=
                   2480: doc-du>
                   2481: doc-du>=
1.1       anton    2482: 
1.21      crook    2483: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    2484: @subsection Mixed precision
                   2485: @cindex mixed precision arithmetic words
                   2486: 
                   2487: doc-m+
                   2488: doc-*/
                   2489: doc-*/mod
                   2490: doc-m*
                   2491: doc-um*
                   2492: doc-m*/
                   2493: doc-um/mod
                   2494: doc-fm/mod
                   2495: doc-sm/rem
                   2496: 
1.21      crook    2497: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    2498: @subsection Floating Point
                   2499: @cindex floating point arithmetic words
                   2500: 
1.21      crook    2501: @xref{Number Conversion} for the rules used by the text interpreter for
                   2502: recognising floating-point numbers.
1.1       anton    2503: 
                   2504: @cindex angles in trigonometric operations
                   2505: @cindex trigonometric operations
                   2506: Angles in floating point operations are given in radians (a full circle
1.26      crook    2507: has 2 pi radians). Gforth has a separate floating point
                   2508: stack, but the documentation uses the unified notation.
1.1       anton    2509: 
                   2510: @cindex floating-point arithmetic, pitfalls
                   2511: Floating point numbers have a number of unpleasant surprises for the
                   2512: unwary (e.g., floating point addition is not associative) and even a few
                   2513: for the wary. You should not use them unless you know what you are doing
                   2514: or you don't care that the results you get are totally bogus. If you
                   2515: want to learn about the problems of floating point numbers (and how to
                   2516: avoid them), you might start with @cite{David Goldberg, What Every
                   2517: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
1.17      anton    2518: Computing Surveys 23(1):5@minus{}48, March 1991}
                   2519: (@url{http://www.validgh.com/goldberg/paper.ps}).
1.1       anton    2520: 
1.21      crook    2521: doc-d>f
                   2522: doc-f>d
1.1       anton    2523: doc-f+
                   2524: doc-f-
                   2525: doc-f*
                   2526: doc-f/
                   2527: doc-fnegate
                   2528: doc-fabs
                   2529: doc-fmax
                   2530: doc-fmin
                   2531: doc-floor
                   2532: doc-fround
                   2533: doc-f**
                   2534: doc-fsqrt
                   2535: doc-fexp
                   2536: doc-fexpm1
                   2537: doc-fln
                   2538: doc-flnp1
                   2539: doc-flog
                   2540: doc-falog
                   2541: doc-fsin
                   2542: doc-fcos
                   2543: doc-fsincos
                   2544: doc-ftan
                   2545: doc-fasin
                   2546: doc-facos
                   2547: doc-fatan
                   2548: doc-fatan2
                   2549: doc-fsinh
                   2550: doc-fcosh
                   2551: doc-ftanh
                   2552: doc-fasinh
                   2553: doc-facosh
                   2554: doc-fatanh
1.21      crook    2555: doc-pi
1.28      crook    2556: 
1.21      crook    2557: doc-f0<
1.28      crook    2558: doc-f0<=
                   2559: doc-f0<>
1.21      crook    2560: doc-f0=
1.28      crook    2561: doc-f0>
                   2562: doc-f0>=
                   2563: 
1.21      crook    2564: doc-f<
                   2565: doc-f<=
                   2566: doc-f<>
                   2567: doc-f=
                   2568: doc-f>
                   2569: doc-f>=
1.28      crook    2570: 
1.21      crook    2571: doc-f2*
                   2572: doc-f2/
                   2573: doc-1/f
                   2574: doc-f~
                   2575: doc-precision
                   2576: doc-set-precision
1.1       anton    2577: 
                   2578: @node Stack Manipulation, Memory, Arithmetic, Words
                   2579: @section Stack Manipulation
                   2580: @cindex stack manipulation words
                   2581: 
                   2582: @cindex floating-point stack in the standard
1.21      crook    2583: Gforth maintains a number of separate stacks:
                   2584: 
1.29    ! crook    2585: @cindex data stack
        !          2586: @cindex parameter stack
1.21      crook    2587: @itemize @bullet
                   2588: @item
1.29    ! crook    2589: A data stack (also known as the @dfn{parameter stack}) -- for
        !          2590: characters, cells, addresses, and double cells.
1.21      crook    2591: 
1.29    ! crook    2592: @cindex floating-point stack
1.21      crook    2593: @item
                   2594: A floating point stack -- for floating point numbers.
                   2595: 
1.29    ! crook    2596: @cindex return stack
1.21      crook    2597: @item
                   2598: A return stack -- for storing the return addresses of colon
                   2599: definitions and other data.
                   2600: 
1.29    ! crook    2601: @cindex locals stack
1.21      crook    2602: @item
                   2603: A locals stack for storing local variables.
                   2604: @end itemize
                   2605: 
                   2606: Whilst every sane Forth has a separate floating-point stack, it is not
                   2607: strictly required; an ANS Forth system could theoretically keep
                   2608: floating-point numbers on the data stack. As an additional difficulty,
                   2609: you don't know how many cells a floating-point number takes. It is
                   2610: reportedly possible to write words in a way that they work also for a
                   2611: unified stack model, but we do not recommend trying it. Instead, just
                   2612: say that your program has an environmental dependency on a separate
                   2613: floating-point stack.
                   2614: 
                   2615: doc-floating-stack
1.1       anton    2616: 
                   2617: @cindex return stack and locals
                   2618: @cindex locals and return stack
1.21      crook    2619: A Forth system is allowed to keep local variables on the
1.1       anton    2620: return stack. This is reasonable, as local variables usually eliminate
                   2621: the need to use the return stack explicitly. So, if you want to produce
1.21      crook    2622: a standard compliant program and you are using local variables in a
                   2623: word, forget about return stack manipulations in that word (refer to the
1.1       anton    2624: standard document for the exact rules).
                   2625: 
                   2626: @menu
                   2627: * Data stack::                  
                   2628: * Floating point stack::        
                   2629: * Return stack::                
                   2630: * Locals stack::                
                   2631: * Stack pointer manipulation::  
                   2632: @end menu
                   2633: 
                   2634: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   2635: @subsection Data stack
                   2636: @cindex data stack manipulation words
                   2637: @cindex stack manipulations words, data stack
                   2638: 
                   2639: doc-drop
                   2640: doc-nip
                   2641: doc-dup
                   2642: doc-over
                   2643: doc-tuck
                   2644: doc-swap
1.21      crook    2645: doc-pick
1.1       anton    2646: doc-rot
                   2647: doc--rot
                   2648: doc-?dup
                   2649: doc-roll
                   2650: doc-2drop
                   2651: doc-2nip
                   2652: doc-2dup
                   2653: doc-2over
                   2654: doc-2tuck
                   2655: doc-2swap
                   2656: doc-2rot
                   2657: 
                   2658: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   2659: @subsection Floating point stack
                   2660: @cindex floating-point stack manipulation words
                   2661: @cindex stack manipulation words, floating-point stack
                   2662: 
                   2663: doc-fdrop
                   2664: doc-fnip
                   2665: doc-fdup
                   2666: doc-fover
                   2667: doc-ftuck
                   2668: doc-fswap
1.21      crook    2669: doc-fpick
1.1       anton    2670: doc-frot
                   2671: 
                   2672: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   2673: @subsection Return stack
                   2674: @cindex return stack manipulation words
                   2675: @cindex stack manipulation words, return stack
                   2676: 
                   2677: doc->r
                   2678: doc-r>
                   2679: doc-r@
                   2680: doc-rdrop
                   2681: doc-2>r
                   2682: doc-2r>
                   2683: doc-2r@
                   2684: doc-2rdrop
                   2685: 
                   2686: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   2687: @subsection Locals stack
                   2688: 
1.26      crook    2689: @comment TODO
1.21      crook    2690: 
1.1       anton    2691: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   2692: @subsection Stack pointer manipulation
                   2693: @cindex stack pointer manipulation words
                   2694: 
1.21      crook    2695: doc-sp0
                   2696: doc-s0
1.1       anton    2697: doc-sp@
                   2698: doc-sp!
1.21      crook    2699: doc-fp0
1.1       anton    2700: doc-fp@
                   2701: doc-fp!
1.21      crook    2702: doc-rp0
                   2703: doc-r0
1.1       anton    2704: doc-rp@
                   2705: doc-rp!
1.21      crook    2706: doc-lp0
                   2707: doc-l0
1.1       anton    2708: doc-lp@
                   2709: doc-lp!
                   2710: 
                   2711: @node Memory, Control Structures, Stack Manipulation, Words
                   2712: @section Memory
1.26      crook    2713: @cindex memory words
1.1       anton    2714: 
1.27      crook    2715: @cindex dictionary
                   2716: Forth definitions are organised in memory structures that are
1.29    ! crook    2717: collectively called the @dfn{dictionary}. The dictionary can be
1.27      crook    2718: considered as three logical memory regions:
                   2719: 
                   2720: @itemize @bullet
                   2721: @item
                   2722: @cindex code space
                   2723: @cindex code dictionary
1.29    ! crook    2724: Code space, also known as the @dfn{code dictionary}.
1.27      crook    2725: @item
                   2726: @cindex name space
                   2727: @cindex name dictionary
1.29    ! crook    2728: Name space, also known as the @dfn{name dictionary}@footnote{Sometimes,
        !          2729: the term @dfn{dictionary} is used simply to refer to the name
1.27      crook    2730: dictionary, because it is the one region that is used for looking up
                   2731: names, just as you would in a conventional dictionary.}.
                   2732: @item
                   2733: @cindex data space
                   2734: Data space
                   2735: @end itemize
                   2736: 
1.29    ! crook    2737: When you create a colon definition, the text interpreter compiles the
        !          2738: code for the definition into the code dictionary and compiles the name
1.27      crook    2739: of the definition into the name dictionary, together with other
                   2740: information about the definition (such as its execution token).
                   2741: 
                   2742: When you create a variable, the execution of @code{variable} will
                   2743: compile some code, assign once cell in data space, and compile the name
                   2744: of the variable into the name dictionary.
                   2745: 
                   2746: @cindex memory regions - relationship between them
                   2747: ANS Forth does not specify the relationship between the three memory
                   2748: regions, and specifies that a Standard program must not access code or
                   2749: data space directly -- it may only access data space directly. In
                   2750: addition, the Standard defines what relationships you may and may not
                   2751: rely on when allocating regions in data space. These constraints are
                   2752: simply a reflection of the many diverse techniques that are used to
                   2753: implement Forth systems; understanding and following the requirements of
                   2754: the Standard allows you to write portable programs -- programs that run
                   2755: in the same way on any of these diverse systems. Another way of looking
                   2756: at this is to say that ANS Forth was designed to permit compliant Forth
                   2757: systems to be implemented in many diverse ways.
                   2758: 
                   2759: @cindex memory regions - how they are assigned
1.29    ! crook    2760: Here are some examples of ways in which name, code and data spaces
        !          2761: might be assigned in different Forth implementations:
1.27      crook    2762: 
                   2763: @itemize @bullet
                   2764: @item
                   2765: For a Forth system that runs from RAM under a general-purpose operating
                   2766: system, it can be convenient to interleave name, code and data spaces in
                   2767: a single contiguous memory region. This organisation can be
                   2768: memory-efficient (for example, because the relationship between the name
                   2769: dictionary entry and the associated code dictionary entry can be
                   2770: implicit, rather than requiring an explicit memory pointer to reference
                   2771: from the name dictionary and the code dictionary). This is the
                   2772: organisation used by Gforth, as this example@footnote{The addresses
                   2773: in the example have been truncated to fit it onto the page, and the
                   2774: addresses and data shown will not match the output from your system} shows:
                   2775: @example
                   2776: hex
                   2777: variable fred 123456 fred !
                   2778: variable jim abcd jim !
                   2779: : foo + / - ;
                   2780: ' fred 10 - 50 dump 
                   2781: ..80: 5C 46 0E 40  84 66 72 65 - 64 20 20 20  20 20 20 20  \F.@.fred       
                   2782: ..90: D0 9B 04 08  00 00 00 00 - 56 34 12 00  80 46 0E 40  ........V4...F.@
                   2783: ..A0: 83 6A 69 6D  20 20 20 20 - D0 9B 04 08  00 00 00 00  .jim    ........
                   2784: ..B0: CD AB 00 00  9C 46 0E 40 - 83 66 6F 6F  20 20 20 20  .....F.@.foo    
                   2785: ..C0: 80 9B 04 08  00 00 00 00 - E4 2E 05 08  0C 2F 05 08  ............./..
                   2786: @end example
                   2787: 
                   2788: @item
                   2789: For a high-performance system running on a modern RISC processor with a
                   2790: modified Harvard architecture (one that has a unified main memory but
                   2791: separate instruction and data caches), it is desirable to separate
                   2792: processor instructions from processor data. This encourages a high cache
                   2793: density and therefore a high cache hit rate. The Forth code dictionary
                   2794: is not necessarily made up entirely of processor instructions; its
                   2795: nature is dependent upon the Forth implementation. 
                   2796: 
                   2797: @item
                   2798: A Forth compiler that runs on a segmented 8086 processor could be
                   2799: designed to interleave the name, code and data spaces within a single
                   2800: 64Kbyte segment. A more common implementation choice is to use a
                   2801: separate 64Kbyte segment for each region, which provides more memory
                   2802: overall but provides an address map in which only the data space is
                   2803: accessible.
                   2804: 
                   2805: @item
                   2806: Microprocessors exist that run Forth (or many of the primitives required
                   2807: to implement the Forth virtual machine efficiently) directly. On these
                   2808: processors, the relationship between name, code and data spaces may be
                   2809: imposed as a side-effect of the microarchitecture of the processor.
                   2810: 
                   2811: @item
                   2812: A Forth compiler that executes from ROM on an embedded system needs its
                   2813: data space separated from the name and code spaces so that the data
                   2814: space can be mapped to a RAM area.
                   2815: 
                   2816: @item 
                   2817: A Forth compiler that runs on an embedded system may have a requirement
                   2818: for a small memory footprint. On such a system it can be useful to
                   2819: separate the name space from the data and code spaces; once the
                   2820: application has been compiled, the name dictionary is no longer
                   2821: required@footnote{more strictly speaking, most applications can be
                   2822: designed so that this is the case}. The name dictionary can be deleted
1.29    ! crook    2823: entirely, or could be stored in memory on a remote @i{host} system for
1.27      crook    2824: debug and development purposes. In the latter case, the compiler running
1.29    ! crook    2825: on the @i{target} system could implement a protocol across a
1.27      crook    2826: communication link that would allow it to interrogate the name dictionary.
                   2827: @end itemize
                   2828: 
1.1       anton    2829: @menu
1.27      crook    2830: * Reserving Data Space::
                   2831: * Memory Access::
                   2832: * Address Arithmetic::
                   2833: * Memory Blocks::
                   2834: * Dynamic Allocation::
1.1       anton    2835: @end menu
                   2836: 
1.27      crook    2837: 
                   2838: @node Reserving Data Space, Memory Access, Memory, Memory
                   2839: @subsection Reserving Data Space
                   2840: @cindex reserving data space
                   2841: @cindex data space - reserving some
                   2842: 
                   2843: @cindex data space pointer - contiguous regions
1.29    ! crook    2844: Data space may be reserved as individual chars or cells or in contiguous
        !          2845: regions. These are the rules for reserving contiguous regions in a
        !          2846: Standard (i.e., portable) way:
1.27      crook    2847: @itemize @bullet
                   2848: @item
                   2849: The value of the data-space pointer, @code{here}, always defines the
                   2850: beginning of a contiguous region of data space.
                   2851: 
                   2852: @item
                   2853: @code{CREATE} establishes the beginning of a contiguous region of data
                   2854: space (the @code{CREATE}d definition returns the initial address of the
                   2855: region).
                   2856: 
                   2857: @item
1.29    ! crook    2858: @code{variable} does @i{not} establish the beginning of a contiguous
1.27      crook    2859: region in data space; @code{variable} followed by @code{allot} is not
                   2860: guaranteed to allocate data space region that is contiguous with the
                   2861: storage allocated by @code{variable}. Instead, use @code{create} --
                   2862: @xref{Simple Defining Words} for examples.
                   2863: 
                   2864: @item
                   2865: Successive calls to @code{allot}, @code{,} (comma), @code{2,} (2-comma),
                   2866: @code{c,} (c-comma) and @code{align} reserve a single contiguous region
                   2867: in data space. The contiguity of the region is interrupted by compiling
                   2868: (or removing) definitions from the dictionary.
                   2869: 
                   2870: @item
                   2871: The most recently reserved contiguous region may be released by calling
                   2872: @code{allot} with a negative argument, provided that the region has not
                   2873: been interrupted by compiling (or removing) definitions from the
                   2874: dictionary.
                   2875: @end itemize
                   2876: 
1.29    ! crook    2877: @cindex data space pointer - alignment
        !          2878: These factors affect the alignment of @code{here}, the data
        !          2879: space pointer:
        !          2880: 
        !          2881: @itemize @bullet
        !          2882: @item
        !          2883: If the data-space pointer is aligned@footnote{In ANS Forth-speak,
        !          2884: @i{aligned} implictly means @code{CELL}-aligned.} before an
        !          2885: @code{allot}, and a whole number of characters are reserved or released, it
        !          2886: will remain aligned after the @code{allot}.
        !          2887: 
        !          2888: @item
        !          2889: If the data-space pointer is character-aligned before an @code{allot},
        !          2890: and a whole number of cells are reserved or released, it will remain
        !          2891: character-aligned after the @code{allot}.
        !          2892: 
        !          2893: @item
        !          2894: The initial contents of data space reserved using @code{allot} is
        !          2895: undefined.
        !          2896: 
        !          2897: @item
        !          2898: Definitions created by @code{create}, @code{variable}, @code{2variable}
        !          2899: return aligned addresses.
        !          2900: 
        !          2901: @item
        !          2902: After a definition is compiled or @code{align} is executed, the data
        !          2903: space pointer is guaranteed to be aligned.
        !          2904: @end itemize
        !          2905: 
1.27      crook    2906: doc-here
                   2907: doc-unused
                   2908: doc-allot
                   2909: doc-c,
1.29    ! crook    2910: doc-f,
1.27      crook    2911: doc-,
                   2912: doc-2,
1.29    ! crook    2913: @cindex user space
        !          2914: doc-udp
        !          2915: doc-uallot
1.27      crook    2916: 
                   2917: 
                   2918: @node Memory Access, Address Arithmetic, Reserving Data Space, Memory
1.1       anton    2919: @subsection Memory Access
                   2920: @cindex memory access words
                   2921: 
                   2922: doc-@
                   2923: doc-!
                   2924: doc-+!
                   2925: doc-c@
                   2926: doc-c!
                   2927: doc-2@
                   2928: doc-2!
                   2929: doc-f@
                   2930: doc-f!
                   2931: doc-sf@
                   2932: doc-sf!
                   2933: doc-df@
                   2934: doc-df!
                   2935: 
1.27      crook    2936: @node Address Arithmetic, Memory Blocks, Memory Access, Memory
                   2937: @subsection Address Arithmetic
1.1       anton    2938: @cindex address arithmetic words
                   2939: 
                   2940: ANS Forth does not specify the sizes of the data types. Instead, it
                   2941: offers a number of words for computing sizes and doing address
1.29    ! crook    2942: arithmetic. Address arithmetic is performed in terms of address units
        !          2943: (aus); on most systems the address unit is one byte. Note that a
        !          2944: character may have more than one au, so @code{chars} is no noop (on
        !          2945: systems where it is a noop, it compiles to nothing).
1.1       anton    2946: 
                   2947: @cindex alignment of addresses for types
                   2948: ANS Forth also defines words for aligning addresses for specific
                   2949: types. Many computers require that accesses to specific data types
                   2950: must only occur at specific addresses; e.g., that cells may only be
                   2951: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   2952: accesses, it can usually perform aligned accesses faster. 
                   2953: 
                   2954: For the performance-conscious: alignment operations are usually only
                   2955: necessary during the definition of a data structure, not during the
                   2956: (more frequent) accesses to it.
                   2957: 
                   2958: ANS Forth defines no words for character-aligning addresses. This is not
                   2959: an oversight, but reflects the fact that addresses that are not
                   2960: char-aligned have no use in the standard and therefore will not be
                   2961: created.
                   2962: 
                   2963: @cindex @code{CREATE} and alignment
1.29    ! crook    2964: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    2965: are cell-aligned; in addition, Gforth guarantees that these addresses
                   2966: are aligned for all purposes.
                   2967: 
1.26      crook    2968: Note that the ANS Forth word @code{char} has nothing to do with address
                   2969: arithmetic.
1.1       anton    2970: 
                   2971: doc-chars
                   2972: doc-char+
                   2973: doc-cells
                   2974: doc-cell+
                   2975: doc-cell
                   2976: doc-align
                   2977: doc-aligned
                   2978: doc-floats
                   2979: doc-float+
                   2980: doc-float
                   2981: doc-falign
                   2982: doc-faligned
                   2983: doc-sfloats
                   2984: doc-sfloat+
                   2985: doc-sfalign
                   2986: doc-sfaligned
                   2987: doc-dfloats
                   2988: doc-dfloat+
                   2989: doc-dfalign
                   2990: doc-dfaligned
                   2991: doc-maxalign
                   2992: doc-maxaligned
                   2993: doc-cfalign
                   2994: doc-cfaligned
                   2995: doc-address-unit-bits
                   2996: 
1.27      crook    2997: @node Memory Blocks, Dynamic Allocation, Address Arithmetic, Memory
1.1       anton    2998: @subsection Memory Blocks
                   2999: @cindex memory block words
1.27      crook    3000: @cindex character strings - moving and copying
                   3001: 
                   3002: Memory blocks often represent character strings; @xref{String Formats}
                   3003: for ways of storing character strings in memory. @xref{Displaying
                   3004: characters and strings} for other string-processing words.
1.1       anton    3005: 
1.21      crook    3006: Some of these words work on address units (increments of @code{CELL}),
                   3007: and expect a @code{CELL}-aligned address. Others work on character units
                   3008: (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
                   3009: address. Choose the correct operation depending upon your data type. If
                   3010: you are moving a block of memory (for example, a region reserved by
                   3011: @code{allot}) it is safe to use @code{move}, and it should be faster
                   3012: than using @code{cmove}. If you are moving (for example) a string
                   3013: compiled using @code{S"}, it is not portable to use @code{move}; the
                   3014: alignment of the string in memory could change, and the relationship
                   3015: between @code{CELL} and @code{CHAR} could change.
                   3016: 
                   3017: When copying characters between overlapping memory regions, choose
                   3018: carefully between @code{cmove} and @code{cmove>}.
                   3019: 
1.29    ! crook    3020: You can only use any of these words @i{portably} to access data space.
1.21      crook    3021: 
1.27      crook    3022: @comment TODO - think the naming of the arguments is wrong for move
1.29    ! crook    3023: @comment well, really it seems to be the Standard that's wrong; it
        !          3024: @comment describes MOVE as a word that requires a CELL-aligned source
        !          3025: @comment and destination address but a xtranfer count that need not
        !          3026: @comment be a multiple of CELL.
1.1       anton    3027: doc-move
                   3028: doc-erase
                   3029: doc-cmove
                   3030: doc-cmove>
                   3031: doc-fill
                   3032: doc-blank
1.21      crook    3033: doc-compare
                   3034: doc-search
1.27      crook    3035: doc--trailing
                   3036: doc-/string
                   3037: 
                   3038: @comment TODO examples
                   3039: 
                   3040: @node Dynamic Allocation, ,Memory Blocks, Memory
                   3041: @subsection Dynamic Allocation of Memory
                   3042: @cindex dynamic allocation of memory
                   3043: @cindex memory-allocation word set
                   3044: 
                   3045: The ANS Forth memory-allocation word set allows memory regions to be
                   3046: dynamically assigned, resized and released without affecting the data
                   3047: space pointer. In Gforth, these words are implemented using
                   3048: the standard C library calls malloc(), free() and resize().
                   3049: 
                   3050: doc-allocate
                   3051: doc-free
                   3052: doc-resize
                   3053: 
1.1       anton    3054: 
1.26      crook    3055: @node Control Structures, Defining Words, Memory, Words
1.1       anton    3056: @section Control Structures
                   3057: @cindex control structures
                   3058: 
                   3059: Control structures in Forth cannot be used in interpret state, only in
1.29    ! crook    3060: compile state@footnote{To be precise, they have no interpretation
        !          3061: semantics (@pxref{Interpretation and Compilation Semantics}).}, i.e., in
1.1       anton    3062: a colon definition. We do not like this limitation, but have not seen a
                   3063: satisfying way around it yet, although many schemes have been proposed.
                   3064: 
                   3065: @menu
1.29    ! crook    3066: * Selection::                   IF.. ELSE.. ENDIF
        !          3067: * Simple Loops::                BEGIN..
        !          3068: * Counted Loops::               DO
        !          3069: * Arbitrary control structures::
        !          3070: * Calls and returns::
1.1       anton    3071: * Exception Handling::          
                   3072: @end menu
                   3073: 
                   3074: @node Selection, Simple Loops, Control Structures, Control Structures
                   3075: @subsection Selection
                   3076: @cindex selection control structures
                   3077: @cindex control structures for selection
                   3078: 
                   3079: @cindex @code{IF} control structure
                   3080: @example
1.29    ! crook    3081: @i{flag}
1.1       anton    3082: IF
1.29    ! crook    3083:   @i{code}
1.1       anton    3084: ENDIF
                   3085: @end example
1.21      crook    3086: @noindent
1.1       anton    3087: or
                   3088: @example
1.29    ! crook    3089: @i{flag}
1.1       anton    3090: IF
1.29    ! crook    3091:   @i{code1}
1.1       anton    3092: ELSE
1.29    ! crook    3093:   @i{code2}
1.1       anton    3094: ENDIF
                   3095: @end example
                   3096: 
                   3097: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   3098: standard, and @code{ENDIF} is not, although it is quite popular. We
                   3099: recommend using @code{ENDIF}, because it is less confusing for people
                   3100: who also know other languages (and is not prone to reinforcing negative
                   3101: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   3102: system that only supplies @code{THEN} is simple:
                   3103: @example
1.21      crook    3104: : ENDIF   POSTPONE THEN ; immediate
1.1       anton    3105: @end example
                   3106: 
                   3107: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   3108: (adv.)}  has the following meanings:
                   3109: @quotation
                   3110: ... 2b: following next after in order ... 3d: as a necessary consequence
                   3111: (if you were there, then you saw them).
                   3112: @end quotation
                   3113: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   3114: and many other programming languages has the meaning 3d.]
                   3115: 
1.21      crook    3116: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    3117: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    3118: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    3119: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   3120: @file{compat/control.fs}.
                   3121: 
                   3122: @cindex @code{CASE} control structure
                   3123: @example
1.29    ! crook    3124: @i{n}
1.1       anton    3125: CASE
1.29    ! crook    3126:   @i{n1} OF @i{code1} ENDOF
        !          3127:   @i{n2} OF @i{code2} ENDOF
1.1       anton    3128:   @dots{}
                   3129: ENDCASE
                   3130: @end example
                   3131: 
1.29    ! crook    3132: Executes the first @i{codei}, where the @i{ni} is equal to
        !          3133: @i{n}. A default case can be added by simply writing the code after
        !          3134: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
1.1       anton    3135: but must not consume it.
                   3136: 
                   3137: @node Simple Loops, Counted Loops, Selection, Control Structures
                   3138: @subsection Simple Loops
                   3139: @cindex simple loops
                   3140: @cindex loops without count 
                   3141: 
                   3142: @cindex @code{WHILE} loop
                   3143: @example
                   3144: BEGIN
1.29    ! crook    3145:   @i{code1}
        !          3146:   @i{flag}
1.1       anton    3147: WHILE
1.29    ! crook    3148:   @i{code2}
1.1       anton    3149: REPEAT
                   3150: @end example
                   3151: 
1.29    ! crook    3152: @i{code1} is executed and @i{flag} is computed. If it is true,
        !          3153: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    3154: false, execution continues after the @code{REPEAT}.
                   3155: 
                   3156: @cindex @code{UNTIL} loop
                   3157: @example
                   3158: BEGIN
1.29    ! crook    3159:   @i{code}
        !          3160:   @i{flag}
1.1       anton    3161: UNTIL
                   3162: @end example
                   3163: 
1.29    ! crook    3164: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    3165: 
                   3166: @cindex endless loop
                   3167: @cindex loops, endless
                   3168: @example
                   3169: BEGIN
1.29    ! crook    3170:   @i{code}
1.1       anton    3171: AGAIN
                   3172: @end example
                   3173: 
                   3174: This is an endless loop.
                   3175: 
                   3176: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   3177: @subsection Counted Loops
                   3178: @cindex counted loops
                   3179: @cindex loops, counted
                   3180: @cindex @code{DO} loops
                   3181: 
                   3182: The basic counted loop is:
                   3183: @example
1.29    ! crook    3184: @i{limit} @i{start}
1.1       anton    3185: ?DO
1.29    ! crook    3186:   @i{body}
1.1       anton    3187: LOOP
                   3188: @end example
                   3189: 
1.29    ! crook    3190: This performs one iteration for every integer, starting from @i{start}
        !          3191: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    3192: accessed with @code{i}. For example, the loop:
1.1       anton    3193: @example
                   3194: 10 0 ?DO
                   3195:   i .
                   3196: LOOP
                   3197: @end example
1.21      crook    3198: @noindent
                   3199: prints @code{0 1 2 3 4 5 6 7 8 9}
                   3200: 
1.1       anton    3201: The index of the innermost loop can be accessed with @code{i}, the index
                   3202: of the next loop with @code{j}, and the index of the third loop with
                   3203: @code{k}.
                   3204: 
                   3205: doc-i
                   3206: doc-j
                   3207: doc-k
                   3208: 
                   3209: The loop control data are kept on the return stack, so there are some
1.21      crook    3210: restrictions on mixing return stack accesses and counted loop words. In
                   3211: particuler, if you put values on the return stack outside the loop, you
                   3212: cannot read them inside the loop@footnote{well, not in a way that is
                   3213: portable.}. If you put values on the return stack within a loop, you
                   3214: have to remove them before the end of the loop and before accessing the
                   3215: index of the loop.
1.1       anton    3216: 
                   3217: There are several variations on the counted loop:
                   3218: 
1.21      crook    3219: @itemize @bullet
                   3220: @item
                   3221: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   3222: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   3223: 
                   3224: @example
                   3225: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   3226: @end example
                   3227: prints @code{0 1 2 3}
                   3228: 
1.1       anton    3229: 
1.21      crook    3230: @item
                   3231: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   3232: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   3233: return stack so @code{EXIT} can get to its return address. For example:
                   3234: 
                   3235: @example
                   3236: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   3237: @end example
                   3238: prints @code{0 1 2 3}
                   3239: 
                   3240: 
                   3241: @item
1.29    ! crook    3242: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    3243: (and @code{LOOP} iterates until they become equal by wrap-around
                   3244: arithmetic). This behaviour is usually not what you want. Therefore,
                   3245: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29    ! crook    3246: @code{?DO}), which do not enter the loop if @i{start} is greater than
        !          3247: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    3248: unsigned loop parameters.
                   3249: 
1.21      crook    3250: @item
                   3251: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   3252: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   3253: if you know that the loop is entered in any case. Such knowledge tends
                   3254: to become invalid during maintenance of a program, and then the
                   3255: @code{DO} will make trouble.
                   3256: 
                   3257: @item
1.29    ! crook    3258: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
        !          3259: index by @i{n} instead of by 1. The loop is terminated when the border
        !          3260: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    3261: 
1.21      crook    3262: @example
                   3263: 4 0 +DO  i .  2 +LOOP
                   3264: @end example
                   3265: @noindent
                   3266: prints @code{0 2}
                   3267: 
                   3268: @example
                   3269: 4 1 +DO  i .  2 +LOOP
                   3270: @end example
                   3271: @noindent
                   3272: prints @code{1 3}
1.1       anton    3273: 
                   3274: 
                   3275: @cindex negative increment for counted loops
                   3276: @cindex counted loops with negative increment
1.29    ! crook    3277: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    3278: 
1.21      crook    3279: @example
                   3280: -1 0 ?DO  i .  -1 +LOOP
                   3281: @end example
                   3282: @noindent
                   3283: prints @code{0 -1}
1.1       anton    3284: 
1.21      crook    3285: @example
                   3286: 0 0 ?DO  i .  -1 +LOOP
                   3287: @end example
                   3288: prints nothing.
1.1       anton    3289: 
1.29    ! crook    3290: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
        !          3291: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
        !          3292: index by @i{u} each iteration. The loop is terminated when the border
        !          3293: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    3294: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   3295: 
1.21      crook    3296: @example
                   3297: -2 0 -DO  i .  1 -LOOP
                   3298: @end example
                   3299: @noindent
                   3300: prints @code{0 -1}
1.1       anton    3301: 
1.21      crook    3302: @example
                   3303: -1 0 -DO  i .  1 -LOOP
                   3304: @end example
                   3305: @noindent
                   3306: prints @code{0}
                   3307: 
                   3308: @example
                   3309: 0 0 -DO  i .  1 -LOOP
                   3310: @end example
                   3311: @noindent
                   3312: prints nothing.
1.1       anton    3313: 
1.21      crook    3314: @end itemize
1.1       anton    3315: 
                   3316: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    3317: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   3318: for these words that uses only standard words is provided in
                   3319: @file{compat/loops.fs}.
1.1       anton    3320: 
                   3321: 
                   3322: @cindex @code{FOR} loops
1.26      crook    3323: Another counted loop is:
1.1       anton    3324: @example
1.29    ! crook    3325: @i{n}
1.1       anton    3326: FOR
1.29    ! crook    3327:   @i{body}
1.1       anton    3328: NEXT
                   3329: @end example
                   3330: This is the preferred loop of native code compiler writers who are too
1.26      crook    3331: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29    ! crook    3332: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
        !          3333: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    3334: Forth systems may behave differently, even if they support @code{FOR}
                   3335: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    3336: 
                   3337: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   3338: @subsection Arbitrary control structures
                   3339: @cindex control structures, user-defined
                   3340: 
                   3341: @cindex control-flow stack
                   3342: ANS Forth permits and supports using control structures in a non-nested
                   3343: way. Information about incomplete control structures is stored on the
                   3344: control-flow stack. This stack may be implemented on the Forth data
                   3345: stack, and this is what we have done in Gforth.
                   3346: 
                   3347: @cindex @code{orig}, control-flow stack item
                   3348: @cindex @code{dest}, control-flow stack item
                   3349: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   3350: entry represents a backward branch target. A few words are the basis for
                   3351: building any control structure possible (except control structures that
                   3352: need storage, like calls, coroutines, and backtracking).
                   3353: 
                   3354: doc-if
                   3355: doc-ahead
                   3356: doc-then
                   3357: doc-begin
                   3358: doc-until
                   3359: doc-again
                   3360: doc-cs-pick
                   3361: doc-cs-roll
                   3362: 
1.21      crook    3363: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   3364: manipulate the control-flow stack in a portable way. Without them, you
                   3365: would need to know how many stack items are occupied by a control-flow
                   3366: entry (many systems use one cell. In Gforth they currently take three,
                   3367: but this may change in the future).
                   3368: 
1.1       anton    3369: Some standard control structure words are built from these words:
                   3370: 
                   3371: doc-else
                   3372: doc-while
                   3373: doc-repeat
                   3374: 
                   3375: Gforth adds some more control-structure words:
                   3376: 
                   3377: doc-endif
                   3378: doc-?dup-if
                   3379: doc-?dup-0=-if
                   3380: 
                   3381: Counted loop words constitute a separate group of words:
                   3382: 
                   3383: doc-?do
                   3384: doc-+do
                   3385: doc-u+do
                   3386: doc--do
                   3387: doc-u-do
                   3388: doc-do
                   3389: doc-for
                   3390: doc-loop
                   3391: doc-+loop
                   3392: doc--loop
                   3393: doc-next
                   3394: doc-leave
                   3395: doc-?leave
                   3396: doc-unloop
                   3397: doc-done
                   3398: 
1.21      crook    3399: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   3400: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    3401: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   3402: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   3403: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   3404: resolved (by using one of the loop-ending words or @code{DONE}).
                   3405: 
1.26      crook    3406: Another group of control structure words are:
1.1       anton    3407: 
                   3408: doc-case
                   3409: doc-endcase
                   3410: doc-of
                   3411: doc-endof
                   3412: 
1.21      crook    3413: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   3414: @code{CS-ROLL}.
1.1       anton    3415: 
                   3416: @subsubsection Programming Style
                   3417: 
                   3418: In order to ensure readability we recommend that you do not create
                   3419: arbitrary control structures directly, but define new control structure
                   3420: words for the control structure you want and use these words in your
1.26      crook    3421: program. For example, instead of writing:
1.1       anton    3422: 
                   3423: @example
1.26      crook    3424: BEGIN
1.1       anton    3425:   ...
1.26      crook    3426: IF [ 1 CS-ROLL ]
1.1       anton    3427:   ...
1.26      crook    3428: AGAIN THEN
1.1       anton    3429: @end example
                   3430: 
1.21      crook    3431: @noindent
1.1       anton    3432: we recommend defining control structure words, e.g.,
                   3433: 
                   3434: @example
1.26      crook    3435: : WHILE ( DEST -- ORIG DEST )
                   3436:  POSTPONE IF
                   3437:  1 CS-ROLL ; immediate
                   3438: 
                   3439: : REPEAT ( orig dest -- )
                   3440:  POSTPONE AGAIN
                   3441:  POSTPONE THEN ; immediate
1.1       anton    3442: @end example
                   3443: 
1.21      crook    3444: @noindent
1.1       anton    3445: and then using these to create the control structure:
                   3446: 
                   3447: @example
1.26      crook    3448: BEGIN
1.1       anton    3449:   ...
1.26      crook    3450: WHILE
1.1       anton    3451:   ...
1.26      crook    3452: REPEAT
1.1       anton    3453: @end example
                   3454: 
                   3455: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   3456: @code{WHILE} are predefined, so in this example it would not be
                   3457: necessary to define them.
                   3458: 
                   3459: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   3460: @subsection Calls and returns
                   3461: @cindex calling a definition
                   3462: @cindex returning from a definition
                   3463: 
1.3       anton    3464: @cindex recursive definitions
                   3465: A definition can be called simply be writing the name of the definition
1.26      crook    3466: to be called. Normally a definition is invisible during its own
1.3       anton    3467: definition. If you want to write a directly recursive definition, you
1.26      crook    3468: can use @code{recursive} to make the current definition visible, or
                   3469: @code{recurse} to call the current definition directly.
1.3       anton    3470: 
                   3471: doc-recursive
                   3472: doc-recurse
                   3473: 
1.21      crook    3474: @comment TODO add example of the two recursion methods
1.12      anton    3475: @quotation
                   3476: @progstyle
                   3477: I prefer using @code{recursive} to @code{recurse}, because calling the
                   3478: definition by name is more descriptive (if the name is well-chosen) than
                   3479: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   3480: implementation, it is much better to read (and think) ``now sort the
                   3481: partitions'' than to read ``now do a recursive call''.
                   3482: @end quotation
1.3       anton    3483: 
1.29    ! crook    3484: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    3485: 
                   3486: @example
1.28      crook    3487: Defer foo
1.3       anton    3488: 
                   3489: : bar ( ... -- ... )
                   3490:  ... foo ... ;
                   3491: 
                   3492: :noname ( ... -- ... )
                   3493:  ... bar ... ;
                   3494: IS foo
                   3495: @end example
                   3496: 
1.26      crook    3497: The current definition returns control to the calling definition when
1.29    ! crook    3498: the end of the definition is reached or @code{EXIT} is
        !          3499: encountered. Deferred words are discussed in more detail in @ref{Simple
        !          3500: Defining Words}.
1.1       anton    3501: 
                   3502: doc-exit
                   3503: doc-;s
                   3504: 
                   3505: @node Exception Handling,  , Calls and returns, Control Structures
                   3506: @subsection Exception Handling
1.26      crook    3507: @cindex exceptions
1.1       anton    3508: 
1.26      crook    3509: If your program detects a fatal error condition, the simplest action
                   3510: that it can take is to @code{quit}. This resets the return stack and
                   3511: restarts the text interpreter, but does not print any error message.
1.21      crook    3512: 
1.26      crook    3513: The next stage in severity is to execute @code{abort}, which has the
                   3514: same effect as @code{quit}, with the addition that it resets the data
                   3515: stack.
1.1       anton    3516: 
1.26      crook    3517: A slightly more sophisticated approach is use use @code{abort"}, which
                   3518: compiles a string to be used as an error message and does a conditional
                   3519: @code{abort} at run-time. For example:
1.1       anton    3520: 
1.26      crook    3521: @example
                   3522: @kbd{: checker abort" That flag was true" ." A false flag" ;<return>}  ok
                   3523: @kbd{0 checker<return>} A false flag ok
                   3524: @kbd{1 checker<return>}
                   3525: :1: That flag was true
                   3526: 1 checker
                   3527:   ^^^^^^^
                   3528: $400D1648 throw 
                   3529: $400E4660
                   3530: @end example
1.1       anton    3531: 
1.26      crook    3532: These simple techniques allow a program to react to a fatal error
                   3533: condition, but they are not exactly user-friendly. The ANS Forth
                   3534: Exception word set provides the pair of words @code{throw} and
                   3535: @code{catch}, which can be used to provide sophisticated error-handling.
1.1       anton    3536: 
1.26      crook    3537: @code{catch} has a similar behaviour to @code{execute}, in that it takes
1.29    ! crook    3538: an @i{xt} as a parameter and starts execution of the xt. However,
1.26      crook    3539: before passing control to the xt, @code{catch} pushes an
1.29    ! crook    3540: @dfn{exception frame} onto the @dfn{exception stack}. This exception
1.26      crook    3541: frame is used to restore the system to a known state if a detected error
                   3542: occurs during the execution of the xt. A typical way to use @code{catch}
                   3543: would be:
1.1       anton    3544: 
1.26      crook    3545: @example
                   3546: ... ['] foo catch IF ...
                   3547: @end example
1.1       anton    3548: 
1.26      crook    3549: Whilst @code{foo} executes, it can call other words to any level of
                   3550: nesting, as usual.  If @code{foo} (and all the words that it calls)
                   3551: execute successfully, control will ultimately passes to the word following
                   3552: the @code{catch}, and there will be a @code{true} flag (0) at
                   3553: TOS. However, if any word detects an error, it can terminate the
                   3554: execution of @code{foo} by pushing an error code onto the stack and then
                   3555: performing a @code{throw}. The execution of @code{throw} will pass 
                   3556: control to the word following the @code{catch}, but this time the TOS
                   3557: will hold the error code. Therefore, the @code{IF} in the example
                   3558: can be used to determine whether @code{foo} executed successfully.
1.1       anton    3559: 
1.26      crook    3560: This simple example shows how you can use @code{throw} and @code{catch}
                   3561: to ``take over'' exception handling from the system:
1.1       anton    3562: @example
1.26      crook    3563: : my-div ['] / catch if ." DIVIDE ERROR" else ." OK.. " . then ;
1.1       anton    3564: @end example
                   3565: 
1.26      crook    3566: The next example is more sophisticated and shows a multi-level
                   3567: @code{throw} and @code{catch}. To understand this example, start at the
                   3568: definition of @code{top-level} and work backwards:
                   3569: 
1.1       anton    3570: @example
1.26      crook    3571: : lowest-level ( -- c )
                   3572:     key dup 27 = if
                   3573:        1 throw \ ESCAPE key pressed
                   3574:     else
                   3575:        ." lowest-level successfull" CR
                   3576:     then
                   3577: ;
                   3578: 
                   3579: : lower-level ( -- c )
                   3580:     lowest-level
                   3581:     \ at this level consider a CTRL-U to be a fatal error
                   3582:     dup 21 = if \ CTRL-U
                   3583:        2 throw
                   3584:     else
                   3585:        ." lower-level successfull" CR
                   3586:     then
                   3587: ;
                   3588: 
                   3589: : low-level ( -- c )
                   3590:     ['] lower-level catch
                   3591:     ?dup if
                   3592:        \ error occurred - do we recognise it?
                   3593:        dup 1 = if
                   3594:            \ ESCAPE key pressed.. pretend it was an E
                   3595:            [char] E
                   3596:        else throw \ propogate the error upwards
                   3597:        then
                   3598:     then
                   3599:     ." low-level successfull" CR
                   3600: ;
                   3601: 
                   3602: : top-level ( -- )
                   3603:     CR ['] low-level catch \ CATCH is used like EXECUTE
                   3604:     ?dup if \ error occurred..
                   3605:        ." Error " . ." occurred - contact your supplier"
                   3606:     else
                   3607:        ." The '" emit ." ' key was pressed" CR
                   3608:     then
                   3609: ;
1.1       anton    3610: @end example
                   3611: 
1.26      crook    3612: The ANS Forth document assigns @code{throw} codes thus:
1.1       anton    3613: 
1.26      crook    3614: @itemize @bullet
                   3615: @item
                   3616: codes in the range -1 -- -255 are reserved to be assigned by the
                   3617: Standard. Assignments for codes in the range -1 -- -58 are currently
                   3618: documented in the Standard. In particular, @code{-1 throw} is equivalent
                   3619: to @code{abort} and @code{-2 throw} is equivalent to @code{abort"}.
                   3620: @item
                   3621: codes in the range -256 -- -4095 are reserved to be assigned by the system.
                   3622: @item
                   3623: all other codes may be assigned by programs.
                   3624: @end itemize
1.1       anton    3625: 
1.26      crook    3626: Gforth provides the word @code{exception} as a mechanism for assigning
                   3627: system throw codes to applications. This allows multiple applications to
                   3628: co-exist in memory without any clash of @code{throw} codes. A definition
                   3629: of @code{exception} in ANS Forth is provided in
                   3630: @file{compat/exception.fs}.
1.1       anton    3631: 
1.26      crook    3632: doc-quit
                   3633: doc-abort
                   3634: doc-abort"
1.1       anton    3635: 
1.26      crook    3636: doc-catch
1.29    ! crook    3637: doc-throw
        !          3638: doc---exception-exception
        !          3639: 
        !          3640: 
        !          3641: @c -------------------------------------------------------------
        !          3642: @node Defining Words, The Text Interpreter, Control Structures, Words
        !          3643: @section Defining Words
        !          3644: @cindex defining words
        !          3645: 
        !          3646: @menu
        !          3647: * Simple Defining Words::       Variables, values and constants
        !          3648: * Colon Definitions::
        !          3649: * User-defined Defining Words::
        !          3650: * Supplying names::
        !          3651: * Interpretation and Compilation Semantics::
        !          3652: @end menu
        !          3653: 
        !          3654: @node Simple Defining Words, Colon Definitions, Defining Words, Defining Words
        !          3655: @subsection Simple Defining Words
        !          3656: @cindex simple defining words
        !          3657: @cindex defining words, simple
        !          3658: 
        !          3659: Defining words are used to create new entries in the dictionary. The
        !          3660: simplest defining word is @code{CREATE}. @code{CREATE} is used like
        !          3661: this:
        !          3662: 
        !          3663: @example
        !          3664: CREATE new-word1
        !          3665: @end example
        !          3666: 
        !          3667: @code{CREATE} is a parsing word that generates a dictionary entry for
        !          3668: @code{new-word1}. When @code{new-word1} is executed, all that it does is
        !          3669: leave an address on the stack. The address represents the value of
        !          3670: the data space pointer (@code{HERE}) at the time that @code{new-word1}
        !          3671: was defined. Therefore, @code{CREATE} is a way of associating a name
        !          3672: with the address of a region of memory.
        !          3673: 
        !          3674: By extending this example to reserve some memory in data space, we end
        !          3675: up with a @i{variable}. Here are two different ways to do it:
        !          3676: 
        !          3677: @example
        !          3678: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
        !          3679: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
        !          3680: @end example
        !          3681: 
        !          3682: The variable can be examined and modified using @code{@@} (``fetch'') and
        !          3683: @code{!} (``store'') like this:
        !          3684: 
        !          3685: @example
        !          3686: new-word2 @@ .      \ get address, fetch from it and display
        !          3687: 1234 new-word2 !   \ new value, get address, store to it
        !          3688: @end example
        !          3689: 
        !          3690: As a final refinement, the whole code sequence can be wrapped up in a
        !          3691: defining word (pre-empting the subject of the next section), making it
        !          3692: easier to create new variables:
        !          3693: 
        !          3694: @example
        !          3695: : myvariable ( "name" -- a-addr ) CREATE 1 cells allot ;
        !          3696: 
        !          3697: myvariable foo
        !          3698: myvariable joe
        !          3699: 
        !          3700: 45 3 * foo !   \ set foo to 135
        !          3701: 1234 joe !     \ set joe to 1234
        !          3702: 3 joe +!       \ increment joe by 3.. to 1237
        !          3703: @end example
        !          3704: 
        !          3705: Not surprisingly, there is no need to define @code{myvariable}, since
        !          3706: Forth already has a definition @code{Variable}. It behaves in exactly
        !          3707: the same way as @code{myvariable} but it is implemented in an optimised
        !          3708: way. Forth also provides @code{2Variable} and @code{fvariable} for
        !          3709: double and floating-point variables, respectively.
        !          3710: 
        !          3711: @cindex arrays
        !          3712: A similar mechanism can be used to create arrays. For example, an
        !          3713: 80-character text input buffer:
        !          3714: 
        !          3715: @example
        !          3716: CREATE text-buf 80 chars allot
        !          3717: 
        !          3718: text-buf 0 chars c@@ \ the 1st character (offset 0)
        !          3719: text-buf 3 chars c@@ \ the 4th character (offset 3)
        !          3720: @end example
        !          3721: 
        !          3722: You can build arbitrarily complex data structures by allocating
        !          3723: appropriate areas of memory. @xref{Structures} for further discussions
        !          3724: of this, and to learn about some Gforth tools that make it easier.
        !          3725: 
        !          3726: @cindex user variables
        !          3727: @cindex user space
        !          3728: The defining word @code{User} behaves in the same way as @code{Variable}.
        !          3729: The difference is that it reserves space in @i{user (data) space} rather
        !          3730: than normal data space. In a Forth system that has a multi-tasker, each
        !          3731: task has its own set of user variables.
        !          3732: 
        !          3733: @comment TODO is that stuff about user variables strictly correct? Is it
        !          3734: @comment just terminal tasks that have user variables?
        !          3735: @comment should document tasker.fs (with some examples) elsewhere
        !          3736: @comment in this manual, then expand on user space and user variables.
        !          3737: 
        !          3738: After @code{CREATE} and @code{Variable}s, the next defining word to
        !          3739: consider is @code{Constant}. @code{Constant} allows you to declare a
        !          3740: fixed value and refer to it by name. For example:
        !          3741: 
        !          3742: @example
        !          3743: 12 Constant INCHES-PER-FOOT
        !          3744: 3E+08 fconstant SPEED-O-LIGHT
        !          3745: @end example
        !          3746: 
        !          3747: A @code{Variable} can be both read and written, so its run-time
        !          3748: behaviour is to supply an address through which its current value can be
        !          3749: manipulated. In contrast, the value of a @code{Constant} cannot be
        !          3750: changed once it has been declared@footnote{Well, often it can be -- but
        !          3751: not in a Standard, portable way. It's safer to use a @code{Value} (read
        !          3752: on).} so it's not necessary to supply the address -- it is more
        !          3753: efficient to return the value of the constant directly. That's exactly
        !          3754: what happens; the run-time effect of a constant is to put its value on
        !          3755: the top of the stack (@ref{User-defined Defining Words} describes one
        !          3756: way of implementing @code{Constant}).
        !          3757: 
        !          3758: Gforth also provides @code{2Constant} and @code{fconstant} for defining
        !          3759: double and floating-point constants, respectively.
        !          3760: 
        !          3761: Constants in Forth behave differently from their equivalents in other
        !          3762: programming languages. In other languages, a constant (such as an EQU in
        !          3763: assembler or a #define in C) only exists at compile-time; in the
        !          3764: executable program the constant has been translated into an absolute
        !          3765: number and, unless you are using a symbolic debugger, it's impossible to
        !          3766: know what abstract thing that number represents. In Forth a constant has
        !          3767: an entry in the name dictionary and remains there after the code that
        !          3768: uses it has been defined. In fact, it must remain in the dictionary
        !          3769: since it has run-time duties to perform. For example:
        !          3770: 
        !          3771: @example
        !          3772: 12 Constant INCHES-PER-FOOT
        !          3773: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
        !          3774: @end example
        !          3775: 
        !          3776: @cindex in-lining of constants
        !          3777: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
        !          3778: associated with the constant @code{INCHES-PER-FOOT}. If you use
        !          3779: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
        !          3780: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
        !          3781: attempt to optimise constants by in-lining them where they are used. You
        !          3782: can force Gforth to in-line a constant like this:
        !          3783: 
        !          3784: @example
        !          3785: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
        !          3786: @end example
        !          3787: 
        !          3788: If you use @code{see} to decompile @i{this} version of
        !          3789: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
        !          3790: longer present. @xref{Interpret/Compile states} and @xref{Literals}
        !          3791: explain to this works.
        !          3792: 
        !          3793: In-lining constants in this way might improve execution time
        !          3794: fractionally, and can ensure that a constant is now only referenced at
        !          3795: compile-time. However, the definition of the constant still remains in
        !          3796: the dictionary. Some Forth compilers provide a mechanism for controlling
        !          3797: a second dictionary for holding transient words such that this second
        !          3798: dictionary can be deleted later in order to recover memory
        !          3799: space. However, there is no standard way of doing this.
        !          3800: 
        !          3801: One aspect of constants and variables that can sometimes be confusing is
        !          3802: that they have different stack effects; one returns its value whilst the
        !          3803: other returns the address of its value. The defining word @code{Value}
        !          3804: provides an alternative to @code{Variable}, and has the same stack
        !          3805: effect as a constant. A @code{Value} needs an additional word, @code{TO}
        !          3806: to allow its value to be changed. Here are some examples:
        !          3807: 
        !          3808: @example
        !          3809: 12 Value APPLES \ a Value is initialised when it is declared.. like a
        !          3810:                 \ constant but unlike a variable
        !          3811: 34 TO APPLES    \ Change the value of APPLES. TO is a parsing word
        !          3812: APPLES          \ puts 34 on the top of the stack.
        !          3813: @end example
        !          3814: 
        !          3815: The defining word @code{Defer} allows you to define a word by name
        !          3816: without defining its behaviour; the definition of its behaviour is
        !          3817: deferred. Here are two situation where this can be useful:
        !          3818: 
        !          3819: @itemize @bullet
        !          3820: @item
        !          3821: Where you want to allow the behaviour of a word to be altered later, and
        !          3822: for all precompiled references to the word to change when its behaviour
        !          3823: is changed.
        !          3824: @item
        !          3825: For mutual recursion; @xref{Calls and returns}.
        !          3826: @end itemize
        !          3827: 
        !          3828: In the following example, @code{foo} always invokes the version of
        !          3829: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
        !          3830: always invokes the version that prints ``@code{Hello}''. There is no way
        !          3831: of getting @code{foo} to use the later version without re-ordering the
        !          3832: source code and recompilng it.
        !          3833: 
        !          3834: @example
        !          3835: : greet ." Good morning" ;
        !          3836: : foo ... greet ... ;
        !          3837: : greet ." Hello" ;
        !          3838: : bar ... greet ... ;
        !          3839: @end example
        !          3840: 
        !          3841: This problem can be solved by defining @code{greet} as a @code{Defer}red
        !          3842: word. The behaviour of a @code{Defer}red word can be defined and
        !          3843: redefined at any time by using @code{IS} to associate the xt of a
        !          3844: previously-defined word with it. The previous example becomes:
        !          3845: 
        !          3846: @example
        !          3847: Defer greet
        !          3848: : foo ... greet ... ;
        !          3849: : bar ... greet ... ;
        !          3850: : greet1 ." Good morning" ;
        !          3851: : greet2 ." Hello" ;
        !          3852: ' greet2 IS greet  \ make greet behave like greet2
        !          3853: @end example
        !          3854: 
        !          3855: A deferred word can only inherit default semantics from the xt (because
        !          3856: that is all that an xt can represent -- @pxref{Tokens for Words} for
        !          3857: more discussion of this). However, the semantics of the deferred word
        !          3858: itself can be modified at the time that it is defined. For example:
        !          3859: 
        !          3860: @example
        !          3861: : bar .... ; compile-only
        !          3862: Defer fred immediate
        !          3863: Defer jim
        !          3864: 
        !          3865: ' bar IS jim  \ jim has default semantics
        !          3866: ' bar IS fred \ fred is immediate
        !          3867: @end example
1.1       anton    3868: 
1.29    ! crook    3869: The defining word @code{Alias} allows you to define a word by name that
        !          3870: has the same behaviour as some other word. Here are two situation where
        !          3871: this can be useful:
1.1       anton    3872: 
1.29    ! crook    3873: @itemize @bullet
        !          3874: @item
        !          3875: When you want access to a word's definition from a different word list
        !          3876: (for an example of this, see the definition of the @code{Root} word list
        !          3877: in the Gforth source).
        !          3878: @item
        !          3879: When you want to create a synonym; a definition that can be known by
        !          3880: either of two names (for example, @code{THEN} and @code{ENDIF} are
        !          3881: aliases).
        !          3882: @end itemize
1.1       anton    3883: 
1.29    ! crook    3884: The word whose behaviour the alias is to inherit is represented by an
        !          3885: xt. Therefore, the alias can only inherits default semantics from its
        !          3886: ancestor. The semantics of the alias itself can be modified at the time
        !          3887: that it is defined. For example:
1.1       anton    3888: 
1.29    ! crook    3889: @example
        !          3890: : foo ... ; immediate
1.1       anton    3891: 
1.29    ! crook    3892: ' foo Alias bar \ bar is not an immediate word
        !          3893: ' foo Alias fooby immediate \ fooby is an immediate word
        !          3894: @end example
1.26      crook    3895: 
1.29    ! crook    3896: Words that are aliases have the same xt. Their semantics can differ
        !          3897: because the rules about a word's semantics are stored in the name
        !          3898: dictionary, and the aliases each have their own dictionary entry. It
        !          3899: follows that words that are aliases have different name tokens and may
        !          3900: have the same or different compilation tokens. Once again, see
        !          3901: @ref{Tokens for Words} for more discussions of this.
1.27      crook    3902: 
1.29    ! crook    3903: doc-create
1.26      crook    3904: doc-variable
                   3905: doc-2variable
                   3906: doc-fvariable
                   3907: doc-user
1.29    ! crook    3908: doc-constant
        !          3909: doc-2constant
        !          3910: doc-fconstant
1.26      crook    3911: doc-value
                   3912: doc-to
                   3913: doc-defer
                   3914: doc-is
1.29    ! crook    3915: doc-alias
        !          3916: @comment TODO document these: what's defers <is> [is]
        !          3917: doc-what's
1.28      crook    3918: doc-defers
1.26      crook    3919: 
                   3920: Definitions in ANS Forth for @code{defer}, @code{<is>} and
                   3921: @code{[is]} are provided in @file{compat/defer.fs}.
1.29    ! crook    3922: 
1.1       anton    3923: 
1.26      crook    3924: @node Colon Definitions, User-defined Defining Words, Simple Defining Words, Defining Words
                   3925: @subsection Colon Definitions
                   3926: @cindex colon definitions
1.1       anton    3927: 
1.26      crook    3928: @example
                   3929: : name ( ... -- ... )
                   3930:     word1 word2 word3 ;
                   3931: @end example
1.1       anton    3932: 
1.29    ! crook    3933: @noindent
        !          3934: Creates a word called @code{name} that, upon execution, executes
1.26      crook    3935: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.1       anton    3936: 
1.29    ! crook    3937: The explanation above is somewhat superficial. @xref{Your first
        !          3938: definition} for simple examples of colon definitions, then
        !          3939: @xref{Interpretation and Compilation Semantics} for an in-depth
        !          3940: discussion of some of the issues involved.
1.26      crook    3941: 
                   3942: doc-:
                   3943: doc-;
1.1       anton    3944: 
1.26      crook    3945: @node User-defined Defining Words, Supplying names, Colon Definitions, Defining Words
                   3946: @subsection User-defined Defining Words
                   3947: @cindex user-defined defining words
                   3948: @cindex defining words, user-defined
1.1       anton    3949: 
1.29    ! crook    3950: You can create a new defining word by wrapping defining-time code around
        !          3951: an existing defining word and putting the sequence in a colon
        !          3952: definition. For example, suppose that you have a word @code{stats} that
        !          3953: gathers statistics about colon definitions given the @i{xt} of the
        !          3954: definition, and you want every colon definition in your application to
        !          3955: make a call to @code{stats}. You can define and use a new version of
        !          3956: @code{:} like this:
        !          3957: 
        !          3958: @example
        !          3959: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
        !          3960:   ... ;  \ other code
        !          3961: 
        !          3962: : my: : lastxt postpone literal ['] stats compile, ;
        !          3963: 
        !          3964: my: foo + - ;
        !          3965: @end example
        !          3966: 
        !          3967: When @code{foo} is defined using @code{my:} these steps occur:
        !          3968: 
        !          3969: @itemize @bullet
        !          3970: @item
        !          3971: @code{my:} is executed.
        !          3972: @item
        !          3973: The @code{:} within the definition (the one between @code{my:} and
        !          3974: @code{lastxt}) is executed, and does just what it always does; it parses
        !          3975: the input stream for a name, builds a dictionary header for the name
        !          3976: @code{foo} and switches @code{state} from interpret to compile.
        !          3977: @item
        !          3978: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
        !          3979: being defined -- @code{foo} -- onto the stack.
        !          3980: @item
        !          3981: The code that was produced by @code{postpone literal} is executed; this
        !          3982: causes the value on the stack to be compiled as a literal in the code
        !          3983: area of @code{foo}.
        !          3984: @item
        !          3985: The code @code{['] stats} compiles a literal into the definition of
        !          3986: @code{my:}. When @code{compile,} is executed, that literal -- the
        !          3987: execution token for @code{stats} -- is layed down in the code area of
        !          3988: @code{foo} , following the literal@footnote{Strictly speaking, the
        !          3989: mechanism that @code{compile,} uses to convert an @i{xt} into something
        !          3990: in the code area is implementation-dependent. A threaded implementation
        !          3991: might spit out the execution token directly whilst another
        !          3992: implementation might spit out a native code sequence.}.
        !          3993: @item
        !          3994: At this point, the execution of @code{my:} is complete, and control
        !          3995: returns to the text interpreter. The text interpreter is in compile
        !          3996: state, so subsequent text @code{+ -} is compiled into the definition of
        !          3997: @code{foo} and the @code{;} terminates the definition as always.
        !          3998: @end itemize
        !          3999: 
        !          4000: You can use @code{see} to decompile a word that was defined using
        !          4001: @code{my:} and see how it is different from a normal @code{:}
        !          4002: definition. For example:
        !          4003: 
        !          4004: @example
        !          4005: : bar + - ;  \ like foo but using : rather than my:
        !          4006: see bar
        !          4007: : bar
        !          4008:   + - ;
        !          4009: see foo
        !          4010: : foo
        !          4011:   107645672 stats + - ;
        !          4012: 
        !          4013: \ use ' stats . to show that 107645672 is the xt for stats
        !          4014: @end example
        !          4015: 
        !          4016: 
        !          4017: Rather than edit your application's source code to change every @code{:}
        !          4018: to a @code{my:}, use a deferred word:
        !          4019: 
        !          4020: @example
        !          4021: : real: : ;     \ retain access to the original
        !          4022: defer :         \ redefine as a deferred word
        !          4023: ' my: IS :      \ use special version of :
        !          4024: \
        !          4025: \ load application here
        !          4026: \
        !          4027: ' real: IS :    \ go back to the original
        !          4028: @end example
        !          4029: 
        !          4030: You can use techniques like this to make new defining words in terms of
        !          4031: @i{any} existing defining word.
1.1       anton    4032: 
                   4033: 
1.29    ! crook    4034: @cindex defining defining words
1.26      crook    4035: @cindex @code{CREATE} ... @code{DOES>}
                   4036: If you want the words defined with your defining words to behave
                   4037: differently from words defined with standard defining words, you can
                   4038: write your defining word like this:
1.1       anton    4039: 
                   4040: @example
1.26      crook    4041: : def-word ( "name" -- )
1.29    ! crook    4042:     CREATE @i{code1}
1.26      crook    4043: DOES> ( ... -- ... )
1.29    ! crook    4044:     @i{code2} ;
1.26      crook    4045: 
                   4046: def-word name
1.1       anton    4047: @end example
                   4048: 
1.29    ! crook    4049: @cindex child words
        !          4050: This fragment defines a @dfn{defining word} @code{def-word} and then
        !          4051: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
        !          4052: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
        !          4053: is not executed at this time. The word @code{name} is sometimes called a
        !          4054: @dfn{child} of @code{def-word}.
        !          4055: 
        !          4056: When you execute @code{name}, the address of the body of @code{name} is
        !          4057: put on the data stack and @i{code2} is executed (the address of the body
        !          4058: of @code{name} is the address @code{HERE} returns immediately after the
        !          4059: @code{CREATE}).
        !          4060: 
        !          4061: @cindex atavism in child words
        !          4062: You can use @code{def-word} to define a set of child word that behave
        !          4063: differently, though atavistically; they all have a common run-time
        !          4064: behaviour determined by @i{code2}. Typically, the @i{code1} sequence
        !          4065: builds a data area in the body of the child word. The structure of the
        !          4066: data is common to all children of @code{def-word}, but the data values
        !          4067: are specific -- and private -- to each child word. When a child word is
        !          4068: executed, the address of its private data area is passed as a parameter
        !          4069: on TOS to be used and manipulated@footnote{It is legitimate both to read
        !          4070: and write to this data area.} by @i{code2}.
        !          4071: 
        !          4072: The two fragments of code that make up the defining words act (are
        !          4073: executed) at two completely separate times:
1.1       anton    4074: 
1.29    ! crook    4075: @itemize @bullet
        !          4076: @item
        !          4077: At @i{define time}, the defining word executes @i{code1} to generate a
        !          4078: child word
        !          4079: @item
        !          4080: At @i{child execution time}, when a child word is invoked, @i{code2}
        !          4081: is executed, using parameters (data) that are private and specific to
        !          4082: the child word.
        !          4083: @end itemize
        !          4084: 
        !          4085: @c NAC I think this is a really bad example, because it diminishes
        !          4086: @c rather than emphasising the fact that some important stuff happens
        !          4087: @c at define time, and other important stuff happens at child-invocation
        !          4088: @c time, and that those two times are potentially very different.
        !          4089: @c
        !          4090: @c In other words, if you make the following definitions:
        !          4091: @c @example
        !          4092: @c : def-word1 ( "name" -- )
        !          4093: @c     CREATE @i{code1} ;
        !          4094: @c 
        !          4095: @c : action1 ( ... -- ... )
        !          4096: @c     @i{code2} ;
        !          4097: @c 
        !          4098: @c def-word1 name1
        !          4099: @c @end example
        !          4100: @c 
        !          4101: @c Using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    4102: 
1.29    ! crook    4103: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    4104: 
1.1       anton    4105: @example
1.29    ! crook    4106: : CONSTANT ( w "name" -- )
        !          4107:     CREATE ,
1.26      crook    4108: DOES> ( -- w )
                   4109:     @@ ;
1.1       anton    4110: @end example
                   4111: 
1.29    ! crook    4112: @comment There is a beautiful description of how this works and what
        !          4113: @comment it does in the Forthwrite 100th edition.. as well as an elegant
        !          4114: @comment commentary on the Counting Fruits problem.
        !          4115: 
        !          4116: When you create a constant with @code{5 CONSTANT five}, a set of
        !          4117: define-time actions take place; first a new word @code{five} is created,
        !          4118: then the value 5 is laid down in the body of @code{five} with
        !          4119: @code{,}. When @code{five} is invoked, the address of the body is put on
        !          4120: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
        !          4121: no code of its own; it simply contains a data field and a pointer to the
        !          4122: code that follows @code{DOES>} in its defining word. That makes words
        !          4123: created in this way very compact.
        !          4124: 
        !          4125: The final example in this section is intended to remind you that space
        !          4126: reserved in @code{CREATE}d words is @i{data} space and therefore can be
        !          4127: both read and written by a Standard program@footnote{Exercise: use this
        !          4128: example as a starting point for your own implementation of @code{Value}
        !          4129: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
        !          4130: @code{[']}.}:
        !          4131: 
        !          4132: @example
        !          4133: : foo ( "name" -- )
        !          4134:     CREATE -1 ,
        !          4135: DOES> ( -- )
        !          4136:     @@ .;
        !          4137: 
        !          4138: foo first-word
        !          4139: foo second-word
        !          4140: 
        !          4141: 123 ' first-word >BODY !
        !          4142: @end example
        !          4143: 
        !          4144: If @code{first-word} had been a @code{CREATE}d word, we could simply
        !          4145: have executed it to get the address of its data field. However, since it
        !          4146: was defined to have @code{DOES>} actions, its execution semantics are to
        !          4147: perform those @code{DOES>} actions. To get the address of its data field
        !          4148: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
        !          4149: translate the xt into the address of the data field.  When you execute
        !          4150: @code{first-word}, it will display @code{123}. When you execute
        !          4151: @code{second-word} it will display @code{-1}.
1.26      crook    4152: 
                   4153: @cindex stack effect of @code{DOES>}-parts
                   4154: @cindex @code{DOES>}-parts, stack effect
1.29    ! crook    4155: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    4156: the stack effect of the defined words, not the stack effect of the
                   4157: following code (the following code expects the address of the body on
                   4158: the top of stack, which is not reflected in the stack comment). This is
                   4159: the convention that I use and recommend (it clashes a bit with using
                   4160: locals declarations for stack effect specification, though).
1.1       anton    4161: 
1.26      crook    4162: @subsubsection Applications of @code{CREATE..DOES>}
                   4163: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1       anton    4164: 
1.26      crook    4165: You may wonder how to use this feature. Here are some usage patterns:
1.1       anton    4166: 
1.26      crook    4167: @cindex factoring similar colon definitions
                   4168: When you see a sequence of code occurring several times, and you can
                   4169: identify a meaning, you will factor it out as a colon definition. When
                   4170: you see similar colon definitions, you can factor them using
                   4171: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   4172: that look very similar:
1.1       anton    4173: @example
1.26      crook    4174: : ori, ( reg-target reg-source n -- )
                   4175:     0 asm-reg-reg-imm ;
                   4176: : andi, ( reg-target reg-source n -- )
                   4177:     1 asm-reg-reg-imm ;
1.1       anton    4178: @end example
                   4179: 
1.26      crook    4180: @noindent
                   4181: This could be factored with:
                   4182: @example
                   4183: : reg-reg-imm ( op-code -- )
                   4184:     CREATE ,
                   4185: DOES> ( reg-target reg-source n -- )
                   4186:     @@ asm-reg-reg-imm ;
                   4187: 
                   4188: 0 reg-reg-imm ori,
                   4189: 1 reg-reg-imm andi,
                   4190: @end example
1.1       anton    4191: 
1.26      crook    4192: @cindex currying
                   4193: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   4194: supply a part of the parameters for a word (known as @dfn{currying} in
                   4195: the functional language community). E.g., @code{+} needs two
                   4196: parameters. Creating versions of @code{+} with one parameter fixed can
                   4197: be done like this:
1.1       anton    4198: @example
1.26      crook    4199: : curry+ ( n1 -- )
                   4200:     CREATE ,
                   4201: DOES> ( n2 -- n1+n2 )
                   4202:     @@ + ;
                   4203: 
                   4204:  3 curry+ 3+
                   4205: -2 curry+ 2-
1.1       anton    4206: @end example
                   4207: 
1.26      crook    4208: @subsubsection The gory details of @code{CREATE..DOES>}
                   4209: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    4210: 
1.26      crook    4211: doc-does>
1.1       anton    4212: 
1.26      crook    4213: @cindex @code{DOES>} in a separate definition
                   4214: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   4215: same definition; you can put the @code{DOES>}-part in a separate
1.29    ! crook    4216: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    4217: @example
                   4218: : does1 
                   4219: DOES> ( ... -- ... )
                   4220:     ... ;
1.1       anton    4221: 
1.26      crook    4222: : does2
                   4223: DOES> ( ... -- ... )
                   4224:     ... ;
1.1       anton    4225: 
1.26      crook    4226: : def-word ( ... -- ... )
                   4227:     create ...
                   4228:     IF
                   4229:        does1
                   4230:     ELSE
                   4231:        does2
                   4232:     ENDIF ;
                   4233: @end example
1.1       anton    4234: 
1.26      crook    4235: In this example, the selection of whether to use @code{does1} or
                   4236: @code{does2} is made at compile-time; at the time that the child word is
1.29    ! crook    4237: @code{CREATE}d.
1.1       anton    4238: 
1.26      crook    4239: @cindex @code{DOES>} in interpretation state
                   4240: In a standard program you can apply a @code{DOES>}-part only if the last
                   4241: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   4242: will override the behaviour of the last word defined in any case. In a
                   4243: standard program, you can use @code{DOES>} only in a colon
                   4244: definition. In Gforth, you can also use it in interpretation state, in a
                   4245: kind of one-shot mode; for example:
1.1       anton    4246: @example
1.26      crook    4247: CREATE name ( ... -- ... )
1.29    ! crook    4248:   @i{initialization}
1.26      crook    4249: DOES>
1.29    ! crook    4250:   @i{code} ;
1.1       anton    4251: @end example
                   4252: 
1.26      crook    4253: @noindent
                   4254: is equivalent to the standard:
1.1       anton    4255: @example
1.26      crook    4256: :noname
                   4257: DOES>
1.29    ! crook    4258:     @i{code} ;
1.26      crook    4259: CREATE name EXECUTE ( ... -- ... )
1.29    ! crook    4260:     @i{initialization}
1.1       anton    4261: @end example
                   4262: 
1.26      crook    4263: You can get the address of the body of a word with:
                   4264: 
                   4265: doc->body
1.1       anton    4266: 
1.26      crook    4267: @node Supplying names, Interpretation and Compilation Semantics, User-defined Defining Words, Defining Words
1.29    ! crook    4268: @subsection Supplying the name of a defined word
1.26      crook    4269: @cindex names for defined words
                   4270: @cindex defining words, name parameter
1.1       anton    4271: 
1.26      crook    4272: @cindex defining words, name given in a string
1.29    ! crook    4273: By default, a defining word takes the name for the defined word from the
1.26      crook    4274: input stream. Sometimes you want to supply the name from a string. You
                   4275: can do this with:
1.1       anton    4276: 
1.26      crook    4277: doc-nextname
1.1       anton    4278: 
1.26      crook    4279: For example:
1.1       anton    4280: 
1.26      crook    4281: @example
                   4282: s" foo" nextname create
                   4283: @end example
                   4284: @noindent
                   4285: is equivalent to:
                   4286: @example
                   4287: create foo
                   4288: @end example
1.1       anton    4289: 
1.26      crook    4290: @cindex defining words without name
1.29    ! crook    4291: Sometimes you want to define an @dfn{anonymous word}; a word without a
1.26      crook    4292: name. You can do this with:
1.1       anton    4293: 
1.26      crook    4294: doc-:noname
1.1       anton    4295: 
1.26      crook    4296: This leaves the execution token for the word on the stack after the
                   4297: closing @code{;}. Here's an example in which a deferred word is
                   4298: initialised with an @code{xt} from an anonymous colon definition:
                   4299: @example
                   4300: Defer deferred
                   4301: :noname ( ... -- ... )
                   4302:   ... ;
                   4303: IS deferred
                   4304: @end example
1.1       anton    4305: 
1.29    ! crook    4306: @noindent
1.26      crook    4307: Gforth provides an alternative way of doing this, using two separate
                   4308: words:
1.1       anton    4309: 
1.26      crook    4310: doc-noname
                   4311: @cindex execution token of last defined word
                   4312: doc-lastxt
1.1       anton    4313: 
1.29    ! crook    4314: @noindent
1.26      crook    4315: The previous example can be rewritten using @code{noname} and
                   4316: @code{lastxt}:
1.1       anton    4317: 
1.26      crook    4318: @example
                   4319: Defer deferred
                   4320: noname : ( ... -- ... )
                   4321:   ... ;
                   4322: lastxt IS deferred
                   4323: @end example
1.1       anton    4324: 
1.29    ! crook    4325: @noindent
1.26      crook    4326: @code{lastxt} also works when the last word was not defined as
1.29    ! crook    4327: @code{noname}. It also has the useful property that is is valid as soon
        !          4328: as the header for a definition has been build. Thus:
        !          4329: 
        !          4330: @example
        !          4331: lastxt . : foo [ lastxt . ] ; ' foo .
        !          4332: @end example
        !          4333: 
        !          4334: @noindent
        !          4335: prints 3 numbers; the last two are the same.
1.1       anton    4336: 
                   4337: 
1.26      crook    4338: @node Interpretation and Compilation Semantics,  , Supplying names, Defining Words
                   4339: @subsection Interpretation and Compilation Semantics
                   4340: @cindex semantics, interpretation and compilation
1.1       anton    4341: 
1.26      crook    4342: @cindex interpretation semantics
                   4343: The @dfn{interpretation semantics} of a word are what the text
                   4344: interpreter does when it encounters the word in interpret state. It also
                   4345: appears in some other contexts, e.g., the execution token returned by
1.29    ! crook    4346: @code{' @i{word}} identifies the interpretation semantics of
        !          4347: @i{word} (in other words, @code{' @i{word} execute} is equivalent to
        !          4348: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    4349: 
1.26      crook    4350: @cindex compilation semantics
                   4351: The @dfn{compilation semantics} of a word are what the text interpreter
                   4352: does when it encounters the word in compile state. It also appears in
1.29    ! crook    4353: other contexts, e.g, @code{POSTPONE @i{word}} compiles@footnote{In
1.26      crook    4354: standard terminology, ``appends to the current definition''.} the
1.29    ! crook    4355: compilation semantics of @i{word}.
1.1       anton    4356: 
1.26      crook    4357: @cindex execution semantics
                   4358: The standard also talks about @dfn{execution semantics}. They are used
                   4359: only for defining the interpretation and compilation semantics of many
                   4360: words. By default, the interpretation semantics of a word are to
                   4361: @code{execute} its execution semantics, and the compilation semantics of
                   4362: a word are to @code{compile,} its execution semantics.@footnote{In
                   4363: standard terminology: The default interpretation semantics are its
                   4364: execution semantics; the default compilation semantics are to append its
                   4365: execution semantics to the execution semantics of the current
                   4366: definition.}
                   4367: 
                   4368: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   4369: 
                   4370: @cindex immediate words
                   4371: @cindex compile-only words
                   4372: You can change the semantics of the most-recently defined word:
                   4373: 
                   4374: doc-immediate
                   4375: doc-compile-only
                   4376: doc-restrict
                   4377: 
                   4378: Note that ticking (@code{'}) a compile-only word gives an error
                   4379: (``Interpreting a compile-only word'').
1.1       anton    4380: 
1.26      crook    4381: Gforth also allows you to define words with arbitrary combinations of
                   4382: interpretation and compilation semantics.
1.1       anton    4383: 
1.26      crook    4384: doc-interpret/compile:
1.1       anton    4385: 
1.26      crook    4386: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   4387: recommend that you do not define such words, as cute as they may be:
                   4388: they make it hard to get at both parts of the word in some contexts.
                   4389: E.g., assume you want to get an execution token for the compilation
                   4390: part. Instead, define two words, one that embodies the interpretation
                   4391: part, and one that embodies the compilation part.  Once you have done
                   4392: that, you can define a combined word with @code{interpret/compile:} for
                   4393: the convenience of your users.
1.1       anton    4394: 
1.26      crook    4395: You might try to use this feature to provide an optimizing
                   4396: implementation of the default compilation semantics of a word. For
                   4397: example, by defining:
1.1       anton    4398: @example
1.26      crook    4399: :noname
                   4400:    foo bar ;
                   4401: :noname
                   4402:    POSTPONE foo POSTPONE bar ;
1.29    ! crook    4403: interpret/compile: opti-foobar
1.1       anton    4404: @end example
1.26      crook    4405: 
1.23      crook    4406: @noindent
1.26      crook    4407: as an optimizing version of:
                   4408: 
1.1       anton    4409: @example
1.26      crook    4410: : foobar
                   4411:     foo bar ;
1.1       anton    4412: @end example
                   4413: 
1.26      crook    4414: Unfortunately, this does not work correctly with @code{[compile]},
                   4415: because @code{[compile]} assumes that the compilation semantics of all
                   4416: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29    ! crook    4417: opti-foobar} would compile compilation semantics, whereas
        !          4418: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    4419: 
1.26      crook    4420: @cindex state-smart words (are a bad idea)
1.29    ! crook    4421: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    4422: by @code{interpret/compile:} (words are state-smart if they check
                   4423: @code{STATE} during execution). E.g., they would try to code
                   4424: @code{foobar} like this:
1.1       anton    4425: 
1.26      crook    4426: @example
                   4427: : foobar
                   4428:   STATE @@
                   4429:   IF ( compilation state )
                   4430:     POSTPONE foo POSTPONE bar
                   4431:   ELSE
                   4432:     foo bar
                   4433:   ENDIF ; immediate
                   4434: @end example
1.1       anton    4435: 
1.26      crook    4436: Although this works if @code{foobar} is only processed by the text
                   4437: interpreter, it does not work in other contexts (like @code{'} or
                   4438: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   4439: for a state-smart word, not for the interpretation semantics of the
                   4440: original @code{foobar}; when you execute this execution token (directly
                   4441: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   4442: state, the result will not be what you expected (i.e., it will not
                   4443: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   4444: write them@footnote{For a more detailed discussion of this topic, see
                   4445: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
                   4446: Ertl; presented at EuroForth '98 and available from
                   4447: @url{http://www.complang.tuwien.ac.at/papers/}}!
1.1       anton    4448: 
1.26      crook    4449: @cindex defining words with arbitrary semantics combinations
                   4450: It is also possible to write defining words that define words with
                   4451: arbitrary combinations of interpretation and compilation semantics. In
                   4452: general, they look like this:
1.1       anton    4453: 
1.26      crook    4454: @example
                   4455: : def-word
                   4456:     create-interpret/compile
1.29    ! crook    4457:     @i{code1}
1.26      crook    4458: interpretation>
1.29    ! crook    4459:     @i{code2}
1.26      crook    4460: <interpretation
                   4461: compilation>
1.29    ! crook    4462:     @i{code3}
1.26      crook    4463: <compilation ;
                   4464: @end example
1.1       anton    4465: 
1.29    ! crook    4466: For a @i{word} defined with @code{def-word}, the interpretation
        !          4467: semantics are to push the address of the body of @i{word} and perform
        !          4468: @i{code2}, and the compilation semantics are to push the address of
        !          4469: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    4470: can also be defined like this (except that the defined constants don't
                   4471: behave correctly when @code{[compile]}d):
1.1       anton    4472: 
1.26      crook    4473: @example
                   4474: : constant ( n "name" -- )
                   4475:     create-interpret/compile
                   4476:     ,
                   4477: interpretation> ( -- n )
                   4478:     @@
                   4479: <interpretation
                   4480: compilation> ( compilation. -- ; run-time. -- n )
                   4481:     @@ postpone literal
                   4482: <compilation ;
                   4483: @end example
1.1       anton    4484: 
1.26      crook    4485: doc-create-interpret/compile
                   4486: doc-interpretation>
                   4487: doc-<interpretation
                   4488: doc-compilation>
                   4489: doc-<compilation
1.1       anton    4490: 
1.29    ! crook    4491: Words defined with @code{interpret/compile:} and
1.26      crook    4492: @code{create-interpret/compile} have an extended header structure that
                   4493: differs from other words; however, unless you try to access them with
                   4494: plain address arithmetic, you should not notice this. Words for
                   4495: accessing the header structure usually know how to deal with this; e.g.,
1.29    ! crook    4496: @code{'} @i{word} @code{>body} also gives you the body of a word created
        !          4497: with @code{create-interpret/compile}.
1.1       anton    4498: 
1.27      crook    4499: doc-postpone
1.29    ! crook    4500: @comment TODO -- expand glossary text for POSTPONE
1.27      crook    4501: 
1.26      crook    4502: @c ----------------------------------------------------------
                   4503: @node The Text Interpreter, Tokens for Words, Defining Words, Words
                   4504: @section  The Text Interpreter
                   4505: @cindex interpreter - outer
                   4506: @cindex text interpreter
                   4507: @cindex outer interpreter
1.1       anton    4508: 
1.29    ! crook    4509: The text interpreter@footnote{This is an expanded version of the
        !          4510: material in @ref{Introducing the Text Interpreter}.} is an endless loop
        !          4511: that processes input from the current input device. A popular
        !          4512: implementation technique for Forth is to implement a @dfn{forth virtual
        !          4513: machine} using a loop called the @dfn{inner interpreter}. Because of
        !          4514: this naming, the text interpreter is also known as the @dfn{outer
1.27      crook    4515: interpreter}.
                   4516: 
1.29    ! crook    4517: @cindex interpret state
        !          4518: @cindex compile state
        !          4519: The text interpreter operates in one of two states: @dfn{interpret
        !          4520: state} and @dfn{compile state}. The current state is defined by the
        !          4521: aptly-named variable, @code{state}.
        !          4522: 
        !          4523: This section starts by describing how the text interpreter behaves when
        !          4524: it is in interpret state, processing input from the user input device --
        !          4525: the keyboard. This is the mode that a Forth system is in after it starts
        !          4526: up.
        !          4527: 
        !          4528: @cindex input buffer
        !          4529: @cindex terminal input buffer
        !          4530: The text interpreter works from an area of memory called the @dfn{input
        !          4531: buffer}@footnote{When the text interpreter is processing input from the
        !          4532: keyboard, this area of memory is called the @dfn{terminal input buffer}
        !          4533: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
        !          4534: @code{#TIB}.}, which stores your keyboard input when you press the
        !          4535: <return> key. Starting at the beginning of the input buffer, it skips
        !          4536: leading spaces (called @dfn{delimiters}) then parses a string (a
        !          4537: sequence of non-space characters) until it reaches either a space
        !          4538: character or the end of the buffer. Having parsed a string, it makes two
        !          4539: attempts to process it:
1.27      crook    4540: 
1.29    ! crook    4541: @cindex dictionary
1.27      crook    4542: @itemize @bullet
                   4543: @item
1.29    ! crook    4544: It looks for the string in a @dfn{dictionary} of definitions. If the
        !          4545: string is found, the string names a @dfn{definition} (also known as a
        !          4546: @dfn{word}) and the dictionary search returns information that allows
        !          4547: the text interpreter to perform the word's @dfn{interpretation
        !          4548: semantics}. In most cases, this simply means that the word will be
        !          4549: executed.
1.27      crook    4550: @item
                   4551: If the string is not found in the dictionary, the text interpreter
1.29    ! crook    4552: attempts to treat it as a number, using the rules described in
        !          4553: @ref{Number Conversion}. If the string represents a legal number in the
        !          4554: current radix, the number is pushed onto a parameter stack (the data
        !          4555: stack for integers, the floating-point stack for floating-point
        !          4556: numbers).
        !          4557: @end itemize
        !          4558: 
        !          4559: If both attempts fail, or if the word is found in the dictionary but has
        !          4560: no interpretation semantics@footnote{This happens if the word was
        !          4561: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
        !          4562: remainder of the input buffer, issues an error message and waits for
        !          4563: more input. If one of the attempts succeeds, the text interpreter
        !          4564: repeats the parsing process until the whole of the input buffer has been
        !          4565: processed, at which point it prints the status message ``@code{ ok}''
        !          4566: and waits for more input.
        !          4567: 
        !          4568: @cindex parse area
        !          4569: The text interpreter keeps track of its position in the input buffer by
        !          4570: updating a variable called @code{>IN} (pronounced ``to-in''). The value
        !          4571: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
        !          4572: of the input buffer. The region from offset @code{>IN @@} to the end of
        !          4573: the input buffer is called the @dfn{parse area}@footnote{In other words,
        !          4574: the text interpreter processes the contents of the input buffer by
        !          4575: parsing strings from the parse area until the parse area is empty.}.
        !          4576: This example shows how @code{>IN} changes as the text interpreter parses
        !          4577: the input buffer:
        !          4578: 
        !          4579: @example
        !          4580: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
        !          4581:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
        !          4582: 
        !          4583: 1 2 3 remaining + remaining . 
        !          4584: 
        !          4585: : foo 1 2 3 remaining SWAP remaining ;
        !          4586: @end example
        !          4587: 
        !          4588: @noindent
        !          4589: The result is:
        !          4590: 
        !          4591: @example
        !          4592: ->+ remaining .<-
        !          4593: ->.<-5  ok
        !          4594: 
        !          4595: ->SWAP remaining ;-<
        !          4596: ->;<-  ok
        !          4597: @end example
        !          4598: 
        !          4599: @cindex parsing words
        !          4600: The value of @code{>IN} can also be modified by a word in the input
        !          4601: buffer that is executed by the text interpreter.  This means that a word
        !          4602: can ``trick'' the text interpreter into either skipping a section of the
        !          4603: input buffer@footnote{This is how parsing words work.} or into parsing a
        !          4604: section twice. For example:
1.27      crook    4605: 
1.29    ! crook    4606: @example
        !          4607: : lat ." <<lat>>" ;
        !          4608: : flat ." <<flat>>" >IN DUP @@ 3 - SWAP ! ;
        !          4609: @end example
        !          4610: 
        !          4611: @noindent
        !          4612: When @code{flat} is executed, this output is produced@footnote{Exercise
        !          4613: for the reader: what would happen if the @code{3} were replaced with
        !          4614: @code{4}?}:
        !          4615: 
        !          4616: @example
        !          4617: <<flat>><<lat>>
        !          4618: @end example
        !          4619: 
        !          4620: @noindent
        !          4621: Two important notes about the behaviour of the text interpreter:
1.27      crook    4622: 
                   4623: @itemize @bullet
                   4624: @item
                   4625: It processes each input string to completion before parsing additional
1.29    ! crook    4626: characters from the input buffer.
        !          4627: @item
        !          4628: It treats the input buffer as a read-only region (and so must your code).
        !          4629: @end itemize
        !          4630: 
        !          4631: @noindent
        !          4632: When the text interpreter is in compile state, its behaviour changes in
        !          4633: these ways:
        !          4634: 
        !          4635: @itemize @bullet
        !          4636: @item
        !          4637: If a parsed string is found in the dictionary, the text interpreter will
        !          4638: perform the word's @dfn{compilation semantics}. In most cases, this
        !          4639: simply means that the execution semantics of the word will be appended
        !          4640: to the current definition.
1.27      crook    4641: @item
1.29    ! crook    4642: When a number is encountered, it is compiled into the current definition
        !          4643: (as a literal) rather than being pushed onto a parameter stack.
        !          4644: @item
        !          4645: If an error occurs, @code{state} is modified to put the text interpreter
        !          4646: back into interpret state.
        !          4647: @item
        !          4648: Each time a line is entered from the keyboard, Gforth prints
        !          4649: ``@code{ compiled}'' rather than `` @code{ok}''.
        !          4650: @end itemize
        !          4651: 
        !          4652: @cindex text interpreter - input sources
        !          4653: When the text interpreter is using an input device other than the
        !          4654: keyboard, its behaviour changes in these ways:
        !          4655: 
        !          4656: @itemize @bullet
        !          4657: @item
        !          4658: When the parse area is empty, the text interpreter attempts to refill
        !          4659: the input buffer from the input source. When the input source is
        !          4660: exhausted, the input source is set back to the user input device.
        !          4661: @item
        !          4662: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
        !          4663: time the parse area is emptied.
        !          4664: @item
        !          4665: If an error occurs, the input source is set back to the user input
        !          4666: device.
1.27      crook    4667: @end itemize
1.21      crook    4668: 
1.29    ! crook    4669: @ref{Input Sources} describes this in more detail.
        !          4670: 
1.26      crook    4671: doc->in
1.27      crook    4672: doc-source
                   4673: 
1.26      crook    4674: doc-tib
                   4675: doc-#tib
1.1       anton    4676: 
1.26      crook    4677: @menu
1.29    ! crook    4678: * Input Sources::
1.26      crook    4679: * Number Conversion::
                   4680: * Interpret/Compile states::
                   4681: * Literals::
                   4682: * Interpreter Directives::
                   4683: @end menu
1.1       anton    4684: 
1.29    ! crook    4685: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
        !          4686: @subsection Input Sources
        !          4687: @cindex input sources
        !          4688: @cindex text interpreter - input sources
        !          4689: 
        !          4690: By default, the text interpreter accepts input from the user input
        !          4691: device (the keyboard) when Forth starts up. The text interpreter can
        !          4692: process input from any of these sources:
        !          4693: 
        !          4694: @itemize @bullet
        !          4695: @item
        !          4696: The user input device -- the keyboard.
        !          4697: @item
        !          4698: A file, using the words described in @ref{Forth source files}.
        !          4699: @item
        !          4700: A block, using the words described in @ref{Blocks}.
        !          4701: @item
        !          4702: A text string, using @code{evaluate}.
        !          4703: @end itemize
        !          4704: 
        !          4705: A program can identify the current input device from the values of
        !          4706: @code{source-id} and @code{blk}.
        !          4707: 
        !          4708: doc-source-id
        !          4709: doc-blk
        !          4710: 
        !          4711: doc-save-input
        !          4712: doc-restore-input
        !          4713: 
        !          4714: doc-evaluate
1.1       anton    4715: 
1.29    ! crook    4716: 
        !          4717: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    4718: @subsection Number Conversion
                   4719: @cindex number conversion
                   4720: @cindex double-cell numbers, input format
                   4721: @cindex input format for double-cell numbers
                   4722: @cindex single-cell numbers, input format
                   4723: @cindex input format for single-cell numbers
                   4724: @cindex floating-point numbers, input format
                   4725: @cindex input format for floating-point numbers
1.1       anton    4726: 
1.29    ! crook    4727: This section describes the rules that the text interpreter uses when it
        !          4728: tries to convert a string into a number.
1.1       anton    4729: 
1.26      crook    4730: Let <digit> represent any character that is a legal digit in the current
1.29    ! crook    4731: number base@footnote{For example, 0-9 when the number base is decimal or
        !          4732: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    4733: 
1.26      crook    4734: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    4735: 
1.29    ! crook    4736: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
        !          4737: in the braces (@i{a} or @i{b} or neither).
1.1       anton    4738: 
1.26      crook    4739: Let * represent any number of instances of the previous character
                   4740: (including none).
1.1       anton    4741: 
1.26      crook    4742: Let any other character represent itself.
1.1       anton    4743: 
1.29    ! crook    4744: @noindent
1.26      crook    4745: Now, the conversion rules are:
1.21      crook    4746: 
1.26      crook    4747: @itemize @bullet
                   4748: @item
                   4749: A string of the form <digit><digit>* is treated as a single-precision
1.29    ! crook    4750: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    4751: @item
                   4752: A string of the form -<digit><digit>* is treated as a single-precision
1.29    ! crook    4753: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    4754: arithmetic. Examples are -45 -5681 -0
                   4755: @item
                   4756: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29    ! crook    4757: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
        !          4758: (all three of these represent the same number).
1.26      crook    4759: @item
                   4760: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29    ! crook    4761: double-precision (double-cell-sized) negative integer, and is
1.26      crook    4762: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29    ! crook    4763: -34.65 (all three of these represent the same number).
1.26      crook    4764: @item
1.29    ! crook    4765: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
        !          4766: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.26      crook    4767: number. Examples are 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29    ! crook    4768: number) +12.E-4
1.26      crook    4769: @end itemize
1.1       anton    4770: 
1.26      crook    4771: By default, the number base used for integer number conversion is given
1.29    ! crook    4772: by the contents of the variable @code{BASE}. Base 10 (decimal) is
1.26      crook    4773: always used for floating-point number conversion.
1.1       anton    4774: 
1.29    ! crook    4775: doc-dpl
1.26      crook    4776: doc-base
                   4777: doc-hex
                   4778: doc-decimal
1.1       anton    4779: 
1.26      crook    4780: @cindex '-prefix for character strings
                   4781: @cindex &-prefix for decimal numbers
                   4782: @cindex %-prefix for binary numbers
                   4783: @cindex $-prefix for hexadecimal numbers
1.29    ! crook    4784: Gforth allows you to override the value of @code{BASE} by using a
        !          4785: prefix@footnote{Some Forth implementations provide a similar scheme by
        !          4786: implementing @code{$} etc. as parsing words that process the subsequent
        !          4787: number in the input stream and push it onto the stack. For example, see
        !          4788: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
        !          4789: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
        !          4790: is required between the prefix and the number.} before the first digit
        !          4791: of an (integer) number. Four prefixes are supported:
1.1       anton    4792: 
1.26      crook    4793: @itemize @bullet
                   4794: @item
                   4795: @code{&} -- decimal number
                   4796: @item
                   4797: @code{%} -- binary number
                   4798: @item
                   4799: @code{$} -- hexadecimal number
                   4800: @item
                   4801: @code{'} -- base 256 number
                   4802: @end itemize
1.1       anton    4803: 
1.26      crook    4804: Here are some examples, with the equivalent decimal number shown after
                   4805: in braces:
1.1       anton    4806: 
1.26      crook    4807: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
                   4808: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
                   4809: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
                   4810: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    4811: 
1.26      crook    4812: @cindex number conversion - traps for the unwary
1.29    ! crook    4813: @noindent
1.26      crook    4814: Number conversion has a number of traps for the unwary:
1.1       anton    4815: 
1.26      crook    4816: @itemize @bullet
                   4817: @item
                   4818: You cannot determine the current number base using the code sequence
                   4819: @code{BASE @@ .} -- the number base is always 10 in the current number
                   4820: base. Instead, use something like @code{BASE @@ DECIMAL DUP . BASE !}
                   4821: @item
                   4822: If the number base is set to a value greater than 14 (for example,
                   4823: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   4824: it to be intepreted as either a single-precision integer or a
                   4825: floating-point number (Gforth treats it as an integer). The ambiguity
                   4826: can be resolved by explicitly stating the sign of the mantissa and/or
                   4827: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   4828: ambiguity arises; either representation will be treated as a
                   4829: floating-point number.
                   4830: @item
1.29    ! crook    4831: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    4832: It is used to specify file types.
                   4833: @item
                   4834: ANS Forth requires the @code{.} of a double-precision number to
                   4835: be the final character in the string. Allowing the @code{.} to be
                   4836: anywhere after the first digit is a Gforth extension.
                   4837: @item
                   4838: The number conversion process does not check for overflow.
                   4839: @item
                   4840: In Gforth, number conversion to floating-point numbers always use base
                   4841: 10, irrespective of the value of @code{BASE}. In ANS Forth,
                   4842: conversion to floating-point numbers whilst the value of
                   4843: @code{BASE} is not 10 is an ambiguous condition.
                   4844: @end itemize
1.1       anton    4845: 
1.29    ! crook    4846: @ref{Input} describes words that you can use to read numbers into your
        !          4847: programs.
1.1       anton    4848: 
1.26      crook    4849: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
                   4850: @subsection Interpret/Compile states
                   4851: @cindex Interpret/Compile states
1.1       anton    4852: 
1.29    ! crook    4853: A standard program is not permitted to change @code{state}
        !          4854: explicitly. However, it can change @code{state} implicitly, using the
        !          4855: words @code{[} and @code{]}. When @code{[} is executed it switches
        !          4856: @code{state} to interpret state, and therefore the text interpreter
        !          4857: starts interpreting. When @code{]} is executed it switches @code{state}
        !          4858: to compile state and therefore the text interpreter starts
        !          4859: compiling. The most common usage for these words is to compile literals,
        !          4860: as shown in @ref{Literals}. However, they give you the freedom to switch
        !          4861: modes at will. Here is an example of building a jump-table of execution
        !          4862: tokens:
        !          4863: 
        !          4864: @example
        !          4865: : AA ." this is A" ;
        !          4866: : BB ." this is B" ;
        !          4867: : CC ." this is C" ;
        !          4868: 
        !          4869: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
        !          4870: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
        !          4871:   cells table + @ execute ;
        !          4872: @end example
        !          4873: 
        !          4874: @noindent
        !          4875: Now @code{0 go} will display ``@code{this is A}''. The table can be
        !          4876: built far more neatly@footnote{The source code is neater.. what is
        !          4877: compiled in memory in each case is identical.} like this:
        !          4878: 
        !          4879: @example
        !          4880: create table ] aa bb cc [
        !          4881: @end example
        !          4882: 
        !          4883: The problem with this code is that it is not portable; it will only work
        !          4884: on systems where code space and data space co-incide. The reason is that
        !          4885: both tables @i{compile} execution tokens -- into code space. The
        !          4886: Standard only allows data space to be assigned for a @code{CREATE}d
        !          4887: word. In addition, the Standard only allows @code{@@} to access data
        !          4888: space, whilst this example is using it to access code space. The only
        !          4889: portable, Standard way to build this table is to build it in data space,
        !          4890: like this:
        !          4891: 
        !          4892: @example
        !          4893: create table ' aa , ' bb , ' cc ,
        !          4894: @end example
        !          4895: 
        !          4896: @noindent
        !          4897: A similar technique can be used to build a table of constants:
        !          4898: 
        !          4899: @example
        !          4900: create primes 1 , 3 , 5 , 7 , 11 ,
        !          4901: @end example
1.1       anton    4902: 
1.26      crook    4903: doc-state
                   4904: doc-[
                   4905: doc-]
1.1       anton    4906: 
1.26      crook    4907: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
                   4908: @subsection Literals
                   4909: @cindex Literals
1.21      crook    4910: 
1.29    ! crook    4911: Often, you want to use a number within a colon definition. When you do
        !          4912: this, the text interpreter automatically compiles the number as a
        !          4913: @i{literal}. A literal is a number whose run-time effect is to be pushed
        !          4914: onto the stack.  If you had to do some maths to generate the number, you
        !          4915: might write it like this:
        !          4916: 
        !          4917: @example
        !          4918: : HOUR-TO-SEC ( n1 -- n2 )
        !          4919:   60 *      \ to minutes
        !          4920:   60 * ;    \ to seconds
        !          4921: @end example
        !          4922: 
        !          4923: It is very clear what this definition is doing, but it's inefficient
        !          4924: since it is performing 2 multiples at run-time. An alternative would be
        !          4925: to write:
        !          4926: 
        !          4927: @example
        !          4928: : HOUR-TO-SEC ( n1 -- n2 )
        !          4929:   3600 * ;  \ to seconds
        !          4930: @end example
        !          4931: 
        !          4932: Which does the same thing, and has the advantage of using a single
        !          4933: multiply. Ideally, we'd like the efficiency of the second with the
        !          4934: readability of the first.
        !          4935: 
        !          4936: @code{Literal} allows us to achieve that. It takes a number from the
        !          4937: stack and lays it down in the current definition just as though the
        !          4938: number had been typed directly into the definition. Our first attempt
        !          4939: might look like this:
        !          4940: 
        !          4941: @example
        !          4942: 60          \ mins per hour
        !          4943: 60 *        \ seconds per minute
        !          4944: : HOUR-TO-SEC ( n1 -- n2 )
        !          4945:   Literal * ;  \ to seconds
        !          4946: @end example
        !          4947: 
        !          4948: But this produces the error message @code{unstructured}. What happened?
        !          4949: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
        !          4950: @i{colon-sys} is implementation-defined. In other words, once we start a
        !          4951: colon definition we can't portably access anything that was on the stack
        !          4952: before the definition began@footnote{@cite{Two Problems in ANS Forth},
        !          4953: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
        !          4954: some situations where you might want to access stack items above
        !          4955: colon-sys, and provides a solution to the problem.}. The correct way of
        !          4956: solving this problem in this instance is to use @code{[ ]} like this:
        !          4957: 
        !          4958: @example
        !          4959: : HOUR-TO-SEC ( n1 -- n2 )
        !          4960:   [ 60          \ minutes per hour
        !          4961:     60 * ]      \ seconds per minute
        !          4962:   LITERAL * ;   \ to seconds
        !          4963: @end example
1.23      crook    4964: 
1.26      crook    4965: doc-literal
                   4966: doc-]L
                   4967: doc-2literal
                   4968: doc-fliteral
1.1       anton    4969: 
1.29    ! crook    4970: @node Interpreter Directives, , Literals, The Text Interpreter
1.26      crook    4971: @subsection Interpreter Directives
                   4972: @cindex interpreter directives
1.1       anton    4973: 
1.29    ! crook    4974: These words are usually used in interpret state; typically to control
        !          4975: which parts of a source file are processed by the text
1.26      crook    4976: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   4977: supplements these with a rich set of immediate control structure words
                   4978: to compensate for the fact that the non-immediate versions can only be
1.29    ! crook    4979: used in compile state (@pxref{Control Structures}). Typical usages:
        !          4980: 
        !          4981: @example
        !          4982: FALSE Constant ASSEMBLER
        !          4983: .
        !          4984: .
        !          4985: ASSEMBLER [IF]
        !          4986: : ASSEMBLER-FEATURE
        !          4987:   ...
        !          4988: ;
        !          4989: [ENDIF]
        !          4990: .
        !          4991: .
        !          4992: : SEE
        !          4993:   ... \ general-purpose SEE code
        !          4994:   [ ASSEMBLER [IF] ]
        !          4995:   ... \ assembler-specific SEE code
        !          4996:   [ [ENDIF] ]
        !          4997: ;
        !          4998: @end example
1.1       anton    4999: 
1.26      crook    5000: doc-[IF]
                   5001: doc-[ELSE]
                   5002: doc-[THEN]
                   5003: doc-[ENDIF]
1.1       anton    5004: 
1.26      crook    5005: doc-[IFDEF]
                   5006: doc-[IFUNDEF]
1.1       anton    5007: 
1.26      crook    5008: doc-[?DO]
                   5009: doc-[DO]
                   5010: doc-[FOR]
                   5011: doc-[LOOP]
                   5012: doc-[+LOOP]
                   5013: doc-[NEXT]
1.1       anton    5014: 
1.26      crook    5015: doc-[BEGIN]
                   5016: doc-[UNTIL]
                   5017: doc-[AGAIN]
                   5018: doc-[WHILE]
                   5019: doc-[REPEAT]
1.1       anton    5020: 
1.27      crook    5021: 
                   5022: 
1.26      crook    5023: @c -------------------------------------------------------------
                   5024: @node Tokens for Words, Word Lists, The Text Interpreter, Words
                   5025: @section Tokens for Words
                   5026: @cindex tokens for words
1.1       anton    5027: 
1.28      crook    5028: This section describes the creation and use of tokens that represent
1.29    ! crook    5029: words.
        !          5030: 
        !          5031: Named words have information stored in their name dictionary entries to
        !          5032: indicate any non-default semantics (@pxref{Interpretation and
        !          5033: Compilation Semantics}). The semantics can be modified, using
        !          5034: @code{immediate} and/or @code{compile-only}, at the time that the words
        !          5035: are defined. Unnamed words have (by definition) no name dictionary
        !          5036: entry, and therefore must have default semantics.
1.21      crook    5037: 
1.26      crook    5038: Named words have interpretation and compilation semantics. Unnamed words
                   5039: just have execution semantics.
1.21      crook    5040: 
1.29    ! crook    5041: @cindex xt
        !          5042: @cindex execution token
        !          5043: The execution semantics of an unnamed word are represented by an
        !          5044: @dfn{execution token} (@i{xt}). As explained in @ref{Supplying names},
        !          5045: the execution token of the last word defined can be produced with
        !          5046: @code{lastxt}.
        !          5047: 
        !          5048: The interpretation semantics of a named word are also represented by an
        !          5049: execution token. You can produce the execution token using @code{'} or
        !          5050: @code{[']}. A simple example shows the difference between the two:
1.21      crook    5051: 
1.29    ! crook    5052: @example
        !          5053: : greet ( -- )   ." Hello" ;
        !          5054: : foo ( -- xt )  ['] greet ; \ ['] parses greet at compile-time
        !          5055: : bar ( -- )     ' EXECUTE ; \  '  parses at run-time
1.1       anton    5056: 
1.29    ! crook    5057: \ the next four lines all do the same thing
        !          5058: foo EXECUTE
        !          5059: greet
        !          5060: ' greet EXECUTE
        !          5061: boo greet
        !          5062: @end example
1.1       anton    5063: 
1.29    ! crook    5064: An execution token occupies one cell.
1.26      crook    5065: @cindex code field address
                   5066: @cindex CFA
1.29    ! crook    5067: In Gforth, the abstract data type @i{execution token} is implemented
1.26      crook    5068: as a code field address (CFA).
                   5069: @comment TODO note that the standard does not say what it represents..
                   5070: @comment and you cannot necessarily compile it in all Forths (eg native
                   5071: @comment compilers?).
1.1       anton    5072: 
1.29    ! crook    5073: For literals, use @code{'} in interpreted code and @code{[']} in
        !          5074: compiled code. Gforth's @code{'} and @code{[']} behave somewhat
        !          5075: unusually by complaining about compile-only words. To get the execution
        !          5076: token for a compile-only word @i{name}, use @code{COMP' @i{name} DROP}
        !          5077: or @code{[COMP'] @i{name} DROP}.
1.1       anton    5078: 
1.26      crook    5079: @cindex compilation token
1.29    ! crook    5080: The compilation semantics of a named word are represented by a
        !          5081: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
        !          5082: @i{xt} is an execution token. The compilation semantics represented by
        !          5083: the compilation token can be performed with @code{execute}, which
        !          5084: consumes the whole compilation token, with an additional stack effect
        !          5085: determined by the represented compilation semantics.
        !          5086: 
        !          5087: At present, the @i{w} part of a compilation token is an execution token,
        !          5088: and the @i{xt} part represents either @code{execute} or
        !          5089: @code{compile,}@footnote{Depending upon the compilation semantics of the
        !          5090: word. If the word has default compilation semantics, the @i{xt} will
        !          5091: represent @code{compile,}. If the word is @code{immediate}, the @i{xt}
        !          5092: will represent @code{execute}.}. However, don't rely on that knowledge,
        !          5093: unless necessary; future versions of Gforth may introduce unusual
        !          5094: compilation tokens (e.g., a compilation token that represents the
        !          5095: compilation semantics of a literal).
1.1       anton    5096: 
1.26      crook    5097: You can compile the compilation semantics with @code{postpone,}. I.e.,
1.29    ! crook    5098: @code{COMP' @i{word} postpone,} is equivalent to @code{postpone
        !          5099: @i{word}}.
1.21      crook    5100: 
1.26      crook    5101: @cindex name token
                   5102: @cindex name field address
                   5103: @cindex NFA
1.29    ! crook    5104: Named words are also represented by the @dfn{name token}, (@i{nt}). In
        !          5105: Gforth, the abstract data type @emph{name token} is implemented as a
        !          5106: name field address (NFA).
        !          5107: 
        !          5108: doc-execute
        !          5109: doc-compile,
        !          5110: doc-[']
        !          5111: doc-'
        !          5112: doc-[comp']
        !          5113: doc-comp'
        !          5114: doc-postpone,
1.1       anton    5115: 
1.26      crook    5116: doc-find-name
                   5117: doc-name>int
                   5118: doc-name?int
                   5119: doc-name>comp
                   5120: doc-name>string
1.1       anton    5121: 
1.26      crook    5122: @c -------------------------------------------------------------
                   5123: @node Word Lists, Environmental Queries, Tokens for Words, Words
                   5124: @section Word Lists
                   5125: @cindex word lists
                   5126: @cindex name dictionary
1.1       anton    5127: 
1.26      crook    5128: @cindex wid
                   5129: All definitions other than those created by @code{:noname} have an entry
                   5130: in the name dictionary. The name dictionary is fragmented into a number
1.29    ! crook    5131: of parts, called @dfn{word lists}. A word list is identified by a
        !          5132: cell-sized word list identifier (@i{wid}) in much the same way as a
1.26      crook    5133: file is identified by a file handle. The numerical value of the wid has
                   5134: no (portable) meaning, and might change from session to session.
1.1       anton    5135: 
1.26      crook    5136: @cindex compilation word list
                   5137: At any one time, a single word list is defined as the word list to which
1.29    ! crook    5138: all new definitions will be added -- this is called the @dfn{compilation
1.26      crook    5139: word list}. When Gforth is started, the compilation word list is the
                   5140: word list called @code{FORTH-WORDLIST}.
1.1       anton    5141: 
1.26      crook    5142: @cindex search order stack
1.29    ! crook    5143: Forth maintains a stack of word lists, representing the @dfn{search
1.26      crook    5144: order}.  When the name dictionary is searched (for example, when
                   5145: attempting to find a word's execution token during compilation), only
                   5146: those word lists that are currently in the search order are
                   5147: searched. The most recently-defined word in the word list at the top of
                   5148: the word list stack is searched first, and the search proceeds until
                   5149: either the word is located or the oldest definition in the word list at
                   5150: the bottom of the stack is reached. Definitions of the word may exist in
                   5151: more than one word lists; the search order determines which version will
                   5152: be found.
1.1       anton    5153: 
1.29    ! crook    5154: The ANS Forth ``Search order'' word set is intended to provide a set of
        !          5155: low-level tools that allow various different schemes to be
1.26      crook    5156: implemented. Gforth provides @code{vocabulary}, a traditional Forth
                   5157: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
                   5158: Standard Forth.
1.1       anton    5159: 
1.27      crook    5160: @comment TODO: locals section refers to here, saying that every word list (aka
                   5161: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.1       anton    5162: 
1.27      crook    5163: @comment the thisone- prefix is used to pick out the true definition of a
                   5164: @comment word from the source files, rather than some alias.
1.26      crook    5165: doc-forth-wordlist
                   5166: doc-definitions
                   5167: doc-get-current
                   5168: doc-set-current
                   5169: doc-get-order
1.27      crook    5170: doc---thisone-set-order
1.26      crook    5171: doc-wordlist
                   5172: doc-also
1.27      crook    5173: doc---thisone-forth
1.26      crook    5174: doc-only
1.27      crook    5175: doc---thisone-order
1.26      crook    5176: doc-previous
1.15      anton    5177: 
1.26      crook    5178: doc-find
                   5179: doc-search-wordlist
1.15      anton    5180: 
1.26      crook    5181: doc-words
                   5182: doc-vlist
1.1       anton    5183: 
1.26      crook    5184: doc-mappedwordlist
                   5185: doc-root
                   5186: doc-vocabulary
                   5187: doc-seal
                   5188: doc-vocs
                   5189: doc-current
                   5190: doc-context
1.1       anton    5191: 
1.26      crook    5192: @menu
                   5193: * Why use word lists?::
                   5194: * Word list examples::
                   5195: @end menu
                   5196: 
                   5197: @node Why use word lists?, Word list examples, Word Lists, Word Lists
                   5198: @subsection Why use word lists?
                   5199: @cindex word lists - why use them?
                   5200: 
1.29    ! crook    5201: Here are some reasons for using multiple word lists:
1.26      crook    5202: 
                   5203: @itemize @bullet
                   5204: @item
                   5205: To improve compilation speed by reducing the number of name dictionary
                   5206: entries that must be searched. This is achieved by creating a new
                   5207: word list that contains all of the definitions that are used in the
                   5208: definition of a Forth system but which would not usually be used by
                   5209: programs running on that system. That word list would be on the search
                   5210: list when the Forth system was compiled but would be removed from the
                   5211: search list for normal operation. This can be a useful technique for
                   5212: low-performance systems (for example, 8-bit processors in embedded
                   5213: systems) but is unlikely to be necessary in high-performance desktop
                   5214: systems.
                   5215: @item
                   5216: To prevent a set of words from being used outside the context in which
                   5217: they are valid. Two classic examples of this are an integrated editor
                   5218: (all of the edit commands are defined in a separate word list; the
                   5219: search order is set to the editor word list when the editor is invoked;
                   5220: the old search order is restored when the editor is terminated) and an
                   5221: integrated assembler (the op-codes for the machine are defined in a
                   5222: separate word list which is used when a @code{CODE} word is defined).
                   5223: @item
                   5224: To prevent a name-space clash between multiple definitions with the same
                   5225: name. For example, when building a cross-compiler you might have a word
                   5226: @code{IF} that generates conditional code for your target system. By
                   5227: placing this definition in a different word list you can control whether
                   5228: the host system's @code{IF} or the target system's @code{IF} get used in
                   5229: any particular context by controlling the order of the word lists on the
                   5230: search order stack.
                   5231: @end itemize
1.1       anton    5232: 
1.26      crook    5233: @node Word list examples, ,Why use word lists?, Word Lists
                   5234: @subsection Word list examples
                   5235: @cindex word lists - examples
1.1       anton    5236: 
1.26      crook    5237: Here is an example of creating and using a new wordlist using ANS
                   5238: Forth Standard words:
1.1       anton    5239: 
                   5240: @example
1.26      crook    5241: wordlist constant my-new-words-wordlist
                   5242: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
1.21      crook    5243: 
1.26      crook    5244: \ add it to the search order
                   5245: also my-new-words
1.21      crook    5246: 
1.26      crook    5247: \ alternatively, add it to the search order and make it
                   5248: \ the compilation word list
                   5249: also my-new-words definitions
                   5250: \ type "order" to see the problem
1.21      crook    5251: @end example
                   5252: 
1.26      crook    5253: The problem with this example is that @code{order} has no way to
                   5254: associate the name @code{my-new-words} with the wid of the word list (in
                   5255: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   5256: that has no associated name). There is no Standard way of associating a
                   5257: name with a wid.
                   5258: 
                   5259: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   5260: associates a name with a wid:
1.21      crook    5261: 
1.26      crook    5262: @example
                   5263: vocabulary my-new-words
1.21      crook    5264: 
1.26      crook    5265: \ add it to the search order
                   5266: my-new-words
1.21      crook    5267: 
1.26      crook    5268: \ alternatively, add it to the search order and make it
                   5269: \ the compilation word list
                   5270: my-new-words definitions
                   5271: \ type "order" to see that the problem is solved
                   5272: @end example
1.23      crook    5273: 
1.26      crook    5274: @c -------------------------------------------------------------
                   5275: @node Environmental Queries, Files, Word Lists, Words
                   5276: @section Environmental Queries
                   5277: @cindex environmental queries
1.21      crook    5278: 
1.26      crook    5279: ANS Forth introduced the idea of ``environmental queries'' as a way
                   5280: for a program running on a system to determine certain characteristics of the system.
                   5281: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    5282: 
1.26      crook    5283: The Standard requires that the name space used for environmental queries
                   5284: be distinct from the name space used for definitions.
1.21      crook    5285: 
1.26      crook    5286: Typically, environmental queries are supported by creating a set of
1.29    ! crook    5287: definitions in a word list that is @i{only} used during environmental
1.26      crook    5288: queries; that is what Gforth does. There is no Standard way of adding
                   5289: definitions to the set of recognised environmental queries, but any
                   5290: implementation that supports the loading of optional word sets must have
                   5291: some mechanism for doing this (after loading the word set, the
                   5292: associated environmental query string must return @code{true}). In
                   5293: Gforth, the word list used to honour environmental queries can be
                   5294: manipulated just like any other word list.
1.21      crook    5295: 
1.26      crook    5296: doc-environment?
                   5297: doc-environment-wordlist
1.21      crook    5298: 
1.26      crook    5299: doc-gforth
                   5300: doc-os-class
1.21      crook    5301: 
1.26      crook    5302: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   5303: returning two items on the stack, querying it using @code{environment?}
                   5304: will return an additional item; the @code{true} flag that shows that the
                   5305: string was recognised.
1.21      crook    5306: 
1.26      crook    5307: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    5308: 
1.26      crook    5309: Here are some examples of using environmental queries:
1.21      crook    5310: 
1.26      crook    5311: @example
                   5312: s" address-unit-bits" environment? 0=
                   5313: [IF]
                   5314:      cr .( environmental attribute address-units-bits unknown... ) cr
                   5315: [THEN]
1.21      crook    5316: 
1.26      crook    5317: s" block" environment? [IF] DROP include block.fs [THEN]
1.21      crook    5318: 
1.26      crook    5319: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
1.21      crook    5320: 
1.26      crook    5321: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   5322:                         [ELSE] .( Not Gforth..) [THEN]
                   5323: @end example
1.21      crook    5324: 
                   5325: 
1.26      crook    5326: Here is an example of adding a definition to the environment word list:
1.21      crook    5327: 
1.26      crook    5328: @example
                   5329: get-current environment-wordlist set-current
                   5330: true constant block
                   5331: true constant block-ext
                   5332: set-current
                   5333: @end example
1.21      crook    5334: 
1.26      crook    5335: You can see what definitions are in the environment word list like this:
1.21      crook    5336: 
1.26      crook    5337: @example
                   5338: get-order 1+ environment-wordlist swap set-order words previous
                   5339: @end example
1.21      crook    5340: 
                   5341: 
1.26      crook    5342: @c -------------------------------------------------------------
                   5343: @node Files, Blocks, Environmental Queries, Words
                   5344: @section Files
1.28      crook    5345: @cindex files
                   5346: @cindex I/O - file-handling
1.21      crook    5347: 
1.26      crook    5348: Gforth provides facilities for accessing files that are stored in the
                   5349: host operating system's file-system. Files that are processed by Gforth
                   5350: can be divided into two categories:
1.21      crook    5351: 
1.23      crook    5352: @itemize @bullet
                   5353: @item
1.29    ! crook    5354: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    5355: @item
1.29    ! crook    5356: Files that are processed by some other program (@dfn{general files}).
1.26      crook    5357: @end itemize
                   5358: 
                   5359: @menu
                   5360: * Forth source files::
                   5361: * General files::         
                   5362: * Search Paths::                 
                   5363: * Forth Search Paths::    
                   5364: * General Search Paths::        
                   5365: @end menu
                   5366: 
1.21      crook    5367: 
1.26      crook    5368: @c -------------------------------------------------------------
                   5369: @node Forth source files, General files, Files, Files
                   5370: @subsection Forth source files
                   5371: @cindex including files
                   5372: @cindex Forth source files
1.21      crook    5373: 
1.26      crook    5374: The simplest way to interpret the contents of a file is to use one of
                   5375: these two formats:
1.21      crook    5376: 
1.26      crook    5377: @example
                   5378: include mysource.fs
                   5379: s" mysource.fs" included
                   5380: @end example
1.21      crook    5381: 
1.26      crook    5382: Sometimes you want to include a file only if it is not included already
                   5383: (by, say, another source file). In that case, you can use one of these
                   5384: fomats:
1.21      crook    5385: 
1.26      crook    5386: @example
                   5387: require mysource.fs
                   5388: needs mysource.fs
                   5389: s" mysource.fs" required
                   5390: @end example
1.21      crook    5391: 
1.26      crook    5392: @cindex stack effect of included files
                   5393: @cindex including files, stack effect
                   5394: I recommend that you write your source files such that interpreting them
                   5395: does not change the stack. This allows using these files with
                   5396: @code{required} and friends without complications. For example:
1.21      crook    5397: 
1.26      crook    5398: @example
                   5399: 1 require foo.fs drop
                   5400: @end example
1.21      crook    5401: 
1.26      crook    5402: doc-include-file
                   5403: doc-included
1.28      crook    5404: doc-included?
1.26      crook    5405: doc-include
                   5406: doc-required
                   5407: doc-require
                   5408: doc-needs
1.28      crook    5409: doc-init-included-files
1.21      crook    5410: 
1.26      crook    5411: A definition in ANS Forth for @code{required} is provided in
                   5412: @file{compat/required.fs}.
1.21      crook    5413: 
1.26      crook    5414: @c -------------------------------------------------------------
                   5415: @node General files, Search Paths, Forth source files, Files
                   5416: @subsection General files
                   5417: @cindex general files
                   5418: @cindex file-handling
1.21      crook    5419: 
1.26      crook    5420: Files are opened/created by name and type. The following types are
                   5421: recognised:
1.1       anton    5422: 
1.26      crook    5423: doc-r/o
                   5424: doc-r/w
                   5425: doc-w/o
                   5426: doc-bin
1.1       anton    5427: 
1.26      crook    5428: When a file is opened/created, it returns a file identifier,
1.29    ! crook    5429: @i{wfileid} that is used for all other file commands. All file
        !          5430: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    5431: successful operation and an implementation-defined non-zero value in the
                   5432: case of an error.
1.21      crook    5433: 
1.26      crook    5434: doc-open-file
                   5435: doc-create-file
1.21      crook    5436: 
1.26      crook    5437: doc-close-file
                   5438: doc-delete-file
                   5439: doc-rename-file
                   5440: doc-read-file
                   5441: doc-read-line
                   5442: doc-write-file
                   5443: doc-write-line
                   5444: doc-emit-file
                   5445: doc-flush-file
1.21      crook    5446: 
1.26      crook    5447: doc-file-status
                   5448: doc-file-position
                   5449: doc-reposition-file
                   5450: doc-file-size
                   5451: doc-resize-file
1.21      crook    5452: 
1.26      crook    5453: @c ---------------------------------------------------------
                   5454: @node Search Paths, Forth Search Paths, General files, Files
                   5455: @subsection Search Paths
                   5456: @cindex path for @code{included}
                   5457: @cindex file search path
                   5458: @cindex @code{include} search path
                   5459: @cindex search path for files
1.21      crook    5460: 
1.26      crook    5461: If you specify an absolute filename (i.e., a filename starting with
                   5462: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   5463: @samp{C:...})) for @code{included} and friends, that file is included
                   5464: just as you would expect.
1.21      crook    5465: 
1.26      crook    5466: For relative filenames, Gforth uses a search path similar to Forth's
                   5467: search order (@pxref{Word Lists}). It tries to find the given filename
                   5468: in the directories present in the path, and includes the first one it
                   5469: finds. There are separate search paths for Forth source files and
                   5470: general files.
1.21      crook    5471: 
1.26      crook    5472: If the search path contains the directory @file{.} (as it should), this
                   5473: refers to the directory that the present file was @code{included}
                   5474: from. This allows files to include other files relative to their own
                   5475: position (irrespective of the current working directory or the absolute
                   5476: position).  This feature is essential for libraries consisting of
                   5477: several files, where a file may include other files from the library.
                   5478: It corresponds to @code{#include "..."} in C. If the current input
                   5479: source is not a file, @file{.} refers to the directory of the innermost
                   5480: file being included, or, if there is no file being included, to the
                   5481: current working directory.
1.21      crook    5482: 
1.26      crook    5483: Use @file{~+} to refer to the current working directory (as in the
                   5484: @code{bash}).
1.1       anton    5485: 
1.26      crook    5486: If the filename starts with @file{./}, the search path is not searched
                   5487: (just as with absolute filenames), and the @file{.} has the same meaning
                   5488: as described above.
1.1       anton    5489: 
1.26      crook    5490: @c ---------------------------------------------------------
                   5491: @node Forth Search Paths, General Search Paths, Search Paths, Files
                   5492: @subsubsection Forth Search Paths
1.28      crook    5493: @cindex search path control - Forth
1.5       anton    5494: 
1.26      crook    5495: The search path is initialized when you start Gforth (@pxref{Invoking
                   5496: Gforth}). You can display it and change it using these words:
1.5       anton    5497: 
1.26      crook    5498: doc-.fpath
                   5499: doc-fpath+
                   5500: doc-fpath=
                   5501: doc-open-fpath-file
1.5       anton    5502: 
1.26      crook    5503: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    5504: 
1.26      crook    5505: @example
                   5506: fpath= /usr/lib/forth/|./
                   5507: require timer.fs
                   5508: @end example
1.5       anton    5509: 
1.26      crook    5510: @c ---------------------------------------------------------
                   5511: @node General Search Paths,  , Forth Search Paths, Files
                   5512: @subsubsection General Search Paths
                   5513: @cindex search path control - for user applications
1.5       anton    5514: 
1.26      crook    5515: Your application may need to search files in several directories, like
                   5516: @code{included} does. To facilitate this, Gforth allows you to define
                   5517: and use your own search paths, by providing generic equivalents of the
                   5518: Forth search path words:
1.5       anton    5519: 
1.26      crook    5520: doc-.path
                   5521: doc-path+
                   5522: doc-path=
                   5523: doc-open-path-file
1.5       anton    5524: 
1.26      crook    5525: Here's an example of creating a search path:
1.5       anton    5526: 
1.26      crook    5527: @example
                   5528: \ Make a buffer for the path:
                   5529: create mypath   100 chars ,     \ maximum length (is checked)
                   5530:                 0 ,             \ real len
                   5531:                 100 chars allot \ space for path
                   5532: @end example
1.5       anton    5533: 
1.26      crook    5534: @c -------------------------------------------------------------
                   5535: @node Blocks, Other I/O, Files, Words
                   5536: @section Blocks
1.28      crook    5537: @cindex I/O - blocks
                   5538: @cindex blocks
                   5539: 
                   5540: When you run Gforth on a modern desk-top computer, it runs under the
                   5541: control of an operating system which provides certain services.  One of
                   5542: these services is @var{file services}, which allows Forth source code
                   5543: and data to be stored in files and read into Gforth (@pxref{Files}).
                   5544: 
                   5545: Traditionally, Forth has been an important programming language on
                   5546: systems where it has interfaced directly to the underlying hardware with
                   5547: no intervening operating system. Forth provides a mechanism, called
1.29    ! crook    5548: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    5549: 
                   5550: A block is a 1024-byte data area, which can be used to hold data or
                   5551: Forth source code. No structure is imposed on the contents of the
                   5552: block. A block is identified by its number; blocks are numbered
                   5553: contiguously from 1 to an implementation-defined maximum.
                   5554: 
                   5555: A typical system that used blocks but no operating system might use a
                   5556: single floppy-disk drive for mass storage, with the disks formatted to
                   5557: provide 256-byte sectors. Blocks would be implemented by assigning the
                   5558: first four sectors of the disk to block 1, the second four sectors to
                   5559: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   5560: would not contain any file system information, just the set of blocks.
                   5561: 
1.29    ! crook    5562: @cindex blocks file
1.28      crook    5563: On systems that do provide file services, blocks are typically
1.29    ! crook    5564: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    5565: file}.  The size of the blocks file will be an exact multiple of 1024
                   5566: bytes, corresponding to the number of blocks it contains. This is the
                   5567: mechanism that Gforth uses.
                   5568: 
1.29    ! crook    5569: @cindex @file{blocks.fb}
1.28      crook    5570: Only 1 blocks file can be open at a time. If you use block words without
                   5571: having specified a blocks file, Gforth defaults to the blocks file
                   5572: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
                   5573: locate a blocks file (@pxref{Forth Search Paths}).
                   5574: 
1.29    ! crook    5575: @cindex block buffers
1.28      crook    5576: When you read and write blocks under program control, Gforth uses a
1.29    ! crook    5577: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    5578: not used when you use @code{load} to interpret the contents of a block.
                   5579: 
                   5580: The behaviour of the block buffers is directly analagous to that of a
                   5581: cache. Each block buffer has three states:
                   5582: 
                   5583: @itemize @bullet
                   5584: @item
                   5585: Unassigned
                   5586: @item
                   5587: Assigned-clean
                   5588: @item
                   5589: Assigned-dirty
                   5590: @end itemize
                   5591: 
1.29    ! crook    5592: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    5593: block, the block (specified by its block number) must be assigned to a
                   5594: block buffer.
                   5595: 
                   5596: The assignment of a block to a block buffer is performed by @code{block}
                   5597: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   5598: contents of a block. Use @code{buffer} when you don't care about the
                   5599: existing contents of the block@footnote{The ANS Forth definition of
                   5600: @code{block} is intended not to cause disk I/O; if the data associated
                   5601: with the particular block is already stored in a block buffer due to an
                   5602: earlier @code{block} command, @code{buffer} will return that block
                   5603: buffer and the existing contents of the block will be
                   5604: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29    ! crook    5605: block buffer for the block.}.
1.28      crook    5606: 
                   5607: Once a block has been assigned to a block buffer, the block buffer state
1.29    ! crook    5608: becomes @i{assigned-clean}. Data can now be manipulated within the
1.28      crook    5609: block buffer.
                   5610: 
                   5611: When the contents of a block buffer is changed it is necessary,
                   5612: @i{before calling} @code{block} @i{or} @code{buffer} @i{again}, to
                   5613: either abandon the changes (by doing nothing) or commit the changes,
                   5614: using @code{update}. Using @code{update} does not change the blocks
1.29    ! crook    5615: file; it simply changes a block buffer's state to @i{assigned-dirty}.
1.28      crook    5616: 
1.29    ! crook    5617: The word @code{flush} causes all @i{assigned-dirty} blocks to be
1.28      crook    5618: written back to the blocks file on disk. Leaving Gforth using @code{bye}
                   5619: also causes a @code{flush} to be performed.
                   5620: 
1.29    ! crook    5621: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    5622: algorithm to assign a block buffer to a block. That means that any
                   5623: particular block can only be assigned to one specific block buffer,
1.29    ! crook    5624: called (for the particular operation) the @i{victim buffer}. If the
        !          5625: victim buffer is @i{unassigned} or @i{assigned-clean} it can be
        !          5626: allocated to the new block immediately. If it is @i{assigned-dirty}
1.28      crook    5627: its current contents must be written out to disk before it can be
                   5628: allocated to the new block.
                   5629: 
                   5630: Although no structure is imposed on the contents of a block, it is
                   5631: traditional to display the contents as 16 lines each of 64 characters.  A
                   5632: block provides a single, continuous stream of input (for example, it
                   5633: acts as a single parse area) -- there are no end-of-line characters
                   5634: within a block, and no end-of-file character at the end of a
                   5635: block. There are two consequences of this:
1.26      crook    5636: 
1.28      crook    5637: @itemize @bullet
                   5638: @item
                   5639: The last character of one line wraps straight into the first character
                   5640: of the following line
                   5641: @item
                   5642: The word @code{\} -- comment to end of line -- requires special
                   5643: treatment; in the context of a block it causes all characters until the
                   5644: end of the current 64-character ``line'' to be ignored.
                   5645: @end itemize
                   5646: 
                   5647: In Gforth, when you use @code{block} with a non-existent block number,
                   5648: the current block file will be extended to the appropriate size and the
                   5649: block buffer will be initialised with spaces.
                   5650: 
1.29    ! crook    5651: Gforth doesn't encourage the use of blocks; the mechanism is only
        !          5652: provided for backward compatibility -- ANS Forth requires blocks to be
        !          5653: available when files are.
1.28      crook    5654: 
                   5655: Common techniques that are used when working with blocks include:
                   5656: 
                   5657: @itemize @bullet
                   5658: @item
                   5659: A screen editor that allows you to edit blocks without leaving the Forth
                   5660: environment.
                   5661: @item
                   5662: Shadow screens; where every code block has an associated block
                   5663: containing comments (for example: code in odd block numbers, comments in
                   5664: even block numbers). Typically, the block editor provides a convenient
                   5665: mechanism to toggle between code and comments.
                   5666: @item
                   5667: Load blocks; a single block (typically block 1) contains a number of
                   5668: @code{thru} commands which @code{load} the whole of the application.
                   5669: @item
                   5670: Chaining blocks; a block terminates with a @code{-->} so that a whole
                   5671: application can be @code{load}ed by @code{load}ing a single block.
                   5672: @end itemize
1.26      crook    5673: 
1.29    ! crook    5674: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
        !          5675: integrated into a Forth programming environment.
1.26      crook    5676: 
                   5677: @comment TODO what about errors on open-blocks?
                   5678: doc-open-blocks
                   5679: doc-use
                   5680: doc-get-block-fid
                   5681: doc-block-position
1.28      crook    5682: 
                   5683: doc-scr
                   5684: doc-list
                   5685: 
                   5686: doc---block-block
                   5687: doc-buffer
                   5688: 
1.26      crook    5689: doc-update
1.28      crook    5690: doc-updated?
1.26      crook    5691: doc-save-buffers
                   5692: doc-empty-buffers
                   5693: doc-empty-buffer
                   5694: doc-flush
1.28      crook    5695: 
1.26      crook    5696: doc-load
                   5697: doc-thru
                   5698: doc-+load
                   5699: doc-+thru
                   5700: doc---block--->
                   5701: doc-block-included
                   5702: 
                   5703: @c -------------------------------------------------------------
                   5704: @node Other I/O, Programming Tools, Blocks, Words
                   5705: @section Other I/O
1.28      crook    5706: @cindex I/O - keyboard and display
1.26      crook    5707: 
                   5708: @menu
                   5709: * Simple numeric output::       Predefined formats
                   5710: * Formatted numeric output::    Formatted (pictured) output
                   5711: * String Formats::              How Forth stores strings in memory
                   5712: * Displaying characters and strings:: Other stuff
                   5713: * Input::                       Input
                   5714: @end menu
                   5715: 
                   5716: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   5717: @subsection Simple numeric output
1.28      crook    5718: @cindex numeric output - simple/free-format
1.5       anton    5719: 
1.26      crook    5720: The simplest output functions are those that display numbers from the
                   5721: data or floating-point stacks. Floating-point output is always displayed
                   5722: using base 10. Numbers displayed from the data stack use the value stored
                   5723: in @code{base}.
1.5       anton    5724: 
1.26      crook    5725: doc-.
                   5726: doc-dec.
                   5727: doc-hex.
                   5728: doc-u.
                   5729: doc-.r
                   5730: doc-u.r
                   5731: doc-d.
                   5732: doc-ud.
                   5733: doc-d.r
                   5734: doc-ud.r
                   5735: doc-f.
                   5736: doc-fe.
                   5737: doc-fs.
1.5       anton    5738: 
1.26      crook    5739: Examples of printing the number 1234.5678E23 in the different floating-point output
                   5740: formats are shown below:
1.5       anton    5741: 
                   5742: @example
1.26      crook    5743: f. 123456779999999000000000000.
                   5744: fe. 123.456779999999E24
                   5745: fs. 1.23456779999999E26
1.5       anton    5746: @end example
                   5747: 
                   5748: 
1.26      crook    5749: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   5750: @subsection Formatted numeric output
1.28      crook    5751: @cindex formatted numeric output
1.26      crook    5752: @cindex pictured numeric output
1.28      crook    5753: @cindex numeric output - formatted
1.26      crook    5754: 
1.29    ! crook    5755: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    5756: output} for formatted printing of integers.  In this technique, digits
                   5757: are extracted from the number (using the current output radix defined by
                   5758: @code{base}), converted to ASCII codes and appended to a string that is
                   5759: built in a scratch-pad area of memory (@pxref{core-idef,
                   5760: Implementation-defined options, Implementation-defined
                   5761: options}). Arbitrary characters can be appended to the string during the
                   5762: extraction process. The completed string is specified by an address
                   5763: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   5764: under program control.
1.5       anton    5765: 
1.26      crook    5766: All of the words described in the previous section for simple numeric
                   5767: output are implemented in Gforth using pictured numeric output.
1.5       anton    5768: 
1.26      crook    5769: Three important things to remember about Pictured Numeric Output:
1.5       anton    5770: 
1.26      crook    5771: @itemize @bullet
                   5772: @item
1.28      crook    5773: It always operates on double-precision numbers; to display a
                   5774: single-precision number, convert it first (@pxref{Double precision} for
                   5775: ways of doing this).
1.26      crook    5776: @item
1.28      crook    5777: It always treats the double-precision number as though it were
                   5778: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    5779: @item
                   5780: The string is built up from right to left; least significant digit first.
                   5781: @end itemize
1.5       anton    5782: 
1.26      crook    5783: doc-<#
                   5784: doc-#
                   5785: doc-#s
                   5786: doc-hold
                   5787: doc-sign
                   5788: doc-#>
1.5       anton    5789: 
1.26      crook    5790: doc-represent
1.5       anton    5791: 
1.26      crook    5792: Here are some examples of using pictured numeric output:
1.5       anton    5793: 
                   5794: @example
1.26      crook    5795: : my-u. ( u -- )
                   5796:   \ Simplest use of pns.. behaves like Standard u. 
                   5797:   0              \ convert to unsigned double
                   5798:   <#             \ start conversion
                   5799:   #s             \ convert all digits
                   5800:   #>             \ complete conversion
                   5801:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    5802: 
1.26      crook    5803: : cents-only ( u -- )
                   5804:   0              \ convert to unsigned double
                   5805:   <#             \ start conversion
                   5806:   # #            \ convert two least-significant digits
                   5807:   #>             \ complete conversion, discard other digits
                   5808:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    5809: 
1.26      crook    5810: : dollars-and-cents ( u -- )
                   5811:   0              \ convert to unsigned double
                   5812:   <#             \ start conversion
                   5813:   # #            \ convert two least-significant digits
                   5814:   [char] . hold  \ insert decimal point
                   5815:   #s             \ convert remaining digits
                   5816:   [char] $ hold  \ append currency symbol
                   5817:   #>             \ complete conversion
                   5818:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    5819: 
1.26      crook    5820: : my-. ( n -- )
                   5821:   \ handling negatives.. behaves like Standard .
                   5822:   s>d            \ convert to signed double
                   5823:   swap over dabs \ leave sign byte followed by unsigned double
                   5824:   <#             \ start conversion
                   5825:   #s             \ convert all digits
                   5826:   rot sign       \ get at sign byte, append "-" if needed
                   5827:   #>             \ complete conversion
                   5828:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    5829: 
1.26      crook    5830: : account. ( n -- )
                   5831:   \ accountants don't like minus signs, they use braces
                   5832:   \ for negative numbers
                   5833:   s>d            \ convert to signed double
                   5834:   swap over dabs \ leave sign byte followed by unsigned double
                   5835:   <#             \ start conversion
                   5836:   2 pick         \ get copy of sign byte
                   5837:   0< IF [char] ) hold THEN \ right-most character of output
                   5838:   #s             \ convert all digits
                   5839:   rot            \ get at sign byte
                   5840:   0< IF [char] ( hold THEN
                   5841:   #>             \ complete conversion
                   5842:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    5843: @end example
                   5844: 
1.26      crook    5845: Here are some examples of using these words:
1.5       anton    5846: 
                   5847: @example
1.26      crook    5848: 1 my-u. 1
                   5849: hex -1 my-u. decimal FFFFFFFF
                   5850: 1 cents-only 01
                   5851: 1234 cents-only 34
                   5852: 2 dollars-and-cents $0.02
                   5853: 1234 dollars-and-cents $12.34
                   5854: 123 my-. 123
                   5855: -123 my. -123
                   5856: 123 account. 123
                   5857: -456 account. (456)
1.5       anton    5858: @end example
                   5859: 
                   5860: 
1.26      crook    5861: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   5862: @subsection String Formats
1.27      crook    5863: @cindex strings - see character strings
                   5864: @cindex character strings - formats
1.28      crook    5865: @cindex I/O - see character strings
1.26      crook    5866: 
1.27      crook    5867: Forth commonly uses two different methods for representing character
                   5868: strings:
1.26      crook    5869: 
                   5870: @itemize @bullet
                   5871: @item
                   5872: @cindex address of counted string
1.29    ! crook    5873: As a @dfn{counted string}, represented by a @i{c-addr}. The char
        !          5874: addressed by @i{c-addr} contains a character-count, @i{n}, of the
        !          5875: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    5876: memory.
                   5877: @item
1.29    ! crook    5878: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
        !          5879: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    5880: first byte of the string.
                   5881: @end itemize
                   5882: 
                   5883: ANS Forth encourages the use of the second format when representing
                   5884: strings on the stack, whilst conceeding that the counted string format
                   5885: remains useful as a way of storing strings in memory.
                   5886: 
                   5887: doc-count
                   5888: 
                   5889: @xref{Memory Blocks} for words that move, copy and search
                   5890: for strings. @xref{Displaying characters and strings,} for words that
                   5891: display characters and strings.
                   5892: 
                   5893: 
                   5894: @node Displaying characters and strings, Input, String Formats, Other I/O
                   5895: @subsection Displaying characters and strings
1.27      crook    5896: @cindex characters - compiling and displaying
                   5897: @cindex character strings - compiling and displaying
1.26      crook    5898: 
                   5899: This section starts with a glossary of Forth words and ends with a set
                   5900: of examples.
                   5901: 
                   5902: doc-bl
                   5903: doc-space
                   5904: doc-spaces
                   5905: doc-emit
                   5906: doc-toupper
                   5907: doc-."
                   5908: doc-.(
                   5909: doc-type
                   5910: doc-cr
1.27      crook    5911: @cindex cursor control
1.26      crook    5912: doc-at-xy
                   5913: doc-page
                   5914: doc-s"
                   5915: doc-c"
                   5916: doc-char
                   5917: doc-[char]
                   5918: doc-sliteral
                   5919: 
                   5920: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    5921: 
                   5922: @example
1.26      crook    5923: .( text-1)
                   5924: : my-word
                   5925:   ." text-2" cr
                   5926:   .( text-3)
                   5927: ;
                   5928: 
                   5929: ." text-4"
                   5930: 
                   5931: : my-char
                   5932:   [char] ALPHABET emit
                   5933:   char emit
                   5934: ;
1.5       anton    5935: @end example
                   5936: 
1.26      crook    5937: When you load this code into Gforth, the following output is generated:
1.5       anton    5938: 
1.26      crook    5939: @example
                   5940: @kbd{include test.fs <return>} text-1text-3text-4 ok
                   5941: @end example
1.5       anton    5942: 
1.26      crook    5943: @itemize @bullet
                   5944: @item
                   5945: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   5946: is an immediate word; it behaves in the same way whether it is used inside
                   5947: or outside a colon definition.
                   5948: @item
                   5949: Message @code{text-4} is displayed because of Gforth's added interpretation
                   5950: semantics for @code{."}.
                   5951: @item
1.29    ! crook    5952: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    5953: performs the compilation semantics for @code{."} within the definition of
                   5954: @code{my-word}.
                   5955: @end itemize
1.5       anton    5956: 
1.26      crook    5957: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    5958: 
1.26      crook    5959: @example
                   5960: @kbd{my-word <return>} text-2
                   5961:  ok
                   5962: @kbd{my-char fred <return>} Af ok
                   5963: @kbd{my-char jim <return>} Aj ok
                   5964: @end example
1.5       anton    5965: 
                   5966: @itemize @bullet
                   5967: @item
1.26      crook    5968: Message @code{text-2} is displayed because of the run-time behaviour of
                   5969: @code{."}.
                   5970: @item
                   5971: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   5972: on the stack at run-time. @code{emit} always displays the character
                   5973: when @code{my-char} is executed.
                   5974: @item
                   5975: @code{char} parses a string at run-time and the second @code{emit} displays
                   5976: the first character of the string.
1.5       anton    5977: @item
1.26      crook    5978: If you type @code{see my-char} you can see that @code{[char]} discarded
                   5979: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   5980: definition of @code{my-char}.
1.5       anton    5981: @end itemize
                   5982: 
                   5983: 
                   5984: 
1.26      crook    5985: @node Input, , Displaying characters and strings, Other I/O
                   5986: @subsection Input
                   5987: @cindex input
1.28      crook    5988: @cindex I/O - see input
                   5989: @cindex parsing a string
1.5       anton    5990: 
1.27      crook    5991: @xref{String Formats} for ways of storing character strings in memory.
1.5       anton    5992: 
1.27      crook    5993: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29    ! crook    5994: @comment then index them
1.27      crook    5995: 
                   5996: doc-key
                   5997: doc-key?
1.26      crook    5998: doc->number
                   5999: doc->float
                   6000: doc-accept
1.27      crook    6001: doc-pad
                   6002: doc-parse
                   6003: doc-word
                   6004: doc-sword
                   6005: doc-refill
                   6006: @comment obsolescent words..
                   6007: doc-convert
1.26      crook    6008: doc-query
                   6009: doc-expect
1.27      crook    6010: doc-span
1.5       anton    6011: 
                   6012: 
                   6013: @c -------------------------------------------------------------
1.26      crook    6014: @node Programming Tools, Assembler and Code Words, Other I/O, Words
                   6015: @section Programming Tools
                   6016: @cindex programming tools
1.12      anton    6017: 
                   6018: @menu
1.26      crook    6019: * Debugging::                   Simple and quick.
                   6020: * Assertions::                  Making your programs self-checking.
                   6021: * Singlestep Debugger::                Executing your program word by word.
1.5       anton    6022: @end menu
                   6023: 
1.26      crook    6024: @node Debugging, Assertions, Programming Tools, Programming Tools
                   6025: @subsection Debugging
                   6026: @cindex debugging
1.5       anton    6027: 
1.26      crook    6028: Languages with a slow edit/compile/link/test development loop tend to
                   6029: require sophisticated tracing/stepping debuggers to facilate
                   6030: productive debugging.
1.5       anton    6031: 
1.26      crook    6032: A much better (faster) way in fast-compiling languages is to add
                   6033: printing code at well-selected places, let the program run, look at
                   6034: the output, see where things went wrong, add more printing code, etc.,
                   6035: until the bug is found.
1.5       anton    6036: 
1.26      crook    6037: The simple debugging aids provided in @file{debugs.fs}
                   6038: are meant to support this style of debugging. In addition, there are
                   6039: words for non-destructively inspecting the stack and memory:
1.5       anton    6040: 
1.26      crook    6041: doc-.s
                   6042: doc-f.s
1.5       anton    6043: 
1.29    ! crook    6044: There is a word @code{.r} but it does @i{not} display the return
1.26      crook    6045: stack! It is used for formatted numeric output.
1.5       anton    6046: 
1.26      crook    6047: doc-depth
                   6048: doc-fdepth
                   6049: doc-clearstack
                   6050: doc-?
                   6051: doc-dump
1.5       anton    6052: 
1.26      crook    6053: The word @code{~~} prints debugging information (by default the source
                   6054: location and the stack contents). It is easy to insert. If you use Emacs
                   6055: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   6056: query-replace them with nothing). The deferred words
                   6057: @code{printdebugdata} and @code{printdebugline} control the output of
                   6058: @code{~~}. The default source location output format works well with
                   6059: Emacs' compilation mode, so you can step through the program at the
                   6060: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   6061: is that you can step in any direction and you know where the crash has
                   6062: happened or where the strange data has occurred).
1.5       anton    6063: 
1.26      crook    6064: The default actions of @code{~~} clobber the contents of the pictured
                   6065: numeric output string, so you should not use @code{~~}, e.g., between
                   6066: @code{<#} and @code{#>}.
1.5       anton    6067: 
1.26      crook    6068: doc-~~
                   6069: doc-printdebugdata
                   6070: doc-printdebugline
1.5       anton    6071: 
1.26      crook    6072: doc-see
                   6073: doc-marker
1.5       anton    6074: 
1.26      crook    6075: Here's an example of using @code{marker} at the start of a source file
                   6076: that you are debugging; it ensures that you only ever have one copy of
                   6077: the file's definitions compiled at any time:
1.5       anton    6078: 
1.26      crook    6079: @example
                   6080: [IFDEF] my-code
                   6081:     my-code
                   6082: [ENDIF]
1.5       anton    6083: 
1.26      crook    6084: marker my-code
1.28      crook    6085: init-included-files
1.5       anton    6086: 
1.26      crook    6087: \ .. definitions start here
                   6088: \ .
                   6089: \ .
                   6090: \ end
                   6091: @end example
1.5       anton    6092: 
                   6093: 
                   6094: 
1.26      crook    6095: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
                   6096: @subsection Assertions
                   6097: @cindex assertions
1.5       anton    6098: 
1.26      crook    6099: It is a good idea to make your programs self-checking, especially if you
                   6100: make an assumption that may become invalid during maintenance (for
                   6101: example, that a certain field of a data structure is never zero). Gforth
1.29    ! crook    6102: supports @dfn{assertions} for this purpose. They are used like this:
1.23      crook    6103: 
1.26      crook    6104: @example
1.29    ! crook    6105: assert( @i{flag} )
1.26      crook    6106: @end example
1.23      crook    6107: 
1.26      crook    6108: The code between @code{assert(} and @code{)} should compute a flag, that
                   6109: should be true if everything is alright and false otherwise. It should
                   6110: not change anything else on the stack. The overall stack effect of the
                   6111: assertion is @code{( -- )}. E.g.
1.23      crook    6112: 
1.26      crook    6113: @example
                   6114: assert( 1 1 + 2 = ) \ what we learn in school
                   6115: assert( dup 0<> ) \ assert that the top of stack is not zero
                   6116: assert( false ) \ this code should not be reached
                   6117: @end example
1.23      crook    6118: 
1.26      crook    6119: The need for assertions is different at different times. During
                   6120: debugging, we want more checking, in production we sometimes care more
                   6121: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   6122: becomes a comment. Depending on the importance of an assertion and the
                   6123: time it takes to check it, you may want to turn off some assertions and
                   6124: keep others turned on. Gforth provides several levels of assertions for
                   6125: this purpose:
1.23      crook    6126: 
1.26      crook    6127: doc-assert0(
                   6128: doc-assert1(
                   6129: doc-assert2(
                   6130: doc-assert3(
                   6131: doc-assert(
                   6132: doc-)
1.23      crook    6133: 
1.26      crook    6134: The variable @code{assert-level} specifies the highest assertions that
                   6135: are turned on. I.e., at the default @code{assert-level} of one,
                   6136: @code{assert0(} and @code{assert1(} assertions perform checking, while
                   6137: @code{assert2(} and @code{assert3(} assertions are treated as comments.
                   6138: 
                   6139: The value of @code{assert-level} is evaluated at compile-time, not at
                   6140: run-time. Therefore you cannot turn assertions on or off at run-time;
                   6141: you have to set the @code{assert-level} appropriately before compiling a
                   6142: piece of code. You can compile different pieces of code at different
                   6143: @code{assert-level}s (e.g., a trusted library at level 1 and
                   6144: newly-written code at level 3).
1.23      crook    6145: 
1.26      crook    6146: doc-assert-level
1.23      crook    6147: 
1.26      crook    6148: If an assertion fails, a message compatible with Emacs' compilation mode
                   6149: is produced and the execution is aborted (currently with @code{ABORT"}.
                   6150: If there is interest, we will introduce a special throw code. But if you
                   6151: intend to @code{catch} a specific condition, using @code{throw} is
                   6152: probably more appropriate than an assertion).
1.23      crook    6153: 
1.26      crook    6154: Definitions in ANS Forth for these assertion words are provided
                   6155: in @file{compat/assert.fs}.
1.23      crook    6156: 
                   6157: 
1.26      crook    6158: @node Singlestep Debugger, , Assertions, Programming Tools
                   6159: @subsection Singlestep Debugger
                   6160: @cindex singlestep Debugger
                   6161: @cindex debugging Singlestep
                   6162: @cindex @code{dbg}
                   6163: @cindex @code{BREAK:}
                   6164: @cindex @code{BREAK"}
1.23      crook    6165: 
1.26      crook    6166: When you create a new word there's often the need to check whether it
                   6167: behaves correctly or not. You can do this by typing @code{dbg
                   6168: badword}. A debug session might look like this:
1.23      crook    6169: 
1.26      crook    6170: @example
                   6171: : badword 0 DO i . LOOP ;  ok
                   6172: 2 dbg badword 
                   6173: : badword  
                   6174: Scanning code...
1.23      crook    6175: 
1.26      crook    6176: Nesting debugger ready!
1.23      crook    6177: 
1.26      crook    6178: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   6179: 400D4740  8049F68 DO             -> [ 0 ] 
                   6180: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   6181: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   6182: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   6183: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   6184: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   6185: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   6186: 400D4758  804B384 ;              ->  ok
                   6187: @end example
1.23      crook    6188: 
1.26      crook    6189: Each line displayed is one step. You always have to hit return to
                   6190: execute the next word that is displayed. If you don't want to execute
                   6191: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   6192: an overview what keys are available:
1.23      crook    6193: 
1.26      crook    6194: @table @i
1.23      crook    6195: 
1.26      crook    6196: @item <return>
                   6197: Next; Execute the next word.
1.23      crook    6198: 
1.26      crook    6199: @item n
                   6200: Nest; Single step through next word.
1.5       anton    6201: 
1.26      crook    6202: @item u
                   6203: Unnest; Stop debugging and execute rest of word. If we got to this word
                   6204: with nest, continue debugging with the calling word.
1.5       anton    6205: 
1.26      crook    6206: @item d
                   6207: Done; Stop debugging and execute rest.
1.5       anton    6208: 
1.26      crook    6209: @item s
                   6210: Stop; Abort immediately.
1.5       anton    6211: 
1.26      crook    6212: @end table
1.5       anton    6213: 
1.26      crook    6214: Debugging large application with this mechanism is very difficult, because
                   6215: you have to nest very deeply into the program before the interesting part
                   6216: begins. This takes a lot of time. 
1.5       anton    6217: 
1.26      crook    6218: To do it more directly put a @code{BREAK:} command into your source code.
                   6219: When program execution reaches @code{BREAK:} the single step debugger is
                   6220: invoked and you have all the features described above.
1.23      crook    6221: 
1.26      crook    6222: If you have more than one part to debug it is useful to know where the
                   6223: program has stopped at the moment. You can do this by the 
                   6224: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   6225: string is typed out when the ``breakpoint'' is reached.
                   6226: 
                   6227: doc-dbg
                   6228: doc-BREAK:
                   6229: doc-BREAK"
                   6230: 
                   6231: 
                   6232: @c -------------------------------------------------------------
                   6233: @node Assembler and Code Words, Threading Words, Programming Tools, Words
                   6234: @section Assembler and Code Words
                   6235: @cindex assembler
                   6236: @cindex code words
1.5       anton    6237: 
1.26      crook    6238: Gforth provides some words for defining primitives (words written in
1.29    ! crook    6239: machine code), and for defining the machine-code equivalent of
1.26      crook    6240: @code{DOES>}-based defining words. However, the machine-independent
                   6241: nature of Gforth poses a few problems: First of all, Gforth runs on
                   6242: several architectures, so it can provide no standard assembler. What's
                   6243: worse is that the register allocation not only depends on the processor,
                   6244: but also on the @code{gcc} version and options used.
1.5       anton    6245: 
1.29    ! crook    6246: The words that Gforth offers encapsulate some system dependences (e.g.,
        !          6247: the header structure), so a system-independent assembler may be used in
1.26      crook    6248: Gforth. If you do not have an assembler, you can compile machine code
1.29    ! crook    6249: directly with @code{,} and @code{c,}@footnote{This isn't portable,
        !          6250: because these words emit stuff in @i{data} space; it works because
        !          6251: Gforth has unified code/data spaces. Assembler isn't likely to be
        !          6252: portable anyway.}.
1.5       anton    6253: 
1.26      crook    6254: doc-assembler
                   6255: doc-code
                   6256: doc-end-code
                   6257: doc-;code
                   6258: doc-flush-icache
1.5       anton    6259: 
1.26      crook    6260: If @code{flush-icache} does not work correctly, @code{code} words
                   6261: etc. will not work (reliably), either.
1.5       anton    6262: 
1.29    ! crook    6263: The typical usage of these @code{code} words can be shown most easily by
        !          6264: analogy to the equivalent high-level defining words:
        !          6265: 
        !          6266: @example
        !          6267: : foo                                        code foo
        !          6268:    <high-level Forth words>                        <assembler>
        !          6269: ;                                            end-code
        !          6270: 
        !          6271: : bar                                        : bar
        !          6272:    <high-level Forth words>                     <high-level Forth words>
        !          6273:    CREATE                                       CREATE
        !          6274:       <high-level Forth words>                     <high-level Forth words>
        !          6275:    DOES>                                        ;code
        !          6276:       <high-level Forth words>                     <assembler>
        !          6277: ;                                            end-code
        !          6278: @end example
        !          6279: 
1.26      crook    6280: @code{flush-icache} is always present. The other words are rarely used
                   6281: and reside in @code{code.fs}, which is usually not loaded. You can load
                   6282: it with @code{require code.fs}.
1.5       anton    6283: 
1.26      crook    6284: @cindex registers of the inner interpreter
                   6285: In the assembly code you will want to refer to the inner interpreter's
                   6286: registers (e.g., the data stack pointer) and you may want to use other
                   6287: registers for temporary storage. Unfortunately, the register allocation
                   6288: is installation-dependent.
1.5       anton    6289: 
1.26      crook    6290: The easiest solution is to use explicit register declarations
                   6291: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
                   6292: GNU C Manual}) for all of the inner interpreter's registers: You have to
                   6293: compile Gforth with @code{-DFORCE_REG} (configure option
                   6294: @code{--enable-force-reg}) and the appropriate declarations must be
                   6295: present in the @code{machine.h} file (see @code{mips.h} for an example;
                   6296: you can find a full list of all declarable register symbols with
                   6297: @code{grep register engine.c}). If you give explicit registers to all
                   6298: variables that are declared at the beginning of @code{engine()}, you
                   6299: should be able to use the other caller-saved registers for temporary
                   6300: storage. Alternatively, you can use the @code{gcc} option
                   6301: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
                   6302: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
                   6303: (however, this restriction on register allocation may slow Gforth
                   6304: significantly).
1.5       anton    6305: 
1.26      crook    6306: If this solution is not viable (e.g., because @code{gcc} does not allow
                   6307: you to explicitly declare all the registers you need), you have to find
                   6308: out by looking at the code where the inner interpreter's registers
                   6309: reside and which registers can be used for temporary storage. You can
                   6310: get an assembly listing of the engine's code with @code{make engine.s}.
1.5       anton    6311: 
1.26      crook    6312: In any case, it is good practice to abstract your assembly code from the
                   6313: actual register allocation. E.g., if the data stack pointer resides in
                   6314: register @code{$17}, create an alias for this register called @code{sp},
                   6315: and use that in your assembly code.
1.5       anton    6316: 
1.26      crook    6317: @cindex code words, portable
                   6318: Another option for implementing normal and defining words efficiently
                   6319: is to add the desired functionality to the source of Gforth. For normal
                   6320: words you just have to edit @file{primitives} (@pxref{Automatic
                   6321: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
                   6322: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
                   6323: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.5       anton    6324: 
                   6325: 
1.26      crook    6326: @c -------------------------------------------------------------
                   6327: @node Threading Words, Locals, Assembler and Code Words, Words
                   6328: @section Threading Words
                   6329: @cindex threading words
1.5       anton    6330: 
1.26      crook    6331: @cindex code address
                   6332: These words provide access to code addresses and other threading stuff
                   6333: in Gforth (and, possibly, other interpretive Forths). It more or less
                   6334: abstracts away the differences between direct and indirect threading
                   6335: (and, for direct threading, the machine dependences). However, at
                   6336: present this wordset is still incomplete. It is also pretty low-level;
                   6337: some day it will hopefully be made unnecessary by an internals wordset
                   6338: that abstracts implementation details away completely.
1.5       anton    6339: 
1.26      crook    6340: doc-threading-method
                   6341: doc->code-address
                   6342: doc->does-code
                   6343: doc-code-address!
                   6344: doc-does-code!
                   6345: doc-does-handler!
                   6346: doc-/does-handler
1.5       anton    6347: 
1.26      crook    6348: The code addresses produced by various defining words are produced by
                   6349: the following words:
1.5       anton    6350: 
1.26      crook    6351: doc-docol:
                   6352: doc-docon:
                   6353: doc-dovar:
                   6354: doc-douser:
                   6355: doc-dodefer:
                   6356: doc-dofield:
1.5       anton    6357: 
1.26      crook    6358: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
                   6359: with @code{>does-code}. If the word was defined in that way, the value
                   6360: returned is non-zero and identifies the @code{DOES>} used by the
                   6361: defining word.
                   6362: @comment TODO should that be ``identifies the xt of the DOES> ??''
1.5       anton    6363: 
1.26      crook    6364: @c -------------------------------------------------------------
                   6365: @node Locals, Structures, Threading Words, Words
                   6366: @section Locals
                   6367: @cindex locals
1.5       anton    6368: 
1.26      crook    6369: Local variables can make Forth programming more enjoyable and Forth
                   6370: programs easier to read. Unfortunately, the locals of ANS Forth are
                   6371: laden with restrictions. Therefore, we provide not only the ANS Forth
                   6372: locals wordset, but also our own, more powerful locals wordset (we
                   6373: implemented the ANS Forth locals wordset through our locals wordset).
1.5       anton    6374: 
1.26      crook    6375: The ideas in this section have also been published in the paper
                   6376: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
                   6377: at EuroForth '94; it is available at
                   6378: @*@url{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
1.5       anton    6379: 
1.26      crook    6380: @menu
                   6381: * Gforth locals::               
                   6382: * ANS Forth locals::            
                   6383: @end menu
1.5       anton    6384: 
1.26      crook    6385: @node Gforth locals, ANS Forth locals, Locals, Locals
                   6386: @subsection Gforth locals
                   6387: @cindex Gforth locals
                   6388: @cindex locals, Gforth style
1.5       anton    6389: 
1.26      crook    6390: Locals can be defined with
1.5       anton    6391: 
                   6392: @example
1.26      crook    6393: @{ local1 local2 ... -- comment @}
                   6394: @end example
                   6395: or
                   6396: @example
                   6397: @{ local1 local2 ... @}
1.5       anton    6398: @end example
                   6399: 
1.26      crook    6400: E.g.,
1.5       anton    6401: @example
1.26      crook    6402: : max @{ n1 n2 -- n3 @}
                   6403:  n1 n2 > if
                   6404:    n1
                   6405:  else
                   6406:    n2
                   6407:  endif ;
1.5       anton    6408: @end example
                   6409: 
1.26      crook    6410: The similarity of locals definitions with stack comments is intended. A
                   6411: locals definition often replaces the stack comment of a word. The order
                   6412: of the locals corresponds to the order in a stack comment and everything
                   6413: after the @code{--} is really a comment.
1.5       anton    6414: 
1.26      crook    6415: This similarity has one disadvantage: It is too easy to confuse locals
                   6416: declarations with stack comments, causing bugs and making them hard to
                   6417: find. However, this problem can be avoided by appropriate coding
                   6418: conventions: Do not use both notations in the same program. If you do,
                   6419: they should be distinguished using additional means, e.g. by position.
                   6420: 
                   6421: @cindex types of locals
                   6422: @cindex locals types
                   6423: The name of the local may be preceded by a type specifier, e.g.,
                   6424: @code{F:} for a floating point value:
                   6425: 
                   6426: @example
                   6427: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   6428: \ complex multiplication
                   6429:  Ar Br f* Ai Bi f* f-
                   6430:  Ar Bi f* Ai Br f* f+ ;
                   6431: @end example
                   6432: 
                   6433: @cindex flavours of locals
                   6434: @cindex locals flavours
                   6435: @cindex value-flavoured locals
                   6436: @cindex variable-flavoured locals
                   6437: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   6438: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   6439: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   6440: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   6441: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   6442: produces its address (which becomes invalid when the variable's scope is
                   6443: left). E.g., the standard word @code{emit} can be defined in terms of
                   6444: @code{type} like this:
1.5       anton    6445: 
                   6446: @example
1.26      crook    6447: : emit @{ C^ char* -- @}
                   6448:     char* 1 type ;
1.5       anton    6449: @end example
                   6450: 
1.26      crook    6451: @cindex default type of locals
                   6452: @cindex locals, default type
                   6453: A local without type specifier is a @code{W:} local. Both flavours of
                   6454: locals are initialized with values from the data or FP stack.
1.5       anton    6455: 
1.26      crook    6456: Currently there is no way to define locals with user-defined data
                   6457: structures, but we are working on it.
1.5       anton    6458: 
1.26      crook    6459: Gforth allows defining locals everywhere in a colon definition. This
                   6460: poses the following questions:
1.5       anton    6461: 
1.26      crook    6462: @menu
                   6463: * Where are locals visible by name?::  
                   6464: * How long do locals live?::    
                   6465: * Programming Style::           
                   6466: * Implementation::              
                   6467: @end menu
1.5       anton    6468: 
1.26      crook    6469: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   6470: @subsubsection Where are locals visible by name?
                   6471: @cindex locals visibility
                   6472: @cindex visibility of locals
                   6473: @cindex scope of locals
1.5       anton    6474: 
1.26      crook    6475: Basically, the answer is that locals are visible where you would expect
                   6476: it in block-structured languages, and sometimes a little longer. If you
                   6477: want to restrict the scope of a local, enclose its definition in
                   6478: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    6479: 
1.26      crook    6480: doc-scope
                   6481: doc-endscope
1.5       anton    6482: 
1.26      crook    6483: These words behave like control structure words, so you can use them
                   6484: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   6485: arbitrary ways.
1.5       anton    6486: 
1.26      crook    6487: If you want a more exact answer to the visibility question, here's the
                   6488: basic principle: A local is visible in all places that can only be
                   6489: reached through the definition of the local@footnote{In compiler
                   6490: construction terminology, all places dominated by the definition of the
                   6491: local.}. In other words, it is not visible in places that can be reached
                   6492: without going through the definition of the local. E.g., locals defined
                   6493: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   6494: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   6495: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.5       anton    6496: 
1.26      crook    6497: The reasoning behind this solution is: We want to have the locals
                   6498: visible as long as it is meaningful. The user can always make the
                   6499: visibility shorter by using explicit scoping. In a place that can
                   6500: only be reached through the definition of a local, the meaning of a
                   6501: local name is clear. In other places it is not: How is the local
                   6502: initialized at the control flow path that does not contain the
                   6503: definition? Which local is meant, if the same name is defined twice in
                   6504: two independent control flow paths?
1.5       anton    6505: 
1.26      crook    6506: This should be enough detail for nearly all users, so you can skip the
                   6507: rest of this section. If you really must know all the gory details and
                   6508: options, read on.
1.5       anton    6509: 
1.26      crook    6510: In order to implement this rule, the compiler has to know which places
                   6511: are unreachable. It knows this automatically after @code{AHEAD},
                   6512: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   6513: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   6514: compiler that the control flow never reaches that place. If
                   6515: @code{UNREACHABLE} is not used where it could, the only consequence is
                   6516: that the visibility of some locals is more limited than the rule above
                   6517: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   6518: lie to the compiler), buggy code will be produced.
1.5       anton    6519: 
1.26      crook    6520: doc-unreachable
1.5       anton    6521: 
1.26      crook    6522: Another problem with this rule is that at @code{BEGIN}, the compiler
                   6523: does not know which locals will be visible on the incoming
                   6524: back-edge. All problems discussed in the following are due to this
                   6525: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   6526: loops as examples; the discussion also applies to @code{?DO} and other
                   6527: loops). Perhaps the most insidious example is:
1.5       anton    6528: @example
1.26      crook    6529: AHEAD
                   6530: BEGIN
                   6531:   x
                   6532: [ 1 CS-ROLL ] THEN
                   6533:   @{ x @}
                   6534:   ...
                   6535: UNTIL
                   6536: @end example
1.5       anton    6537: 
1.26      crook    6538: This should be legal according to the visibility rule. The use of
                   6539: @code{x} can only be reached through the definition; but that appears
                   6540: textually below the use.
1.5       anton    6541: 
1.26      crook    6542: From this example it is clear that the visibility rules cannot be fully
                   6543: implemented without major headaches. Our implementation treats common
                   6544: cases as advertised and the exceptions are treated in a safe way: The
                   6545: compiler makes a reasonable guess about the locals visible after a
                   6546: @code{BEGIN}; if it is too pessimistic, the
                   6547: user will get a spurious error about the local not being defined; if the
                   6548: compiler is too optimistic, it will notice this later and issue a
                   6549: warning. In the case above the compiler would complain about @code{x}
                   6550: being undefined at its use. You can see from the obscure examples in
                   6551: this section that it takes quite unusual control structures to get the
                   6552: compiler into trouble, and even then it will often do fine.
1.5       anton    6553: 
1.26      crook    6554: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   6555: is that all locals visible before the @code{BEGIN} will also be
                   6556: visible after the @code{BEGIN}. This guess is valid for all loops that
                   6557: are entered only through the @code{BEGIN}, in particular, for normal
                   6558: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   6559: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   6560: compiler. When the branch to the @code{BEGIN} is finally generated by
                   6561: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   6562: warns the user if it was too optimistic:
                   6563: @example
                   6564: IF
                   6565:   @{ x @}
                   6566: BEGIN
                   6567:   \ x ? 
                   6568: [ 1 cs-roll ] THEN
                   6569:   ...
                   6570: UNTIL
1.5       anton    6571: @end example
                   6572: 
1.26      crook    6573: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   6574: optimistically assumes that it lives until the @code{THEN}. It notices
                   6575: this difference when it compiles the @code{UNTIL} and issues a
                   6576: warning. The user can avoid the warning, and make sure that @code{x}
                   6577: is not used in the wrong area by using explicit scoping:
                   6578: @example
                   6579: IF
                   6580:   SCOPE
                   6581:   @{ x @}
                   6582:   ENDSCOPE
                   6583: BEGIN
                   6584: [ 1 cs-roll ] THEN
                   6585:   ...
                   6586: UNTIL
                   6587: @end example
1.5       anton    6588: 
1.26      crook    6589: Since the guess is optimistic, there will be no spurious error messages
                   6590: about undefined locals.
1.5       anton    6591: 
1.26      crook    6592: If the @code{BEGIN} is not reachable from above (e.g., after
                   6593: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   6594: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   6595: defined later. Therefore, the compiler assumes that no locals are
                   6596: visible after the @code{BEGIN}. However, the user can use
                   6597: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   6598: visible at the BEGIN as at the point where the top control-flow stack
                   6599: item was created.
1.5       anton    6600: 
1.26      crook    6601: doc-assume-live
1.5       anton    6602: 
1.26      crook    6603: E.g.,
1.5       anton    6604: @example
1.26      crook    6605: @{ x @}
                   6606: AHEAD
                   6607: ASSUME-LIVE
                   6608: BEGIN
                   6609:   x
                   6610: [ 1 CS-ROLL ] THEN
                   6611:   ...
                   6612: UNTIL
1.5       anton    6613: @end example
                   6614: 
1.26      crook    6615: Other cases where the locals are defined before the @code{BEGIN} can be
                   6616: handled by inserting an appropriate @code{CS-ROLL} before the
                   6617: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   6618: behind the @code{ASSUME-LIVE}).
1.5       anton    6619: 
1.26      crook    6620: Cases where locals are defined after the @code{BEGIN} (but should be
                   6621: visible immediately after the @code{BEGIN}) can only be handled by
                   6622: rearranging the loop. E.g., the ``most insidious'' example above can be
                   6623: arranged into:
1.5       anton    6624: @example
1.26      crook    6625: BEGIN
                   6626:   @{ x @}
                   6627:   ... 0=
                   6628: WHILE
                   6629:   x
                   6630: REPEAT
1.5       anton    6631: @end example
                   6632: 
1.26      crook    6633: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
                   6634: @subsubsection How long do locals live?
                   6635: @cindex locals lifetime
                   6636: @cindex lifetime of locals
1.5       anton    6637: 
1.26      crook    6638: The right answer for the lifetime question would be: A local lives at
                   6639: least as long as it can be accessed. For a value-flavoured local this
                   6640: means: until the end of its visibility. However, a variable-flavoured
                   6641: local could be accessed through its address far beyond its visibility
                   6642: scope. Ultimately, this would mean that such locals would have to be
                   6643: garbage collected. Since this entails un-Forth-like implementation
                   6644: complexities, I adopted the same cowardly solution as some other
                   6645: languages (e.g., C): The local lives only as long as it is visible;
                   6646: afterwards its address is invalid (and programs that access it
                   6647: afterwards are erroneous).
1.5       anton    6648: 
1.26      crook    6649: @node Programming Style, Implementation, How long do locals live?, Gforth locals
                   6650: @subsubsection Programming Style
                   6651: @cindex locals programming style
                   6652: @cindex programming style, locals
1.5       anton    6653: 
1.26      crook    6654: The freedom to define locals anywhere has the potential to change
                   6655: programming styles dramatically. In particular, the need to use the
                   6656: return stack for intermediate storage vanishes. Moreover, all stack
                   6657: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   6658: determined arguments) can be eliminated: If the stack items are in the
                   6659: wrong order, just write a locals definition for all of them; then
                   6660: write the items in the order you want.
1.5       anton    6661: 
1.26      crook    6662: This seems a little far-fetched and eliminating stack manipulations is
                   6663: unlikely to become a conscious programming objective. Still, the number
                   6664: of stack manipulations will be reduced dramatically if local variables
                   6665: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
                   6666: a traditional implementation of @code{max}).
1.5       anton    6667: 
1.26      crook    6668: This shows one potential benefit of locals: making Forth programs more
                   6669: readable. Of course, this benefit will only be realized if the
                   6670: programmers continue to honour the principle of factoring instead of
                   6671: using the added latitude to make the words longer.
1.5       anton    6672: 
1.26      crook    6673: @cindex single-assignment style for locals
                   6674: Using @code{TO} can and should be avoided.  Without @code{TO},
                   6675: every value-flavoured local has only a single assignment and many
                   6676: advantages of functional languages apply to Forth. I.e., programs are
                   6677: easier to analyse, to optimize and to read: It is clear from the
                   6678: definition what the local stands for, it does not turn into something
                   6679: different later.
1.5       anton    6680: 
1.26      crook    6681: E.g., a definition using @code{TO} might look like this:
1.5       anton    6682: @example
1.26      crook    6683: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   6684:  u1 u2 min 0
                   6685:  ?do
                   6686:    addr1 c@@ addr2 c@@ -
                   6687:    ?dup-if
                   6688:      unloop exit
                   6689:    then
                   6690:    addr1 char+ TO addr1
                   6691:    addr2 char+ TO addr2
                   6692:  loop
                   6693:  u1 u2 - ;
1.5       anton    6694: @end example
1.26      crook    6695: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   6696: every loop iteration. @code{strcmp} is a typical example of the
                   6697: readability problems of using @code{TO}. When you start reading
                   6698: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   6699: string. Only near the end of the loop you realize that it is something
                   6700: else.
1.5       anton    6701: 
1.26      crook    6702: This can be avoided by defining two locals at the start of the loop that
                   6703: are initialized with the right value for the current iteration.
1.5       anton    6704: @example
1.26      crook    6705: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   6706:  addr1 addr2
                   6707:  u1 u2 min 0 
                   6708:  ?do @{ s1 s2 @}
                   6709:    s1 c@@ s2 c@@ -
                   6710:    ?dup-if
                   6711:      unloop exit
                   6712:    then
                   6713:    s1 char+ s2 char+
                   6714:  loop
                   6715:  2drop
                   6716:  u1 u2 - ;
1.5       anton    6717: @end example
1.26      crook    6718: Here it is clear from the start that @code{s1} has a different value
                   6719: in every loop iteration.
1.5       anton    6720: 
1.26      crook    6721: @node Implementation,  , Programming Style, Gforth locals
                   6722: @subsubsection Implementation
                   6723: @cindex locals implementation
                   6724: @cindex implementation of locals
1.5       anton    6725: 
1.26      crook    6726: @cindex locals stack
                   6727: Gforth uses an extra locals stack. The most compelling reason for
                   6728: this is that the return stack is not float-aligned; using an extra stack
                   6729: also eliminates the problems and restrictions of using the return stack
                   6730: as locals stack. Like the other stacks, the locals stack grows toward
                   6731: lower addresses. A few primitives allow an efficient implementation:
1.5       anton    6732: 
1.26      crook    6733: doc-@local#
                   6734: doc-f@local#
                   6735: doc-laddr#
                   6736: doc-lp+!#
                   6737: doc-lp!
                   6738: doc->l
                   6739: doc-f>l
1.5       anton    6740: 
1.26      crook    6741: In addition to these primitives, some specializations of these
                   6742: primitives for commonly occurring inline arguments are provided for
                   6743: efficiency reasons, e.g., @code{@@local0} as specialization of
                   6744: @code{@@local#} for the inline argument 0. The following compiling words
                   6745: compile the right specialized version, or the general version, as
                   6746: appropriate:
1.6       pazsan   6747: 
1.26      crook    6748: doc-compile-@local
                   6749: doc-compile-f@local
                   6750: doc-compile-lp+!
1.12      anton    6751: 
1.26      crook    6752: Combinations of conditional branches and @code{lp+!#} like
                   6753: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   6754: is taken) are provided for efficiency and correctness in loops.
1.6       pazsan   6755: 
1.26      crook    6756: A special area in the dictionary space is reserved for keeping the
                   6757: local variable names. @code{@{} switches the dictionary pointer to this
                   6758: area and @code{@}} switches it back and generates the locals
                   6759: initializing code. @code{W:} etc.@ are normal defining words. This
                   6760: special area is cleared at the start of every colon definition.
1.6       pazsan   6761: 
1.26      crook    6762: @cindex word list for defining locals
                   6763: A special feature of Gforth's dictionary is used to implement the
                   6764: definition of locals without type specifiers: every word list (aka
                   6765: vocabulary) has its own methods for searching
                   6766: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   6767: with a special search method: When it is searched for a word, it
                   6768: actually creates that word using @code{W:}. @code{@{} changes the search
                   6769: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   6770: and then the word list for defining locals without type specifiers.
1.12      anton    6771: 
1.26      crook    6772: The lifetime rules support a stack discipline within a colon
                   6773: definition: The lifetime of a local is either nested with other locals
                   6774: lifetimes or it does not overlap them.
1.6       pazsan   6775: 
1.26      crook    6776: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   6777: pointer manipulation is generated. Between control structure words
                   6778: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   6779: is the simplest of the other three control flow words. It has to
                   6780: restore the locals stack depth of the corresponding @code{BEGIN}
                   6781: before branching. The code looks like this:
                   6782: @format
                   6783: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   6784: @code{branch} <begin>
                   6785: @end format
1.6       pazsan   6786: 
1.26      crook    6787: @code{UNTIL} is a little more complicated: If it branches back, it
                   6788: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   6789: the locals stack must not be changed. The compiler generates the
                   6790: following code:
                   6791: @format
                   6792: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   6793: @end format
                   6794: The locals stack pointer is only adjusted if the branch is taken.
1.6       pazsan   6795: 
1.26      crook    6796: @code{THEN} can produce somewhat inefficient code:
                   6797: @format
                   6798: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   6799: <orig target>:
                   6800: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   6801: @end format
                   6802: The second @code{lp+!#} adjusts the locals stack pointer from the
1.29    ! crook    6803: level at the @i{orig} point to the level after the @code{THEN}. The
1.26      crook    6804: first @code{lp+!#} adjusts the locals stack pointer from the current
                   6805: level to the level at the orig point, so the complete effect is an
                   6806: adjustment from the current level to the right level after the
                   6807: @code{THEN}.
1.6       pazsan   6808: 
1.26      crook    6809: @cindex locals information on the control-flow stack
                   6810: @cindex control-flow stack items, locals information
                   6811: In a conventional Forth implementation a dest control-flow stack entry
                   6812: is just the target address and an orig entry is just the address to be
                   6813: patched. Our locals implementation adds a word list to every orig or dest
                   6814: item. It is the list of locals visible (or assumed visible) at the point
                   6815: described by the entry. Our implementation also adds a tag to identify
                   6816: the kind of entry, in particular to differentiate between live and dead
                   6817: (reachable and unreachable) orig entries.
1.6       pazsan   6818: 
1.26      crook    6819: A few unusual operations have to be performed on locals word lists:
1.6       pazsan   6820: 
1.26      crook    6821: doc-common-list
                   6822: doc-sub-list?
                   6823: doc-list-size
1.6       pazsan   6824: 
1.26      crook    6825: Several features of our locals word list implementation make these
                   6826: operations easy to implement: The locals word lists are organised as
                   6827: linked lists; the tails of these lists are shared, if the lists
                   6828: contain some of the same locals; and the address of a name is greater
                   6829: than the address of the names behind it in the list.
1.6       pazsan   6830: 
1.26      crook    6831: Another important implementation detail is the variable
                   6832: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   6833: determine if they can be reached directly or only through the branch
                   6834: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   6835: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   6836: definition, by @code{BEGIN} and usually by @code{THEN}.
1.6       pazsan   6837: 
1.26      crook    6838: Counted loops are similar to other loops in most respects, but
                   6839: @code{LEAVE} requires special attention: It performs basically the same
                   6840: service as @code{AHEAD}, but it does not create a control-flow stack
                   6841: entry. Therefore the information has to be stored elsewhere;
                   6842: traditionally, the information was stored in the target fields of the
                   6843: branches created by the @code{LEAVE}s, by organizing these fields into a
                   6844: linked list. Unfortunately, this clever trick does not provide enough
                   6845: space for storing our extended control flow information. Therefore, we
                   6846: introduce another stack, the leave stack. It contains the control-flow
                   6847: stack entries for all unresolved @code{LEAVE}s.
1.6       pazsan   6848: 
1.26      crook    6849: Local names are kept until the end of the colon definition, even if
                   6850: they are no longer visible in any control-flow path. In a few cases
                   6851: this may lead to increased space needs for the locals name area, but
                   6852: usually less than reclaiming this space would cost in code size.
1.6       pazsan   6853: 
                   6854: 
1.26      crook    6855: @node ANS Forth locals,  , Gforth locals, Locals
                   6856: @subsection ANS Forth locals
                   6857: @cindex locals, ANS Forth style
1.6       pazsan   6858: 
1.26      crook    6859: The ANS Forth locals wordset does not define a syntax for locals, but
                   6860: words that make it possible to define various syntaxes. One of the
                   6861: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   6862: wordset, i.e.:
1.6       pazsan   6863: 
                   6864: @example
1.26      crook    6865: @{ local1 local2 ... -- comment @}
1.6       pazsan   6866: @end example
1.23      crook    6867: @noindent
1.26      crook    6868: or
1.6       pazsan   6869: @example
1.26      crook    6870: @{ local1 local2 ... @}
1.6       pazsan   6871: @end example
                   6872: 
1.26      crook    6873: The order of the locals corresponds to the order in a stack comment. The
                   6874: restrictions are:
1.6       pazsan   6875: 
                   6876: @itemize @bullet
                   6877: @item
1.26      crook    6878: Locals can only be cell-sized values (no type specifiers are allowed).
1.6       pazsan   6879: @item
1.26      crook    6880: Locals can be defined only outside control structures.
1.6       pazsan   6881: @item
1.26      crook    6882: Locals can interfere with explicit usage of the return stack. For the
                   6883: exact (and long) rules, see the standard. If you don't use return stack
                   6884: accessing words in a definition using locals, you will be all right. The
                   6885: purpose of this rule is to make locals implementation on the return
                   6886: stack easier.
1.6       pazsan   6887: @item
1.26      crook    6888: The whole definition must be in one line.
                   6889: @end itemize
1.6       pazsan   6890: 
1.26      crook    6891: Locals defined in this way behave like @code{VALUE}s (@xref{Simple
                   6892: Defining Words}). I.e., they are initialized from the stack. Using their
                   6893: name produces their value. Their value can be changed using @code{TO}.
1.6       pazsan   6894: 
1.26      crook    6895: Since this syntax is supported by Gforth directly, you need not do
                   6896: anything to use it. If you want to port a program using this syntax to
                   6897: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   6898: syntax on the other system.
1.6       pazsan   6899: 
1.26      crook    6900: Note that a syntax shown in the standard, section A.13 looks
                   6901: similar, but is quite different in having the order of locals
                   6902: reversed. Beware!
1.6       pazsan   6903: 
1.26      crook    6904: The ANS Forth locals wordset itself consists of a word:
1.6       pazsan   6905: 
1.26      crook    6906: doc-(local)
1.6       pazsan   6907: 
1.26      crook    6908: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
                   6909: awful that we strongly recommend not to use it. We have implemented this
                   6910: syntax to make porting to Gforth easy, but do not document it here. The
                   6911: problem with this syntax is that the locals are defined in an order
                   6912: reversed with respect to the standard stack comment notation, making
                   6913: programs harder to read, and easier to misread and miswrite. The only
                   6914: merit of this syntax is that it is easy to implement using the ANS Forth
                   6915: locals wordset.
1.7       pazsan   6916: 
                   6917: 
1.26      crook    6918: @c ----------------------------------------------------------
                   6919: @node Structures, Object-oriented Forth, Locals, Words
                   6920: @section  Structures
                   6921: @cindex structures
                   6922: @cindex records
1.7       pazsan   6923: 
1.26      crook    6924: This section presents the structure package that comes with Gforth. A
                   6925: version of the package implemented in ANS Forth is available in
                   6926: @file{compat/struct.fs}. This package was inspired by a posting on
                   6927: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   6928: possibly John Hayes). A version of this section has been published in
                   6929: ???. Marcel Hendrix provided helpful comments.
1.7       pazsan   6930: 
1.26      crook    6931: @menu
                   6932: * Why explicit structure support?::  
                   6933: * Structure Usage::             
                   6934: * Structure Naming Convention::  
                   6935: * Structure Implementation::    
                   6936: * Structure Glossary::          
                   6937: @end menu
1.7       pazsan   6938: 
1.26      crook    6939: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   6940: @subsection Why explicit structure support?
1.7       pazsan   6941: 
1.26      crook    6942: @cindex address arithmetic for structures
                   6943: @cindex structures using address arithmetic
                   6944: If we want to use a structure containing several fields, we could simply
                   6945: reserve memory for it, and access the fields using address arithmetic
1.27      crook    6946: (@pxref{Address Arithmetic}). As an example, consider a structure with
1.26      crook    6947: the following fields
1.7       pazsan   6948: 
1.26      crook    6949: @table @code
                   6950: @item a
                   6951: is a float
                   6952: @item b
                   6953: is a cell
                   6954: @item c
                   6955: is a float
                   6956: @end table
1.7       pazsan   6957: 
1.26      crook    6958: Given the (float-aligned) base address of the structure we get the
                   6959: address of the field
1.13      pazsan   6960: 
1.26      crook    6961: @table @code
                   6962: @item a
                   6963: without doing anything further.
                   6964: @item b
                   6965: with @code{float+}
                   6966: @item c
                   6967: with @code{float+ cell+ faligned}
                   6968: @end table
1.13      pazsan   6969: 
1.26      crook    6970: It is easy to see that this can become quite tiring. 
1.13      pazsan   6971: 
1.26      crook    6972: Moreover, it is not very readable, because seeing a
                   6973: @code{cell+} tells us neither which kind of structure is
                   6974: accessed nor what field is accessed; we have to somehow infer the kind
                   6975: of structure, and then look up in the documentation, which field of
                   6976: that structure corresponds to that offset.
1.13      pazsan   6977: 
1.26      crook    6978: Finally, this kind of address arithmetic also causes maintenance
                   6979: troubles: If you add or delete a field somewhere in the middle of the
                   6980: structure, you have to find and change all computations for the fields
                   6981: afterwards.
1.13      pazsan   6982: 
1.26      crook    6983: So, instead of using @code{cell+} and friends directly, how
                   6984: about storing the offsets in constants:
1.13      pazsan   6985: 
                   6986: @example
1.26      crook    6987: 0 constant a-offset
                   6988: 0 float+ constant b-offset
                   6989: 0 float+ cell+ faligned c-offset
1.13      pazsan   6990: @end example
                   6991: 
1.26      crook    6992: Now we can get the address of field @code{x} with @code{x-offset
                   6993: +}. This is much better in all respects. Of course, you still
                   6994: have to change all later offset definitions if you add a field. You can
                   6995: fix this by declaring the offsets in the following way:
1.13      pazsan   6996: 
                   6997: @example
1.26      crook    6998: 0 constant a-offset
                   6999: a-offset float+ constant b-offset
                   7000: b-offset cell+ faligned constant c-offset
1.13      pazsan   7001: @end example
                   7002: 
1.26      crook    7003: Since we always use the offsets with @code{+}, we could use a defining
                   7004: word @code{cfield} that includes the @code{+} in the action of the
                   7005: defined word:
1.8       pazsan   7006: 
                   7007: @example
1.26      crook    7008: : cfield ( n "name" -- )
                   7009:     create ,
                   7010: does> ( name execution: addr1 -- addr2 )
                   7011:     @@ + ;
1.13      pazsan   7012: 
1.26      crook    7013: 0 cfield a
                   7014: 0 a float+ cfield b
                   7015: 0 b cell+ faligned cfield c
1.13      pazsan   7016: @end example
                   7017: 
1.26      crook    7018: Instead of @code{x-offset +}, we now simply write @code{x}.
                   7019: 
                   7020: The structure field words now can be used quite nicely. However,
                   7021: their definition is still a bit cumbersome: We have to repeat the
                   7022: name, the information about size and alignment is distributed before
                   7023: and after the field definitions etc.  The structure package presented
                   7024: here addresses these problems.
                   7025: 
                   7026: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   7027: @subsection Structure Usage
                   7028: @cindex structure usage
1.13      pazsan   7029: 
1.26      crook    7030: @cindex @code{field} usage
                   7031: @cindex @code{struct} usage
                   7032: @cindex @code{end-struct} usage
                   7033: You can define a structure for a (data-less) linked list with:
1.13      pazsan   7034: @example
1.26      crook    7035: struct
                   7036:     cell% field list-next
                   7037: end-struct list%
1.13      pazsan   7038: @end example
                   7039: 
1.26      crook    7040: With the address of the list node on the stack, you can compute the
                   7041: address of the field that contains the address of the next node with
                   7042: @code{list-next}. E.g., you can determine the length of a list
                   7043: with:
1.13      pazsan   7044: 
                   7045: @example
1.26      crook    7046: : list-length ( list -- n )
                   7047: \ "list" is a pointer to the first element of a linked list
                   7048: \ "n" is the length of the list
                   7049:     0 BEGIN ( list1 n1 )
                   7050:         over
                   7051:     WHILE ( list1 n1 )
                   7052:         1+ swap list-next @@ swap
                   7053:     REPEAT
                   7054:     nip ;
1.13      pazsan   7055: @end example
                   7056: 
1.26      crook    7057: You can reserve memory for a list node in the dictionary with
                   7058: @code{list% %allot}, which leaves the address of the list node on the
                   7059: stack. For the equivalent allocation on the heap you can use @code{list%
                   7060: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   7061: use @code{list% %allocate}). You can get the the size of a list
                   7062: node with @code{list% %size} and its alignment with @code{list%
                   7063: %alignment}.
1.13      pazsan   7064: 
1.26      crook    7065: Note that in ANS Forth the body of a @code{create}d word is
                   7066: @code{aligned} but not necessarily @code{faligned};
                   7067: therefore, if you do a:
1.13      pazsan   7068: @example
1.26      crook    7069: create @emph{name} foo% %allot
1.8       pazsan   7070: @end example
                   7071: 
1.26      crook    7072: @noindent
                   7073: then the memory alloted for @code{foo%} is
                   7074: guaranteed to start at the body of @code{@emph{name}} only if
                   7075: @code{foo%} contains only character, cell and double fields.
1.20      pazsan   7076: 
1.26      crook    7077: @cindex strcutures containing structures
                   7078: You can include a structure @code{foo%} as a field of
                   7079: another structure, like this:
1.20      pazsan   7080: @example
1.26      crook    7081: struct
                   7082: ...
                   7083:     foo% field ...
                   7084: ...
                   7085: end-struct ...
1.20      pazsan   7086: @end example
                   7087: 
1.26      crook    7088: @cindex structure extension
                   7089: @cindex extended records
                   7090: Instead of starting with an empty structure, you can extend an
                   7091: existing structure. E.g., a plain linked list without data, as defined
                   7092: above, is hardly useful; You can extend it to a linked list of integers,
                   7093: like this:@footnote{This feature is also known as @emph{extended
                   7094: records}. It is the main innovation in the Oberon language; in other
                   7095: words, adding this feature to Modula-2 led Wirth to create a new
                   7096: language, write a new compiler etc.  Adding this feature to Forth just
                   7097: required a few lines of code.}
1.20      pazsan   7098: 
                   7099: @example
1.26      crook    7100: list%
                   7101:     cell% field intlist-int
                   7102: end-struct intlist%
1.20      pazsan   7103: @end example
                   7104: 
1.26      crook    7105: @code{intlist%} is a structure with two fields:
                   7106: @code{list-next} and @code{intlist-int}.
1.20      pazsan   7107: 
1.26      crook    7108: @cindex structures containing arrays
                   7109: You can specify an array type containing @emph{n} elements of
                   7110: type @code{foo%} like this:
1.20      pazsan   7111: 
                   7112: @example
1.26      crook    7113: foo% @emph{n} *
1.20      pazsan   7114: @end example
                   7115: 
1.26      crook    7116: You can use this array type in any place where you can use a normal
                   7117: type, e.g., when defining a @code{field}, or with
                   7118: @code{%allot}.
1.20      pazsan   7119: 
1.26      crook    7120: @cindex first field optimization
                   7121: The first field is at the base address of a structure and the word
                   7122: for this field (e.g., @code{list-next}) actually does not change
                   7123: the address on the stack. You may be tempted to leave it away in the
                   7124: interest of run-time and space efficiency. This is not necessary,
                   7125: because the structure package optimizes this case and compiling such
                   7126: words does not generate any code. So, in the interest of readability
                   7127: and maintainability you should include the word for the field when
                   7128: accessing the field.
1.20      pazsan   7129: 
1.26      crook    7130: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   7131: @subsection Structure Naming Convention
                   7132: @cindex structure naming convention
1.20      pazsan   7133: 
1.26      crook    7134: The field names that come to (my) mind are often quite generic, and,
                   7135: if used, would cause frequent name clashes. E.g., many structures
                   7136: probably contain a @code{counter} field. The structure names
                   7137: that come to (my) mind are often also the logical choice for the names
                   7138: of words that create such a structure.
1.20      pazsan   7139: 
1.26      crook    7140: Therefore, I have adopted the following naming conventions: 
1.20      pazsan   7141: 
1.26      crook    7142: @itemize @bullet
                   7143: @cindex field naming convention
                   7144: @item
                   7145: The names of fields are of the form
                   7146: @code{@emph{struct}-@emph{field}}, where
                   7147: @code{@emph{struct}} is the basic name of the structure, and
                   7148: @code{@emph{field}} is the basic name of the field. You can
                   7149: think of field words as converting the (address of the)
                   7150: structure into the (address of the) field.
1.20      pazsan   7151: 
1.26      crook    7152: @cindex structure naming convention
                   7153: @item
                   7154: The names of structures are of the form
                   7155: @code{@emph{struct}%}, where
                   7156: @code{@emph{struct}} is the basic name of the structure.
                   7157: @end itemize
1.20      pazsan   7158: 
1.26      crook    7159: This naming convention does not work that well for fields of extended
                   7160: structures; e.g., the integer list structure has a field
                   7161: @code{intlist-int}, but has @code{list-next}, not
                   7162: @code{intlist-next}.
1.20      pazsan   7163: 
1.26      crook    7164: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   7165: @subsection Structure Implementation
                   7166: @cindex structure implementation
                   7167: @cindex implementation of structures
1.20      pazsan   7168: 
1.26      crook    7169: The central idea in the implementation is to pass the data about the
                   7170: structure being built on the stack, not in some global
                   7171: variable. Everything else falls into place naturally once this design
                   7172: decision is made.
1.20      pazsan   7173: 
1.26      crook    7174: The type description on the stack is of the form @emph{align
                   7175: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   7176: very simple.
1.20      pazsan   7177: 
1.26      crook    7178: @code{field} is a defining word that uses @code{Create}
                   7179: and @code{DOES>}. The body of the field contains the offset
                   7180: of the field, and the normal @code{DOES>} action is simply:
1.20      pazsan   7181: 
                   7182: @example
1.26      crook    7183: @ +
1.20      pazsan   7184: @end example
                   7185: 
1.23      crook    7186: @noindent
1.26      crook    7187: i.e., add the offset to the address, giving the stack effect
1.29    ! crook    7188: @i{addr1 -- addr2} for a field.
1.20      pazsan   7189: 
1.26      crook    7190: @cindex first field optimization, implementation
                   7191: This simple structure is slightly complicated by the optimization
                   7192: for fields with offset 0, which requires a different
                   7193: @code{DOES>}-part (because we cannot rely on there being
                   7194: something on the stack if such a field is invoked during
                   7195: compilation). Therefore, we put the different @code{DOES>}-parts
                   7196: in separate words, and decide which one to invoke based on the
                   7197: offset. For a zero offset, the field is basically a noop; it is
                   7198: immediate, and therefore no code is generated when it is compiled.
1.20      pazsan   7199: 
1.26      crook    7200: @node Structure Glossary,  , Structure Implementation, Structures
                   7201: @subsection Structure Glossary
                   7202: @cindex structure glossary
1.20      pazsan   7203: 
1.26      crook    7204: doc-%align
                   7205: doc-%alignment
                   7206: doc-%alloc
                   7207: doc-%allocate
                   7208: doc-%allot
                   7209: doc-cell%
                   7210: doc-char%
                   7211: doc-dfloat%
                   7212: doc-double%
                   7213: doc-end-struct
                   7214: doc-field
                   7215: doc-float%
                   7216: doc-naligned
                   7217: doc-sfloat%
                   7218: doc-%size
                   7219: doc-struct
1.23      crook    7220: 
1.26      crook    7221: @c -------------------------------------------------------------
                   7222: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
                   7223: @section Object-oriented Forth
1.20      pazsan   7224: 
1.26      crook    7225: Gforth comes with three packages for object-oriented programming:
                   7226: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   7227: is preloaded, so you have to @code{include} them before use. The most
                   7228: important differences between these packages (and others) are discussed
                   7229: in @ref{Comparison with other object models}. All packages are written
                   7230: in ANS Forth and can be used with any other ANS Forth.
1.20      pazsan   7231: 
1.26      crook    7232: @menu
                   7233: * Why object-oriented programming?::
                   7234: * Object-Oriented Terminology::
                   7235: * Objects::
                   7236: * OOF::
                   7237: * Mini-OOF::
                   7238: * Comparison with other object models::  
                   7239: @end menu
1.20      pazsan   7240: 
1.23      crook    7241: 
1.26      crook    7242: @node Why object-oriented programming?, Object-Oriented Terminology, , Object-oriented Forth
                   7243: @subsubsection Why object-oriented programming?
                   7244: @cindex object-oriented programming motivation
                   7245: @cindex motivation for object-oriented programming
1.23      crook    7246: 
1.26      crook    7247: Often we have to deal with several data structures (@emph{objects}),
                   7248: that have to be treated similarly in some respects, but differently in
                   7249: others. Graphical objects are the textbook example: circles, triangles,
                   7250: dinosaurs, icons, and others, and we may want to add more during program
                   7251: development. We want to apply some operations to any graphical object,
                   7252: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   7253: has to do something different for every kind of object.
                   7254: @comment TODO add some other operations eg perimeter, area
                   7255: @comment and tie in to concrete examples later..
1.23      crook    7256: 
1.26      crook    7257: We could implement @code{draw} as a big @code{CASE}
                   7258: control structure that executes the appropriate code depending on the
                   7259: kind of object to be drawn. This would be not be very elegant, and,
                   7260: moreover, we would have to change @code{draw} every time we add
                   7261: a new kind of graphical object (say, a spaceship).
1.23      crook    7262: 
1.26      crook    7263: What we would rather do is: When defining spaceships, we would tell
                   7264: the system: ``Here's how you @code{draw} a spaceship; you figure
                   7265: out the rest''.
1.23      crook    7266: 
1.26      crook    7267: This is the problem that all systems solve that (rightfully) call
                   7268: themselves object-oriented; the object-oriented packages presented here
                   7269: solve this problem (and not much else).
                   7270: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.23      crook    7271: 
1.26      crook    7272: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
                   7273: @subsubsection Object-Oriented Terminology
                   7274: @cindex object-oriented terminology
                   7275: @cindex terminology for object-oriented programming
1.23      crook    7276: 
1.26      crook    7277: This section is mainly for reference, so you don't have to understand
                   7278: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   7279: short:
1.23      crook    7280: 
1.26      crook    7281: @table @emph
                   7282: @cindex class
                   7283: @item class
                   7284: a data structure definition with some extras.
1.23      crook    7285: 
1.26      crook    7286: @cindex object
                   7287: @item object
                   7288: an instance of the data structure described by the class definition.
1.23      crook    7289: 
1.26      crook    7290: @cindex instance variables
                   7291: @item instance variables
                   7292: fields of the data structure.
1.23      crook    7293: 
1.26      crook    7294: @cindex selector
                   7295: @cindex method selector
                   7296: @cindex virtual function
                   7297: @item selector
                   7298: (or @emph{method selector}) a word (e.g.,
                   7299: @code{draw}) that performs an operation on a variety of data
                   7300: structures (classes). A selector describes @emph{what} operation to
                   7301: perform. In C++ terminology: a (pure) virtual function.
1.23      crook    7302: 
1.26      crook    7303: @cindex method
                   7304: @item method
                   7305: the concrete definition that performs the operation
                   7306: described by the selector for a specific class. A method specifies
                   7307: @emph{how} the operation is performed for a specific class.
1.23      crook    7308: 
1.26      crook    7309: @cindex selector invocation
                   7310: @cindex message send
                   7311: @cindex invoking a selector
                   7312: @item selector invocation
                   7313: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   7314: is used for determining which method is used. In Smalltalk terminology:
                   7315: a message (consisting of the selector and the other arguments) is sent
                   7316: to the object.
1.1       anton    7317: 
1.26      crook    7318: @cindex receiving object
                   7319: @item receiving object
                   7320: the object used for determining the method executed by a selector
                   7321: invocation. In the @file{objects.fs} model, it is the object that is on
                   7322: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   7323: the Smalltalk @emph{message} terminology.)
1.1       anton    7324: 
1.26      crook    7325: @cindex child class
                   7326: @cindex parent class
                   7327: @cindex inheritance
                   7328: @item child class
                   7329: a class that has (@emph{inherits}) all properties (instance variables,
                   7330: selectors, methods) from a @emph{parent class}. In Smalltalk
                   7331: terminology: The subclass inherits from the superclass. In C++
                   7332: terminology: The derived class inherits from the base class.
1.1       anton    7333: 
1.26      crook    7334: @end table
1.21      crook    7335: 
1.26      crook    7336: @c If you wonder about the message sending terminology, it comes from
                   7337: @c a time when each object had it's own task and objects communicated via
                   7338: @c message passing; eventually the Smalltalk developers realized that
                   7339: @c they can do most things through simple (indirect) calls. They kept the
                   7340: @c terminology.
1.1       anton    7341: 
                   7342: 
1.26      crook    7343: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   7344: @subsection The @file{objects.fs} model
                   7345: @cindex objects
                   7346: @cindex object-oriented programming
1.1       anton    7347: 
1.26      crook    7348: @cindex @file{objects.fs}
                   7349: @cindex @file{oof.fs}
1.1       anton    7350: 
1.26      crook    7351: This section describes the @file{objects.fs} package. This material also has been published in @cite{Yet Another Forth Objects Package} by Anton Ertl and appeared in Forth Dimensions 19(2), pages 37--43 (@url{http://www.complang.tuwien.ac.at/forth/objects/objects.html}).
                   7352: @c McKewan's and Zsoter's packages
1.1       anton    7353: 
1.26      crook    7354: This section assumes that you have read @ref{Structures}.
1.1       anton    7355: 
1.26      crook    7356: The techniques on which this model is based have been used to implement
                   7357: the parser generator, Gray, and have also been used in Gforth for
                   7358: implementing the various flavours of word lists (hashed or not,
                   7359: case-sensitive or not, special-purpose word lists for locals etc.).
1.1       anton    7360: 
                   7361: 
1.26      crook    7362: @menu
                   7363: * Properties of the Objects model::  
                   7364: * Basic Objects Usage::         
                   7365: * The Objects base class::            
                   7366: * Creating objects::            
                   7367: * Object-Oriented Programming Style::  
                   7368: * Class Binding::               
                   7369: * Method conveniences::         
                   7370: * Classes and Scoping::         
                   7371: * Object Interfaces::           
                   7372: * Objects Implementation::      
                   7373: * Objects Glossary::            
                   7374: @end menu
1.1       anton    7375: 
1.26      crook    7376: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
                   7377: and Bernd Paysan helped me with the related works section.
1.1       anton    7378: 
1.26      crook    7379: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   7380: @subsubsection Properties of the @file{objects.fs} model
                   7381: @cindex @file{objects.fs} properties
1.1       anton    7382: 
1.26      crook    7383: @itemize @bullet
                   7384: @item
                   7385: It is straightforward to pass objects on the stack. Passing
                   7386: selectors on the stack is a little less convenient, but possible.
1.1       anton    7387: 
1.26      crook    7388: @item
                   7389: Objects are just data structures in memory, and are referenced by their
                   7390: address. You can create words for objects with normal defining words
                   7391: like @code{constant}. Likewise, there is no difference between instance
                   7392: variables that contain objects and those that contain other data.
1.1       anton    7393: 
1.26      crook    7394: @item
                   7395: Late binding is efficient and easy to use.
1.21      crook    7396: 
1.26      crook    7397: @item
                   7398: It avoids parsing, and thus avoids problems with state-smartness
                   7399: and reduced extensibility; for convenience there are a few parsing
                   7400: words, but they have non-parsing counterparts. There are also a few
                   7401: defining words that parse. This is hard to avoid, because all standard
                   7402: defining words parse (except @code{:noname}); however, such
                   7403: words are not as bad as many other parsing words, because they are not
                   7404: state-smart.
1.21      crook    7405: 
1.26      crook    7406: @item
                   7407: It does not try to incorporate everything. It does a few things and does
                   7408: them well (IMO). In particular, this model was not designed to support
                   7409: information hiding (although it has features that may help); you can use
                   7410: a separate package for achieving this.
1.21      crook    7411: 
1.26      crook    7412: @item
                   7413: It is layered; you don't have to learn and use all features to use this
                   7414: model. Only a few features are necessary (@xref{Basic Objects Usage},
                   7415: @xref{The Objects base class}, @xref{Creating objects}.), the others
                   7416: are optional and independent of each other.
1.21      crook    7417: 
1.26      crook    7418: @item
                   7419: An implementation in ANS Forth is available.
1.21      crook    7420: 
1.26      crook    7421: @end itemize
1.21      crook    7422: 
                   7423: 
1.26      crook    7424: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   7425: @subsubsection Basic @file{objects.fs} Usage
                   7426: @cindex basic objects usage
                   7427: @cindex objects, basic usage
1.21      crook    7428: 
1.26      crook    7429: You can define a class for graphical objects like this:
1.21      crook    7430: 
1.26      crook    7431: @cindex @code{class} usage
                   7432: @cindex @code{end-class} usage
                   7433: @cindex @code{selector} usage
                   7434: @example
                   7435: object class \ "object" is the parent class
                   7436:   selector draw ( x y graphical -- )
                   7437: end-class graphical
                   7438: @end example
1.21      crook    7439: 
1.26      crook    7440: This code defines a class @code{graphical} with an
                   7441: operation @code{draw}.  We can perform the operation
                   7442: @code{draw} on any @code{graphical} object, e.g.:
1.21      crook    7443: 
1.26      crook    7444: @example
                   7445: 100 100 t-rex draw
                   7446: @end example
1.21      crook    7447: 
1.26      crook    7448: @noindent
                   7449: where @code{t-rex} is a word (say, a constant) that produces a
                   7450: graphical object.
1.21      crook    7451: 
1.29    ! crook    7452: @comment TODO add a 2nd operation eg perimeter.. and use for
1.26      crook    7453: @comment a concrete example
1.21      crook    7454: 
1.26      crook    7455: @cindex abstract class
                   7456: How do we create a graphical object? With the present definitions,
                   7457: we cannot create a useful graphical object. The class
                   7458: @code{graphical} describes graphical objects in general, but not
                   7459: any concrete graphical object type (C++ users would call it an
                   7460: @emph{abstract class}); e.g., there is no method for the selector
                   7461: @code{draw} in the class @code{graphical}.
1.21      crook    7462: 
1.26      crook    7463: For concrete graphical objects, we define child classes of the
                   7464: class @code{graphical}, e.g.:
1.21      crook    7465: 
1.26      crook    7466: @cindex @code{overrides} usage
                   7467: @cindex @code{field} usage in class definition
                   7468: @example
                   7469: graphical class \ "graphical" is the parent class
                   7470:   cell% field circle-radius
1.21      crook    7471: 
1.26      crook    7472: :noname ( x y circle -- )
                   7473:   circle-radius @@ draw-circle ;
                   7474: overrides draw
1.21      crook    7475: 
1.26      crook    7476: :noname ( n-radius circle -- )
                   7477:   circle-radius ! ;
                   7478: overrides construct
1.21      crook    7479: 
1.26      crook    7480: end-class circle
1.21      crook    7481: @end example
                   7482: 
1.26      crook    7483: Here we define a class @code{circle} as a child of @code{graphical},
                   7484: with field @code{circle-radius} (which behaves just like a field
                   7485: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   7486: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   7487: defined in @code{object}, the parent class of @code{graphical}).
1.21      crook    7488: 
1.26      crook    7489: Now we can create a circle on the heap (i.e.,
                   7490: @code{allocate}d memory) with:
1.21      crook    7491: 
1.26      crook    7492: @cindex @code{heap-new} usage
1.21      crook    7493: @example
1.26      crook    7494: 50 circle heap-new constant my-circle
                   7495: @end example
1.21      crook    7496: 
1.26      crook    7497: @noindent
                   7498: @code{heap-new} invokes @code{construct}, thus
                   7499: initializing the field @code{circle-radius} with 50. We can draw
                   7500: this new circle at (100,100) with:
1.21      crook    7501: 
1.26      crook    7502: @example
                   7503: 100 100 my-circle draw
1.21      crook    7504: @end example
                   7505: 
1.26      crook    7506: @cindex selector invocation, restrictions
                   7507: @cindex class definition, restrictions
                   7508: Note: You can only invoke a selector if the object on the TOS
                   7509: (the receiving object) belongs to the class where the selector was
                   7510: defined or one of its descendents; e.g., you can invoke
                   7511: @code{draw} only for objects belonging to @code{graphical}
                   7512: or its descendents (e.g., @code{circle}).  Immediately before
                   7513: @code{end-class}, the search order has to be the same as
                   7514: immediately after @code{class}.
1.21      crook    7515: 
1.26      crook    7516: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   7517: @subsubsection The @file{object.fs} base class
                   7518: @cindex @code{object} class
1.21      crook    7519: 
1.26      crook    7520: When you define a class, you have to specify a parent class.  So how do
                   7521: you start defining classes? There is one class available from the start:
                   7522: @code{object}. It is ancestor for all classes and so is the
                   7523: only class that has no parent. It has two selectors: @code{construct}
                   7524: and @code{print}.
1.21      crook    7525: 
1.26      crook    7526: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   7527: @subsubsection Creating objects
                   7528: @cindex creating objects
                   7529: @cindex object creation
                   7530: @cindex object allocation options
1.21      crook    7531: 
1.26      crook    7532: @cindex @code{heap-new} discussion
                   7533: @cindex @code{dict-new} discussion
                   7534: @cindex @code{construct} discussion
                   7535: You can create and initialize an object of a class on the heap with
                   7536: @code{heap-new} ( ... class -- object ) and in the dictionary
                   7537: (allocation with @code{allot}) with @code{dict-new} (
                   7538: ... class -- object ). Both words invoke @code{construct}, which
                   7539: consumes the stack items indicated by "..." above.
1.21      crook    7540: 
1.26      crook    7541: @cindex @code{init-object} discussion
                   7542: @cindex @code{class-inst-size} discussion
                   7543: If you want to allocate memory for an object yourself, you can get its
                   7544: alignment and size with @code{class-inst-size 2@@} ( class --
                   7545: align size ). Once you have memory for an object, you can initialize
                   7546: it with @code{init-object} ( ... class object -- );
                   7547: @code{construct} does only a part of the necessary work.
1.21      crook    7548: 
1.26      crook    7549: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   7550: @subsubsection Object-Oriented Programming Style
                   7551: @cindex object-oriented programming style
1.21      crook    7552: 
1.26      crook    7553: This section is not exhaustive.
1.1       anton    7554: 
1.26      crook    7555: @cindex stack effects of selectors
                   7556: @cindex selectors and stack effects
                   7557: In general, it is a good idea to ensure that all methods for the
                   7558: same selector have the same stack effect: when you invoke a selector,
                   7559: you often have no idea which method will be invoked, so, unless all
                   7560: methods have the same stack effect, you will not know the stack effect
                   7561: of the selector invocation.
1.21      crook    7562: 
1.26      crook    7563: One exception to this rule is methods for the selector
                   7564: @code{construct}. We know which method is invoked, because we
                   7565: specify the class to be constructed at the same place. Actually, I
                   7566: defined @code{construct} as a selector only to give the users a
                   7567: convenient way to specify initialization. The way it is used, a
                   7568: mechanism different from selector invocation would be more natural
                   7569: (but probably would take more code and more space to explain).
1.21      crook    7570: 
1.26      crook    7571: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   7572: @subsubsection Class Binding
                   7573: @cindex class binding
                   7574: @cindex early binding
1.21      crook    7575: 
1.26      crook    7576: @cindex late binding
                   7577: Normal selector invocations determine the method at run-time depending
                   7578: on the class of the receiving object. This run-time selection is called
1.29    ! crook    7579: @i{late binding}.
1.21      crook    7580: 
1.26      crook    7581: Sometimes it's preferable to invoke a different method. For example,
                   7582: you might want to use the simple method for @code{print}ing
                   7583: @code{object}s instead of the possibly long-winded @code{print} method
                   7584: of the receiver class. You can achieve this by replacing the invocation
                   7585: of @code{print} with:
1.21      crook    7586: 
1.26      crook    7587: @cindex @code{[bind]} usage
                   7588: @example
                   7589: [bind] object print
1.21      crook    7590: @end example
                   7591: 
1.26      crook    7592: @noindent
                   7593: in compiled code or:
1.21      crook    7594: 
1.26      crook    7595: @cindex @code{bind} usage
1.21      crook    7596: @example
1.26      crook    7597: bind object print
1.21      crook    7598: @end example
                   7599: 
1.26      crook    7600: @cindex class binding, alternative to
                   7601: @noindent
                   7602: in interpreted code. Alternatively, you can define the method with a
                   7603: name (e.g., @code{print-object}), and then invoke it through the
                   7604: name. Class binding is just a (often more convenient) way to achieve
                   7605: the same effect; it avoids name clutter and allows you to invoke
                   7606: methods directly without naming them first.
                   7607: 
                   7608: @cindex superclass binding
                   7609: @cindex parent class binding
                   7610: A frequent use of class binding is this: When we define a method
                   7611: for a selector, we often want the method to do what the selector does
                   7612: in the parent class, and a little more. There is a special word for
                   7613: this purpose: @code{[parent]}; @code{[parent]
                   7614: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   7615: selector}}, where @code{@emph{parent}} is the parent
                   7616: class of the current class. E.g., a method definition might look like:
1.21      crook    7617: 
1.26      crook    7618: @cindex @code{[parent]} usage
1.21      crook    7619: @example
1.26      crook    7620: :noname
                   7621:   dup [parent] foo \ do parent's foo on the receiving object
                   7622:   ... \ do some more
                   7623: ; overrides foo
1.21      crook    7624: @end example
                   7625: 
1.26      crook    7626: @cindex class binding as optimization
                   7627: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   7628: March 1997), Andrew McKewan presents class binding as an optimization
                   7629: technique. I recommend not using it for this purpose unless you are in
                   7630: an emergency. Late binding is pretty fast with this model anyway, so the
                   7631: benefit of using class binding is small; the cost of using class binding
                   7632: where it is not appropriate is reduced maintainability.
1.21      crook    7633: 
1.26      crook    7634: While we are at programming style questions: You should bind
                   7635: selectors only to ancestor classes of the receiving object. E.g., say,
                   7636: you know that the receiving object is of class @code{foo} or its
                   7637: descendents; then you should bind only to @code{foo} and its
                   7638: ancestors.
1.21      crook    7639: 
1.26      crook    7640: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   7641: @subsubsection Method conveniences
                   7642: @cindex method conveniences
1.1       anton    7643: 
1.26      crook    7644: In a method you usually access the receiving object pretty often.  If
                   7645: you define the method as a plain colon definition (e.g., with
                   7646: @code{:noname}), you may have to do a lot of stack
                   7647: gymnastics. To avoid this, you can define the method with @code{m:
                   7648: ... ;m}. E.g., you could define the method for
                   7649: @code{draw}ing a @code{circle} with
1.20      pazsan   7650: 
1.26      crook    7651: @cindex @code{this} usage
                   7652: @cindex @code{m:} usage
                   7653: @cindex @code{;m} usage
                   7654: @example
                   7655: m: ( x y circle -- )
                   7656:   ( x y ) this circle-radius @@ draw-circle ;m
                   7657: @end example
1.20      pazsan   7658: 
1.26      crook    7659: @cindex @code{exit} in @code{m: ... ;m}
                   7660: @cindex @code{exitm} discussion
                   7661: @cindex @code{catch} in @code{m: ... ;m}
                   7662: When this method is executed, the receiver object is removed from the
                   7663: stack; you can access it with @code{this} (admittedly, in this
                   7664: example the use of @code{m: ... ;m} offers no advantage). Note
                   7665: that I specify the stack effect for the whole method (i.e. including
                   7666: the receiver object), not just for the code between @code{m:}
                   7667: and @code{;m}. You cannot use @code{exit} in
                   7668: @code{m:...;m}; instead, use
                   7669: @code{exitm}.@footnote{Moreover, for any word that calls
                   7670: @code{catch} and was defined before loading
                   7671: @code{objects.fs}, you have to redefine it like I redefined
                   7672: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.20      pazsan   7673: 
1.26      crook    7674: @cindex @code{inst-var} usage
                   7675: You will frequently use sequences of the form @code{this
                   7676: @emph{field}} (in the example above: @code{this
                   7677: circle-radius}). If you use the field only in this way, you can
                   7678: define it with @code{inst-var} and eliminate the
                   7679: @code{this} before the field name. E.g., the @code{circle}
                   7680: class above could also be defined with:
1.20      pazsan   7681: 
1.26      crook    7682: @example
                   7683: graphical class
                   7684:   cell% inst-var radius
1.20      pazsan   7685: 
1.26      crook    7686: m: ( x y circle -- )
                   7687:   radius @@ draw-circle ;m
                   7688: overrides draw
1.20      pazsan   7689: 
1.26      crook    7690: m: ( n-radius circle -- )
                   7691:   radius ! ;m
                   7692: overrides construct
1.12      anton    7693: 
1.26      crook    7694: end-class circle
                   7695: @end example
1.12      anton    7696: 
1.26      crook    7697: @code{radius} can only be used in @code{circle} and its
                   7698: descendent classes and inside @code{m:...;m}.
1.12      anton    7699: 
1.26      crook    7700: @cindex @code{inst-value} usage
                   7701: You can also define fields with @code{inst-value}, which is
                   7702: to @code{inst-var} what @code{value} is to
                   7703: @code{variable}.  You can change the value of such a field with
                   7704: @code{[to-inst]}.  E.g., we could also define the class
                   7705: @code{circle} like this:
1.12      anton    7706: 
1.26      crook    7707: @example
                   7708: graphical class
                   7709:   inst-value radius
1.12      anton    7710: 
1.26      crook    7711: m: ( x y circle -- )
                   7712:   radius draw-circle ;m
                   7713: overrides draw
1.12      anton    7714: 
1.26      crook    7715: m: ( n-radius circle -- )
                   7716:   [to-inst] radius ;m
                   7717: overrides construct
1.21      crook    7718: 
1.26      crook    7719: end-class circle
1.12      anton    7720: @end example
                   7721: 
                   7722: 
1.26      crook    7723: @node Classes and Scoping, Object Interfaces, Method conveniences, Objects
                   7724: @subsubsection Classes and Scoping
                   7725: @cindex classes and scoping
                   7726: @cindex scoping and classes
1.12      anton    7727: 
1.26      crook    7728: Inheritance is frequent, unlike structure extension. This exacerbates
                   7729: the problem with the field name convention (@pxref{Structure Naming
                   7730: Convention}): One always has to remember in which class the field was
                   7731: originally defined; changing a part of the class structure would require
                   7732: changes for renaming in otherwise unaffected code.
1.12      anton    7733: 
1.26      crook    7734: @cindex @code{inst-var} visibility
                   7735: @cindex @code{inst-value} visibility
                   7736: To solve this problem, I added a scoping mechanism (which was not in my
                   7737: original charter): A field defined with @code{inst-var} (or
                   7738: @code{inst-value}) is visible only in the class where it is defined and in
                   7739: the descendent classes of this class.  Using such fields only makes
                   7740: sense in @code{m:}-defined methods in these classes anyway.
1.12      anton    7741: 
1.26      crook    7742: This scoping mechanism allows us to use the unadorned field name,
                   7743: because name clashes with unrelated words become much less likely.
1.12      anton    7744: 
1.26      crook    7745: @cindex @code{protected} discussion
                   7746: @cindex @code{private} discussion
                   7747: Once we have this mechanism, we can also use it for controlling the
                   7748: visibility of other words: All words defined after
                   7749: @code{protected} are visible only in the current class and its
                   7750: descendents. @code{public} restores the compilation
                   7751: (i.e. @code{current}) word list that was in effect before. If you
                   7752: have several @code{protected}s without an intervening
                   7753: @code{public} or @code{set-current}, @code{public}
                   7754: will restore the compilation word list in effect before the first of
                   7755: these @code{protected}s.
1.12      anton    7756: 
1.26      crook    7757: @node Object Interfaces, Objects Implementation, Classes and Scoping, Objects
                   7758: @subsubsection Object Interfaces
                   7759: @cindex object interfaces
                   7760: @cindex interfaces for objects
1.12      anton    7761: 
1.26      crook    7762: In this model you can only call selectors defined in the class of the
                   7763: receiving objects or in one of its ancestors. If you call a selector
                   7764: with a receiving object that is not in one of these classes, the
                   7765: result is undefined; if you are lucky, the program crashes
                   7766: immediately.
1.12      anton    7767: 
1.26      crook    7768: @cindex selectors common to hardly-related classes
                   7769: Now consider the case when you want to have a selector (or several)
                   7770: available in two classes: You would have to add the selector to a
                   7771: common ancestor class, in the worst case to @code{object}. You
                   7772: may not want to do this, e.g., because someone else is responsible for
                   7773: this ancestor class.
1.12      anton    7774: 
1.26      crook    7775: The solution for this problem is interfaces. An interface is a
                   7776: collection of selectors. If a class implements an interface, the
                   7777: selectors become available to the class and its descendents. A class
                   7778: can implement an unlimited number of interfaces. For the problem
                   7779: discussed above, we would define an interface for the selector(s), and
                   7780: both classes would implement the interface.
1.12      anton    7781: 
1.26      crook    7782: As an example, consider an interface @code{storage} for
                   7783: writing objects to disk and getting them back, and a class
                   7784: @code{foo} that implements it. The code would look like this:
1.12      anton    7785: 
1.26      crook    7786: @cindex @code{interface} usage
                   7787: @cindex @code{end-interface} usage
                   7788: @cindex @code{implementation} usage
                   7789: @example
                   7790: interface
                   7791:   selector write ( file object -- )
                   7792:   selector read1 ( file object -- )
                   7793: end-interface storage
1.12      anton    7794: 
1.26      crook    7795: bar class
                   7796:   storage implementation
1.12      anton    7797: 
1.26      crook    7798: ... overrides write
                   7799: ... overrides read
                   7800: ...
                   7801: end-class foo
1.12      anton    7802: @end example
                   7803: 
1.26      crook    7804: @noindent
1.29    ! crook    7805: (I would add a word @code{read} @i{( file -- object )} that uses
1.26      crook    7806: @code{read1} internally, but that's beyond the point illustrated
                   7807: here.)
1.12      anton    7808: 
1.26      crook    7809: Note that you cannot use @code{protected} in an interface; and
                   7810: of course you cannot define fields.
1.12      anton    7811: 
1.26      crook    7812: In the Neon model, all selectors are available for all classes;
                   7813: therefore it does not need interfaces. The price you pay in this model
                   7814: is slower late binding, and therefore, added complexity to avoid late
                   7815: binding.
1.12      anton    7816: 
1.26      crook    7817: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   7818: @subsubsection @file{objects.fs} Implementation
                   7819: @cindex @file{objects.fs} implementation
1.12      anton    7820: 
1.26      crook    7821: @cindex @code{object-map} discussion
                   7822: An object is a piece of memory, like one of the data structures
                   7823: described with @code{struct...end-struct}. It has a field
                   7824: @code{object-map} that points to the method map for the object's
                   7825: class.
1.12      anton    7826: 
1.26      crook    7827: @cindex method map
                   7828: @cindex virtual function table
                   7829: The @emph{method map}@footnote{This is Self terminology; in C++
                   7830: terminology: virtual function table.} is an array that contains the
1.29    ! crook    7831: execution tokens (@i{xt}s) of the methods for the object's class. Each
1.26      crook    7832: selector contains an offset into a method map.
1.12      anton    7833: 
1.26      crook    7834: @cindex @code{selector} implementation, class
                   7835: @code{selector} is a defining word that uses
                   7836: @code{CREATE} and @code{DOES>}. The body of the
                   7837: selector contains the offset; the @code{does>} action for a
                   7838: class selector is, basically:
1.21      crook    7839: 
1.26      crook    7840: @example
                   7841: ( object addr ) @@ over object-map @@ + @@ execute
                   7842: @end example
1.12      anton    7843: 
1.26      crook    7844: Since @code{object-map} is the first field of the object, it
                   7845: does not generate any code. As you can see, calling a selector has a
                   7846: small, constant cost.
1.12      anton    7847: 
1.26      crook    7848: @cindex @code{current-interface} discussion
                   7849: @cindex class implementation and representation
                   7850: A class is basically a @code{struct} combined with a method
                   7851: map. During the class definition the alignment and size of the class
                   7852: are passed on the stack, just as with @code{struct}s, so
                   7853: @code{field} can also be used for defining class
                   7854: fields. However, passing more items on the stack would be
                   7855: inconvenient, so @code{class} builds a data structure in memory,
                   7856: which is accessed through the variable
                   7857: @code{current-interface}. After its definition is complete, the
                   7858: class is represented on the stack by a pointer (e.g., as parameter for
                   7859: a child class definition).
1.1       anton    7860: 
1.26      crook    7861: A new class starts off with the alignment and size of its parent,
                   7862: and a copy of the parent's method map. Defining new fields extends the
                   7863: size and alignment; likewise, defining new selectors extends the
1.29    ! crook    7864: method map. @code{overrides} just stores a new @i{xt} in the method
1.26      crook    7865: map at the offset given by the selector.
1.20      pazsan   7866: 
1.26      crook    7867: @cindex class binding, implementation
1.29    ! crook    7868: Class binding just gets the @i{xt} at the offset given by the selector
1.26      crook    7869: from the class's method map and @code{compile,}s (in the case of
                   7870: @code{[bind]}) it.
1.21      crook    7871: 
1.26      crook    7872: @cindex @code{this} implementation
                   7873: @cindex @code{catch} and @code{this}
                   7874: @cindex @code{this} and @code{catch}
                   7875: I implemented @code{this} as a @code{value}. At the
                   7876: start of an @code{m:...;m} method the old @code{this} is
                   7877: stored to the return stack and restored at the end; and the object on
                   7878: the TOS is stored @code{TO this}. This technique has one
                   7879: disadvantage: If the user does not leave the method via
                   7880: @code{;m}, but via @code{throw} or @code{exit},
                   7881: @code{this} is not restored (and @code{exit} may
                   7882: crash). To deal with the @code{throw} problem, I have redefined
                   7883: @code{catch} to save and restore @code{this}; the same
                   7884: should be done with any word that can catch an exception. As for
                   7885: @code{exit}, I simply forbid it (as a replacement, there is
                   7886: @code{exitm}).
1.21      crook    7887: 
1.26      crook    7888: @cindex @code{inst-var} implementation
                   7889: @code{inst-var} is just the same as @code{field}, with
                   7890: a different @code{DOES>} action:
                   7891: @example
                   7892: @@ this +
                   7893: @end example
                   7894: Similar for @code{inst-value}.
1.21      crook    7895: 
1.26      crook    7896: @cindex class scoping implementation
                   7897: Each class also has a word list that contains the words defined with
                   7898: @code{inst-var} and @code{inst-value}, and its protected
                   7899: words. It also has a pointer to its parent. @code{class} pushes
                   7900: the word lists of the class and all its ancestors onto the search order stack,
                   7901: and @code{end-class} drops them.
1.21      crook    7902: 
1.26      crook    7903: @cindex interface implementation
                   7904: An interface is like a class without fields, parent and protected
                   7905: words; i.e., it just has a method map. If a class implements an
                   7906: interface, its method map contains a pointer to the method map of the
                   7907: interface. The positive offsets in the map are reserved for class
                   7908: methods, therefore interface map pointers have negative
                   7909: offsets. Interfaces have offsets that are unique throughout the
                   7910: system, unlike class selectors, whose offsets are only unique for the
                   7911: classes where the selector is available (invokable).
1.21      crook    7912: 
1.26      crook    7913: This structure means that interface selectors have to perform one
                   7914: indirection more than class selectors to find their method. Their body
                   7915: contains the interface map pointer offset in the class method map, and
                   7916: the method offset in the interface method map. The
                   7917: @code{does>} action for an interface selector is, basically:
1.21      crook    7918: 
                   7919: @example
1.26      crook    7920: ( object selector-body )
                   7921: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   7922: swap object-map @@ + @@ ( object selector-body map )
                   7923: swap selector-offset @@ + @@ execute
1.21      crook    7924: @end example
                   7925: 
1.26      crook    7926: where @code{object-map} and @code{selector-offset} are
                   7927: first fields and generate no code.
                   7928: 
                   7929: As a concrete example, consider the following code:
1.21      crook    7930: 
1.26      crook    7931: @example
                   7932: interface
                   7933:   selector if1sel1
                   7934:   selector if1sel2
                   7935: end-interface if1
1.21      crook    7936: 
1.26      crook    7937: object class
                   7938:   if1 implementation
                   7939:   selector cl1sel1
                   7940:   cell% inst-var cl1iv1
1.21      crook    7941: 
1.26      crook    7942: ' m1 overrides construct
                   7943: ' m2 overrides if1sel1
                   7944: ' m3 overrides if1sel2
                   7945: ' m4 overrides cl1sel2
                   7946: end-class cl1
1.21      crook    7947: 
1.26      crook    7948: create obj1 object dict-new drop
                   7949: create obj2 cl1    dict-new drop
                   7950: @end example
1.21      crook    7951: 
1.26      crook    7952: The data structure created by this code (including the data structure
                   7953: for @code{object}) is shown in the <a
                   7954: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
1.29    ! crook    7955: @comment TODO add this diagram..
1.21      crook    7956: 
1.26      crook    7957: @node Objects Glossary,  , Objects Implementation, Objects
                   7958: @subsubsection @file{objects.fs} Glossary
                   7959: @cindex @file{objects.fs} Glossary
1.21      crook    7960: 
1.26      crook    7961: doc---objects-bind
                   7962: doc---objects-<bind>
                   7963: doc---objects-bind'
                   7964: doc---objects-[bind]
                   7965: doc---objects-class
                   7966: doc---objects-class->map
                   7967: doc---objects-class-inst-size
                   7968: doc---objects-class-override!
                   7969: doc---objects-construct
                   7970: doc---objects-current'
                   7971: doc---objects-[current]
                   7972: doc---objects-current-interface
                   7973: doc---objects-dict-new
                   7974: doc---objects-drop-order
                   7975: doc---objects-end-class
                   7976: doc---objects-end-class-noname
                   7977: doc---objects-end-interface
                   7978: doc---objects-end-interface-noname
                   7979: doc---objects-exitm
                   7980: doc---objects-heap-new
                   7981: doc---objects-implementation
                   7982: doc---objects-init-object
                   7983: doc---objects-inst-value
                   7984: doc---objects-inst-var
                   7985: doc---objects-interface
                   7986: doc---objects-;m
                   7987: doc---objects-m:
                   7988: doc---objects-method
                   7989: doc---objects-object
                   7990: doc---objects-overrides
                   7991: doc---objects-[parent]
                   7992: doc---objects-print
                   7993: doc---objects-protected
                   7994: doc---objects-public
                   7995: doc---objects-push-order
                   7996: doc---objects-selector
                   7997: doc---objects-this
                   7998: doc---objects-<to-inst>
                   7999: doc---objects-[to-inst]
                   8000: doc---objects-to-this
                   8001: doc---objects-xt-new
1.21      crook    8002: 
1.26      crook    8003: @c -------------------------------------------------------------
                   8004: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   8005: @subsection The @file{oof.fs} model
                   8006: @cindex oof
                   8007: @cindex object-oriented programming
1.21      crook    8008: 
1.26      crook    8009: @cindex @file{objects.fs}
                   8010: @cindex @file{oof.fs}
1.21      crook    8011: 
1.26      crook    8012: This section describes the @file{oof.fs} package.
1.21      crook    8013: 
1.26      crook    8014: The package described in this section has been used in bigFORTH since 1991, and
                   8015: used for two large applications: a chromatographic system used to
                   8016: create new medicaments, and a graphic user interface library (MINOS).
1.21      crook    8017: 
1.26      crook    8018: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   8019: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   8020: 10(2), 1994.
1.21      crook    8021: 
1.26      crook    8022: @menu
                   8023: * Properties of the OOF model::
                   8024: * Basic OOF Usage::
                   8025: * The OOF base class::
                   8026: * Class Declaration::
                   8027: * Class Implementation::
                   8028: @end menu
1.21      crook    8029: 
1.26      crook    8030: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   8031: @subsubsection Properties of the @file{oof.fs} model
                   8032: @cindex @file{oof.fs} properties
1.21      crook    8033: 
1.26      crook    8034: @itemize @bullet
                   8035: @item
                   8036: This model combines object oriented programming with information
                   8037: hiding. It helps you writing large application, where scoping is
                   8038: necessary, because it provides class-oriented scoping.
1.21      crook    8039: 
1.26      crook    8040: @item
                   8041: Named objects, object pointers, and object arrays can be created,
                   8042: selector invocation uses the ``object selector'' syntax. Selector invocation
                   8043: to objects and/or selectors on the stack is a bit less convenient, but
                   8044: possible.
1.21      crook    8045: 
1.26      crook    8046: @item
                   8047: Selector invocation and instance variable usage of the active object is
                   8048: straightforward, since both make use of the active object.
1.21      crook    8049: 
1.26      crook    8050: @item
                   8051: Late binding is efficient and easy to use.
1.21      crook    8052: 
1.26      crook    8053: @item
                   8054: State-smart objects parse selectors. However, extensibility is provided
                   8055: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.21      crook    8056: 
                   8057: @item
1.26      crook    8058: An implementation in ANS Forth is available.
                   8059: 
1.21      crook    8060: @end itemize
                   8061: 
                   8062: 
1.26      crook    8063: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   8064: @subsubsection Basic @file{oof.fs} Usage
                   8065: @cindex @file{oof.fs} usage
                   8066: 
                   8067: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.21      crook    8068: 
1.26      crook    8069: You can define a class for graphical objects like this:
1.21      crook    8070: 
1.26      crook    8071: @cindex @code{class} usage
                   8072: @cindex @code{class;} usage
                   8073: @cindex @code{method} usage
                   8074: @example
                   8075: object class graphical \ "object" is the parent class
                   8076:   method draw ( x y graphical -- )
                   8077: class;
                   8078: @end example
1.21      crook    8079: 
1.26      crook    8080: This code defines a class @code{graphical} with an
                   8081: operation @code{draw}.  We can perform the operation
                   8082: @code{draw} on any @code{graphical} object, e.g.:
1.21      crook    8083: 
1.26      crook    8084: @example
                   8085: 100 100 t-rex draw
                   8086: @end example
1.21      crook    8087: 
1.26      crook    8088: @noindent
                   8089: where @code{t-rex} is an object or object pointer, created with e.g.
                   8090: @code{graphical : t-rex}.
1.21      crook    8091: 
1.26      crook    8092: @cindex abstract class
                   8093: How do we create a graphical object? With the present definitions,
                   8094: we cannot create a useful graphical object. The class
                   8095: @code{graphical} describes graphical objects in general, but not
                   8096: any concrete graphical object type (C++ users would call it an
                   8097: @emph{abstract class}); e.g., there is no method for the selector
                   8098: @code{draw} in the class @code{graphical}.
1.21      crook    8099: 
1.26      crook    8100: For concrete graphical objects, we define child classes of the
                   8101: class @code{graphical}, e.g.:
1.21      crook    8102: 
                   8103: @example
1.26      crook    8104: graphical class circle \ "graphical" is the parent class
                   8105:   cell var circle-radius
                   8106: how:
                   8107:   : draw ( x y -- )
                   8108:     circle-radius @@ draw-circle ;
                   8109: 
                   8110:   : init ( n-radius -- (
                   8111:     circle-radius ! ;
                   8112: class;
                   8113: @end example
                   8114: 
                   8115: Here we define a class @code{circle} as a child of @code{graphical},
                   8116: with a field @code{circle-radius}; it defines new methods for the
                   8117: selectors @code{draw} and @code{init} (@code{init} is defined in
                   8118: @code{object}, the parent class of @code{graphical}).
1.21      crook    8119: 
1.26      crook    8120: Now we can create a circle in the dictionary with:
1.21      crook    8121: 
1.26      crook    8122: @example
                   8123: 50 circle : my-circle
1.21      crook    8124: @end example
                   8125: 
1.26      crook    8126: @noindent
                   8127: @code{:} invokes @code{init}, thus initializing the field
                   8128: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   8129: with:
1.21      crook    8130: 
                   8131: @example
1.26      crook    8132: 100 100 my-circle draw
1.21      crook    8133: @end example
                   8134: 
1.26      crook    8135: @cindex selector invocation, restrictions
                   8136: @cindex class definition, restrictions
                   8137: Note: You can only invoke a selector if the receiving object belongs to
                   8138: the class where the selector was defined or one of its descendents;
                   8139: e.g., you can invoke @code{draw} only for objects belonging to
                   8140: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   8141: mechanism will check if you try to invoke a selector that is not
                   8142: defined in this class hierarchy, so you'll get an error at compilation
                   8143: time.
                   8144: 
                   8145: 
                   8146: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   8147: @subsubsection The @file{oof.fs} base class
                   8148: @cindex @file{oof.fs} base class
                   8149: 
                   8150: When you define a class, you have to specify a parent class.  So how do
                   8151: you start defining classes? There is one class available from the start:
                   8152: @code{object}. You have to use it as ancestor for all classes. It is the
                   8153: only class that has no parent. Classes are also objects, except that
                   8154: they don't have instance variables; class manipulation such as
                   8155: inheritance or changing definitions of a class is handled through
                   8156: selectors of the class @code{object}.
                   8157: 
                   8158: @code{object} provides a number of selectors:
                   8159: 
1.21      crook    8160: @itemize @bullet
                   8161: @item
1.26      crook    8162: @code{class} for subclassing, @code{definitions} to add definitions
                   8163: later on, and @code{class?} to get type informations (is the class a
                   8164: subclass of the class passed on the stack?).
                   8165: doc---object-class
                   8166: doc---object-definitions
                   8167: doc---object-class?
                   8168: 
1.21      crook    8169: @item
1.26      crook    8170: @code{init} and @code{dispose} as constructor and destructor of the
                   8171: object. @code{init} is invocated after the object's memory is allocated,
                   8172: while @code{dispose} also handles deallocation. Thus if you redefine
                   8173: @code{dispose}, you have to call the parent's dispose with @code{super
                   8174: dispose}, too.
                   8175: doc---object-init
                   8176: doc---object-dispose
                   8177: 
1.21      crook    8178: @item
1.26      crook    8179: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   8180: @code{[]} to create named and unnamed objects and object arrays or
                   8181: object pointers.
                   8182: doc---object-new
                   8183: doc---object-new[]
                   8184: doc---object-:
                   8185: doc---object-ptr
                   8186: doc---object-asptr
                   8187: doc---object-[]
1.21      crook    8188: 
1.26      crook    8189: @item
                   8190: @code{::} and @code{super} for explicit scoping. You should use explicit
                   8191: scoping only for super classes or classes with the same set of instance
                   8192: variables. Explicitly-scoped selectors use early binding.
                   8193: doc---object-::
                   8194: doc---object-super
1.21      crook    8195: 
1.26      crook    8196: @item
                   8197: @code{self} to get the address of the object
                   8198: doc---object-self
1.21      crook    8199: 
                   8200: @item
1.26      crook    8201: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   8202: pointers and instance defers.
                   8203: doc---object-bind
                   8204: doc---object-bound
                   8205: doc---object-link
                   8206: doc---object-is
                   8207: 
1.21      crook    8208: @item
1.26      crook    8209: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   8210: form the stack, and @code{postpone} to generate selector invocation code.
                   8211: doc---object-'
                   8212: doc---object-postpone
                   8213: 
1.21      crook    8214: @item
1.26      crook    8215: @code{with} and @code{endwith} to select the active object from the
                   8216: stack, and enable its scope. Using @code{with} and @code{endwith}
                   8217: also allows you to create code using selector @code{postpone} without being
                   8218: trapped by the state-smart objects.
                   8219: doc---object-with
                   8220: doc---object-endwith
                   8221: 
1.21      crook    8222: @end itemize
                   8223: 
1.26      crook    8224: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   8225: @subsubsection Class Declaration
                   8226: @cindex class declaration
                   8227: 
                   8228: @itemize @bullet
                   8229: @item
                   8230: Instance variables
                   8231: doc---oof-var
1.21      crook    8232: 
1.26      crook    8233: @item
                   8234: Object pointers
                   8235: doc---oof-ptr
                   8236: doc---oof-asptr
1.21      crook    8237: 
1.26      crook    8238: @item
                   8239: Instance defers
                   8240: doc---oof-defer
1.21      crook    8241: 
1.26      crook    8242: @item
                   8243: Method selectors
                   8244: doc---oof-early
                   8245: doc---oof-method
1.21      crook    8246: 
1.26      crook    8247: @item
                   8248: Class-wide variables
                   8249: doc---oof-static
1.21      crook    8250: 
1.26      crook    8251: @item
                   8252: End declaration
                   8253: doc---oof-how:
                   8254: doc---oof-class;
1.21      crook    8255: 
1.26      crook    8256: @end itemize
1.21      crook    8257: 
1.26      crook    8258: @c -------------------------------------------------------------
                   8259: @node Class Implementation,  , Class Declaration, OOF
                   8260: @subsubsection Class Implementation
                   8261: @cindex class implementation
1.21      crook    8262: 
1.26      crook    8263: @c -------------------------------------------------------------
                   8264: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   8265: @subsection The @file{mini-oof.fs} model
                   8266: @cindex mini-oof
1.1       anton    8267: 
1.26      crook    8268: Gforth's third object oriented Forth package is a 12-liner. It uses a
                   8269: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
                   8270: and reduces to the bare minimum of features. This is based on a posting
                   8271: of Bernd Paysan in comp.arch.
1.1       anton    8272: 
                   8273: @menu
1.26      crook    8274: * Basic Mini-OOF Usage::
                   8275: * Mini-OOF Example::
                   8276: * Mini-OOF Implementation::
1.1       anton    8277: @end menu
                   8278: 
1.26      crook    8279: @c -------------------------------------------------------------
                   8280: @node Basic Mini-OOF Usage, Mini-OOF Example, , Mini-OOF
                   8281: @subsubsection Basic @file{mini-oof.fs} Usage
                   8282: @cindex mini-oof usage
1.1       anton    8283: 
1.28      crook    8284: There is a base class (@code{class}, which allocates one cell for the
                   8285: object pointer) plus seven other words: to define a method, a variable,
                   8286: a class; to end a class, to resolve binding, to allocate an object and
                   8287: to compile a class method.
1.26      crook    8288: @comment TODO better description of the last one
1.1       anton    8289: 
1.26      crook    8290: doc-object
                   8291: doc-method
                   8292: doc-var
                   8293: doc-class
                   8294: doc-end-class
                   8295: doc-defines
                   8296: doc-new
                   8297: doc-::
1.1       anton    8298: 
1.21      crook    8299: 
1.26      crook    8300: @c -------------------------------------------------------------
                   8301: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   8302: @subsubsection Mini-OOF Example
                   8303: @cindex mini-oof example
1.21      crook    8304: 
1.26      crook    8305: A short example shows how to use this package. This example, in slightly
                   8306: extended form, is supplied as @file{moof-exm.fs}
1.29    ! crook    8307: @comment TODO could flesh this out with some comments from the Forthwrite article
1.21      crook    8308: 
1.26      crook    8309: @example
                   8310: object class
                   8311:   method init
                   8312:   method draw
                   8313: end-class graphical
                   8314: @end example
1.21      crook    8315: 
1.26      crook    8316: This code defines a class @code{graphical} with an
                   8317: operation @code{draw}.  We can perform the operation
                   8318: @code{draw} on any @code{graphical} object, e.g.:
1.1       anton    8319: 
1.26      crook    8320: @example
                   8321: 100 100 t-rex draw
                   8322: @end example
1.1       anton    8323: 
1.26      crook    8324: where @code{t-rex} is an object or object pointer, created with e.g.
                   8325: @code{graphical new Constant t-rex}.
1.1       anton    8326: 
1.26      crook    8327: For concrete graphical objects, we define child classes of the
                   8328: class @code{graphical}, e.g.:
1.21      crook    8329: 
                   8330: @example
1.26      crook    8331: graphical class
                   8332:   cell var circle-radius
                   8333: end-class circle \ "graphical" is the parent class
1.21      crook    8334: 
1.26      crook    8335: :noname ( x y -- )
                   8336:   circle-radius @@ draw-circle ; circle defines draw
                   8337: :noname ( r -- )
                   8338:   circle-radius ! ; circle defines init
1.21      crook    8339: @end example
                   8340: 
1.26      crook    8341: There is no implicit init method, so we have to define one. The creation
                   8342: code of the object now has to call init explicitely.
1.21      crook    8343: 
1.26      crook    8344: @example
                   8345: circle new Constant my-circle
                   8346: 50 my-circle init
                   8347: @end example
1.21      crook    8348: 
1.26      crook    8349: It is also possible to add a function to create named objects with
                   8350: automatic call of @code{init}, given that all objects have @code{init}
                   8351: on the same place:
1.1       anton    8352: 
                   8353: @example
1.26      crook    8354: : new: ( .. o "name" -- )
                   8355:     new dup Constant init ;
                   8356: 80 circle new: large-circle
1.1       anton    8357: @end example
                   8358: 
1.26      crook    8359: We can draw this new circle at (100,100) with:
1.1       anton    8360: 
                   8361: @example
1.26      crook    8362: 100 100 my-circle draw
1.1       anton    8363: @end example
                   8364: 
1.26      crook    8365: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
                   8366: @subsubsection @file{mini-oof.fs} Implementation
1.1       anton    8367: 
1.26      crook    8368: Object-oriented systems with late binding typically use a
                   8369: ``vtable''-approach: the first variable in each object is a pointer to a
                   8370: table, which contains the methods as function pointers. The vtable
                   8371: may also contain other information.
1.1       anton    8372: 
1.26      crook    8373: So first, let's declare methods:
1.1       anton    8374: 
1.26      crook    8375: @example
                   8376: : method ( m v -- m' v ) Create  over , swap cell+ swap
                   8377:   DOES> ( ... o -- ... ) @ over @ + @ execute ;
                   8378: @end example
1.1       anton    8379: 
1.26      crook    8380: During method declaration, the number of methods and instance
                   8381: variables is on the stack (in address units). @code{method} creates
                   8382: one method and increments the method number. To execute a method, it
                   8383: takes the object, fetches the vtable pointer, adds the offset, and
1.29    ! crook    8384: executes the @i{xt} stored there. Each method takes the object it is
1.26      crook    8385: invoked from as top of stack parameter. The method itself should
                   8386: consume that object.
1.1       anton    8387: 
1.26      crook    8388: Now, we also have to declare instance variables
1.21      crook    8389: 
1.26      crook    8390: @example
                   8391: : var ( m v size -- m v' ) Create  over , +
                   8392:   DOES> ( o -- addr ) @ + ;
                   8393: @end example
1.21      crook    8394: 
1.26      crook    8395: As before, a word is created with the current offset. Instance
                   8396: variables can have different sizes (cells, floats, doubles, chars), so
                   8397: all we do is take the size and add it to the offset. If your machine
                   8398: has alignment restrictions, put the proper @code{aligned} or
                   8399: @code{faligned} before the variable, to adjust the variable
                   8400: offset. That's why it is on the top of stack.
1.2       jwilke   8401: 
1.26      crook    8402: We need a starting point (the base object) and some syntactic sugar:
1.21      crook    8403: 
1.26      crook    8404: @example
                   8405: Create object  1 cells , 2 cells ,
                   8406: : class ( class -- class methods vars ) dup 2@ ;
                   8407: @end example
1.21      crook    8408: 
1.26      crook    8409: For inheritance, the vtable of the parent object has to be
                   8410: copied when a new, derived class is declared. This gives all the
                   8411: methods of the parent class, which can be overridden, though.
1.21      crook    8412: 
1.2       jwilke   8413: @example
1.26      crook    8414: : end-class  ( class methods vars -- )
                   8415:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   8416:   cell+ dup cell+ r> rot @ 2 cells /string move ;
                   8417: @end example
                   8418: 
                   8419: The first line creates the vtable, initialized with
                   8420: @code{noop}s. The second line is the inheritance mechanism, it
                   8421: copies the xts from the parent vtable.
1.2       jwilke   8422: 
1.26      crook    8423: We still have no way to define new methods, let's do that now:
1.2       jwilke   8424: 
1.26      crook    8425: @example
                   8426: : defines ( xt class -- ) ' >body @ + ! ;
1.2       jwilke   8427: @end example
                   8428: 
1.26      crook    8429: To allocate a new object, we need a word, too:
1.2       jwilke   8430: 
1.26      crook    8431: @example
                   8432: : new ( class -- o )  here over @ allot swap over ! ;
                   8433: @end example
1.2       jwilke   8434: 
1.26      crook    8435: Sometimes derived classes want to access the method of the
                   8436: parent object. There are two ways to achieve this with Mini-OOF:
                   8437: first, you could use named words, and second, you could look up the
                   8438: vtable of the parent object.
1.2       jwilke   8439: 
1.26      crook    8440: @example
                   8441: : :: ( class "name" -- ) ' >body @ + @ compile, ;
                   8442: @end example
1.2       jwilke   8443: 
                   8444: 
1.26      crook    8445: Nothing can be more confusing than a good example, so here is
                   8446: one. First let's declare a text object (called
                   8447: @code{button}), that stores text and position:
1.2       jwilke   8448: 
1.26      crook    8449: @example
                   8450: object class
                   8451:   cell var text
                   8452:   cell var len
                   8453:   cell var x
                   8454:   cell var y
                   8455:   method init
                   8456:   method draw
                   8457: end-class button
                   8458: @end example
1.2       jwilke   8459: 
1.26      crook    8460: @noindent
                   8461: Now, implement the two methods, @code{draw} and @code{init}:
1.2       jwilke   8462: 
1.26      crook    8463: @example
                   8464: :noname ( o -- )
                   8465:  >r r@ x @ r@ y @ at-xy  r@ text @ r> len @ type ;
                   8466:  button defines draw
                   8467: :noname ( addr u o -- )
                   8468:  >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
                   8469:  button defines init
                   8470: @end example
1.2       jwilke   8471: 
1.26      crook    8472: @noindent
                   8473: To demonstrate inheritance, we define a class @code{bold-button}, with no
                   8474: new data and no new methods:
1.2       jwilke   8475: 
1.26      crook    8476: @example
                   8477: button class
                   8478: end-class bold-button
1.1       anton    8479: 
1.26      crook    8480: : bold   27 emit ." [1m" ;
                   8481: : normal 27 emit ." [0m" ;
                   8482: @end example
1.1       anton    8483: 
1.26      crook    8484: @noindent
                   8485: The class @code{bold-button} has a different draw method to
                   8486: @code{button}, but the new method is defined in terms of the draw method
                   8487: for @code{button}:
1.1       anton    8488: 
1.26      crook    8489: @example
                   8490: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   8491: @end example
1.1       anton    8492: 
1.26      crook    8493: @noindent
                   8494: Finally, create two objects and apply methods:
1.1       anton    8495: 
1.26      crook    8496: @example
                   8497: button new Constant foo
                   8498: s" thin foo" foo init
                   8499: page
                   8500: foo draw
                   8501: bold-button new Constant bar
                   8502: s" fat bar" bar init
                   8503: 1 bar y !
                   8504: bar draw
                   8505: @end example
1.1       anton    8506: 
                   8507: 
1.26      crook    8508: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
                   8509: @subsubsection Comparison with other object models
                   8510: @cindex comparison of object models
                   8511: @cindex object models, comparison
1.1       anton    8512: 
1.26      crook    8513: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   8514: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   8515: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   8516: relation of the object models described here to two well-known and two
                   8517: closely-related (by the use of method maps) models.
1.1       anton    8518: 
1.26      crook    8519: @cindex Neon model
                   8520: The most popular model currently seems to be the Neon model (see
                   8521: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   8522: 1997) by Andrew McKewan) but this model has a number of limitations
                   8523: @footnote{A longer version of this critique can be
                   8524: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   8525: Dimensions, May 1997) by Anton Ertl.}:
1.1       anton    8526: 
1.26      crook    8527: @itemize @bullet
                   8528: @item
                   8529: It uses a @code{@emph{selector
                   8530: object}} syntax, which makes it unnatural to pass objects on the
                   8531: stack.
1.1       anton    8532: 
1.26      crook    8533: @item
                   8534: It requires that the selector parses the input stream (at
                   8535: compile time); this leads to reduced extensibility and to bugs that are+
                   8536: hard to find.
1.1       anton    8537: 
1.26      crook    8538: @item
                   8539: It allows using every selector to every object;
                   8540: this eliminates the need for classes, but makes it harder to create
                   8541: efficient implementations. 
                   8542: @end itemize
1.1       anton    8543: 
1.26      crook    8544: @cindex Pountain's object-oriented model
                   8545: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   8546: Press, London, 1987) by Dick Pountain. However, it is not really about
                   8547: object-oriented programming, because it hardly deals with late
                   8548: binding. Instead, it focuses on features like information hiding and
                   8549: overloading that are characteristic of modular languages like Ada (83).
1.1       anton    8550: 
1.26      crook    8551: @cindex Zsoter's object-oriented model
                   8552: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1) 1996, pages 31-35)
                   8553: Andras Zsoter describes a model that makes heavy use of an active object
                   8554: (like @code{this} in @file{objects.fs}): The active object is not only
                   8555: used for accessing all fields, but also specifies the receiving object
                   8556: of every selector invocation; you have to change the active object
                   8557: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
                   8558: changes more or less implicitly at @code{m: ... ;m}. Such a change at
                   8559: the method entry point is unnecessary with the Zsoter's model, because
                   8560: the receiving object is the active object already. On the other hand, the explicit
                   8561: change is absolutely necessary in that model, because otherwise no one
                   8562: could ever change the active object. An ANS Forth implementation of this
                   8563: model is available at @url{http://www.forth.org/fig/oopf.html}.
1.1       anton    8564: 
1.26      crook    8565: @cindex @file{oof.fs}, differences to other models
                   8566: The @file{oof.fs} model combines information hiding and overloading
                   8567: resolution (by keeping names in various word lists) with object-oriented
                   8568: programming. It sets the active object implicitly on method entry, but
                   8569: also allows explicit changing (with @code{>o...o>} or with
                   8570: @code{with...endwith}). It uses parsing and state-smart objects and
                   8571: classes for resolving overloading and for early binding: the object or
                   8572: class parses the selector and determines the method from this. If the
                   8573: selector is not parsed by an object or class, it performs a call to the
                   8574: selector for the active object (late binding), like Zsoter's model.
                   8575: Fields are always accessed through the active object. The big
                   8576: disadvantage of this model is the parsing and the state-smartness, which
                   8577: reduces extensibility and increases the opportunities for subtle bugs;
                   8578: essentially, you are only safe if you never tick or @code{postpone} an
                   8579: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.1       anton    8580: 
1.26      crook    8581: @cindex @file{mini-oof.fs}, differences to other models
                   8582: The @file{mini-oof.fs} model is quite similar to a very stripped-down version of
                   8583: the @file{objects.fs} model, but syntactically it is a mixture of the @file{objects.fs} and
                   8584: @file{oof.fs} models.
1.1       anton    8585: 
1.26      crook    8586: @c -------------------------------------------------------------
                   8587: @node Passing Commands to the OS, Miscellaneous Words, Object-oriented Forth, Words
1.21      crook    8588: @section Passing Commands to the Operating System
                   8589: @cindex operating system - passing commands
                   8590: @cindex shell commands
                   8591: 
                   8592: Gforth allows you to pass an arbitrary string to the host operating
                   8593: system shell (if such a thing exists) for execution.
                   8594: 
                   8595: doc-sh
                   8596: doc-system
                   8597: doc-$?
1.23      crook    8598: doc-getenv
1.21      crook    8599: 
1.26      crook    8600: @c -------------------------------------------------------------
1.21      crook    8601: @node Miscellaneous Words,  , Passing Commands to the OS, Words
                   8602: @section Miscellaneous Words
                   8603: @cindex miscellaneous words
                   8604: 
1.29    ! crook    8605: @comment TODO find homes for these
        !          8606: 
1.26      crook    8607: These section lists the ANS Forth words that are not documented
1.21      crook    8608: elsewhere in this manual. Ultimately, they all need proper homes.
                   8609: 
                   8610: doc-ms
                   8611: doc-time&date
1.27      crook    8612: 
1.21      crook    8613: doc-[compile]
                   8614: 
1.26      crook    8615: The following ANS Forth words are not currently supported by Gforth 
1.27      crook    8616: (@pxref{ANS conformance}):
1.21      crook    8617: 
                   8618: @code{EDITOR} 
                   8619: @code{EKEY} 
                   8620: @code{EKEY>CHAR} 
                   8621: @code{EKEY?} 
                   8622: @code{EMIT?} 
                   8623: @code{FORGET} 
                   8624: 
1.24      anton    8625: @c ******************************************************************
                   8626: @node Error messages, Tools, Words, Top
                   8627: @chapter Error messages
                   8628: @cindex error messages
                   8629: @cindex backtrace
                   8630: 
                   8631: A typical Gforth error message looks like this:
                   8632: 
                   8633: @example
                   8634: in file included from :-1
                   8635: in file included from ./yyy.fs:1
                   8636: ./xxx.fs:4: Invalid memory address
                   8637: bar
                   8638: ^^^
1.25      anton    8639: $400E664C @@
                   8640: $400E6664 foo
1.24      anton    8641: @end example
                   8642: 
                   8643: The message identifying the error is @code{Invalid memory address}.  The
                   8644: error happened when text-interpreting line 4 of the file
                   8645: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
                   8646: word on the line where the error happened, is pointed out (with
                   8647: @code{^^^}).
                   8648: 
                   8649: The file containing the error was included in line 1 of @file{./yyy.fs},
                   8650: and @file{yyy.fs} was included from a non-file (in this case, by giving
                   8651: @file{yyy.fs} as command-line parameter to Gforth).
                   8652: 
                   8653: At the end of the error message you find a return stack dump that can be
                   8654: interpreted as a backtrace (possibly empty). On top you find the top of
                   8655: the return stack when the @code{throw} happened, and at the bottom you
                   8656: find the return stack entry just above the return stack of the topmost
                   8657: text interpreter.
                   8658: 
                   8659: To the right of most return stack entries you see a guess for the word
                   8660: that pushed that return stack entry as its return address. This gives a
                   8661: backtrace. In our case we see that @code{bar} called @code{foo}, and
                   8662: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
                   8663: address} exception).
                   8664: 
                   8665: Note that the backtrace is not perfect: We don't know which return stack
                   8666: entries are return addresses (so we may get false positives); and in
                   8667: some cases (e.g., for @code{abort"}) we cannot determine from the return
                   8668: address the word that pushed the return address, so for some return
                   8669: addresses you see no names in the return stack dump.
1.25      anton    8670: 
                   8671: @cindex @code{catch} and backtraces
                   8672: The return stack dump represents the return stack at the time when a
                   8673: specific @code{throw} was executed.  In programs that make use of
                   8674: @code{catch}, it is not necessarily clear which @code{throw} should be
                   8675: used for the return stack dump (e.g., consider one @code{throw} that
                   8676: indicates an error, which is caught, and during recovery another error
                   8677: happens; which @code{throw} should be used for the stack dump).  Gforth
                   8678: presents the return stack dump for the first @code{throw} after the last
                   8679: executed (not returned-to) @code{catch}; this works well in the usual
                   8680: case.
                   8681: 
                   8682: @cindex @code{gforth-fast} and backtraces
                   8683: @cindex @code{gforth-fast}, difference from @code{gforth}
                   8684: @cindex backtraces with @code{gforth-fast}
                   8685: @cindex return stack dump with @code{gforth-fast}
                   8686: @code{gforth} is able to do a return stack dump for throws generated
                   8687: from primitives (e.g., invalid memory address, stack empty etc.);
                   8688: @code{gforth-fast} is only able to do a return stack dump from a
                   8689: directly called @code{throw} (including @code{abort} etc.).  This is the
                   8690: only difference (apart from a speed difference of about 30%) between
                   8691: @code{gforth} and @code{gforth-fast}.  Given an exception caused by a
                   8692: primitive in @code{gforth-fast}, you will typically see no return stack
                   8693: dump at all; however, if the exception is caught by @code{catch} (e.g.,
                   8694: for restoring some state), and then @code{throw}n again, the return
                   8695: stack dump will be for the first such @code{throw}.
1.2       jwilke   8696: 
1.5       anton    8697: @c ******************************************************************
1.24      anton    8698: @node Tools, ANS conformance, Error messages, Top
1.1       anton    8699: @chapter Tools
                   8700: 
                   8701: @menu
                   8702: * ANS Report::                  Report the words used, sorted by wordset.
                   8703: @end menu
                   8704: 
                   8705: See also @ref{Emacs and Gforth}.
                   8706: 
                   8707: @node ANS Report,  , Tools, Tools
                   8708: @section @file{ans-report.fs}: Report the words used, sorted by wordset
                   8709: @cindex @file{ans-report.fs}
                   8710: @cindex report the words used in your program
                   8711: @cindex words used in your program
                   8712: 
                   8713: If you want to label a Forth program as ANS Forth Program, you must
                   8714: document which wordsets the program uses; for extension wordsets, it is
                   8715: helpful to list the words the program requires from these wordsets
                   8716: (because Forth systems are allowed to provide only some words of them).
                   8717: 
                   8718: The @file{ans-report.fs} tool makes it easy for you to determine which
                   8719: words from which wordset and which non-ANS words your application
                   8720: uses. You simply have to include @file{ans-report.fs} before loading the
                   8721: program you want to check. After loading your program, you can get the
                   8722: report with @code{print-ans-report}. A typical use is to run this as
                   8723: batch job like this:
                   8724: @example
                   8725: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
                   8726: @end example
                   8727: 
                   8728: The output looks like this (for @file{compat/control.fs}):
                   8729: @example
                   8730: The program uses the following words
                   8731: from CORE :
                   8732: : POSTPONE THEN ; immediate ?dup IF 0= 
                   8733: from BLOCK-EXT :
                   8734: \ 
                   8735: from FILE :
                   8736: ( 
                   8737: @end example
                   8738: 
                   8739: @subsection Caveats
                   8740: 
                   8741: Note that @file{ans-report.fs} just checks which words are used, not whether
                   8742: they are used in an ANS Forth conforming way!
                   8743: 
                   8744: Some words are defined in several wordsets in the
                   8745: standard. @file{ans-report.fs} reports them for only one of the
                   8746: wordsets, and not necessarily the one you expect. It depends on usage
                   8747: which wordset is the right one to specify. E.g., if you only use the
                   8748: compilation semantics of @code{S"}, it is a Core word; if you also use
                   8749: its interpretation semantics, it is a File word.
                   8750: 
                   8751: @c ******************************************************************
                   8752: @node ANS conformance, Model, Tools, Top
                   8753: @chapter ANS conformance
                   8754: @cindex ANS conformance of Gforth
                   8755: 
                   8756: To the best of our knowledge, Gforth is an
                   8757: 
                   8758: ANS Forth System
                   8759: @itemize @bullet
                   8760: @item providing the Core Extensions word set
                   8761: @item providing the Block word set
                   8762: @item providing the Block Extensions word set
                   8763: @item providing the Double-Number word set
                   8764: @item providing the Double-Number Extensions word set
                   8765: @item providing the Exception word set
                   8766: @item providing the Exception Extensions word set
                   8767: @item providing the Facility word set
                   8768: @item providing @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
                   8769: @item providing the File Access word set
                   8770: @item providing the File Access Extensions word set
                   8771: @item providing the Floating-Point word set
                   8772: @item providing the Floating-Point Extensions word set
                   8773: @item providing the Locals word set
                   8774: @item providing the Locals Extensions word set
                   8775: @item providing the Memory-Allocation word set
                   8776: @item providing the Memory-Allocation Extensions word set (that one's easy)
                   8777: @item providing the Programming-Tools word set
                   8778: @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
                   8779: @item providing the Search-Order word set
                   8780: @item providing the Search-Order Extensions word set
                   8781: @item providing the String word set
                   8782: @item providing the String Extensions word set (another easy one)
                   8783: @end itemize
                   8784: 
                   8785: @cindex system documentation
                   8786: In addition, ANS Forth systems are required to document certain
                   8787: implementation choices. This chapter tries to meet these
                   8788: requirements. In many cases it gives a way to ask the system for the
                   8789: information instead of providing the information directly, in
                   8790: particular, if the information depends on the processor, the operating
                   8791: system or the installation options chosen, or if they are likely to
                   8792: change during the maintenance of Gforth.
                   8793: 
                   8794: @comment The framework for the rest has been taken from pfe.
                   8795: 
                   8796: @menu
                   8797: * The Core Words::              
                   8798: * The optional Block word set::  
                   8799: * The optional Double Number word set::  
                   8800: * The optional Exception word set::  
                   8801: * The optional Facility word set::  
                   8802: * The optional File-Access word set::  
                   8803: * The optional Floating-Point word set::  
                   8804: * The optional Locals word set::  
                   8805: * The optional Memory-Allocation word set::  
                   8806: * The optional Programming-Tools word set::  
                   8807: * The optional Search-Order word set::  
                   8808: @end menu
                   8809: 
                   8810: 
                   8811: @c =====================================================================
                   8812: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
                   8813: @comment  node-name,  next,  previous,  up
                   8814: @section The Core Words
                   8815: @c =====================================================================
                   8816: @cindex core words, system documentation
                   8817: @cindex system documentation, core words
                   8818: 
                   8819: @menu
                   8820: * core-idef::                   Implementation Defined Options                   
                   8821: * core-ambcond::                Ambiguous Conditions                
                   8822: * core-other::                  Other System Documentation                  
                   8823: @end menu
                   8824: 
                   8825: @c ---------------------------------------------------------------------
                   8826: @node core-idef, core-ambcond, The Core Words, The Core Words
                   8827: @subsection Implementation Defined Options
                   8828: @c ---------------------------------------------------------------------
                   8829: @cindex core words, implementation-defined options
                   8830: @cindex implementation-defined options, core words
                   8831: 
                   8832: 
                   8833: @table @i
                   8834: @item (Cell) aligned addresses:
                   8835: @cindex cell-aligned addresses
                   8836: @cindex aligned addresses
                   8837: processor-dependent. Gforth's alignment words perform natural alignment
                   8838: (e.g., an address aligned for a datum of size 8 is divisible by
                   8839: 8). Unaligned accesses usually result in a @code{-23 THROW}.
                   8840: 
                   8841: @item @code{EMIT} and non-graphic characters:
                   8842: @cindex @code{EMIT} and non-graphic characters
                   8843: @cindex non-graphic characters and @code{EMIT}
                   8844: The character is output using the C library function (actually, macro)
                   8845: @code{putc}.
                   8846: 
                   8847: @item character editing of @code{ACCEPT} and @code{EXPECT}:
                   8848: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
                   8849: @cindex editing in @code{ACCEPT} and @code{EXPECT}
                   8850: @cindex @code{ACCEPT}, editing
                   8851: @cindex @code{EXPECT}, editing
                   8852: This is modeled on the GNU readline library (@pxref{Readline
                   8853: Interaction, , Command Line Editing, readline, The GNU Readline
                   8854: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
                   8855: producing a full word completion every time you type it (instead of
1.28      crook    8856: producing the common prefix of all completions). @xref{Command-line editing}.
1.1       anton    8857: 
                   8858: @item character set:
                   8859: @cindex character set
                   8860: The character set of your computer and display device. Gforth is
                   8861: 8-bit-clean (but some other component in your system may make trouble).
                   8862: 
                   8863: @item Character-aligned address requirements:
                   8864: @cindex character-aligned address requirements
                   8865: installation-dependent. Currently a character is represented by a C
                   8866: @code{unsigned char}; in the future we might switch to @code{wchar_t}
                   8867: (Comments on that requested).
                   8868: 
                   8869: @item character-set extensions and matching of names:
                   8870: @cindex character-set extensions and matching of names
1.26      crook    8871: @cindex case-sensitivity for name lookup
                   8872: @cindex name lookup, case-sensitivity
                   8873: @cindex locale and case-sensitivity
1.21      crook    8874: Any character except the ASCII NUL character can be used in a
1.1       anton    8875: name. Matching is case-insensitive (except in @code{TABLE}s). The
                   8876: matching is performed using the C function @code{strncasecmp}, whose
                   8877: function is probably influenced by the locale. E.g., the @code{C} locale
                   8878: does not know about accents and umlauts, so they are matched
                   8879: case-sensitively in that locale. For portability reasons it is best to
                   8880: write programs such that they work in the @code{C} locale. Then one can
                   8881: use libraries written by a Polish programmer (who might use words
                   8882: containing ISO Latin-2 encoded characters) and by a French programmer
                   8883: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
                   8884: funny results for some of the words (which ones, depends on the font you
                   8885: are using)). Also, the locale you prefer may not be available in other
                   8886: operating systems. Hopefully, Unicode will solve these problems one day.
                   8887: 
                   8888: @item conditions under which control characters match a space delimiter:
                   8889: @cindex space delimiters
                   8890: @cindex control characters as delimiters
                   8891: If @code{WORD} is called with the space character as a delimiter, all
                   8892: white-space characters (as identified by the C macro @code{isspace()})
                   8893: are delimiters. @code{PARSE}, on the other hand, treats space like other
                   8894: delimiters. @code{PARSE-WORD} treats space like @code{WORD}, but behaves
                   8895: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
                   8896: interpreter (aka text interpreter) by default, treats all white-space
                   8897: characters as delimiters.
                   8898: 
1.26      crook    8899: @item format of the control-flow stack:
                   8900: @cindex control-flow stack, format
                   8901: The data stack is used as control-flow stack. The size of a control-flow
1.1       anton    8902: stack item in cells is given by the constant @code{cs-item-size}. At the
                   8903: time of this writing, an item consists of a (pointer to a) locals list
                   8904: (third), an address in the code (second), and a tag for identifying the
                   8905: item (TOS). The following tags are used: @code{defstart},
                   8906: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
                   8907: @code{scopestart}.
                   8908: 
                   8909: @item conversion of digits > 35
                   8910: @cindex digits > 35
                   8911: The characters @code{[\]^_'} are the digits with the decimal value
                   8912: 36@minus{}41. There is no way to input many of the larger digits.
                   8913: 
                   8914: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
                   8915: @cindex @code{EXPECT}, display after end of input
                   8916: @cindex @code{ACCEPT}, display after end of input
                   8917: The cursor is moved to the end of the entered string. If the input is
                   8918: terminated using the @kbd{Return} key, a space is typed.
                   8919: 
                   8920: @item exception abort sequence of @code{ABORT"}:
                   8921: @cindex exception abort sequence of @code{ABORT"}
                   8922: @cindex @code{ABORT"}, exception abort sequence
                   8923: The error string is stored into the variable @code{"error} and a
                   8924: @code{-2 throw} is performed.
                   8925: 
                   8926: @item input line terminator:
                   8927: @cindex input line terminator
                   8928: @cindex line terminator on input
1.26      crook    8929: @cindex newline character on input
1.1       anton    8930: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
                   8931: lines. One of these characters is typically produced when you type the
                   8932: @kbd{Enter} or @kbd{Return} key.
                   8933: 
                   8934: @item maximum size of a counted string:
                   8935: @cindex maximum size of a counted string
                   8936: @cindex counted string, maximum size
                   8937: @code{s" /counted-string" environment? drop .}. Currently 255 characters
                   8938: on all ports, but this may change.
                   8939: 
                   8940: @item maximum size of a parsed string:
                   8941: @cindex maximum size of a parsed string
                   8942: @cindex parsed string, maximum size
                   8943: Given by the constant @code{/line}. Currently 255 characters.
                   8944: 
                   8945: @item maximum size of a definition name, in characters:
                   8946: @cindex maximum size of a definition name, in characters
                   8947: @cindex name, maximum length
                   8948: 31
                   8949: 
                   8950: @item maximum string length for @code{ENVIRONMENT?}, in characters:
                   8951: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
                   8952: @cindex @code{ENVIRONMENT?} string length, maximum
                   8953: 31
                   8954: 
                   8955: @item method of selecting the user input device:
                   8956: @cindex user input device, method of selecting
                   8957: The user input device is the standard input. There is currently no way to
                   8958: change it from within Gforth. However, the input can typically be
                   8959: redirected in the command line that starts Gforth.
                   8960: 
                   8961: @item method of selecting the user output device:
                   8962: @cindex user output device, method of selecting
                   8963: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10      anton    8964: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
                   8965: output when the user output device is a terminal, otherwise the output
                   8966: is buffered.
1.1       anton    8967: 
                   8968: @item methods of dictionary compilation:
                   8969: What are we expected to document here?
                   8970: 
                   8971: @item number of bits in one address unit:
                   8972: @cindex number of bits in one address unit
                   8973: @cindex address unit, size in bits
                   8974: @code{s" address-units-bits" environment? drop .}. 8 in all current
                   8975: ports.
                   8976: 
                   8977: @item number representation and arithmetic:
                   8978: @cindex number representation and arithmetic
                   8979: Processor-dependent. Binary two's complement on all current ports.
                   8980: 
                   8981: @item ranges for integer types:
                   8982: @cindex ranges for integer types
                   8983: @cindex integer types, ranges
                   8984: Installation-dependent. Make environmental queries for @code{MAX-N},
                   8985: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
                   8986: unsigned (and positive) types is 0. The lower bound for signed types on
                   8987: two's complement and one's complement machines machines can be computed
                   8988: by adding 1 to the upper bound.
                   8989: 
                   8990: @item read-only data space regions:
                   8991: @cindex read-only data space regions
                   8992: @cindex data-space, read-only regions
                   8993: The whole Forth data space is writable.
                   8994: 
                   8995: @item size of buffer at @code{WORD}:
                   8996: @cindex size of buffer at @code{WORD}
                   8997: @cindex @code{WORD} buffer size
                   8998: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   8999: shared with the pictured numeric output string. If overwriting
                   9000: @code{PAD} is acceptable, it is as large as the remaining dictionary
                   9001: space, although only as much can be sensibly used as fits in a counted
                   9002: string.
                   9003: 
                   9004: @item size of one cell in address units:
                   9005: @cindex cell size
                   9006: @code{1 cells .}.
                   9007: 
                   9008: @item size of one character in address units:
                   9009: @cindex char size
                   9010: @code{1 chars .}. 1 on all current ports.
                   9011: 
                   9012: @item size of the keyboard terminal buffer:
                   9013: @cindex size of the keyboard terminal buffer
                   9014: @cindex terminal buffer, size
                   9015: Varies. You can determine the size at a specific time using @code{lp@@
                   9016: tib - .}. It is shared with the locals stack and TIBs of files that
                   9017: include the current file. You can change the amount of space for TIBs
                   9018: and locals stack at Gforth startup with the command line option
                   9019: @code{-l}.
                   9020: 
                   9021: @item size of the pictured numeric output buffer:
                   9022: @cindex size of the pictured numeric output buffer
                   9023: @cindex pictured numeric output buffer, size
                   9024: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   9025: shared with @code{WORD}.
                   9026: 
                   9027: @item size of the scratch area returned by @code{PAD}:
                   9028: @cindex size of the scratch area returned by @code{PAD}
                   9029: @cindex @code{PAD} size
                   9030: The remainder of dictionary space. @code{unused pad here - - .}.
                   9031: 
                   9032: @item system case-sensitivity characteristics:
                   9033: @cindex case-sensitivity characteristics
1.26      crook    9034: Dictionary searches are case-insensitive (except in
1.1       anton    9035: @code{TABLE}s). However, as explained above under @i{character-set
                   9036: extensions}, the matching for non-ASCII characters is determined by the
                   9037: locale you are using. In the default @code{C} locale all non-ASCII
                   9038: characters are matched case-sensitively.
                   9039: 
                   9040: @item system prompt:
                   9041: @cindex system prompt
                   9042: @cindex prompt
                   9043: @code{ ok} in interpret state, @code{ compiled} in compile state.
                   9044: 
                   9045: @item division rounding:
                   9046: @cindex division rounding
                   9047: installation dependent. @code{s" floored" environment? drop .}. We leave
                   9048: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
                   9049: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
                   9050: 
                   9051: @item values of @code{STATE} when true:
                   9052: @cindex @code{STATE} values
                   9053: -1.
                   9054: 
                   9055: @item values returned after arithmetic overflow:
                   9056: On two's complement machines, arithmetic is performed modulo
                   9057: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   9058: arithmetic (with appropriate mapping for signed types). Division by zero
                   9059: typically results in a @code{-55 throw} (Floating-point unidentified
                   9060: fault), although a @code{-10 throw} (divide by zero) would be more
                   9061: appropriate.
                   9062: 
                   9063: @item whether the current definition can be found after @t{DOES>}:
                   9064: @cindex @t{DOES>}, visibility of current definition
                   9065: No.
                   9066: 
                   9067: @end table
                   9068: 
                   9069: @c ---------------------------------------------------------------------
                   9070: @node core-ambcond, core-other, core-idef, The Core Words
                   9071: @subsection Ambiguous conditions
                   9072: @c ---------------------------------------------------------------------
                   9073: @cindex core words, ambiguous conditions
                   9074: @cindex ambiguous conditions, core words
                   9075: 
                   9076: @table @i
                   9077: 
                   9078: @item a name is neither a word nor a number:
                   9079: @cindex name not found
1.26      crook    9080: @cindex undefined word
1.1       anton    9081: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
                   9082: preserves the data and FP stack, so you don't lose more work than
                   9083: necessary.
                   9084: 
                   9085: @item a definition name exceeds the maximum length allowed:
1.26      crook    9086: @cindex word name too long
1.1       anton    9087: @code{-19 throw} (Word name too long)
                   9088: 
                   9089: @item addressing a region not inside the various data spaces of the forth system:
                   9090: @cindex Invalid memory address
                   9091: The stacks, code space and name space are accessible. Machine code space is
                   9092: typically readable. Accessing other addresses gives results dependent on
                   9093: the operating system. On decent systems: @code{-9 throw} (Invalid memory
                   9094: address).
                   9095: 
                   9096: @item argument type incompatible with parameter:
1.26      crook    9097: @cindex argument type mismatch
1.1       anton    9098: This is usually not caught. Some words perform checks, e.g., the control
                   9099: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
                   9100: mismatch).
                   9101: 
                   9102: @item attempting to obtain the execution token of a word with undefined execution semantics:
                   9103: @cindex Interpreting a compile-only word, for @code{'} etc.
                   9104: @cindex execution token of words with undefined execution semantics
                   9105: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
                   9106: get an execution token for @code{compile-only-error} (which performs a
                   9107: @code{-14 throw} when executed).
                   9108: 
                   9109: @item dividing by zero:
                   9110: @cindex dividing by zero
                   9111: @cindex floating point unidentified fault, integer division
1.24      anton    9112: On better platforms, this produces a @code{-10 throw} (Division by
                   9113: zero); on other systems, this typically results in a @code{-55 throw}
                   9114: (Floating-point unidentified fault).
1.1       anton    9115: 
                   9116: @item insufficient data stack or return stack space:
                   9117: @cindex insufficient data stack or return stack space
                   9118: @cindex stack overflow
1.26      crook    9119: @cindex address alignment exception, stack overflow
1.1       anton    9120: @cindex Invalid memory address, stack overflow
                   9121: Depending on the operating system, the installation, and the invocation
                   9122: of Gforth, this is either checked by the memory management hardware, or
1.24      anton    9123: it is not checked. If it is checked, you typically get a @code{-3 throw}
                   9124: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
                   9125: throw} (Invalid memory address) (depending on the platform and how you
                   9126: achieved the overflow) as soon as the overflow happens. If it is not
                   9127: checked, overflows typically result in mysterious illegal memory
                   9128: accesses, producing @code{-9 throw} (Invalid memory address) or
                   9129: @code{-23 throw} (Address alignment exception); they might also destroy
                   9130: the internal data structure of @code{ALLOCATE} and friends, resulting in
                   9131: various errors in these words.
1.1       anton    9132: 
                   9133: @item insufficient space for loop control parameters:
                   9134: @cindex insufficient space for loop control parameters
                   9135: like other return stack overflows.
                   9136: 
                   9137: @item insufficient space in the dictionary:
                   9138: @cindex insufficient space in the dictionary
                   9139: @cindex dictionary overflow
1.12      anton    9140: If you try to allot (either directly with @code{allot}, or indirectly
                   9141: with @code{,}, @code{create} etc.) more memory than available in the
                   9142: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
                   9143: to access memory beyond the end of the dictionary, the results are
                   9144: similar to stack overflows.
1.1       anton    9145: 
                   9146: @item interpreting a word with undefined interpretation semantics:
                   9147: @cindex interpreting a word with undefined interpretation semantics
                   9148: @cindex Interpreting a compile-only word
                   9149: For some words, we have defined interpretation semantics. For the
                   9150: others: @code{-14 throw} (Interpreting a compile-only word).
                   9151: 
                   9152: @item modifying the contents of the input buffer or a string literal:
                   9153: @cindex modifying the contents of the input buffer or a string literal
                   9154: These are located in writable memory and can be modified.
                   9155: 
                   9156: @item overflow of the pictured numeric output string:
                   9157: @cindex overflow of the pictured numeric output string
                   9158: @cindex pictured numeric output string, overflow
1.24      anton    9159: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1       anton    9160: 
                   9161: @item parsed string overflow:
                   9162: @cindex parsed string overflow
                   9163: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
                   9164: 
                   9165: @item producing a result out of range:
                   9166: @cindex result out of range
                   9167: On two's complement machines, arithmetic is performed modulo
                   9168: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   9169: arithmetic (with appropriate mapping for signed types). Division by zero
1.24      anton    9170: typically results in a @code{-10 throw} (divide by zero) or @code{-55
                   9171: throw} (floating point unidentified fault). @code{convert} and
                   9172: @code{>number} currently overflow silently.
1.1       anton    9173: 
                   9174: @item reading from an empty data or return stack:
                   9175: @cindex stack empty
                   9176: @cindex stack underflow
1.24      anton    9177: @cindex return stack underflow
1.1       anton    9178: The data stack is checked by the outer (aka text) interpreter after
                   9179: every word executed. If it has underflowed, a @code{-4 throw} (Stack
                   9180: underflow) is performed. Apart from that, stacks may be checked or not,
1.24      anton    9181: depending on operating system, installation, and invocation. If they are
                   9182: caught by a check, they typically result in @code{-4 throw} (Stack
                   9183: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
                   9184: (Invalid memory address), depending on the platform and which stack
                   9185: underflows and by how much. Note that even if the system uses checking
                   9186: (through the MMU), your program may have to underflow by a significant
                   9187: number of stack items to trigger the reaction (the reason for this is
                   9188: that the MMU, and therefore the checking, works with a page-size
                   9189: granularity).  If there is no checking, the symptoms resulting from an
                   9190: underflow are similar to those from an overflow.  Unbalanced return
                   9191: stack errors result in a variaty of symptoms, including @code{-9 throw}
                   9192: (Invalid memory address) and Illegal Instruction (typically @code{-260
                   9193: throw}).
1.1       anton    9194: 
                   9195: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
                   9196: @cindex unexpected end of the input buffer
                   9197: @cindex zero-length string as a name
                   9198: @cindex Attempt to use zero-length string as a name
                   9199: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
                   9200: use zero-length string as a name). Words like @code{'} probably will not
                   9201: find what they search. Note that it is possible to create zero-length
                   9202: names with @code{nextname} (should it not?).
                   9203: 
                   9204: @item @code{>IN} greater than input buffer:
                   9205: @cindex @code{>IN} greater than input buffer
                   9206: The next invocation of a parsing word returns a string with length 0.
                   9207: 
                   9208: @item @code{RECURSE} appears after @code{DOES>}:
                   9209: @cindex @code{RECURSE} appears after @code{DOES>}
                   9210: Compiles a recursive call to the defining word, not to the defined word.
                   9211: 
                   9212: @item argument input source different than current input source for @code{RESTORE-INPUT}:
                   9213: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26      crook    9214: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1       anton    9215: @cindex @code{RESTORE-INPUT}, Argument type mismatch
                   9216: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
                   9217: the end of the file was reached), its source-id may be
                   9218: reused. Therefore, restoring an input source specification referencing a
                   9219: closed file may lead to unpredictable results instead of a @code{-12
                   9220: THROW}.
                   9221: 
                   9222: In the future, Gforth may be able to restore input source specifications
                   9223: from other than the current input source.
                   9224: 
                   9225: @item data space containing definitions gets de-allocated:
                   9226: @cindex data space containing definitions gets de-allocated
                   9227: Deallocation with @code{allot} is not checked. This typically results in
                   9228: memory access faults or execution of illegal instructions.
                   9229: 
                   9230: @item data space read/write with incorrect alignment:
                   9231: @cindex data space read/write with incorrect alignment
                   9232: @cindex alignment faults
1.26      crook    9233: @cindex address alignment exception
1.1       anton    9234: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12      anton    9235: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1       anton    9236: alignment turned on, incorrect alignment results in a @code{-9 throw}
                   9237: (Invalid memory address). There are reportedly some processors with
1.12      anton    9238: alignment restrictions that do not report violations.
1.1       anton    9239: 
                   9240: @item data space pointer not properly aligned, @code{,}, @code{C,}:
                   9241: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
                   9242: Like other alignment errors.
                   9243: 
                   9244: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
                   9245: Like other stack underflows.
                   9246: 
                   9247: @item loop control parameters not available:
                   9248: @cindex loop control parameters not available
                   9249: Not checked. The counted loop words simply assume that the top of return
                   9250: stack items are loop control parameters and behave accordingly.
                   9251: 
                   9252: @item most recent definition does not have a name (@code{IMMEDIATE}):
                   9253: @cindex most recent definition does not have a name (@code{IMMEDIATE})
                   9254: @cindex last word was headerless
                   9255: @code{abort" last word was headerless"}.
                   9256: 
                   9257: @item name not defined by @code{VALUE} used by @code{TO}:
                   9258: @cindex name not defined by @code{VALUE} used by @code{TO}
                   9259: @cindex @code{TO} on non-@code{VALUE}s
                   9260: @cindex Invalid name argument, @code{TO}
                   9261: @code{-32 throw} (Invalid name argument) (unless name is a local or was
                   9262: defined by @code{CONSTANT}; in the latter case it just changes the constant).
                   9263: 
                   9264: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
                   9265: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26      crook    9266: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1       anton    9267: @code{-13 throw} (Undefined word)
                   9268: 
                   9269: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
                   9270: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
                   9271: Gforth behaves as if they were of the same type. I.e., you can predict
                   9272: the behaviour by interpreting all parameters as, e.g., signed.
                   9273: 
                   9274: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
                   9275: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
                   9276: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
                   9277: compilation semantics of @code{TO}.
                   9278: 
                   9279: @item String longer than a counted string returned by @code{WORD}:
1.26      crook    9280: @cindex string longer than a counted string returned by @code{WORD}
1.1       anton    9281: @cindex @code{WORD}, string overflow
                   9282: Not checked. The string will be ok, but the count will, of course,
                   9283: contain only the least significant bits of the length.
                   9284: 
                   9285: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
                   9286: @cindex @code{LSHIFT}, large shift counts
                   9287: @cindex @code{RSHIFT}, large shift counts
                   9288: Processor-dependent. Typical behaviours are returning 0 and using only
                   9289: the low bits of the shift count.
                   9290: 
                   9291: @item word not defined via @code{CREATE}:
                   9292: @cindex @code{>BODY} of non-@code{CREATE}d words
                   9293: @code{>BODY} produces the PFA of the word no matter how it was defined.
                   9294: 
                   9295: @cindex @code{DOES>} of non-@code{CREATE}d words
                   9296: @code{DOES>} changes the execution semantics of the last defined word no
                   9297: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
                   9298: @code{CREATE , DOES>}.
                   9299: 
                   9300: @item words improperly used outside @code{<#} and @code{#>}:
                   9301: Not checked. As usual, you can expect memory faults.
                   9302: 
                   9303: @end table
                   9304: 
                   9305: 
                   9306: @c ---------------------------------------------------------------------
                   9307: @node core-other,  , core-ambcond, The Core Words
                   9308: @subsection Other system documentation
                   9309: @c ---------------------------------------------------------------------
                   9310: @cindex other system documentation, core words
                   9311: @cindex core words, other system documentation
                   9312: 
                   9313: @table @i
                   9314: @item nonstandard words using @code{PAD}:
                   9315: @cindex @code{PAD} use by nonstandard words
                   9316: None.
                   9317: 
                   9318: @item operator's terminal facilities available:
                   9319: @cindex operator's terminal facilities available
                   9320: After processing the command line, Gforth goes into interactive mode,
                   9321: and you can give commands to Gforth interactively. The actual facilities
                   9322: available depend on how you invoke Gforth.
                   9323: 
                   9324: @item program data space available:
                   9325: @cindex program data space available
                   9326: @cindex data space available
                   9327: @code{UNUSED .} gives the remaining dictionary space. The total
                   9328: dictionary space can be specified with the @code{-m} switch
                   9329: (@pxref{Invoking Gforth}) when Gforth starts up.
                   9330: 
                   9331: @item return stack space available:
                   9332: @cindex return stack space available
                   9333: You can compute the total return stack space in cells with
                   9334: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
                   9335: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
                   9336: 
                   9337: @item stack space available:
                   9338: @cindex stack space available
                   9339: You can compute the total data stack space in cells with
                   9340: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
                   9341: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
                   9342: 
                   9343: @item system dictionary space required, in address units:
                   9344: @cindex system dictionary space required, in address units
                   9345: Type @code{here forthstart - .} after startup. At the time of this
                   9346: writing, this gives 80080 (bytes) on a 32-bit system.
                   9347: @end table
                   9348: 
                   9349: 
                   9350: @c =====================================================================
                   9351: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
                   9352: @section The optional Block word set
                   9353: @c =====================================================================
                   9354: @cindex system documentation, block words
                   9355: @cindex block words, system documentation
                   9356: 
                   9357: @menu
                   9358: * block-idef::                  Implementation Defined Options
                   9359: * block-ambcond::               Ambiguous Conditions               
                   9360: * block-other::                 Other System Documentation                 
                   9361: @end menu
                   9362: 
                   9363: 
                   9364: @c ---------------------------------------------------------------------
                   9365: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
                   9366: @subsection Implementation Defined Options
                   9367: @c ---------------------------------------------------------------------
                   9368: @cindex implementation-defined options, block words
                   9369: @cindex block words, implementation-defined options
                   9370: 
                   9371: @table @i
                   9372: @item the format for display by @code{LIST}:
                   9373: @cindex @code{LIST} display format
                   9374: First the screen number is displayed, then 16 lines of 64 characters,
                   9375: each line preceded by the line number.
                   9376: 
                   9377: @item the length of a line affected by @code{\}:
                   9378: @cindex length of a line affected by @code{\}
                   9379: @cindex @code{\}, line length in blocks
                   9380: 64 characters.
                   9381: @end table
                   9382: 
                   9383: 
                   9384: @c ---------------------------------------------------------------------
                   9385: @node block-ambcond, block-other, block-idef, The optional Block word set
                   9386: @subsection Ambiguous conditions
                   9387: @c ---------------------------------------------------------------------
                   9388: @cindex block words, ambiguous conditions
                   9389: @cindex ambiguous conditions, block words
                   9390: 
                   9391: @table @i
                   9392: @item correct block read was not possible:
                   9393: @cindex block read not possible
                   9394: Typically results in a @code{throw} of some OS-derived value (between
                   9395: -512 and -2048). If the blocks file was just not long enough, blanks are
                   9396: supplied for the missing portion.
                   9397: 
                   9398: @item I/O exception in block transfer:
                   9399: @cindex I/O exception in block transfer
                   9400: @cindex block transfer, I/O exception
                   9401: Typically results in a @code{throw} of some OS-derived value (between
                   9402: -512 and -2048).
                   9403: 
                   9404: @item invalid block number:
                   9405: @cindex invalid block number
                   9406: @cindex block number invalid
                   9407: @code{-35 throw} (Invalid block number)
                   9408: 
                   9409: @item a program directly alters the contents of @code{BLK}:
                   9410: @cindex @code{BLK}, altering @code{BLK}
                   9411: The input stream is switched to that other block, at the same
                   9412: position. If the storing to @code{BLK} happens when interpreting
                   9413: non-block input, the system will get quite confused when the block ends.
                   9414: 
                   9415: @item no current block buffer for @code{UPDATE}:
                   9416: @cindex @code{UPDATE}, no current block buffer
                   9417: @code{UPDATE} has no effect.
                   9418: 
                   9419: @end table
                   9420: 
                   9421: @c ---------------------------------------------------------------------
                   9422: @node block-other,  , block-ambcond, The optional Block word set
                   9423: @subsection Other system documentation
                   9424: @c ---------------------------------------------------------------------
                   9425: @cindex other system documentation, block words
                   9426: @cindex block words, other system documentation
                   9427: 
                   9428: @table @i
                   9429: @item any restrictions a multiprogramming system places on the use of buffer addresses:
                   9430: No restrictions (yet).
                   9431: 
                   9432: @item the number of blocks available for source and data:
                   9433: depends on your disk space.
                   9434: 
                   9435: @end table
                   9436: 
                   9437: 
                   9438: @c =====================================================================
                   9439: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
                   9440: @section The optional Double Number word set
                   9441: @c =====================================================================
                   9442: @cindex system documentation, double words
                   9443: @cindex double words, system documentation
                   9444: 
                   9445: @menu
                   9446: * double-ambcond::              Ambiguous Conditions              
                   9447: @end menu
                   9448: 
                   9449: 
                   9450: @c ---------------------------------------------------------------------
                   9451: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
                   9452: @subsection Ambiguous conditions
                   9453: @c ---------------------------------------------------------------------
                   9454: @cindex double words, ambiguous conditions
                   9455: @cindex ambiguous conditions, double words
                   9456: 
                   9457: @table @i
1.29    ! crook    9458: @item @i{d} outside of range of @i{n} in @code{D>S}:
        !          9459: @cindex @code{D>S}, @i{d} out of range of @i{n} 
        !          9460: The least significant cell of @i{d} is produced.
1.1       anton    9461: 
                   9462: @end table
                   9463: 
                   9464: 
                   9465: @c =====================================================================
                   9466: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
                   9467: @section The optional Exception word set
                   9468: @c =====================================================================
                   9469: @cindex system documentation, exception words
                   9470: @cindex exception words, system documentation
                   9471: 
                   9472: @menu
                   9473: * exception-idef::              Implementation Defined Options              
                   9474: @end menu
                   9475: 
                   9476: 
                   9477: @c ---------------------------------------------------------------------
                   9478: @node exception-idef,  , The optional Exception word set, The optional Exception word set
                   9479: @subsection Implementation Defined Options
                   9480: @c ---------------------------------------------------------------------
                   9481: @cindex implementation-defined options, exception words
                   9482: @cindex exception words, implementation-defined options
                   9483: 
                   9484: @table @i
                   9485: @item @code{THROW}-codes used in the system:
                   9486: @cindex @code{THROW}-codes used in the system
                   9487: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29    ! crook    9488: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1       anton    9489: codes -512@minus{}-2047 are used for OS errors (for file and memory
                   9490: allocation operations). The mapping from OS error numbers to throw codes
                   9491: is -512@minus{}@code{errno}. One side effect of this mapping is that
                   9492: undefined OS errors produce a message with a strange number; e.g.,
                   9493: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
                   9494: @end table
                   9495: 
                   9496: @c =====================================================================
                   9497: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
                   9498: @section The optional Facility word set
                   9499: @c =====================================================================
                   9500: @cindex system documentation, facility words
                   9501: @cindex facility words, system documentation
                   9502: 
                   9503: @menu
                   9504: * facility-idef::               Implementation Defined Options               
                   9505: * facility-ambcond::            Ambiguous Conditions            
                   9506: @end menu
                   9507: 
                   9508: 
                   9509: @c ---------------------------------------------------------------------
                   9510: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
                   9511: @subsection Implementation Defined Options
                   9512: @c ---------------------------------------------------------------------
                   9513: @cindex implementation-defined options, facility words
                   9514: @cindex facility words, implementation-defined options
                   9515: 
                   9516: @table @i
                   9517: @item encoding of keyboard events (@code{EKEY}):
                   9518: @cindex keyboard events, encoding in @code{EKEY}
                   9519: @cindex @code{EKEY}, encoding of keyboard events
                   9520: Not yet implemented.
                   9521: 
                   9522: @item duration of a system clock tick:
                   9523: @cindex duration of a system clock tick
                   9524: @cindex clock tick duration
                   9525: System dependent. With respect to @code{MS}, the time is specified in
                   9526: microseconds. How well the OS and the hardware implement this, is
                   9527: another question.
                   9528: 
                   9529: @item repeatability to be expected from the execution of @code{MS}:
                   9530: @cindex repeatability to be expected from the execution of @code{MS}
                   9531: @cindex @code{MS}, repeatability to be expected
                   9532: System dependent. On Unix, a lot depends on load. If the system is
                   9533: lightly loaded, and the delay is short enough that Gforth does not get
                   9534: swapped out, the performance should be acceptable. Under MS-DOS and
                   9535: other single-tasking systems, it should be good.
                   9536: 
                   9537: @end table
                   9538: 
                   9539: 
                   9540: @c ---------------------------------------------------------------------
                   9541: @node facility-ambcond,  , facility-idef, The optional Facility word set
                   9542: @subsection Ambiguous conditions
                   9543: @c ---------------------------------------------------------------------
                   9544: @cindex facility words, ambiguous conditions
                   9545: @cindex ambiguous conditions, facility words
                   9546: 
                   9547: @table @i
                   9548: @item @code{AT-XY} can't be performed on user output device:
                   9549: @cindex @code{AT-XY} can't be performed on user output device
                   9550: Largely terminal dependent. No range checks are done on the arguments.
                   9551: No errors are reported. You may see some garbage appearing, you may see
                   9552: simply nothing happen.
                   9553: 
                   9554: @end table
                   9555: 
                   9556: 
                   9557: @c =====================================================================
                   9558: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
                   9559: @section The optional File-Access word set
                   9560: @c =====================================================================
                   9561: @cindex system documentation, file words
                   9562: @cindex file words, system documentation
                   9563: 
                   9564: @menu
                   9565: * file-idef::                   Implementation Defined Options
                   9566: * file-ambcond::                Ambiguous Conditions                
                   9567: @end menu
                   9568: 
                   9569: @c ---------------------------------------------------------------------
                   9570: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
                   9571: @subsection Implementation Defined Options
                   9572: @c ---------------------------------------------------------------------
                   9573: @cindex implementation-defined options, file words
                   9574: @cindex file words, implementation-defined options
                   9575: 
                   9576: @table @i
                   9577: @item file access methods used:
                   9578: @cindex file access methods used
                   9579: @code{R/O}, @code{R/W} and @code{BIN} work as you would
                   9580: expect. @code{W/O} translates into the C file opening mode @code{w} (or
                   9581: @code{wb}): The file is cleared, if it exists, and created, if it does
                   9582: not (with both @code{open-file} and @code{create-file}).  Under Unix
                   9583: @code{create-file} creates a file with 666 permissions modified by your
                   9584: umask.
                   9585: 
                   9586: @item file exceptions:
                   9587: @cindex file exceptions
                   9588: The file words do not raise exceptions (except, perhaps, memory access
                   9589: faults when you pass illegal addresses or file-ids).
                   9590: 
                   9591: @item file line terminator:
                   9592: @cindex file line terminator
                   9593: System-dependent. Gforth uses C's newline character as line
                   9594: terminator. What the actual character code(s) of this are is
                   9595: system-dependent.
                   9596: 
                   9597: @item file name format:
                   9598: @cindex file name format
                   9599: System dependent. Gforth just uses the file name format of your OS.
                   9600: 
                   9601: @item information returned by @code{FILE-STATUS}:
                   9602: @cindex @code{FILE-STATUS}, returned information
                   9603: @code{FILE-STATUS} returns the most powerful file access mode allowed
                   9604: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
                   9605: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
                   9606: along with the returned mode.
                   9607: 
                   9608: @item input file state after an exception when including source:
                   9609: @cindex exception when including source
                   9610: All files that are left via the exception are closed.
                   9611: 
1.29    ! crook    9612: @item @i{ior} values and meaning:
        !          9613: @cindex @i{ior} values and meaning
        !          9614: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    9615: intended as throw codes. They typically are in the range
                   9616: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29    ! crook    9617: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    9618: 
                   9619: @item maximum depth of file input nesting:
                   9620: @cindex maximum depth of file input nesting
                   9621: @cindex file input nesting, maximum depth
                   9622: limited by the amount of return stack, locals/TIB stack, and the number
                   9623: of open files available. This should not give you troubles.
                   9624: 
                   9625: @item maximum size of input line:
                   9626: @cindex maximum size of input line
                   9627: @cindex input line size, maximum
                   9628: @code{/line}. Currently 255.
                   9629: 
                   9630: @item methods of mapping block ranges to files:
                   9631: @cindex mapping block ranges to files
                   9632: @cindex files containing blocks
                   9633: @cindex blocks in files
                   9634: By default, blocks are accessed in the file @file{blocks.fb} in the
                   9635: current working directory. The file can be switched with @code{USE}.
                   9636: 
                   9637: @item number of string buffers provided by @code{S"}:
                   9638: @cindex @code{S"}, number of string buffers
                   9639: 1
                   9640: 
                   9641: @item size of string buffer used by @code{S"}:
                   9642: @cindex @code{S"}, size of string buffer
                   9643: @code{/line}. currently 255.
                   9644: 
                   9645: @end table
                   9646: 
                   9647: @c ---------------------------------------------------------------------
                   9648: @node file-ambcond,  , file-idef, The optional File-Access word set
                   9649: @subsection Ambiguous conditions
                   9650: @c ---------------------------------------------------------------------
                   9651: @cindex file words, ambiguous conditions
                   9652: @cindex ambiguous conditions, file words
                   9653: 
                   9654: @table @i
                   9655: @item attempting to position a file outside its boundaries:
                   9656: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
                   9657: @code{REPOSITION-FILE} is performed as usual: Afterwards,
                   9658: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
                   9659: 
                   9660: @item attempting to read from file positions not yet written:
                   9661: @cindex reading from file positions not yet written
                   9662: End-of-file, i.e., zero characters are read and no error is reported.
                   9663: 
1.29    ! crook    9664: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
        !          9665: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
1.1       anton    9666: An appropriate exception may be thrown, but a memory fault or other
                   9667: problem is more probable.
                   9668: 
1.29    ! crook    9669: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
        !          9670: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
        !          9671: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
        !          9672: The @i{ior} produced by the operation, that discovered the problem, is
1.1       anton    9673: thrown.
                   9674: 
                   9675: @item named file cannot be opened (@code{INCLUDED}):
                   9676: @cindex @code{INCLUDED}, named file cannot be opened
1.29    ! crook    9677: The @i{ior} produced by @code{open-file} is thrown.
1.1       anton    9678: 
                   9679: @item requesting an unmapped block number:
                   9680: @cindex unmapped block numbers
                   9681: There are no unmapped legal block numbers. On some operating systems,
                   9682: writing a block with a large number may overflow the file system and
                   9683: have an error message as consequence.
                   9684: 
                   9685: @item using @code{source-id} when @code{blk} is non-zero:
                   9686: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
                   9687: @code{source-id} performs its function. Typically it will give the id of
                   9688: the source which loaded the block. (Better ideas?)
                   9689: 
                   9690: @end table
                   9691: 
                   9692: 
                   9693: @c =====================================================================
                   9694: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
                   9695: @section The optional Floating-Point word set
                   9696: @c =====================================================================
                   9697: @cindex system documentation, floating-point words
                   9698: @cindex floating-point words, system documentation
                   9699: 
                   9700: @menu
                   9701: * floating-idef::               Implementation Defined Options
                   9702: * floating-ambcond::            Ambiguous Conditions            
                   9703: @end menu
                   9704: 
                   9705: 
                   9706: @c ---------------------------------------------------------------------
                   9707: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
                   9708: @subsection Implementation Defined Options
                   9709: @c ---------------------------------------------------------------------
                   9710: @cindex implementation-defined options, floating-point words
                   9711: @cindex floating-point words, implementation-defined options
                   9712: 
                   9713: @table @i
                   9714: @item format and range of floating point numbers:
                   9715: @cindex format and range of floating point numbers
                   9716: @cindex floating point numbers, format and range
                   9717: System-dependent; the @code{double} type of C.
                   9718: 
1.29    ! crook    9719: @item results of @code{REPRESENT} when @i{float} is out of range:
        !          9720: @cindex  @code{REPRESENT}, results when @i{float} is out of range
1.1       anton    9721: System dependent; @code{REPRESENT} is implemented using the C library
                   9722: function @code{ecvt()} and inherits its behaviour in this respect.
                   9723: 
                   9724: @item rounding or truncation of floating-point numbers:
                   9725: @cindex rounding of floating-point numbers
                   9726: @cindex truncation of floating-point numbers
                   9727: @cindex floating-point numbers, rounding or truncation
                   9728: System dependent; the rounding behaviour is inherited from the hosting C
                   9729: compiler. IEEE-FP-based (i.e., most) systems by default round to
                   9730: nearest, and break ties by rounding to even (i.e., such that the last
                   9731: bit of the mantissa is 0).
                   9732: 
                   9733: @item size of floating-point stack:
                   9734: @cindex floating-point stack size
                   9735: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
                   9736: the floating-point stack (in floats). You can specify this on startup
                   9737: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
                   9738: 
                   9739: @item width of floating-point stack:
                   9740: @cindex floating-point stack width 
                   9741: @code{1 floats}.
                   9742: 
                   9743: @end table
                   9744: 
                   9745: 
                   9746: @c ---------------------------------------------------------------------
                   9747: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
                   9748: @subsection Ambiguous conditions
                   9749: @c ---------------------------------------------------------------------
                   9750: @cindex floating-point words, ambiguous conditions
                   9751: @cindex ambiguous conditions, floating-point words
                   9752: 
                   9753: @table @i
                   9754: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
                   9755: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
                   9756: System-dependent. Typically results in a @code{-23 THROW} like other
                   9757: alignment violations.
                   9758: 
                   9759: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
                   9760: @cindex @code{f@@} used with an address that is not float aligned
                   9761: @cindex @code{f!} used with an address that is not float aligned
                   9762: System-dependent. Typically results in a @code{-23 THROW} like other
                   9763: alignment violations.
                   9764: 
                   9765: @item floating-point result out of range:
                   9766: @cindex floating-point result out of range
                   9767: System-dependent. Can result in a @code{-55 THROW} (Floating-point
                   9768: unidentified fault), or can produce a special value representing, e.g.,
                   9769: Infinity.
                   9770: 
                   9771: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
                   9772: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
                   9773: System-dependent. Typically results in an alignment fault like other
                   9774: alignment violations.
                   9775: 
                   9776: @item @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
                   9777: @cindex @code{BASE} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
                   9778: The floating-point number is converted into decimal nonetheless.
                   9779: 
                   9780: @item Both arguments are equal to zero (@code{FATAN2}):
                   9781: @cindex @code{FATAN2}, both arguments are equal to zero
                   9782: System-dependent. @code{FATAN2} is implemented using the C library
                   9783: function @code{atan2()}.
                   9784: 
1.29    ! crook    9785: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
        !          9786: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
        !          9787: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1       anton    9788: because of small errors and the tan will be a very large (or very small)
                   9789: but finite number.
                   9790: 
1.29    ! crook    9791: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
        !          9792: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1       anton    9793: The result is rounded to the nearest float.
                   9794: 
                   9795: @item dividing by zero:
                   9796: @cindex dividing by zero, floating-point
                   9797: @cindex floating-point dividing by zero
                   9798: @cindex floating-point unidentified fault, FP divide-by-zero
                   9799: @code{-55 throw} (Floating-point unidentified fault)
                   9800: 
                   9801: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
                   9802: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
                   9803: System dependent. On IEEE-FP based systems the number is converted into
                   9804: an infinity.
                   9805: 
1.29    ! crook    9806: @item @i{float}<1 (@code{FACOSH}):
        !          9807: @cindex @code{FACOSH}, @i{float}<1
1.1       anton    9808: @cindex floating-point unidentified fault, @code{FACOSH}
                   9809: @code{-55 throw} (Floating-point unidentified fault)
                   9810: 
1.29    ! crook    9811: @item @i{float}=<-1 (@code{FLNP1}):
        !          9812: @cindex @code{FLNP1}, @i{float}=<-1
1.1       anton    9813: @cindex floating-point unidentified fault, @code{FLNP1}
                   9814: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29    ! crook    9815: negative infinity is typically produced for @i{float}=-1.
1.1       anton    9816: 
1.29    ! crook    9817: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
        !          9818: @cindex @code{FLN}, @i{float}=<0
        !          9819: @cindex @code{FLOG}, @i{float}=<0
1.1       anton    9820: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
                   9821: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29    ! crook    9822: negative infinity is typically produced for @i{float}=0.
1.1       anton    9823: 
1.29    ! crook    9824: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
        !          9825: @cindex @code{FASINH}, @i{float}<0
        !          9826: @cindex @code{FSQRT}, @i{float}<0
1.1       anton    9827: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
                   9828: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
                   9829: produces values for these inputs on my Linux box (Bug in the C library?)
                   9830: 
1.29    ! crook    9831: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
        !          9832: @cindex @code{FACOS}, |@i{float}|>1
        !          9833: @cindex @code{FASIN}, |@i{float}|>1
        !          9834: @cindex @code{FATANH}, |@i{float}|>1
1.1       anton    9835: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
                   9836: @code{-55 throw} (Floating-point unidentified fault).
                   9837: 
1.29    ! crook    9838: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
        !          9839: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1       anton    9840: @cindex floating-point unidentified fault, @code{F>D}
                   9841: @code{-55 throw} (Floating-point unidentified fault).
                   9842: 
                   9843: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
                   9844: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
                   9845: This does not happen.
                   9846: @end table
                   9847: 
                   9848: @c =====================================================================
                   9849: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
                   9850: @section The optional Locals word set
                   9851: @c =====================================================================
                   9852: @cindex system documentation, locals words
                   9853: @cindex locals words, system documentation
                   9854: 
                   9855: @menu
                   9856: * locals-idef::                 Implementation Defined Options                 
                   9857: * locals-ambcond::              Ambiguous Conditions              
                   9858: @end menu
                   9859: 
                   9860: 
                   9861: @c ---------------------------------------------------------------------
                   9862: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
                   9863: @subsection Implementation Defined Options
                   9864: @c ---------------------------------------------------------------------
                   9865: @cindex implementation-defined options, locals words
                   9866: @cindex locals words, implementation-defined options
                   9867: 
                   9868: @table @i
                   9869: @item maximum number of locals in a definition:
                   9870: @cindex maximum number of locals in a definition
                   9871: @cindex locals, maximum number in a definition
                   9872: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
                   9873: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
                   9874: characters. The number of locals in a definition is bounded by the size
                   9875: of locals-buffer, which contains the names of the locals.
                   9876: 
                   9877: @end table
                   9878: 
                   9879: 
                   9880: @c ---------------------------------------------------------------------
                   9881: @node locals-ambcond,  , locals-idef, The optional Locals word set
                   9882: @subsection Ambiguous conditions
                   9883: @c ---------------------------------------------------------------------
                   9884: @cindex locals words, ambiguous conditions
                   9885: @cindex ambiguous conditions, locals words
                   9886: 
                   9887: @table @i
                   9888: @item executing a named local in interpretation state:
                   9889: @cindex local in interpretation state
                   9890: @cindex Interpreting a compile-only word, for a local
                   9891: Locals have no interpretation semantics. If you try to perform the
                   9892: interpretation semantics, you will get a @code{-14 throw} somewhere
                   9893: (Interpreting a compile-only word). If you perform the compilation
                   9894: semantics, the locals access will be compiled (irrespective of state).
                   9895: 
1.29    ! crook    9896: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1       anton    9897: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
                   9898: @cindex @code{TO} on non-@code{VALUE}s and non-locals
                   9899: @cindex Invalid name argument, @code{TO}
                   9900: @code{-32 throw} (Invalid name argument)
                   9901: 
                   9902: @end table
                   9903: 
                   9904: 
                   9905: @c =====================================================================
                   9906: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
                   9907: @section The optional Memory-Allocation word set
                   9908: @c =====================================================================
                   9909: @cindex system documentation, memory-allocation words
                   9910: @cindex memory-allocation words, system documentation
                   9911: 
                   9912: @menu
                   9913: * memory-idef::                 Implementation Defined Options                 
                   9914: @end menu
                   9915: 
                   9916: 
                   9917: @c ---------------------------------------------------------------------
                   9918: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
                   9919: @subsection Implementation Defined Options
                   9920: @c ---------------------------------------------------------------------
                   9921: @cindex implementation-defined options, memory-allocation words
                   9922: @cindex memory-allocation words, implementation-defined options
                   9923: 
                   9924: @table @i
1.29    ! crook    9925: @item values and meaning of @i{ior}:
        !          9926: @cindex  @i{ior} values and meaning
        !          9927: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    9928: intended as throw codes. They typically are in the range
                   9929: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29    ! crook    9930: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    9931: 
                   9932: @end table
                   9933: 
                   9934: @c =====================================================================
                   9935: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
                   9936: @section The optional Programming-Tools word set
                   9937: @c =====================================================================
                   9938: @cindex system documentation, programming-tools words
                   9939: @cindex programming-tools words, system documentation
                   9940: 
                   9941: @menu
                   9942: * programming-idef::            Implementation Defined Options            
                   9943: * programming-ambcond::         Ambiguous Conditions         
                   9944: @end menu
                   9945: 
                   9946: 
                   9947: @c ---------------------------------------------------------------------
                   9948: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
                   9949: @subsection Implementation Defined Options
                   9950: @c ---------------------------------------------------------------------
                   9951: @cindex implementation-defined options, programming-tools words
                   9952: @cindex programming-tools words, implementation-defined options
                   9953: 
                   9954: @table @i
                   9955: @item ending sequence for input following @code{;CODE} and @code{CODE}:
                   9956: @cindex @code{;CODE} ending sequence
                   9957: @cindex @code{CODE} ending sequence
                   9958: @code{END-CODE}
                   9959: 
                   9960: @item manner of processing input following @code{;CODE} and @code{CODE}:
                   9961: @cindex @code{;CODE}, processing input
                   9962: @cindex @code{CODE}, processing input
                   9963: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
                   9964: the input is processed by the text interpreter, (starting) in interpret
                   9965: state.
                   9966: 
                   9967: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
                   9968: @cindex @code{ASSEMBLER}, search order capability
                   9969: The ANS Forth search order word set.
                   9970: 
                   9971: @item source and format of display by @code{SEE}:
                   9972: @cindex @code{SEE}, source and format of output
                   9973: The source for @code{see} is the intermediate code used by the inner
                   9974: interpreter.  The current @code{see} tries to output Forth source code
                   9975: as well as possible.
                   9976: 
                   9977: @end table
                   9978: 
                   9979: @c ---------------------------------------------------------------------
                   9980: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
                   9981: @subsection Ambiguous conditions
                   9982: @c ---------------------------------------------------------------------
                   9983: @cindex programming-tools words, ambiguous conditions
                   9984: @cindex ambiguous conditions, programming-tools words
                   9985: 
                   9986: @table @i
                   9987: 
1.21      crook    9988: @item deleting the compilation word list (@code{FORGET}):
                   9989: @cindex @code{FORGET}, deleting the compilation word list
1.1       anton    9990: Not implemented (yet).
                   9991: 
1.29    ! crook    9992: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
        !          9993: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
        !          9994: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1       anton    9995: @cindex control-flow stack underflow
                   9996: This typically results in an @code{abort"} with a descriptive error
                   9997: message (may change into a @code{-22 throw} (Control structure mismatch)
                   9998: in the future). You may also get a memory access error. If you are
                   9999: unlucky, this ambiguous condition is not caught.
                   10000: 
1.29    ! crook    10001: @item @i{name} can't be found (@code{FORGET}):
        !          10002: @cindex @code{FORGET}, @i{name} can't be found
1.1       anton    10003: Not implemented (yet).
                   10004: 
1.29    ! crook    10005: @item @i{name} not defined via @code{CREATE}:
        !          10006: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1       anton    10007: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
                   10008: the execution semantics of the last defined word no matter how it was
                   10009: defined.
                   10010: 
                   10011: @item @code{POSTPONE} applied to @code{[IF]}:
                   10012: @cindex @code{POSTPONE} applied to @code{[IF]}
                   10013: @cindex @code{[IF]} and @code{POSTPONE}
                   10014: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
                   10015: equivalent to @code{[IF]}.
                   10016: 
                   10017: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
                   10018: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
                   10019: Continue in the same state of conditional compilation in the next outer
                   10020: input source. Currently there is no warning to the user about this.
                   10021: 
                   10022: @item removing a needed definition (@code{FORGET}):
                   10023: @cindex @code{FORGET}, removing a needed definition
                   10024: Not implemented (yet).
                   10025: 
                   10026: @end table
                   10027: 
                   10028: 
                   10029: @c =====================================================================
                   10030: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
                   10031: @section The optional Search-Order word set
                   10032: @c =====================================================================
                   10033: @cindex system documentation, search-order words
                   10034: @cindex search-order words, system documentation
                   10035: 
                   10036: @menu
                   10037: * search-idef::                 Implementation Defined Options                 
                   10038: * search-ambcond::              Ambiguous Conditions              
                   10039: @end menu
                   10040: 
                   10041: 
                   10042: @c ---------------------------------------------------------------------
                   10043: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
                   10044: @subsection Implementation Defined Options
                   10045: @c ---------------------------------------------------------------------
                   10046: @cindex implementation-defined options, search-order words
                   10047: @cindex search-order words, implementation-defined options
                   10048: 
                   10049: @table @i
                   10050: @item maximum number of word lists in search order:
                   10051: @cindex maximum number of word lists in search order
                   10052: @cindex search order, maximum depth
                   10053: @code{s" wordlists" environment? drop .}. Currently 16.
                   10054: 
                   10055: @item minimum search order:
                   10056: @cindex minimum search order
                   10057: @cindex search order, minimum
                   10058: @code{root root}.
                   10059: 
                   10060: @end table
                   10061: 
                   10062: @c ---------------------------------------------------------------------
                   10063: @node search-ambcond,  , search-idef, The optional Search-Order word set
                   10064: @subsection Ambiguous conditions
                   10065: @c ---------------------------------------------------------------------
                   10066: @cindex search-order words, ambiguous conditions
                   10067: @cindex ambiguous conditions, search-order words
                   10068: 
                   10069: @table @i
1.21      crook    10070: @item changing the compilation word list (during compilation):
                   10071: @cindex changing the compilation word list (during compilation)
                   10072: @cindex compilation word list, change before definition ends
                   10073: The word is entered into the word list that was the compilation word list
1.1       anton    10074: at the start of the definition. Any changes to the name field (e.g.,
                   10075: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
                   10076: are applied to the latest defined word (as reported by @code{last} or
1.21      crook    10077: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1       anton    10078: 
                   10079: @item search order empty (@code{previous}):
                   10080: @cindex @code{previous}, search order empty
1.26      crook    10081: @cindex vocstack empty, @code{previous}
1.1       anton    10082: @code{abort" Vocstack empty"}.
                   10083: 
                   10084: @item too many word lists in search order (@code{also}):
                   10085: @cindex @code{also}, too many word lists in search order
1.26      crook    10086: @cindex vocstack full, @code{also}
1.1       anton    10087: @code{abort" Vocstack full"}.
                   10088: 
                   10089: @end table
                   10090: 
                   10091: @c ***************************************************************
                   10092: @node Model, Integrating Gforth, ANS conformance, Top
                   10093: @chapter Model
                   10094: 
                   10095: This chapter has yet to be written. It will contain information, on
                   10096: which internal structures you can rely.
                   10097: 
                   10098: @c ***************************************************************
                   10099: @node Integrating Gforth, Emacs and Gforth, Model, Top
                   10100: @chapter Integrating Gforth into C programs
                   10101: 
                   10102: This is not yet implemented.
                   10103: 
                   10104: Several people like to use Forth as scripting language for applications
                   10105: that are otherwise written in C, C++, or some other language.
                   10106: 
                   10107: The Forth system ATLAST provides facilities for embedding it into
                   10108: applications; unfortunately it has several disadvantages: most
                   10109: importantly, it is not based on ANS Forth, and it is apparently dead
                   10110: (i.e., not developed further and not supported). The facilities
1.21      crook    10111: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1       anton    10112: making the switch should not be hard.
                   10113: 
                   10114: We also tried to design the interface such that it can easily be
                   10115: implemented by other Forth systems, so that we may one day arrive at a
                   10116: standardized interface. Such a standard interface would allow you to
                   10117: replace the Forth system without having to rewrite C code.
                   10118: 
                   10119: You embed the Gforth interpreter by linking with the library
                   10120: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
                   10121: global symbols in this library that belong to the interface, have the
                   10122: prefix @code{forth_}. (Global symbols that are used internally have the
                   10123: prefix @code{gforth_}).
                   10124: 
                   10125: You can include the declarations of Forth types and the functions and
                   10126: variables of the interface with @code{#include <forth.h>}.
                   10127: 
                   10128: Types.
                   10129: 
                   10130: Variables.
                   10131: 
                   10132: Data and FP Stack pointer. Area sizes.
                   10133: 
                   10134: functions.
                   10135: 
                   10136: forth_init(imagefile)
                   10137: forth_evaluate(string) exceptions?
                   10138: forth_goto(address) (or forth_execute(xt)?)
                   10139: forth_continue() (a corountining mechanism)
                   10140: 
                   10141: Adding primitives.
                   10142: 
                   10143: No checking.
                   10144: 
                   10145: Signals?
                   10146: 
                   10147: Accessing the Stacks
                   10148: 
1.26      crook    10149: @c ******************************************************************
1.1       anton    10150: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
                   10151: @chapter Emacs and Gforth
                   10152: @cindex Emacs and Gforth
                   10153: 
                   10154: @cindex @file{gforth.el}
                   10155: @cindex @file{forth.el}
                   10156: @cindex Rydqvist, Goran
                   10157: @cindex comment editing commands
                   10158: @cindex @code{\}, editing with Emacs
                   10159: @cindex debug tracer editing commands
                   10160: @cindex @code{~~}, removal with Emacs
                   10161: @cindex Forth mode in Emacs
                   10162: Gforth comes with @file{gforth.el}, an improved version of
                   10163: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26      crook    10164: improvements are:
                   10165: 
                   10166: @itemize @bullet
                   10167: @item
                   10168: A better (but still not perfect) handling of indentation.
                   10169: @item
                   10170: Comment paragraph filling (@kbd{M-q})
                   10171: @item
                   10172: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
                   10173: @item
                   10174: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
                   10175: @end itemize
                   10176: 
                   10177: I left the stuff I do not use alone, even though some of it only makes
                   10178: sense for TILE. To get a description of these features, enter Forth mode
                   10179: and type @kbd{C-h m}.
1.1       anton    10180: 
                   10181: @cindex source location of error or debugging output in Emacs
                   10182: @cindex error output, finding the source location in Emacs
                   10183: @cindex debugging output, finding the source location in Emacs
                   10184: In addition, Gforth supports Emacs quite well: The source code locations
                   10185: given in error messages, debugging output (from @code{~~}) and failed
                   10186: assertion messages are in the right format for Emacs' compilation mode
                   10187: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
                   10188: Manual}) so the source location corresponding to an error or other
                   10189: message is only a few keystrokes away (@kbd{C-x `} for the next error,
                   10190: @kbd{C-c C-c} for the error under the cursor).
                   10191: 
                   10192: @cindex @file{TAGS} file
                   10193: @cindex @file{etags.fs}
                   10194: @cindex viewing the source of a word in Emacs
1.26      crook    10195: Also, if you @code{include} @file{etags.fs}, a new @file{TAGS} file will
                   10196: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1       anton    10197: contains the definitions of all words defined afterwards. You can then
                   10198: find the source for a word using @kbd{M-.}. Note that emacs can use
                   10199: several tags files at the same time (e.g., one for the Gforth sources
                   10200: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
                   10201: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
                   10202: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
                   10203: @file{/usr/local/share/gforth/0.2.0/TAGS}).
                   10204: 
                   10205: @cindex @file{.emacs}
                   10206: To get all these benefits, add the following lines to your @file{.emacs}
                   10207: file:
                   10208: 
                   10209: @example
                   10210: (autoload 'forth-mode "gforth.el")
                   10211: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
                   10212: @end example
                   10213: 
1.26      crook    10214: @c ******************************************************************
1.1       anton    10215: @node Image Files, Engine, Emacs and Gforth, Top
                   10216: @chapter Image Files
1.26      crook    10217: @cindex image file
                   10218: @cindex @file{.fi} files
1.1       anton    10219: @cindex precompiled Forth code
                   10220: @cindex dictionary in persistent form
                   10221: @cindex persistent form of dictionary
                   10222: 
                   10223: An image file is a file containing an image of the Forth dictionary,
                   10224: i.e., compiled Forth code and data residing in the dictionary.  By
                   10225: convention, we use the extension @code{.fi} for image files.
                   10226: 
                   10227: @menu
1.18      anton    10228: * Image Licensing Issues::      Distribution terms for images.
                   10229: * Image File Background::       Why have image files?
1.29    ! crook    10230: * Non-Relocatable Image Files::   don't always work.
1.18      anton    10231: * Data-Relocatable Image Files::  are better.
1.29    ! crook    10232: * Fully Relocatable Image Files:: better yet.
1.18      anton    10233: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.29    ! crook    10234: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.18      anton    10235: * Modifying the Startup Sequence::  and turnkey applications.
1.1       anton    10236: @end menu
                   10237: 
1.18      anton    10238: @node Image Licensing Issues, Image File Background, Image Files, Image Files
                   10239: @section Image Licensing Issues
                   10240: @cindex license for images
                   10241: @cindex image license
                   10242: 
                   10243: An image created with @code{gforthmi} (@pxref{gforthmi}) or
                   10244: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
                   10245: original image; i.e., according to copyright law it is a derived work of
                   10246: the original image.
                   10247: 
                   10248: Since Gforth is distributed under the GNU GPL, the newly created image
                   10249: falls under the GNU GPL, too. In particular, this means that if you
                   10250: distribute the image, you have to make all of the sources for the image
                   10251: available, including those you wrote.  For details see @ref{License, ,
                   10252: GNU General Public License (Section 3)}.
                   10253: 
                   10254: If you create an image with @code{cross} (@pxref{cross.fs}), the image
                   10255: contains only code compiled from the sources you gave it; if none of
                   10256: these sources is under the GPL, the terms discussed above do not apply
                   10257: to the image. However, if your image needs an engine (a gforth binary)
                   10258: that is under the GPL, you should make sure that you distribute both in
                   10259: a way that is at most a @emph{mere aggregation}, if you don't want the
                   10260: terms of the GPL to apply to the image.
                   10261: 
                   10262: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1       anton    10263: @section Image File Background
                   10264: @cindex image file background
                   10265: 
                   10266: Our Forth system consists not only of primitives, but also of
                   10267: definitions written in Forth. Since the Forth compiler itself belongs to
                   10268: those definitions, it is not possible to start the system with the
                   10269: primitives and the Forth source alone. Therefore we provide the Forth
1.26      crook    10270: code as an image file in nearly executable form. When Gforth starts up,
                   10271: a C routine loads the image file into memory, optionally relocates the
                   10272: addresses, then sets up the memory (stacks etc.) according to
                   10273: information in the image file, and (finally) starts executing Forth
                   10274: code.
1.1       anton    10275: 
                   10276: The image file variants represent different compromises between the
                   10277: goals of making it easy to generate image files and making them
                   10278: portable.
                   10279: 
                   10280: @cindex relocation at run-time
1.26      crook    10281: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1       anton    10282: run-time. This avoids many of the complications discussed below (image
                   10283: files are data relocatable without further ado), but costs performance
                   10284: (one addition per memory access).
                   10285: 
                   10286: @cindex relocation at load-time
1.26      crook    10287: By contrast, the Gforth loader performs relocation at image load time. The
                   10288: loader also has to replace tokens that represent primitive calls with the
1.1       anton    10289: appropriate code-field addresses (or code addresses in the case of
                   10290: direct threading).
                   10291: 
                   10292: There are three kinds of image files, with different degrees of
                   10293: relocatability: non-relocatable, data-relocatable, and fully relocatable
                   10294: image files.
                   10295: 
                   10296: @cindex image file loader
                   10297: @cindex relocating loader
                   10298: @cindex loader for image files
                   10299: These image file variants have several restrictions in common; they are
                   10300: caused by the design of the image file loader:
                   10301: 
                   10302: @itemize @bullet
                   10303: @item
                   10304: There is only one segment; in particular, this means, that an image file
                   10305: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26      crook    10306: them). The contents of the stacks are not represented, either.
1.1       anton    10307: 
                   10308: @item
                   10309: The only kinds of relocation supported are: adding the same offset to
                   10310: all cells that represent data addresses; and replacing special tokens
                   10311: with code addresses or with pieces of machine code.
                   10312: 
                   10313: If any complex computations involving addresses are performed, the
                   10314: results cannot be represented in the image file. Several applications that
                   10315: use such computations come to mind:
                   10316: @itemize @minus
                   10317: @item
                   10318: Hashing addresses (or data structures which contain addresses) for table
                   10319: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
                   10320: purpose, you will have no problem, because the hash tables are
                   10321: recomputed automatically when the system is started. If you use your own
                   10322: hash tables, you will have to do something similar.
                   10323: 
                   10324: @item
                   10325: There's a cute implementation of doubly-linked lists that uses
                   10326: @code{XOR}ed addresses. You could represent such lists as singly-linked
                   10327: in the image file, and restore the doubly-linked representation on
                   10328: startup.@footnote{In my opinion, though, you should think thrice before
                   10329: using a doubly-linked list (whatever implementation).}
                   10330: 
                   10331: @item
                   10332: The code addresses of run-time routines like @code{docol:} cannot be
                   10333: represented in the image file (because their tokens would be replaced by
                   10334: machine code in direct threaded implementations). As a workaround,
                   10335: compute these addresses at run-time with @code{>code-address} from the
                   10336: executions tokens of appropriate words (see the definitions of
                   10337: @code{docol:} and friends in @file{kernel.fs}).
                   10338: 
                   10339: @item
                   10340: On many architectures addresses are represented in machine code in some
                   10341: shifted or mangled form. You cannot put @code{CODE} words that contain
                   10342: absolute addresses in this form in a relocatable image file. Workarounds
                   10343: are representing the address in some relative form (e.g., relative to
                   10344: the CFA, which is present in some register), or loading the address from
                   10345: a place where it is stored in a non-mangled form.
                   10346: @end itemize
                   10347: @end itemize
                   10348: 
                   10349: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
                   10350: @section Non-Relocatable Image Files
                   10351: @cindex non-relocatable image files
1.26      crook    10352: @cindex image file, non-relocatable
1.1       anton    10353: 
                   10354: These files are simple memory dumps of the dictionary. They are specific
                   10355: to the executable (i.e., @file{gforth} file) they were created
                   10356: with. What's worse, they are specific to the place on which the
                   10357: dictionary resided when the image was created. Now, there is no
                   10358: guarantee that the dictionary will reside at the same place the next
                   10359: time you start Gforth, so there's no guarantee that a non-relocatable
                   10360: image will work the next time (Gforth will complain instead of crashing,
                   10361: though).
                   10362: 
                   10363: You can create a non-relocatable image file with
                   10364: 
                   10365: doc-savesystem
                   10366: 
                   10367: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
                   10368: @section Data-Relocatable Image Files
                   10369: @cindex data-relocatable image files
1.26      crook    10370: @cindex image file, data-relocatable
1.1       anton    10371: 
                   10372: These files contain relocatable data addresses, but fixed code addresses
                   10373: (instead of tokens). They are specific to the executable (i.e.,
                   10374: @file{gforth} file) they were created with. For direct threading on some
                   10375: architectures (e.g., the i386), data-relocatable images do not work. You
                   10376: get a data-relocatable image, if you use @file{gforthmi} with a
                   10377: Gforth binary that is not doubly indirect threaded (@pxref{Fully
                   10378: Relocatable Image Files}).
                   10379: 
                   10380: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
                   10381: @section Fully Relocatable Image Files
                   10382: @cindex fully relocatable image files
1.26      crook    10383: @cindex image file, fully relocatable
1.1       anton    10384: 
                   10385: @cindex @file{kern*.fi}, relocatability
                   10386: @cindex @file{gforth.fi}, relocatability
                   10387: These image files have relocatable data addresses, and tokens for code
                   10388: addresses. They can be used with different binaries (e.g., with and
                   10389: without debugging) on the same machine, and even across machines with
                   10390: the same data formats (byte order, cell size, floating point
                   10391: format). However, they are usually specific to the version of Gforth
                   10392: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
                   10393: are fully relocatable.
                   10394: 
                   10395: There are two ways to create a fully relocatable image file:
                   10396: 
                   10397: @menu
1.29    ! crook    10398: * gforthmi::                    The normal way
1.1       anton    10399: * cross.fs::                    The hard way
                   10400: @end menu
                   10401: 
                   10402: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
                   10403: @subsection @file{gforthmi}
                   10404: @cindex @file{comp-i.fs}
                   10405: @cindex @file{gforthmi}
                   10406: 
                   10407: You will usually use @file{gforthmi}. If you want to create an
1.29    ! crook    10408: image @i{file} that contains everything you would load by invoking
        !          10409: Gforth with @code{gforth @i{options}}, you simply say:
1.1       anton    10410: @example
1.29    ! crook    10411: gforthmi @i{file} @i{options}
1.1       anton    10412: @end example
                   10413: 
                   10414: E.g., if you want to create an image @file{asm.fi} that has the file
                   10415: @file{asm.fs} loaded in addition to the usual stuff, you could do it
                   10416: like this:
                   10417: 
                   10418: @example
                   10419: gforthmi asm.fi asm.fs
                   10420: @end example
                   10421: 
1.27      crook    10422: @file{gforthmi} is implemented as a sh script and works like this: It
                   10423: produces two non-relocatable images for different addresses and then
                   10424: compares them. Its output reflects this: first you see the output (if
                   10425: any) of the two Gforth invocations that produce the nonrelocatable image
                   10426: files, then you see the output of the comparing program: It displays the
                   10427: offset used for data addresses and the offset used for code addresses;
1.1       anton    10428: moreover, for each cell that cannot be represented correctly in the
                   10429: image files, it displays a line like the following one:
                   10430: 
                   10431: @example
                   10432:      78DC         BFFFFA50         BFFFFA40
                   10433: @end example
                   10434: 
                   10435: This means that at offset $78dc from @code{forthstart}, one input image
                   10436: contains $bffffa50, and the other contains $bffffa40. Since these cells
                   10437: cannot be represented correctly in the output image, you should examine
                   10438: these places in the dictionary and verify that these cells are dead
                   10439: (i.e., not read before they are written).
                   10440: 
1.27      crook    10441: If you type @file{gforthmi} with no arguments, it prints some usage
                   10442: instructions.
                   10443: 
1.1       anton    10444: @cindex @code{savesystem} during @file{gforthmi}
                   10445: @cindex @code{bye} during @file{gforthmi}
                   10446: @cindex doubly indirect threaded code
                   10447: @cindex environment variable @code{GFORTHD}
                   10448: @cindex @code{GFORTHD} environment variable
                   10449: @cindex @code{gforth-ditc}
1.29    ! crook    10450: There are a few wrinkles: After processing the passed @i{options}, the
1.1       anton    10451: words @code{savesystem} and @code{bye} must be visible. A special doubly
                   10452: indirect threaded version of the @file{gforth} executable is used for
                   10453: creating the nonrelocatable images; you can pass the exact filename of
                   10454: this executable through the environment variable @code{GFORTHD}
                   10455: (default: @file{gforth-ditc}); if you pass a version that is not doubly
                   10456: indirect threaded, you will not get a fully relocatable image, but a
1.27      crook    10457: data-relocatable image (because there is no code address offset). The
                   10458: normal @file{gforth} executable is used for creating the relocatable
                   10459: image; you can pass the exact filename of this executable through the
                   10460: environment variable @code{GFORTH}.
1.1       anton    10461: 
                   10462: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
                   10463: @subsection @file{cross.fs}
                   10464: @cindex @file{cross.fs}
                   10465: @cindex cross-compiler
                   10466: @cindex metacompiler
                   10467: 
                   10468: You can also use @code{cross}, a batch compiler that accepts a Forth-like
                   10469: programming language. This @code{cross} language has to be documented
                   10470: yet.
                   10471: 
                   10472: @cindex target compiler
                   10473: @code{cross} also allows you to create image files for machines with
                   10474: different data sizes and data formats than the one used for generating
                   10475: the image file. You can also use it to create an application image that
                   10476: does not contain a Forth compiler. These features are bought with
                   10477: restrictions and inconveniences in programming. E.g., addresses have to
                   10478: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
                   10479: order to make the code relocatable.
                   10480: 
                   10481: 
                   10482: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
                   10483: @section Stack and Dictionary Sizes
                   10484: @cindex image file, stack and dictionary sizes
                   10485: @cindex dictionary size default
                   10486: @cindex stack size default
                   10487: 
                   10488: If you invoke Gforth with a command line flag for the size
                   10489: (@pxref{Invoking Gforth}), the size you specify is stored in the
                   10490: dictionary. If you save the dictionary with @code{savesystem} or create
                   10491: an image with @file{gforthmi}, this size will become the default
                   10492: for the resulting image file. E.g., the following will create a
1.21      crook    10493: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1       anton    10494: 
                   10495: @example
                   10496: gforthmi gforth.fi -m 1M
                   10497: @end example
                   10498: 
                   10499: In other words, if you want to set the default size for the dictionary
                   10500: and the stacks of an image, just invoke @file{gforthmi} with the
                   10501: appropriate options when creating the image.
                   10502: 
                   10503: @cindex stack size, cache-friendly
                   10504: Note: For cache-friendly behaviour (i.e., good performance), you should
                   10505: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
                   10506: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
                   10507: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
                   10508: 
                   10509: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
                   10510: @section Running Image Files
                   10511: @cindex running image files
                   10512: @cindex invoking image files
                   10513: @cindex image file invocation
                   10514: 
                   10515: @cindex -i, invoke image file
                   10516: @cindex --image file, invoke image file
1.29    ! crook    10517: You can invoke Gforth with an image file @i{image} instead of the
1.1       anton    10518: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
                   10519: @example
1.29    ! crook    10520: gforth -i @i{image}
1.1       anton    10521: @end example
                   10522: 
                   10523: @cindex executable image file
1.26      crook    10524: @cindex image file, executable
1.1       anton    10525: If your operating system supports starting scripts with a line of the
                   10526: form @code{#! ...}, you just have to type the image file name to start
                   10527: Gforth with this image file (note that the file extension @code{.fi} is
1.29    ! crook    10528: just a convention). I.e., to run Gforth with the image file @i{image},
        !          10529: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27      crook    10530: This works because every @code{.fi} file starts with a line of this
                   10531: format:
                   10532: 
                   10533: @example
                   10534: #! /usr/local/bin/gforth-0.4.0 -i
                   10535: @end example
                   10536: 
                   10537: The file and pathname for the Gforth engine specified on this line is
                   10538: the specific Gforth executable that it was built against; i.e. the value
                   10539: of the environment variable @code{GFORTH} at the time that
                   10540: @file{gforthmi} was executed.
1.1       anton    10541: 
1.27      crook    10542: You can make use of the same shell capability to make a Forth source
                   10543: file into an executable. For example, if you place this text in a file:
1.26      crook    10544: 
                   10545: @example
                   10546: #! /usr/local/bin/gforth
                   10547: 
                   10548: ." Hello, world" CR
                   10549: bye
                   10550: @end example
                   10551: 
                   10552: @noindent
1.27      crook    10553: and then make the file executable (chmod +x in Unix), you can run it
1.26      crook    10554: directly from the command line. The sequence @code{#!} is used in two
                   10555: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29    ! crook    10556: system@footnote{The Unix kernel actually recognises two types of files:
        !          10557: executable files and files of data, where the data is processed by an
        !          10558: interpreter that is specified on the ``interpreter line'' -- the first
        !          10559: line of the file, starting with the sequence #!. There may be a small
        !          10560: limit (e.g., 32) on the number of characters that may be specified on
        !          10561: the interpreter line.} secondly it is treated as a comment character by
        !          10562: Gforth. Because of the second usage, a space is required between
        !          10563: @code{#!} and the path to the executable.
1.27      crook    10564: 
                   10565: The disadvantage of this latter technique, compared with using
                   10566: @file{gforthmi}, is that it is slower; the Forth source code is compiled
                   10567: on-the-fly, each time the program is invoked.
                   10568: 
1.26      crook    10569: @comment TODO describe the #! magic with reference to the Power Tools book.
                   10570: 
1.1       anton    10571: doc-#!
                   10572: 
                   10573: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
                   10574: @section Modifying the Startup Sequence
                   10575: @cindex startup sequence for image file
                   10576: @cindex image file initialization sequence
                   10577: @cindex initialization sequence of image file
                   10578: 
                   10579: You can add your own initialization to the startup sequence through the
1.26      crook    10580: deferred word @code{'cold}. @code{'cold} is invoked just before the
                   10581: image-specific command line processing (by default, loading files and
                   10582: evaluating (@code{-e}) strings) starts.
1.1       anton    10583: 
                   10584: A sequence for adding your initialization usually looks like this:
                   10585: 
                   10586: @example
                   10587: :noname
                   10588:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
                   10589:     ... \ your stuff
                   10590: ; IS 'cold
                   10591: @end example
                   10592: 
                   10593: @cindex turnkey image files
1.26      crook    10594: @cindex image file, turnkey applications
1.1       anton    10595: You can make a turnkey image by letting @code{'cold} execute a word
                   10596: (your turnkey application) that never returns; instead, it exits Gforth
                   10597: via @code{bye} or @code{throw}.
                   10598: 
                   10599: @cindex command-line arguments, access
                   10600: @cindex arguments on the command line, access
                   10601: You can access the (image-specific) command-line arguments through the
1.26      crook    10602: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1       anton    10603: access to @code{argv}.
                   10604: 
1.26      crook    10605: If @code{'cold} exits normally, Gforth processes the command-line
                   10606: arguments as files to be loaded and strings to be evaluated.  Therefore,
                   10607: @code{'cold} should remove the arguments it has used in this case.
                   10608: 
                   10609: doc-'cold
1.1       anton    10610: doc-argc
                   10611: doc-argv
                   10612: doc-arg
                   10613: 
                   10614: 
                   10615: @c ******************************************************************
1.13      pazsan   10616: @node Engine, Binding to System Library, Image Files, Top
1.1       anton    10617: @chapter Engine
                   10618: @cindex engine
                   10619: @cindex virtual machine
                   10620: 
1.26      crook    10621: Reading this chapter is not necessary for programming with Gforth. It
1.1       anton    10622: may be helpful for finding your way in the Gforth sources.
                   10623: 
                   10624: The ideas in this section have also been published in the papers
                   10625: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
                   10626: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
                   10627: Ertl, presented at EuroForth '93; the latter is available at
                   10628: @*@url{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
                   10629: 
                   10630: @menu
                   10631: * Portability::                 
                   10632: * Threading::                   
                   10633: * Primitives::                  
                   10634: * Performance::                 
                   10635: @end menu
                   10636: 
                   10637: @node Portability, Threading, Engine, Engine
                   10638: @section Portability
                   10639: @cindex engine portability
                   10640: 
1.26      crook    10641: An important goal of the Gforth Project is availability across a wide
                   10642: range of personal machines. fig-Forth, and, to a lesser extent, F83,
                   10643: achieved this goal by manually coding the engine in assembly language
                   10644: for several then-popular processors. This approach is very
                   10645: labor-intensive and the results are short-lived due to progress in
                   10646: computer architecture.
1.1       anton    10647: 
                   10648: @cindex C, using C for the engine
                   10649: Others have avoided this problem by coding in C, e.g., Mitch Bradley
                   10650: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
                   10651: particularly popular for UNIX-based Forths due to the large variety of
                   10652: architectures of UNIX machines. Unfortunately an implementation in C
                   10653: does not mix well with the goals of efficiency and with using
                   10654: traditional techniques: Indirect or direct threading cannot be expressed
                   10655: in C, and switch threading, the fastest technique available in C, is
                   10656: significantly slower. Another problem with C is that it is very
                   10657: cumbersome to express double integer arithmetic.
                   10658: 
                   10659: @cindex GNU C for the engine
                   10660: @cindex long long
                   10661: Fortunately, there is a portable language that does not have these
                   10662: limitations: GNU C, the version of C processed by the GNU C compiler
                   10663: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
                   10664: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
                   10665: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
                   10666: threading possible, its @code{long long} type (@pxref{Long Long, ,
                   10667: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
                   10668: double numbers@footnote{Unfortunately, long longs are not implemented
                   10669: properly on all machines (e.g., on alpha-osf1, long longs are only 64
                   10670: bits, the same size as longs (and pointers), but they should be twice as
1.4       anton    10671: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1       anton    10672: C Manual}). So, we had to implement doubles in C after all. Still, on
                   10673: most machines we can use long longs and achieve better performance than
                   10674: with the emulation package.}. GNU C is available for free on all
                   10675: important (and many unimportant) UNIX machines, VMS, 80386s running
                   10676: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
                   10677: on all these machines.
                   10678: 
                   10679: Writing in a portable language has the reputation of producing code that
                   10680: is slower than assembly. For our Forth engine we repeatedly looked at
                   10681: the code produced by the compiler and eliminated most compiler-induced
                   10682: inefficiencies by appropriate changes in the source code.
                   10683: 
                   10684: @cindex explicit register declarations
                   10685: @cindex --enable-force-reg, configuration flag
                   10686: @cindex -DFORCE_REG
                   10687: However, register allocation cannot be portably influenced by the
                   10688: programmer, leading to some inefficiencies on register-starved
                   10689: machines. We use explicit register declarations (@pxref{Explicit Reg
                   10690: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
                   10691: improve the speed on some machines. They are turned on by using the
                   10692: configuration flag @code{--enable-force-reg} (@code{gcc} switch
                   10693: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
                   10694: machine, but also on the compiler version: On some machines some
                   10695: compiler versions produce incorrect code when certain explicit register
                   10696: declarations are used. So by default @code{-DFORCE_REG} is not used.
                   10697: 
                   10698: @node Threading, Primitives, Portability, Engine
                   10699: @section Threading
                   10700: @cindex inner interpreter implementation
                   10701: @cindex threaded code implementation
                   10702: 
                   10703: @cindex labels as values
                   10704: GNU C's labels as values extension (available since @code{gcc-2.0},
                   10705: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29    ! crook    10706: makes it possible to take the address of @i{label} by writing
        !          10707: @code{&&@i{label}}.  This address can then be used in a statement like
        !          10708: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1       anton    10709: @code{goto x}.
                   10710: 
1.26      crook    10711: @cindex @code{NEXT}, indirect threaded
1.1       anton    10712: @cindex indirect threaded inner interpreter
                   10713: @cindex inner interpreter, indirect threaded
1.26      crook    10714: With this feature an indirect threaded @code{NEXT} looks like:
1.1       anton    10715: @example
                   10716: cfa = *ip++;
                   10717: ca = *cfa;
                   10718: goto *ca;
                   10719: @end example
                   10720: @cindex instruction pointer
                   10721: For those unfamiliar with the names: @code{ip} is the Forth instruction
                   10722: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
                   10723: execution token and points to the code field of the next word to be
                   10724: executed; The @code{ca} (code address) fetched from there points to some
                   10725: executable code, e.g., a primitive or the colon definition handler
                   10726: @code{docol}.
                   10727: 
1.26      crook    10728: @cindex @code{NEXT}, direct threaded
1.1       anton    10729: @cindex direct threaded inner interpreter
                   10730: @cindex inner interpreter, direct threaded
                   10731: Direct threading is even simpler:
                   10732: @example
                   10733: ca = *ip++;
                   10734: goto *ca;
                   10735: @end example
                   10736: 
                   10737: Of course we have packaged the whole thing neatly in macros called
1.26      crook    10738: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1       anton    10739: 
                   10740: @menu
                   10741: * Scheduling::                  
                   10742: * Direct or Indirect Threaded?::  
                   10743: * DOES>::                       
                   10744: @end menu
                   10745: 
                   10746: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
                   10747: @subsection Scheduling
                   10748: @cindex inner interpreter optimization
                   10749: 
                   10750: There is a little complication: Pipelined and superscalar processors,
                   10751: i.e., RISC and some modern CISC machines can process independent
                   10752: instructions while waiting for the results of an instruction. The
                   10753: compiler usually reorders (schedules) the instructions in a way that
                   10754: achieves good usage of these delay slots. However, on our first tries
                   10755: the compiler did not do well on scheduling primitives. E.g., for
                   10756: @code{+} implemented as
                   10757: @example
                   10758: n=sp[0]+sp[1];
                   10759: sp++;
                   10760: sp[0]=n;
                   10761: NEXT;
                   10762: @end example
1.26      crook    10763: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
1.1       anton    10764: scheduling. After a little thought the problem becomes clear: The
1.21      crook    10765: compiler cannot know that @code{sp} and @code{ip} point to different
                   10766: addresses (and the version of @code{gcc} we used would not know it even
                   10767: if it was possible), so it could not move the load of the cfa above the
                   10768: store to the TOS. Indeed the pointers could be the same, if code on or
                   10769: very near the top of stack were executed. In the interest of speed we
                   10770: chose to forbid this probably unused ``feature'' and helped the compiler
1.26      crook    10771: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
1.21      crook    10772: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1       anton    10773: @example
                   10774: n=sp[0]+sp[1];
                   10775: sp++;
                   10776: NEXT_P1;
                   10777: sp[0]=n;
                   10778: NEXT_P2;
                   10779: @end example
                   10780: This can be scheduled optimally by the compiler.
                   10781: 
                   10782: This division can be turned off with the switch @code{-DCISC_NEXT}. This
                   10783: switch is on by default on machines that do not profit from scheduling
                   10784: (e.g., the 80386), in order to preserve registers.
                   10785: 
                   10786: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
                   10787: @subsection Direct or Indirect Threaded?
                   10788: @cindex threading, direct or indirect?
                   10789: 
                   10790: @cindex -DDIRECT_THREADED
                   10791: Both! After packaging the nasty details in macro definitions we
                   10792: realized that we could switch between direct and indirect threading by
                   10793: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
                   10794: defining a few machine-specific macros for the direct-threading case.
                   10795: On the Forth level we also offer access words that hide the
                   10796: differences between the threading methods (@pxref{Threading Words}).
                   10797: 
                   10798: Indirect threading is implemented completely machine-independently.
                   10799: Direct threading needs routines for creating jumps to the executable
1.21      crook    10800: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
                   10801: machine-dependent, but they do not amount to many source lines. Therefore,
                   10802: even porting direct threading to a new machine requires little effort.
1.1       anton    10803: 
                   10804: @cindex --enable-indirect-threaded, configuration flag
                   10805: @cindex --enable-direct-threaded, configuration flag
                   10806: The default threading method is machine-dependent. You can enforce a
                   10807: specific threading method when building Gforth with the configuration
                   10808: flag @code{--enable-direct-threaded} or
                   10809: @code{--enable-indirect-threaded}. Note that direct threading is not
                   10810: supported on all machines.
                   10811: 
                   10812: @node DOES>,  , Direct or Indirect Threaded?, Threading
                   10813: @subsection DOES>
                   10814: @cindex @code{DOES>} implementation
                   10815: 
1.26      crook    10816: @cindex @code{dodoes} routine
                   10817: @cindex @code{DOES>}-code
1.1       anton    10818: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
                   10819: the chunk of code executed by every word defined by a
                   10820: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
                   10821: the Forth code to be executed, i.e. the code after the
1.26      crook    10822: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1       anton    10823: 
1.21      crook    10824: In fig-Forth the code field points directly to the @code{dodoes} and the
1.26      crook    10825: @code{DOES>}code address is stored in the cell after the code address (i.e. at
1.29    ! crook    10826: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1       anton    10827: the Forth-79 and all later standards, because in fig-Forth this address
                   10828: lies in the body (which is illegal in these standards). However, by
                   10829: making the code field larger for all words this solution becomes legal
                   10830: again. We use this approach for the indirect threaded version and for
                   10831: direct threading on some machines. Leaving a cell unused in most words
                   10832: is a bit wasteful, but on the machines we are targeting this is hardly a
                   10833: problem. The other reason for having a code field size of two cells is
                   10834: to avoid having different image files for direct and indirect threaded
                   10835: systems (direct threaded systems require two-cell code fields on many
                   10836: machines).
                   10837: 
1.26      crook    10838: @cindex @code{DOES>}-handler
1.1       anton    10839: The other approach is that the code field points or jumps to the cell
1.26      crook    10840: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
                   10841: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
                   10842: @code{DOES>}-code address by computing the code address, i.e., the address of
1.1       anton    10843: the jump to dodoes, and add the length of that jump field. A variant of
                   10844: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
                   10845: return address (which can be found in the return register on RISCs) is
1.26      crook    10846: the @code{DOES>}-code address. Since the two cells available in the code field
1.1       anton    10847: are used up by the jump to the code address in direct threading on many
                   10848: architectures, we use this approach for direct threading on these
                   10849: architectures. We did not want to add another cell to the code field.
                   10850: 
                   10851: @node Primitives, Performance, Threading, Engine
                   10852: @section Primitives
                   10853: @cindex primitives, implementation
                   10854: @cindex virtual machine instructions, implementation
                   10855: 
                   10856: @menu
                   10857: * Automatic Generation::        
                   10858: * TOS Optimization::            
                   10859: * Produced code::               
                   10860: @end menu
                   10861: 
                   10862: @node Automatic Generation, TOS Optimization, Primitives, Primitives
                   10863: @subsection Automatic Generation
                   10864: @cindex primitives, automatic generation
                   10865: 
                   10866: @cindex @file{prims2x.fs}
                   10867: Since the primitives are implemented in a portable language, there is no
                   10868: longer any need to minimize the number of primitives. On the contrary,
                   10869: having many primitives has an advantage: speed. In order to reduce the
                   10870: number of errors in primitives and to make programming them easier, we
                   10871: provide a tool, the primitive generator (@file{prims2x.fs}), that
                   10872: automatically generates most (and sometimes all) of the C code for a
                   10873: primitive from the stack effect notation.  The source for a primitive
                   10874: has the following form:
                   10875: 
                   10876: @cindex primitive source format
                   10877: @format
1.29    ! crook    10878: @i{Forth-name} @i{stack-effect}        @i{category}    [@i{pronounc.}]
        !          10879: [@code{""}@i{glossary entry}@code{""}]
        !          10880: @i{C code}
1.1       anton    10881: [@code{:}
1.29    ! crook    10882: @i{Forth code}]
1.1       anton    10883: @end format
                   10884: 
                   10885: The items in brackets are optional. The category and glossary fields
                   10886: are there for generating the documentation, the Forth code is there
                   10887: for manual implementations on machines without GNU C. E.g., the source
                   10888: for the primitive @code{+} is:
                   10889: @example
                   10890: +    n1 n2 -- n    core    plus
                   10891: n = n1+n2;
                   10892: @end example
                   10893: 
                   10894: This looks like a specification, but in fact @code{n = n1+n2} is C
                   10895: code. Our primitive generation tool extracts a lot of information from
                   10896: the stack effect notations@footnote{We use a one-stack notation, even
                   10897: though we have separate data and floating-point stacks; The separate
                   10898: notation can be generated easily from the unified notation.}: The number
                   10899: of items popped from and pushed on the stack, their type, and by what
                   10900: name they are referred to in the C code. It then generates a C code
                   10901: prelude and postlude for each primitive. The final C code for @code{+}
                   10902: looks like this:
                   10903: 
                   10904: @example
                   10905: I_plus:        /* + ( n1 n2 -- n ) */  /* label, stack effect */
                   10906: /*  */                          /* documentation */
                   10907: @{
                   10908: DEF_CA                          /* definition of variable ca (indirect threading) */
                   10909: Cell n1;                        /* definitions of variables */
                   10910: Cell n2;
                   10911: Cell n;
                   10912: n1 = (Cell) sp[1];              /* input */
                   10913: n2 = (Cell) TOS;
                   10914: sp += 1;                        /* stack adjustment */
                   10915: NAME("+")                       /* debugging output (with -DDEBUG) */
                   10916: @{
                   10917: n = n1+n2;                      /* C code taken from the source */
                   10918: @}
                   10919: NEXT_P1;                        /* NEXT part 1 */
                   10920: TOS = (Cell)n;                  /* output */
                   10921: NEXT_P2;                        /* NEXT part 2 */
                   10922: @}
                   10923: @end example
                   10924: 
                   10925: This looks long and inefficient, but the GNU C compiler optimizes quite
                   10926: well and produces optimal code for @code{+} on, e.g., the R3000 and the
                   10927: HP RISC machines: Defining the @code{n}s does not produce any code, and
                   10928: using them as intermediate storage also adds no cost.
                   10929: 
1.26      crook    10930: There are also other optimizations that are not illustrated by this
                   10931: example: assignments between simple variables are usually for free (copy
1.1       anton    10932: propagation). If one of the stack items is not used by the primitive
                   10933: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
                   10934: (dead code elimination). On the other hand, there are some things that
                   10935: the compiler does not do, therefore they are performed by
                   10936: @file{prims2x.fs}: The compiler does not optimize code away that stores
                   10937: a stack item to the place where it just came from (e.g., @code{over}).
                   10938: 
                   10939: While programming a primitive is usually easy, there are a few cases
                   10940: where the programmer has to take the actions of the generator into
                   10941: account, most notably @code{?dup}, but also words that do not (always)
1.26      crook    10942: fall through to @code{NEXT}.
1.1       anton    10943: 
                   10944: @node TOS Optimization, Produced code, Automatic Generation, Primitives
                   10945: @subsection TOS Optimization
                   10946: @cindex TOS optimization for primitives
                   10947: @cindex primitives, keeping the TOS in a register
                   10948: 
                   10949: An important optimization for stack machine emulators, e.g., Forth
                   10950: engines, is keeping  one or more of the top stack items in
1.29    ! crook    10951: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
        !          10952: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1       anton    10953: @itemize @bullet
                   10954: @item
1.29    ! crook    10955: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1       anton    10956: due to fewer loads from and stores to the stack.
1.29    ! crook    10957: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
        !          10958: @i{y<n}, due to additional moves between registers.
1.1       anton    10959: @end itemize
                   10960: 
                   10961: @cindex -DUSE_TOS
                   10962: @cindex -DUSE_NO_TOS
                   10963: In particular, keeping one item in a register is never a disadvantage,
                   10964: if there are enough registers. Keeping two items in registers is a
                   10965: disadvantage for frequent words like @code{?branch}, constants,
                   10966: variables, literals and @code{i}. Therefore our generator only produces
                   10967: code that keeps zero or one items in registers. The generated C code
                   10968: covers both cases; the selection between these alternatives is made at
                   10969: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
                   10970: code for @code{+} is just a simple variable name in the one-item case,
                   10971: otherwise it is a macro that expands into @code{sp[0]}. Note that the
                   10972: GNU C compiler tries to keep simple variables like @code{TOS} in
                   10973: registers, and it usually succeeds, if there are enough registers.
                   10974: 
                   10975: @cindex -DUSE_FTOS
                   10976: @cindex -DUSE_NO_FTOS
                   10977: The primitive generator performs the TOS optimization for the
                   10978: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
                   10979: operations the benefit of this optimization is even larger:
                   10980: floating-point operations take quite long on most processors, but can be
                   10981: performed in parallel with other operations as long as their results are
                   10982: not used. If the FP-TOS is kept in a register, this works. If
                   10983: it is kept on the stack, i.e., in memory, the store into memory has to
                   10984: wait for the result of the floating-point operation, lengthening the
                   10985: execution time of the primitive considerably.
                   10986: 
                   10987: The TOS optimization makes the automatic generation of primitives a
                   10988: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
                   10989: @code{TOS} is not sufficient. There are some special cases to
                   10990: consider:
                   10991: @itemize @bullet
                   10992: @item In the case of @code{dup ( w -- w w )} the generator must not
                   10993: eliminate the store to the original location of the item on the stack,
                   10994: if the TOS optimization is turned on.
                   10995: @item Primitives with stack effects of the form @code{--}
1.29    ! crook    10996: @i{out1}...@i{outy} must store the TOS to the stack at the start.
        !          10997: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1       anton    10998: must load the TOS from the stack at the end. But for the null stack
                   10999: effect @code{--} no stores or loads should be generated.
                   11000: @end itemize
                   11001: 
                   11002: @node Produced code,  , TOS Optimization, Primitives
                   11003: @subsection Produced code
                   11004: @cindex primitives, assembly code listing
                   11005: 
                   11006: @cindex @file{engine.s}
                   11007: To see what assembly code is produced for the primitives on your machine
                   11008: with your compiler and your flag settings, type @code{make engine.s} and
                   11009: look at the resulting file @file{engine.s}.
                   11010: 
                   11011: @node  Performance,  , Primitives, Engine
                   11012: @section Performance
                   11013: @cindex performance of some Forth interpreters
                   11014: @cindex engine performance
                   11015: @cindex benchmarking Forth systems
                   11016: @cindex Gforth performance
                   11017: 
                   11018: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
                   11019: impossible to write a significantly faster engine.
                   11020: 
                   11021: On register-starved machines like the 386 architecture processors
                   11022: improvements are possible, because @code{gcc} does not utilize the
                   11023: registers as well as a human, even with explicit register declarations;
                   11024: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
                   11025: and hand-tuned it for the 486; this system is 1.19 times faster on the
                   11026: Sieve benchmark on a 486DX2/66 than Gforth compiled with
                   11027: @code{gcc-2.6.3} with @code{-DFORCE_REG}.
                   11028: 
                   11029: @cindex Win32Forth performance
                   11030: @cindex NT Forth performance
                   11031: @cindex eforth performance
                   11032: @cindex ThisForth performance
                   11033: @cindex PFE performance
                   11034: @cindex TILE performance
                   11035: However, this potential advantage of assembly language implementations
                   11036: is not necessarily realized in complete Forth systems: We compared
                   11037: Gforth (direct threaded, compiled with @code{gcc-2.6.3} and
                   11038: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
                   11039: 1994) and Eforth (with and without peephole (aka pinhole) optimization
                   11040: of the threaded code); all these systems were written in assembly
                   11041: language. We also compared Gforth with three systems written in C:
                   11042: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
                   11043: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21      crook    11044: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
                   11045: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1       anton    11046: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
                   11047: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
                   11048: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
                   11049: 486DX2/66 with similar memory performance under Windows NT. Marcel
                   11050: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
                   11051: added the peephole optimizer, ran the benchmarks and reported the
                   11052: results.
                   11053:  
                   11054: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
                   11055: matrix multiplication come from the Stanford integer benchmarks and have
                   11056: been translated into Forth by Martin Fraeman; we used the versions
                   11057: included in the TILE Forth package, but with bigger data set sizes; and
                   11058: a recursive Fibonacci number computation for benchmarking calling
                   11059: performance. The following table shows the time taken for the benchmarks
                   11060: scaled by the time taken by Gforth (in other words, it shows the speedup
                   11061: factor that Gforth achieved over the other systems).
                   11062: 
                   11063: @example
                   11064: relative      Win32-    NT       eforth       This-
                   11065:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
                   11066: sieve     1.00  1.39  1.14   1.39  0.85  1.58  3.18  8.58
                   11067: bubble    1.00  1.31  1.41   1.48  0.88  1.50        3.88
                   11068: matmul    1.00  1.47  1.35   1.46  0.74  1.58        4.09
                   11069: fib       1.00  1.52  1.34   1.22  0.86  1.74  2.99  4.30
                   11070: @end example
                   11071: 
1.26      crook    11072: You may be quite surprised by the good performance of Gforth when
                   11073: compared with systems written in assembly language. One important reason
                   11074: for the disappointing performance of these other systems is probably
                   11075: that they are not written optimally for the 486 (e.g., they use the
                   11076: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
                   11077: but costly method for relocating the Forth image: like @code{cforth}, it
                   11078: computes the actual addresses at run time, resulting in two address
                   11079: computations per @code{NEXT} (@pxref{Image File Background}).
                   11080: 
                   11081: Only Eforth with the peephole optimizer has a performance that is
                   11082: comparable to Gforth. The speedups achieved with peephole optimization
                   11083: of threaded code are quite remarkable. Adding a peephole optimizer to
                   11084: Gforth should cause similar speedups.
1.1       anton    11085: 
                   11086: The speedup of Gforth over PFE, ThisForth and TILE can be easily
                   11087: explained with the self-imposed restriction of the latter systems to
                   11088: standard C, which makes efficient threading impossible (however, the
1.4       anton    11089: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1       anton    11090: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
                   11091: Moreover, current C compilers have a hard time optimizing other aspects
                   11092: of the ThisForth and the TILE source.
                   11093: 
1.26      crook    11094: The performance of Gforth on 386 architecture processors varies widely
                   11095: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
                   11096: allocate any of the virtual machine registers into real machine
                   11097: registers by itself and would not work correctly with explicit register
                   11098: declarations, giving a 1.3 times slower engine (on a 486DX2/66 running
                   11099: the Sieve) than the one measured above.
1.1       anton    11100: 
1.26      crook    11101: Note that there have been several releases of Win32Forth since the
                   11102: release presented here, so the results presented above may have little
1.1       anton    11103: predictive value for the performance of Win32Forth today.
                   11104: 
                   11105: @cindex @file{Benchres}
                   11106: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
                   11107: Maierhofer (presented at EuroForth '95), an indirect threaded version of
                   11108: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
                   11109: version of Gforth is 2%@minus{}8% slower on a 486 than the direct
                   11110: threaded version used here. The paper available at
                   11111: @*@url{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
                   11112: it also contains numbers for some native code systems. You can find a
                   11113: newer version of these measurements at
                   11114: @url{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
                   11115: find numbers for Gforth on various machines in @file{Benchres}.
                   11116: 
1.26      crook    11117: @c ******************************************************************
1.13      pazsan   11118: @node Binding to System Library, Cross Compiler, Engine, Top
1.14      pazsan   11119: @chapter Binding to System Library
1.13      pazsan   11120: 
                   11121: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14      pazsan   11122: @chapter Cross Compiler
1.13      pazsan   11123: 
                   11124: Cross Compiler
                   11125: 
                   11126: @menu
                   11127: * Using the Cross Compiler::
                   11128: * How the Cross Compiler Works::
                   11129: @end menu
                   11130: 
1.21      crook    11131: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14      pazsan   11132: @section Using the Cross Compiler
1.13      pazsan   11133: 
1.21      crook    11134: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14      pazsan   11135: @section How the Cross Compiler Works
1.13      pazsan   11136: 
                   11137: @node Bugs, Origin, Cross Compiler, Top
1.21      crook    11138: @appendix Bugs
1.1       anton    11139: @cindex bug reporting
                   11140: 
1.21      crook    11141: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1       anton    11142: 
                   11143: If you find a bug, please send a bug report to
1.21      crook    11144: @email{bug-gforth@@gnu.ai.mit.edu}. A bug report should include this
                   11145: information:
                   11146: 
                   11147: @itemize @bullet
                   11148: @item
                   11149: The Gforth version used (it is announced at the start of an
                   11150: interactive Gforth session).
                   11151: @item
                   11152: The machine and operating system (on Unix
                   11153: systems @code{uname -a} will report this information).
                   11154: @item
                   11155: The installation options (send the file @file{config.status}).
                   11156: @item
                   11157: A complete list of changes (if any) you (or your installer) have made to the
                   11158: Gforth sources.
                   11159: @item
                   11160: A program (or a sequence of keyboard commands) that reproduces the bug.
                   11161: @item
                   11162: A description of what you think constitutes the buggy behaviour.
                   11163: @end itemize
1.1       anton    11164: 
                   11165: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
                   11166: to Report Bugs, gcc.info, GNU C Manual}.
                   11167: 
                   11168: 
1.21      crook    11169: @node Origin, Forth-related information, Bugs, Top
                   11170: @appendix Authors and Ancestors of Gforth
1.1       anton    11171: 
                   11172: @section Authors and Contributors
                   11173: @cindex authors of Gforth
                   11174: @cindex contributors to Gforth
                   11175: 
                   11176: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
                   11177: Ertl. The third major author was Jens Wilke.  Lennart Benschop (who was
                   11178: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
                   11179: with their continuous feedback. Lennart Benshop contributed
                   11180: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
                   11181: support for calling C libraries. Helpful comments also came from Paul
                   11182: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.12      anton    11183: Wavrik, Barrie Stott, Marc de Groot, and Jorge Acerada. Since the
                   11184: release of Gforth-0.2.1 there were also helpful comments from many
                   11185: others; thank you all, sorry for not listing you here (but digging
1.23      crook    11186: through my mailbox to extract your names is on my to-do list). Since the
                   11187: release of Gforth-0.4.0 Neal Crook worked on the manual.
1.1       anton    11188: 
                   11189: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
                   11190: and autoconf, among others), and to the creators of the Internet: Gforth
1.21      crook    11191: was developed across the Internet, and its authors did not meet
1.20      pazsan   11192: physically for the first 4 years of development.
1.1       anton    11193: 
                   11194: @section Pedigree
1.26      crook    11195: @cindex pedigree of Gforth
1.1       anton    11196: 
1.20      pazsan   11197: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1       anton    11198: Dirk Zoller) will cross-fertilize each other. Of course, a significant
                   11199: part of the design of Gforth was prescribed by ANS Forth.
                   11200: 
1.20      pazsan   11201: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1       anton    11202: 32 bit native code version of VolksForth for the Atari ST, written
                   11203: mostly by Dietrich Weineck.
                   11204: 
                   11205: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
                   11206: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
                   11207: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
                   11208: 
                   11209: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
                   11210: Forth-83 standard. !! Pedigree? When?
                   11211: 
                   11212: A team led by Bill Ragsdale implemented fig-Forth on many processors in
                   11213: 1979. Robert Selzer and Bill Ragsdale developed the original
                   11214: implementation of fig-Forth for the 6502 based on microForth.
                   11215: 
                   11216: The principal architect of microForth was Dean Sanderson. microForth was
                   11217: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
                   11218: the 1802, and subsequently implemented on the 8080, the 6800 and the
                   11219: Z80.
                   11220: 
                   11221: All earlier Forth systems were custom-made, usually by Charles Moore,
                   11222: who discovered (as he puts it) Forth during the late 60s. The first full
                   11223: Forth existed in 1971.
                   11224: 
                   11225: A part of the information in this section comes from @cite{The Evolution
                   11226: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
                   11227: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
                   11228: Notices 28(3), 1993.  You can find more historical and genealogical
                   11229: information about Forth there.
                   11230: 
1.21      crook    11231: @node Forth-related information, Word Index, Origin, Top
                   11232: @appendix Other Forth-related information
                   11233: @cindex Forth-related information
                   11234: 
                   11235: @menu
                   11236: * Internet resources::
                   11237: * Books::
                   11238: * The Forth Interest Group::
                   11239: * Conferences::
                   11240: @end menu
                   11241: 
                   11242: 
                   11243: @node Internet resources, Books, Forth-related information, Forth-related information
                   11244: @section Internet resources
1.26      crook    11245: @cindex internet resources
1.21      crook    11246: 
                   11247: @cindex comp.lang.forth
                   11248: @cindex frequently asked questions
                   11249: There is an active newsgroup (comp.lang.forth) discussing Forth and
                   11250: Forth-related issues. A frequently-asked-questions (FAQ) list
                   11251: is posted to the newsgroup regulary, and archived at these sites:
                   11252: 
                   11253: @itemize @bullet
                   11254: @item
                   11255: @url{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
                   11256: @item
                   11257: @url{ftp://ftp.forth.org/pub/Forth/FAQ/}
                   11258: @end itemize
                   11259: 
                   11260: The FAQ list should be considered mandatory reading before posting to
                   11261: the newsgroup.
                   11262: 
                   11263: Here are some other web sites holding Forth-related material:
                   11264: 
                   11265: @itemize @bullet
                   11266: @item
                   11267: @url{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
                   11268: @item
                   11269: @url{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
                   11270: @item
                   11271: @url{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
                   11272: @item
                   11273: @url{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
                   11274: Research page, including links to the Journal of Forth Application and
                   11275: Research (JFAR) and a searchable Forth bibliography.
                   11276: @end itemize
                   11277: 
                   11278: 
                   11279: @node Books, The Forth Interest Group, Internet resources, Forth-related information
                   11280: @section Books
1.26      crook    11281: @cindex books on Forth
1.21      crook    11282: 
                   11283: As the Standard is relatively new, there are not many books out yet. It
                   11284: is not recommended to learn Forth by using Gforth and a book that is not
                   11285: written for ANS Forth, as you will not know your mistakes from the
                   11286: deviations of the book. However, books based on the Forth-83 standard
                   11287: should be ok, because ANS Forth is primarily an extension of Forth-83.
                   11288: 
                   11289: @cindex standard document for ANS Forth
                   11290: @cindex ANS Forth document
                   11291: The definite reference if you want to write ANS Forth programs is, of
1.26      crook    11292: course, the ANS Forth document. It is available in printed form from the
1.21      crook    11293: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
                   11294: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
                   11295: $200. You can also get it from Global Engineering Documents (Tel.: USA
                   11296: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
                   11297: 
                   11298: @cite{dpANS6}, the last draft of the standard, which was then submitted
                   11299: to ANSI for publication is available electronically and for free in some
                   11300: MS Word format, and it has been converted to HTML
                   11301: (@url{http://www.taygeta.com/forth/dpans.html}; this is my favourite
                   11302: format); this HTML version also includes the answers to Requests for
                   11303: Interpretation (RFIs). Some pointers to these versions can be found
                   11304: through @*@url{http://www.complang.tuwien.ac.at/projects/forth.html}.
                   11305: 
1.26      crook    11306: @cindex introductory book on Forth
                   11307: @cindex book on Forth, introductory
1.21      crook    11308: @cindex Woehr, Jack: @cite{Forth: The New Model}
                   11309: @cindex @cite{Forth: The new model} (book)
                   11310: @cite{Forth: The New Model} by Jack Woehr (Prentice-Hall, 1993) is an
                   11311: introductory book based on a draft version of the standard. It does not
                   11312: cover the whole standard. It also contains interesting background
                   11313: information (Jack Woehr was in the ANS Forth Technical Committee). It is
                   11314: not appropriate for complete newbies, but programmers experienced in
                   11315: other languages should find it ok.
                   11316: 
                   11317: @cindex Conklin, Edward K., and Elizabeth Rather: @cite{Forth Programmer's Handbook}
                   11318: @cindex Rather, Elizabeth and Edward K. Conklin: @cite{Forth Programmer's Handbook}
                   11319: @cindex @cite{Forth Programmer's Handbook} (book)
                   11320: @cite{Forth Programmer's Handbook} by Edward K. Conklin, Elizabeth
                   11321: D. Rather and the technical staff of Forth, Inc. (Forth, Inc., 1997;
                   11322: ISBN 0-9662156-0-5) contains little introductory material. The majority
                   11323: of the book is similar to @ref{Words}, but the book covers most of the
                   11324: standard words and some non-standard words (whereas this manual is
                   11325: quite incomplete). In addition, the book contains a chapter on
                   11326: programming style. The major drawback of this book is that it usually
                   11327: does not identify what is standard and what is specific to the Forth
                   11328: system described in the book (probably one of Forth, Inc.'s systems).
                   11329: Fortunately, many of the non-standard programming practices described in
                   11330: the book work in Gforth, too.  Still, this drawback makes the book
                   11331: hardly more useful than a pre-ANS book.
                   11332: 
                   11333: @node The Forth Interest Group, Conferences, Books, Forth-related information
                   11334: @section The Forth Interest Group
                   11335: @cindex Forth interest group (FIG)
                   11336: 
                   11337: The Forth Interest Group (FIG) is a world-wide, non-profit,
1.26      crook    11338: member-supported organisation. It publishes a regular magazine,
                   11339: @var{FORTH Dimensions}, and offers other benefits of membership. You can
                   11340: contact the FIG through their office email address:
                   11341: @email{office@@forth.org} or by visiting their web site at
                   11342: @url{http://www.forth.org/}. This web site also includes links to FIG
                   11343: chapters in other countries and American cities
1.21      crook    11344: (@url{http://www.forth.org/chapters.html}).
                   11345: 
                   11346: @node Conferences, , The Forth Interest Group, Forth-related information
                   11347: @section Conferences
                   11348: @cindex Conferences
                   11349: 
                   11350: There are several regular conferences related to Forth. They are all
1.26      crook    11351: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
                   11352: news group:
1.21      crook    11353: 
                   11354: @itemize @bullet
                   11355: @item
                   11356: FORML -- the Forth modification laboratory convenes every year near
                   11357: Monterey, California.
                   11358: @item
                   11359: The Rochester Forth Conference -- an annual conference traditionally
                   11360: held in Rochester, New York.
                   11361: @item
                   11362: EuroForth -- this European conference takes place annually.
                   11363: @end itemize
                   11364: 
                   11365: 
                   11366: @node Word Index, Concept Index, Forth-related information, Top
1.1       anton    11367: @unnumbered Word Index
                   11368: 
1.26      crook    11369: This index is a list of Forth words that have ``glossary'' entries
                   11370: within this manual. Each word is listed with its stack effect and
                   11371: wordset.
1.1       anton    11372: 
                   11373: @printindex fn
                   11374: 
                   11375: @node Concept Index,  , Word Index, Top
                   11376: @unnumbered Concept and Word Index
                   11377: 
1.26      crook    11378: Not all entries listed in this index are present verbatim in the
                   11379: text. This index also duplicates, in abbreviated form, all of the words
                   11380: listed in the Word Index (only the names are listed for the words here).
1.1       anton    11381: 
                   11382: @printindex cp
                   11383: 
                   11384: @contents
                   11385: @bye
                   11386: 

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