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

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.36      anton      11: @c          Not an improvement IMO - anton
                     12: @c          and anyway, this should be taken up
                     13: @c          with Karl Berry (the texinfo guy) - anton
1.29      crook      14: @comment .. would be useful to have a word that identified all deferred words
                     15: @comment should semantics stuff in intro be moved to another section
                     16: 
1.28      crook      17: 
1.1       anton      18: @comment %**start of header (This is for running Texinfo on a region.)
                     19: @setfilename gforth.info
                     20: @settitle Gforth Manual
                     21: @dircategory GNU programming tools
                     22: @direntry
                     23: * Gforth: (gforth).             A fast interpreter for the Forth language.
                     24: @end direntry
                     25: @comment @setchapternewpage odd
1.29      crook      26: @comment TODO this gets left in by HTML converter
1.12      anton      27: @macro progstyle {}
                     28: Programming style note:
1.3       anton      29: @end macro
1.1       anton      30: @comment %**end of header (This is for running Texinfo on a region.)
                     31: 
1.29      crook      32: 
                     33: @comment ----------------------------------------------------------
                     34: @comment macros for beautifying glossary entries
                     35: @comment if these are used, need to strip them out for HTML converter
                     36: @comment else they get repeated verbatim in HTML output.
                     37: @comment .. not working yet.
                     38: 
                     39: @macro GLOSS-START {}
                     40: @iftex
                     41: @ninerm
                     42: @end iftex
                     43: @end macro
                     44: 
                     45: @macro GLOSS-END {}
                     46: @iftex
                     47: @rm
                     48: @end iftex
                     49: @end macro
                     50: 
                     51: @comment ----------------------------------------------------------
                     52: 
                     53: 
1.10      anton      54: @include version.texi
                     55: 
1.1       anton      56: @ifinfo
1.11      anton      57: This file documents Gforth @value{VERSION}
1.1       anton      58: 
1.26      crook      59: Copyright @copyright{} 1995-1999 Free Software Foundation, Inc.
1.1       anton      60: 
                     61:      Permission is granted to make and distribute verbatim copies of
                     62:      this manual provided the copyright notice and this permission notice
                     63:      are preserved on all copies.
                     64:      
                     65: @ignore
                     66:      Permission is granted to process this file through TeX and print the
                     67:      results, provided the printed document carries a copying permission
                     68:      notice identical to this one except for the removal of this paragraph
                     69:      (this paragraph not being relevant to the printed manual).
                     70:      
                     71: @end ignore
                     72:      Permission is granted to copy and distribute modified versions of this
                     73:      manual under the conditions for verbatim copying, provided also that the
                     74:      sections entitled "Distribution" and "General Public License" are
                     75:      included exactly as in the original, and provided that the entire
                     76:      resulting derived work is distributed under the terms of a permission
                     77:      notice identical to this one.
                     78:      
                     79:      Permission is granted to copy and distribute translations of this manual
                     80:      into another language, under the above conditions for modified versions,
                     81:      except that the sections entitled "Distribution" and "General Public
                     82:      License" may be included in a translation approved by the author instead
                     83:      of in the original English.
                     84: @end ifinfo
                     85: 
                     86: @finalout
                     87: @titlepage
                     88: @sp 10
                     89: @center @titlefont{Gforth Manual}
                     90: @sp 2
1.11      anton      91: @center for version @value{VERSION}
1.1       anton      92: @sp 2
1.34      anton      93: @center Neal Crook
1.1       anton      94: @center Anton Ertl
1.6       pazsan     95: @center Bernd Paysan
1.5       anton      96: @center Jens Wilke
1.1       anton      97: @sp 3
1.44    ! crook      98: @center This manual is permanently under construction and was last updated on 05-Jun-1999
1.1       anton      99: 
                    100: @comment  The following two commands start the copyright page.
                    101: @page
                    102: @vskip 0pt plus 1filll
1.29      crook     103: Copyright @copyright{} 1995--1999 Free Software Foundation, Inc.
1.1       anton     104: 
                    105: @comment !! Published by ... or You can get a copy of this manual ...
                    106: 
                    107:      Permission is granted to make and distribute verbatim copies of
                    108:      this manual provided the copyright notice and this permission notice
                    109:      are preserved on all copies.
                    110:      
                    111:      Permission is granted to copy and distribute modified versions of this
                    112:      manual under the conditions for verbatim copying, provided also that the
                    113:      sections entitled "Distribution" and "General Public License" are
                    114:      included exactly as in the original, and provided that the entire
                    115:      resulting derived work is distributed under the terms of a permission
                    116:      notice identical to this one.
                    117:      
                    118:      Permission is granted to copy and distribute translations of this manual
                    119:      into another language, under the above conditions for modified versions,
                    120:      except that the sections entitled "Distribution" and "General Public
                    121:      License" may be included in a translation approved by the author instead
                    122:      of in the original English.
                    123: @end titlepage
                    124: 
                    125: 
                    126: @node Top, License, (dir), (dir)
                    127: @ifinfo
                    128: Gforth is a free implementation of ANS Forth available on many
1.11      anton     129: personal machines. This manual corresponds to version @value{VERSION}.
1.1       anton     130: @end ifinfo
                    131: 
                    132: @menu
1.21      crook     133: * License::                     The GPL
1.26      crook     134: * Goals::                       About the Gforth Project
1.29      crook     135: * Gforth Environment::          Starting (and exiting) Gforth
1.21      crook     136: * Introduction::                An introduction to ANS Forth
1.1       anton     137: * Words::                       Forth words available in Gforth
1.24      anton     138: * Error messages::              How to interpret them
1.1       anton     139: * Tools::                       Programming tools
                    140: * ANS conformance::             Implementation-defined options etc.
                    141: * Model::                       The abstract machine of Gforth
                    142: * Integrating Gforth::          Forth as scripting language for applications
                    143: * Emacs and Gforth::            The Gforth Mode
                    144: * Image Files::                 @code{.fi} files contain compiled code
                    145: * Engine::                      The inner interpreter and the primitives
1.24      anton     146: * Binding to System Library::   
1.13      pazsan    147: * Cross Compiler::              The Cross Compiler
1.1       anton     148: * Bugs::                        How to report them
                    149: * Origin::                      Authors and ancestors of Gforth
1.21      crook     150: * Forth-related information::   Books and places to look on the WWW
1.1       anton     151: * Word Index::                  An item for each Forth word
1.41      anton     152: * Name Index::                  Forth words, only names listed
1.1       anton     153: * Concept Index::               A menu covering many topics
1.12      anton     154: 
1.41      anton     155: @detailmenu
                    156:  --- The Detailed Node Listing ---
1.12      anton     157: 
1.26      crook     158: Goals of Gforth
                    159: 
                    160: * Gforth Extensions Sinful?::
                    161: 
1.29      crook     162: Gforth Environment
                    163: 
1.32      anton     164: * Invoking Gforth::             Getting in
                    165: * Leaving Gforth::              Getting out
                    166: * Command-line editing::        
1.29      crook     167: * Upper and lower case::
1.32      anton     168: * Environment variables::       ..that affect how Gforth starts up
                    169: * Gforth Files::                What gets installed and where
1.29      crook     170: 
1.24      anton     171: An Introduction to ANS Forth
                    172: 
                    173: * Introducing the Text Interpreter::
                    174: * Stacks and Postfix notation::
                    175: * Your first definition::
                    176: * How does that work?::
                    177: * Forth is written in Forth::
                    178: * Review - elements of a Forth system::
1.29      crook     179: * Where to go next::
1.24      anton     180: * Exercises::
                    181: 
1.12      anton     182: Forth Words
                    183: 
                    184: * Notation::                    
1.21      crook     185: * Comments::
                    186: * Boolean Flags::
1.12      anton     187: * Arithmetic::                  
                    188: * Stack Manipulation::          
                    189: * Memory::                      
                    190: * Control Structures::          
                    191: * Defining Words::              
1.21      crook     192: * The Text Interpreter::
1.12      anton     193: * Tokens for Words::            
1.21      crook     194: * Word Lists::                   
                    195: * Environmental Queries::
1.12      anton     196: * Files::                       
                    197: * Blocks::                      
                    198: * Other I/O::                   
                    199: * Programming Tools::           
                    200: * Assembler and Code Words::    
                    201: * Threading Words::             
1.26      crook     202: * Locals::                      
                    203: * Structures::                  
                    204: * Object-oriented Forth::       
1.21      crook     205: * Passing Commands to the OS::
                    206: * Miscellaneous Words::
1.12      anton     207: 
                    208: Arithmetic
                    209: 
                    210: * Single precision::            
                    211: * Bitwise operations::          
1.21      crook     212: * Double precision::            Double-cell integer arithmetic
                    213: * Numeric comparison::
1.32      anton     214: * Mixed precision::             Operations with single and double-cell integers
1.12      anton     215: * Floating Point::              
                    216: 
                    217: Stack Manipulation
                    218: 
                    219: * Data stack::                  
                    220: * Floating point stack::        
                    221: * Return stack::                
                    222: * Locals stack::                
                    223: * Stack pointer manipulation::  
                    224: 
                    225: Memory
                    226: 
1.32      anton     227: * Memory model::                
                    228: * Dictionary allocation::       
                    229: * Heap Allocation::             
                    230: * Memory Access::               
                    231: * Address arithmetic::          
                    232: * Memory Blocks::               
1.12      anton     233: 
                    234: Control Structures
                    235: 
1.41      anton     236: * Selection::                   IF ... ELSE ... ENDIF
                    237: * Simple Loops::                BEGIN ...
1.32      anton     238: * Counted Loops::               DO
                    239: * Arbitrary control structures::
                    240: * Calls and returns::
1.12      anton     241: * Exception Handling::          
                    242: 
                    243: Defining Words
                    244: 
1.44    ! crook     245: * @code{CREATE}::
        !           246: * Variables::                   Variables and user variables
        !           247: * Constants::
        !           248: * Values::                      Initialised variables
1.32      anton     249: * Colon Definitions::
1.44    ! crook     250: * Anonymous Definitions::       Definitions without names
1.32      anton     251: * User-defined Defining Words::
1.44    ! crook     252: * Deferred words::              Allow forward references
        !           253: * Aliases::
1.32      anton     254: * Supplying names::
                    255: * Interpretation and Compilation Semantics::
1.44    ! crook     256: * Combined words::
1.12      anton     257: 
1.21      crook     258: The Text Interpreter
                    259: 
1.29      crook     260: * Input Sources::
1.21      crook     261: * Number Conversion::
                    262: * Interpret/Compile states::
                    263: * Literals::
                    264: * Interpreter Directives::
                    265: 
1.26      crook     266: Word Lists
                    267: 
                    268: * Why use word lists?::
                    269: * Word list examples::
                    270: 
                    271: Files
                    272: 
                    273: * Forth source files::
                    274: * General files::         
                    275: * Search Paths::                 
                    276: * Forth Search Paths::    
                    277: * General Search Paths::        
                    278: 
                    279: Other I/O
                    280: 
1.32      anton     281: * Simple numeric output::       Predefined formats
                    282: * Formatted numeric output::    Formatted (pictured) output
                    283: * String Formats::              How Forth stores strings in memory
                    284: * Displaying characters and strings:: Other stuff
                    285: * Input::                       Input
1.26      crook     286: 
                    287: Programming Tools
                    288: 
                    289: * Debugging::                   Simple and quick.
                    290: * Assertions::                  Making your programs self-checking.
                    291: * Singlestep Debugger::                Executing your program word by word.
                    292: 
                    293: Locals
                    294: 
                    295: * Gforth locals::               
                    296: * ANS Forth locals::            
                    297: 
                    298: Gforth locals
                    299: 
                    300: * Where are locals visible by name?::  
                    301: * How long do locals live?::    
                    302: * Programming Style::           
                    303: * Implementation::              
                    304: 
1.12      anton     305: Structures
                    306: 
                    307: * Why explicit structure support?::  
                    308: * Structure Usage::             
                    309: * Structure Naming Convention::  
                    310: * Structure Implementation::    
                    311: * Structure Glossary::          
                    312: 
                    313: Object-oriented Forth
                    314: 
1.24      anton     315: * Why object-oriented programming?::
                    316: * Object-Oriented Terminology::
                    317: * Objects::
                    318: * OOF::
                    319: * Mini-OOF::
1.23      crook     320: * Comparison with other object models::  
1.12      anton     321: 
1.24      anton     322: The @file{objects.fs} model
1.12      anton     323: 
                    324: * Properties of the Objects model::  
                    325: * Basic Objects Usage::         
1.41      anton     326: * The Objects base class::      
1.12      anton     327: * Creating objects::            
                    328: * Object-Oriented Programming Style::  
                    329: * Class Binding::               
                    330: * Method conveniences::         
                    331: * Classes and Scoping::         
1.41      anton     332: * Dividing classes::            
1.12      anton     333: * Object Interfaces::           
                    334: * Objects Implementation::      
                    335: * Objects Glossary::            
                    336: 
1.24      anton     337: The @file{oof.fs} model
1.12      anton     338: 
                    339: * Properties of the OOF model::
                    340: * Basic OOF Usage::
1.23      crook     341: * The OOF base class::
1.12      anton     342: * Class Declaration::
                    343: * Class Implementation::
                    344: 
1.24      anton     345: The @file{mini-oof.fs} model
1.23      crook     346: 
                    347: * Basic Mini-OOF Usage::
                    348: * Mini-OOF Example::
                    349: * Mini-OOF Implementation::
                    350: 
1.12      anton     351: Tools
                    352: 
                    353: * ANS Report::                  Report the words used, sorted by wordset.
                    354: 
                    355: ANS conformance
                    356: 
                    357: * The Core Words::              
                    358: * The optional Block word set::  
                    359: * The optional Double Number word set::  
                    360: * The optional Exception word set::  
                    361: * The optional Facility word set::  
                    362: * The optional File-Access word set::  
                    363: * The optional Floating-Point word set::  
                    364: * The optional Locals word set::  
                    365: * The optional Memory-Allocation word set::  
                    366: * The optional Programming-Tools word set::  
                    367: * The optional Search-Order word set::  
                    368: 
                    369: The Core Words
                    370: 
                    371: * core-idef::                   Implementation Defined Options                   
                    372: * core-ambcond::                Ambiguous Conditions                
                    373: * core-other::                  Other System Documentation                  
                    374: 
                    375: The optional Block word set
                    376: 
                    377: * block-idef::                  Implementation Defined Options
                    378: * block-ambcond::               Ambiguous Conditions               
                    379: * block-other::                 Other System Documentation                 
                    380: 
                    381: The optional Double Number word set
                    382: 
                    383: * double-ambcond::              Ambiguous Conditions              
                    384: 
                    385: The optional Exception word set
                    386: 
                    387: * exception-idef::              Implementation Defined Options              
                    388: 
                    389: The optional Facility word set
                    390: 
                    391: * facility-idef::               Implementation Defined Options               
                    392: * facility-ambcond::            Ambiguous Conditions            
                    393: 
                    394: The optional File-Access word set
                    395: 
                    396: * file-idef::                   Implementation Defined Options
                    397: * file-ambcond::                Ambiguous Conditions                
                    398: 
                    399: The optional Floating-Point word set
                    400: 
                    401: * floating-idef::               Implementation Defined Options
                    402: * floating-ambcond::            Ambiguous Conditions            
                    403: 
                    404: The optional Locals word set
                    405: 
                    406: * locals-idef::                 Implementation Defined Options                 
                    407: * locals-ambcond::              Ambiguous Conditions              
                    408: 
                    409: The optional Memory-Allocation word set
                    410: 
                    411: * memory-idef::                 Implementation Defined Options                 
                    412: 
                    413: The optional Programming-Tools word set
                    414: 
                    415: * programming-idef::            Implementation Defined Options            
                    416: * programming-ambcond::         Ambiguous Conditions         
                    417: 
                    418: The optional Search-Order word set
                    419: 
                    420: * search-idef::                 Implementation Defined Options                 
                    421: * search-ambcond::              Ambiguous Conditions              
                    422: 
                    423: Image Files
                    424: 
1.24      anton     425: * Image Licensing Issues::      Distribution terms for images.
                    426: * Image File Background::       Why have image files?
1.32      anton     427: * Non-Relocatable Image Files::   don't always work.
1.24      anton     428: * Data-Relocatable Image Files::  are better.
1.32      anton     429: * Fully Relocatable Image Files:: better yet.
1.24      anton     430: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.32      anton     431: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.24      anton     432: * Modifying the Startup Sequence::  and turnkey applications.
1.12      anton     433: 
                    434: Fully Relocatable Image Files
                    435: 
1.27      crook     436: * gforthmi::                    The normal way
1.12      anton     437: * cross.fs::                    The hard way
                    438: 
                    439: Engine
                    440: 
                    441: * Portability::                 
                    442: * Threading::                   
                    443: * Primitives::                  
                    444: * Performance::                 
                    445: 
                    446: Threading
                    447: 
                    448: * Scheduling::                  
                    449: * Direct or Indirect Threaded?::  
                    450: * DOES>::                       
                    451: 
                    452: Primitives
                    453: 
                    454: * Automatic Generation::        
                    455: * TOS Optimization::            
                    456: * Produced code::               
1.13      pazsan    457: 
                    458: Cross Compiler
                    459: 
                    460: * Using the Cross Compiler::
                    461: * How the Cross Compiler Works::
                    462: 
1.24      anton     463: Other Forth-related information
1.21      crook     464: 
                    465: * Internet resources::
                    466: * Books::
                    467: * The Forth Interest Group::
                    468: * Conferences::
                    469: 
1.24      anton     470: @end detailmenu
1.1       anton     471: @end menu
                    472: 
1.26      crook     473: @node License, Goals, Top, Top
1.1       anton     474: @unnumbered GNU GENERAL PUBLIC LICENSE
                    475: @center Version 2, June 1991
                    476: 
                    477: @display
                    478: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
                    479: 675 Mass Ave, Cambridge, MA 02139, USA
                    480: 
                    481: Everyone is permitted to copy and distribute verbatim copies
                    482: of this license document, but changing it is not allowed.
                    483: @end display
                    484: 
                    485: @unnumberedsec Preamble
                    486: 
                    487:   The licenses for most software are designed to take away your
                    488: freedom to share and change it.  By contrast, the GNU General Public
                    489: License is intended to guarantee your freedom to share and change free
                    490: software---to make sure the software is free for all its users.  This
                    491: General Public License applies to most of the Free Software
                    492: Foundation's software and to any other program whose authors commit to
                    493: using it.  (Some other Free Software Foundation software is covered by
                    494: the GNU Library General Public License instead.)  You can apply it to
                    495: your programs, too.
                    496: 
                    497:   When we speak of free software, we are referring to freedom, not
                    498: price.  Our General Public Licenses are designed to make sure that you
                    499: have the freedom to distribute copies of free software (and charge for
                    500: this service if you wish), that you receive source code or can get it
                    501: if you want it, that you can change the software or use pieces of it
                    502: in new free programs; and that you know you can do these things.
                    503: 
                    504:   To protect your rights, we need to make restrictions that forbid
                    505: anyone to deny you these rights or to ask you to surrender the rights.
                    506: These restrictions translate to certain responsibilities for you if you
                    507: distribute copies of the software, or if you modify it.
                    508: 
                    509:   For example, if you distribute copies of such a program, whether
                    510: gratis or for a fee, you must give the recipients all the rights that
                    511: you have.  You must make sure that they, too, receive or can get the
                    512: source code.  And you must show them these terms so they know their
                    513: rights.
                    514: 
                    515:   We protect your rights with two steps: (1) copyright the software, and
                    516: (2) offer you this license which gives you legal permission to copy,
                    517: distribute and/or modify the software.
                    518: 
                    519:   Also, for each author's protection and ours, we want to make certain
                    520: that everyone understands that there is no warranty for this free
                    521: software.  If the software is modified by someone else and passed on, we
                    522: want its recipients to know that what they have is not the original, so
                    523: that any problems introduced by others will not reflect on the original
                    524: authors' reputations.
                    525: 
                    526:   Finally, any free program is threatened constantly by software
                    527: patents.  We wish to avoid the danger that redistributors of a free
                    528: program will individually obtain patent licenses, in effect making the
                    529: program proprietary.  To prevent this, we have made it clear that any
                    530: patent must be licensed for everyone's free use or not licensed at all.
                    531: 
                    532:   The precise terms and conditions for copying, distribution and
                    533: modification follow.
                    534: 
                    535: @iftex
                    536: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
                    537: @end iftex
                    538: @ifinfo
                    539: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
                    540: @end ifinfo
                    541: 
                    542: @enumerate 0
                    543: @item
                    544: This License applies to any program or other work which contains
                    545: a notice placed by the copyright holder saying it may be distributed
                    546: under the terms of this General Public License.  The ``Program'', below,
                    547: refers to any such program or work, and a ``work based on the Program''
                    548: means either the Program or any derivative work under copyright law:
                    549: that is to say, a work containing the Program or a portion of it,
                    550: either verbatim or with modifications and/or translated into another
                    551: language.  (Hereinafter, translation is included without limitation in
                    552: the term ``modification''.)  Each licensee is addressed as ``you''.
                    553: 
                    554: Activities other than copying, distribution and modification are not
                    555: covered by this License; they are outside its scope.  The act of
                    556: running the Program is not restricted, and the output from the Program
                    557: is covered only if its contents constitute a work based on the
                    558: Program (independent of having been made by running the Program).
                    559: Whether that is true depends on what the Program does.
                    560: 
                    561: @item
                    562: You may copy and distribute verbatim copies of the Program's
                    563: source code as you receive it, in any medium, provided that you
                    564: conspicuously and appropriately publish on each copy an appropriate
                    565: copyright notice and disclaimer of warranty; keep intact all the
                    566: notices that refer to this License and to the absence of any warranty;
                    567: and give any other recipients of the Program a copy of this License
                    568: along with the Program.
                    569: 
                    570: You may charge a fee for the physical act of transferring a copy, and
                    571: you may at your option offer warranty protection in exchange for a fee.
                    572: 
                    573: @item
                    574: You may modify your copy or copies of the Program or any portion
                    575: of it, thus forming a work based on the Program, and copy and
                    576: distribute such modifications or work under the terms of Section 1
                    577: above, provided that you also meet all of these conditions:
                    578: 
                    579: @enumerate a
                    580: @item
                    581: You must cause the modified files to carry prominent notices
                    582: stating that you changed the files and the date of any change.
                    583: 
                    584: @item
                    585: You must cause any work that you distribute or publish, that in
                    586: whole or in part contains or is derived from the Program or any
                    587: part thereof, to be licensed as a whole at no charge to all third
                    588: parties under the terms of this License.
                    589: 
                    590: @item
                    591: If the modified program normally reads commands interactively
                    592: when run, you must cause it, when started running for such
                    593: interactive use in the most ordinary way, to print or display an
                    594: announcement including an appropriate copyright notice and a
                    595: notice that there is no warranty (or else, saying that you provide
                    596: a warranty) and that users may redistribute the program under
                    597: these conditions, and telling the user how to view a copy of this
                    598: License.  (Exception: if the Program itself is interactive but
                    599: does not normally print such an announcement, your work based on
                    600: the Program is not required to print an announcement.)
                    601: @end enumerate
                    602: 
                    603: These requirements apply to the modified work as a whole.  If
                    604: identifiable sections of that work are not derived from the Program,
                    605: and can be reasonably considered independent and separate works in
                    606: themselves, then this License, and its terms, do not apply to those
                    607: sections when you distribute them as separate works.  But when you
                    608: distribute the same sections as part of a whole which is a work based
                    609: on the Program, the distribution of the whole must be on the terms of
                    610: this License, whose permissions for other licensees extend to the
                    611: entire whole, and thus to each and every part regardless of who wrote it.
                    612: 
                    613: Thus, it is not the intent of this section to claim rights or contest
                    614: your rights to work written entirely by you; rather, the intent is to
                    615: exercise the right to control the distribution of derivative or
                    616: collective works based on the Program.
                    617: 
                    618: In addition, mere aggregation of another work not based on the Program
                    619: with the Program (or with a work based on the Program) on a volume of
                    620: a storage or distribution medium does not bring the other work under
                    621: the scope of this License.
                    622: 
                    623: @item
                    624: You may copy and distribute the Program (or a work based on it,
                    625: under Section 2) in object code or executable form under the terms of
                    626: Sections 1 and 2 above provided that you also do one of the following:
                    627: 
                    628: @enumerate a
                    629: @item
                    630: Accompany it with the complete corresponding machine-readable
                    631: source code, which must be distributed under the terms of Sections
                    632: 1 and 2 above on a medium customarily used for software interchange; or,
                    633: 
                    634: @item
                    635: Accompany it with a written offer, valid for at least three
                    636: years, to give any third party, for a charge no more than your
                    637: cost of physically performing source distribution, a complete
                    638: machine-readable copy of the corresponding source code, to be
                    639: distributed under the terms of Sections 1 and 2 above on a medium
                    640: customarily used for software interchange; or,
                    641: 
                    642: @item
                    643: Accompany it with the information you received as to the offer
                    644: to distribute corresponding source code.  (This alternative is
                    645: allowed only for noncommercial distribution and only if you
                    646: received the program in object code or executable form with such
                    647: an offer, in accord with Subsection b above.)
                    648: @end enumerate
                    649: 
                    650: The source code for a work means the preferred form of the work for
                    651: making modifications to it.  For an executable work, complete source
                    652: code means all the source code for all modules it contains, plus any
                    653: associated interface definition files, plus the scripts used to
                    654: control compilation and installation of the executable.  However, as a
                    655: special exception, the source code distributed need not include
                    656: anything that is normally distributed (in either source or binary
                    657: form) with the major components (compiler, kernel, and so on) of the
                    658: operating system on which the executable runs, unless that component
                    659: itself accompanies the executable.
                    660: 
                    661: If distribution of executable or object code is made by offering
                    662: access to copy from a designated place, then offering equivalent
                    663: access to copy the source code from the same place counts as
                    664: distribution of the source code, even though third parties are not
                    665: compelled to copy the source along with the object code.
                    666: 
                    667: @item
                    668: You may not copy, modify, sublicense, or distribute the Program
                    669: except as expressly provided under this License.  Any attempt
                    670: otherwise to copy, modify, sublicense or distribute the Program is
                    671: void, and will automatically terminate your rights under this License.
                    672: However, parties who have received copies, or rights, from you under
                    673: this License will not have their licenses terminated so long as such
                    674: parties remain in full compliance.
                    675: 
                    676: @item
                    677: You are not required to accept this License, since you have not
                    678: signed it.  However, nothing else grants you permission to modify or
                    679: distribute the Program or its derivative works.  These actions are
                    680: prohibited by law if you do not accept this License.  Therefore, by
                    681: modifying or distributing the Program (or any work based on the
                    682: Program), you indicate your acceptance of this License to do so, and
                    683: all its terms and conditions for copying, distributing or modifying
                    684: the Program or works based on it.
                    685: 
                    686: @item
                    687: Each time you redistribute the Program (or any work based on the
                    688: Program), the recipient automatically receives a license from the
                    689: original licensor to copy, distribute or modify the Program subject to
                    690: these terms and conditions.  You may not impose any further
                    691: restrictions on the recipients' exercise of the rights granted herein.
                    692: You are not responsible for enforcing compliance by third parties to
                    693: this License.
                    694: 
                    695: @item
                    696: If, as a consequence of a court judgment or allegation of patent
                    697: infringement or for any other reason (not limited to patent issues),
                    698: conditions are imposed on you (whether by court order, agreement or
                    699: otherwise) that contradict the conditions of this License, they do not
                    700: excuse you from the conditions of this License.  If you cannot
                    701: distribute so as to satisfy simultaneously your obligations under this
                    702: License and any other pertinent obligations, then as a consequence you
                    703: may not distribute the Program at all.  For example, if a patent
                    704: license would not permit royalty-free redistribution of the Program by
                    705: all those who receive copies directly or indirectly through you, then
                    706: the only way you could satisfy both it and this License would be to
                    707: refrain entirely from distribution of the Program.
                    708: 
                    709: If any portion of this section is held invalid or unenforceable under
                    710: any particular circumstance, the balance of the section is intended to
                    711: apply and the section as a whole is intended to apply in other
                    712: circumstances.
                    713: 
                    714: It is not the purpose of this section to induce you to infringe any
                    715: patents or other property right claims or to contest validity of any
                    716: such claims; this section has the sole purpose of protecting the
                    717: integrity of the free software distribution system, which is
                    718: implemented by public license practices.  Many people have made
                    719: generous contributions to the wide range of software distributed
                    720: through that system in reliance on consistent application of that
                    721: system; it is up to the author/donor to decide if he or she is willing
                    722: to distribute software through any other system and a licensee cannot
                    723: impose that choice.
                    724: 
                    725: This section is intended to make thoroughly clear what is believed to
                    726: be a consequence of the rest of this License.
                    727: 
                    728: @item
                    729: If the distribution and/or use of the Program is restricted in
                    730: certain countries either by patents or by copyrighted interfaces, the
                    731: original copyright holder who places the Program under this License
                    732: may add an explicit geographical distribution limitation excluding
                    733: those countries, so that distribution is permitted only in or among
                    734: countries not thus excluded.  In such case, this License incorporates
                    735: the limitation as if written in the body of this License.
                    736: 
                    737: @item
                    738: The Free Software Foundation may publish revised and/or new versions
                    739: of the General Public License from time to time.  Such new versions will
                    740: be similar in spirit to the present version, but may differ in detail to
                    741: address new problems or concerns.
                    742: 
                    743: Each version is given a distinguishing version number.  If the Program
                    744: specifies a version number of this License which applies to it and ``any
                    745: later version'', you have the option of following the terms and conditions
                    746: either of that version or of any later version published by the Free
                    747: Software Foundation.  If the Program does not specify a version number of
                    748: this License, you may choose any version ever published by the Free Software
                    749: Foundation.
                    750: 
                    751: @item
                    752: If you wish to incorporate parts of the Program into other free
                    753: programs whose distribution conditions are different, write to the author
                    754: to ask for permission.  For software which is copyrighted by the Free
                    755: Software Foundation, write to the Free Software Foundation; we sometimes
                    756: make exceptions for this.  Our decision will be guided by the two goals
                    757: of preserving the free status of all derivatives of our free software and
                    758: of promoting the sharing and reuse of software generally.
                    759: 
                    760: @iftex
                    761: @heading NO WARRANTY
                    762: @end iftex
                    763: @ifinfo
                    764: @center NO WARRANTY
                    765: @end ifinfo
                    766: 
                    767: @item
                    768: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
                    769: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
                    770: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
                    771: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
                    772: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
                    773: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
                    774: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
                    775: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
                    776: REPAIR OR CORRECTION.
                    777: 
                    778: @item
                    779: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
                    780: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
                    781: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
                    782: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
                    783: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
                    784: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
                    785: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
                    786: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
                    787: POSSIBILITY OF SUCH DAMAGES.
                    788: @end enumerate
                    789: 
                    790: @iftex
                    791: @heading END OF TERMS AND CONDITIONS
                    792: @end iftex
                    793: @ifinfo
                    794: @center END OF TERMS AND CONDITIONS
                    795: @end ifinfo
                    796: 
                    797: @page
                    798: @unnumberedsec How to Apply These Terms to Your New Programs
                    799: 
                    800:   If you develop a new program, and you want it to be of the greatest
                    801: possible use to the public, the best way to achieve this is to make it
                    802: free software which everyone can redistribute and change under these terms.
                    803: 
                    804:   To do so, attach the following notices to the program.  It is safest
                    805: to attach them to the start of each source file to most effectively
                    806: convey the exclusion of warranty; and each file should have at least
                    807: the ``copyright'' line and a pointer to where the full notice is found.
                    808: 
                    809: @smallexample
                    810: @var{one line to give the program's name and a brief idea of what it does.}
                    811: Copyright (C) 19@var{yy}  @var{name of author}
                    812: 
                    813: This program is free software; you can redistribute it and/or modify 
                    814: it under the terms of the GNU General Public License as published by 
                    815: the Free Software Foundation; either version 2 of the License, or 
                    816: (at your option) any later version.
                    817: 
                    818: This program is distributed in the hope that it will be useful,
                    819: but WITHOUT ANY WARRANTY; without even the implied warranty of
                    820: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                    821: GNU General Public License for more details.
                    822: 
                    823: You should have received a copy of the GNU General Public License
                    824: along with this program; if not, write to the Free Software
                    825: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
                    826: @end smallexample
                    827: 
                    828: Also add information on how to contact you by electronic and paper mail.
                    829: 
                    830: If the program is interactive, make it output a short notice like this
                    831: when it starts in an interactive mode:
                    832: 
                    833: @smallexample
                    834: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
                    835: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
                    836: type `show w'.  
                    837: This is free software, and you are welcome to redistribute it 
                    838: under certain conditions; type `show c' for details.
                    839: @end smallexample
                    840: 
                    841: The hypothetical commands @samp{show w} and @samp{show c} should show
                    842: the appropriate parts of the General Public License.  Of course, the
                    843: commands you use may be called something other than @samp{show w} and
                    844: @samp{show c}; they could even be mouse-clicks or menu items---whatever
                    845: suits your program.
                    846: 
                    847: You should also get your employer (if you work as a programmer) or your
                    848: school, if any, to sign a ``copyright disclaimer'' for the program, if
                    849: necessary.  Here is a sample; alter the names:
                    850: 
                    851: @smallexample
                    852: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
                    853: `Gnomovision' (which makes passes at compilers) written by James Hacker.
                    854: 
                    855: @var{signature of Ty Coon}, 1 April 1989
                    856: Ty Coon, President of Vice
                    857: @end smallexample
                    858: 
                    859: This General Public License does not permit incorporating your program into
                    860: proprietary programs.  If your program is a subroutine library, you may
                    861: consider it more useful to permit linking proprietary applications with the
                    862: library.  If this is what you want to do, use the GNU Library General
                    863: Public License instead of this License.
                    864: 
                    865: @iftex
                    866: @unnumbered Preface
                    867: @cindex Preface
1.21      crook     868: This manual documents Gforth. Some introductory material is provided for
                    869: readers who are unfamiliar with Forth or who are migrating to Gforth
                    870: from other Forth compilers. However, this manual is primarily a
                    871: reference manual.
1.1       anton     872: @end iftex
                    873: 
1.28      crook     874: @comment TODO much more blurb here.
1.26      crook     875: 
                    876: @c ******************************************************************
1.29      crook     877: @node Goals, Gforth Environment, License, Top
1.26      crook     878: @comment node-name,     next,           previous, up
                    879: @chapter Goals of Gforth
                    880: @cindex goals of the Gforth project
                    881: The goal of the Gforth Project is to develop a standard model for
                    882: ANS Forth. This can be split into several subgoals:
                    883: 
                    884: @itemize @bullet
                    885: @item
                    886: Gforth should conform to the ANS Forth Standard.
                    887: @item
                    888: It should be a model, i.e. it should define all the
                    889: implementation-dependent things.
                    890: @item
                    891: It should become standard, i.e. widely accepted and used. This goal
                    892: is the most difficult one.
                    893: @end itemize
                    894: 
                    895: To achieve these goals Gforth should be
                    896: @itemize @bullet
                    897: @item
                    898: Similar to previous models (fig-Forth, F83)
                    899: @item
                    900: Powerful. It should provide for all the things that are considered
                    901: necessary today and even some that are not yet considered necessary.
                    902: @item
                    903: Efficient. It should not get the reputation of being exceptionally
                    904: slow.
                    905: @item
                    906: Free.
                    907: @item
                    908: Available on many machines/easy to port.
                    909: @end itemize
                    910: 
                    911: Have we achieved these goals? Gforth conforms to the ANS Forth
                    912: standard. It may be considered a model, but we have not yet documented
                    913: which parts of the model are stable and which parts we are likely to
                    914: change. It certainly has not yet become a de facto standard, but it
                    915: appears to be quite popular. It has some similarities to and some
                    916: differences from previous models. It has some powerful features, but not
                    917: yet everything that we envisioned. We certainly have achieved our
                    918: execution speed goals (@pxref{Performance}).  It is free and available
                    919: on many machines.
                    920: 
                    921: @menu
                    922: * Gforth Extensions Sinful?::
                    923: @end menu
                    924: 
                    925: @node Gforth Extensions Sinful?, , Goals, Goals
                    926: @comment node-name,     next,           previous, up
                    927: @section Is it a Sin to use Gforth Extensions?
                    928: @cindex Gforth extensions
                    929: 
                    930: If you've been paying attention, you will have realised that there is an
                    931: ANS (American National Standard) for Forth. As you read through the rest
1.29      crook     932: of this manual, you will see documentation for @i{Standard} words, and
                    933: documentation for some appealing Gforth @i{extensions}. You might ask
                    934: yourself the question: @i{``Given that there is a standard, would I be
1.26      crook     935: committing a sin to use (non-Standard) Gforth extensions?''}
                    936: 
                    937: The answer to that question is somewhat pragmatic and somewhat
                    938: philosophical. Consider these points:
                    939: 
                    940: @itemize @bullet
                    941: @item
                    942: A number of the Gforth extensions can be implemented in ANS Forth using
                    943: files provided in the @file{compat/} directory. These are mentioned in
                    944: the text in passing.
                    945: @item
                    946: Forth has a rich historical precedent for programmers taking advantage
                    947: of implementation-dependent features of their tools (for example,
                    948: relying on a knowledge of the dictionary structure). Sometimes these
                    949: techniques are necessary to extract every last bit of performance from
                    950: the hardware, sometimes they are just a programming shorthand.
                    951: @item
                    952: The best way to break the rules is to know what the rules are. To learn
                    953: the rules, there is no substitute for studying the text of the Standard
                    954: itself. In particular, Appendix A of the Standard (@var{Rationale})
                    955: provides a valuable insight into the thought processes of the technical
                    956: committee.
                    957: @item
                    958: The best reason to break a rule is because you have to; because it's
                    959: more productive to do that, because it makes your code run fast enough
                    960: or because you can see no Standard way to achieve what you want to
                    961: achieve.
                    962: @end itemize
                    963: 
                    964: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
                    965: analyse your program and determine what non-Standard definitions it
                    966: relies upon.
                    967: 
1.29      crook     968: 
1.26      crook     969: @c ******************************************************************
1.29      crook     970: @node Gforth Environment, Introduction, Goals, Top
                    971: @chapter Gforth Environment
                    972: @cindex Gforth environment
1.21      crook     973: 
1.29      crook     974: Note: ultimately, the gforth man page will be auto-generated from the
                    975: material in this chapter.
1.21      crook     976: 
                    977: @menu
1.29      crook     978: * Invoking Gforth::             Getting in
                    979: * Leaving Gforth::              Getting out
                    980: * Command-line editing::        
                    981: * Upper and lower case::
                    982: * Environment variables::       ..that affect how Gforth starts up
                    983: * Gforth Files::                What gets installed and where
1.21      crook     984: @end menu
                    985: 
1.30      anton     986: @xref{Image Files} for related information about the creation of images.
1.29      crook     987: 
1.21      crook     988: @comment ----------------------------------------------
1.29      crook     989: @node Invoking Gforth, Leaving Gforth, ,Gforth Environment
                    990: @section Invoking Gforth
                    991: @cindex invoking Gforth
                    992: @cindex running Gforth
                    993: @cindex command-line options
                    994: @cindex options on the command line
                    995: @cindex flags on the command line
1.21      crook     996: 
1.30      anton     997: Gforth is made up of two parts; an executable ``engine'' (named
                    998: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
                    999: will usually just say @code{gforth} -- this automatically loads the
                   1000: default image file @file{gforth.fi}. In many other cases the default
                   1001: Gforth image will be invoked like this:
1.21      crook    1002: @example
1.30      anton    1003: gforth [file | -e forth-code] ...
1.21      crook    1004: @end example
1.29      crook    1005: @noindent
                   1006: This interprets the contents of the files and the Forth code in the order they
                   1007: are given.
1.21      crook    1008: 
1.30      anton    1009: In addition to the @file{gforth} engine, there is also an engine called
                   1010: @file{gforth-fast}, which is faster, but gives less informative error
                   1011: messages (@pxref{Error messages}).
                   1012: 
1.29      crook    1013: In general, the command line looks like this:
1.21      crook    1014: 
                   1015: @example
1.30      anton    1016: gforth[-fast] [engine options] [image options]
1.21      crook    1017: @end example
                   1018: 
1.30      anton    1019: The engine options must come before the rest of the command
1.29      crook    1020: line. They are:
1.26      crook    1021: 
1.29      crook    1022: @table @code
                   1023: @cindex -i, command-line option
                   1024: @cindex --image-file, command-line option
                   1025: @item --image-file @i{file}
                   1026: @itemx -i @i{file}
                   1027: Loads the Forth image @i{file} instead of the default
                   1028: @file{gforth.fi} (@pxref{Image Files}).
1.21      crook    1029: 
1.39      anton    1030: @cindex --appl-image, command-line option
                   1031: @item --appl-image @i{file}
                   1032: Loads the image @i{file} and leaves all further command-line arguments
                   1033: to the image (instead of processing them as options).  This is useful
                   1034: for building executable application images on Unix, built with
                   1035: @code{gforthmi --application ...}.
                   1036: 
1.29      crook    1037: @cindex --path, command-line option
                   1038: @cindex -p, command-line option
                   1039: @item --path @i{path}
                   1040: @itemx -p @i{path}
                   1041: Uses @i{path} for searching the image file and Forth source code files
                   1042: instead of the default in the environment variable @code{GFORTHPATH} or
                   1043: the path specified at installation time (e.g.,
                   1044: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                   1045: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21      crook    1046: 
1.29      crook    1047: @cindex --dictionary-size, command-line option
                   1048: @cindex -m, command-line option
                   1049: @cindex @i{size} parameters for command-line options
                   1050: @cindex size of the dictionary and the stacks
                   1051: @item --dictionary-size @i{size}
                   1052: @itemx -m @i{size}
                   1053: Allocate @i{size} space for the Forth dictionary space instead of
                   1054: using the default specified in the image (typically 256K). The
                   1055: @i{size} specification for this and subsequent options consists of
                   1056: an integer and a unit (e.g.,
                   1057: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
                   1058: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                   1059: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                   1060: @code{e} is used.
1.21      crook    1061: 
1.29      crook    1062: @cindex --data-stack-size, command-line option
                   1063: @cindex -d, command-line option
                   1064: @item --data-stack-size @i{size}
                   1065: @itemx -d @i{size}
                   1066: Allocate @i{size} space for the data stack instead of using the
                   1067: default specified in the image (typically 16K).
1.21      crook    1068: 
1.29      crook    1069: @cindex --return-stack-size, command-line option
                   1070: @cindex -r, command-line option
                   1071: @item --return-stack-size @i{size}
                   1072: @itemx -r @i{size}
                   1073: Allocate @i{size} space for the return stack instead of using the
                   1074: default specified in the image (typically 15K).
1.21      crook    1075: 
1.29      crook    1076: @cindex --fp-stack-size, command-line option
                   1077: @cindex -f, command-line option
                   1078: @item --fp-stack-size @i{size}
                   1079: @itemx -f @i{size}
                   1080: Allocate @i{size} space for the floating point stack instead of
                   1081: using the default specified in the image (typically 15.5K). In this case
                   1082: the unit specifier @code{e} refers to floating point numbers.
1.21      crook    1083: 
1.29      crook    1084: @cindex --locals-stack-size, command-line option
                   1085: @cindex -l, command-line option
                   1086: @item --locals-stack-size @i{size}
                   1087: @itemx -l @i{size}
                   1088: Allocate @i{size} space for the locals stack instead of using the
                   1089: default specified in the image (typically 14.5K).
1.21      crook    1090: 
1.29      crook    1091: @cindex -h, command-line option
                   1092: @cindex --help, command-line option
                   1093: @item --help
                   1094: @itemx -h
                   1095: Print a message about the command-line options
1.21      crook    1096: 
1.29      crook    1097: @cindex -v, command-line option
                   1098: @cindex --version, command-line option
                   1099: @item --version
                   1100: @itemx -v
                   1101: Print version and exit
1.21      crook    1102: 
1.29      crook    1103: @cindex --debug, command-line option
                   1104: @item --debug
                   1105: Print some information useful for debugging on startup.
1.21      crook    1106: 
1.29      crook    1107: @cindex --offset-image, command-line option
                   1108: @item --offset-image
                   1109: Start the dictionary at a slightly different position than would be used
                   1110: otherwise (useful for creating data-relocatable images,
                   1111: @pxref{Data-Relocatable Image Files}).
1.21      crook    1112: 
1.29      crook    1113: @cindex --no-offset-im, command-line option
                   1114: @item --no-offset-im
                   1115: Start the dictionary at the normal position.
1.21      crook    1116: 
1.29      crook    1117: @cindex --clear-dictionary, command-line option
                   1118: @item --clear-dictionary
                   1119: Initialize all bytes in the dictionary to 0 before loading the image
                   1120: (@pxref{Data-Relocatable Image Files}).
                   1121: 
                   1122: @cindex --die-on-signal, command-line-option
                   1123: @item --die-on-signal
                   1124: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
                   1125: or the segmentation violation SIGSEGV) by translating it into a Forth
                   1126: @code{THROW}. With this option, Gforth exits if it receives such a
                   1127: signal. This option is useful when the engine and/or the image might be
                   1128: severely broken (such that it causes another signal before recovering
                   1129: from the first); this option avoids endless loops in such cases.
                   1130: @end table
                   1131: 
                   1132: @cindex loading files at startup
                   1133: @cindex executing code on startup
                   1134: @cindex batch processing with Gforth
                   1135: As explained above, the image-specific command-line arguments for the
                   1136: default image @file{gforth.fi} consist of a sequence of filenames and
                   1137: @code{-e @var{forth-code}} options that are interpreted in the sequence
                   1138: in which they are given. The @code{-e @var{forth-code}} or
                   1139: @code{--evaluate @var{forth-code}} option evaluates the Forth
                   1140: code. This option takes only one argument; if you want to evaluate more
                   1141: Forth words, you have to quote them or use @code{-e} several times. To exit
                   1142: after processing the command line (instead of entering interactive mode)
                   1143: append @code{-e bye} to the command line.
                   1144: 
                   1145: @cindex versions, invoking other versions of Gforth
                   1146: If you have several versions of Gforth installed, @code{gforth} will
                   1147: invoke the version that was installed last. @code{gforth-@i{version}}
                   1148: invokes a specific version. You may want to use the option
                   1149: @code{--path}, if your environment contains the variable
                   1150: @code{GFORTHPATH}.
                   1151: 
                   1152: Not yet implemented:
                   1153: On startup the system first executes the system initialization file
                   1154: (unless the option @code{--no-init-file} is given; note that the system
                   1155: resulting from using this option may not be ANS Forth conformant). Then
                   1156: the user initialization file @file{.gforth.fs} is executed, unless the
                   1157: option @code{--no-rc} is given; this file is first searched in @file{.},
                   1158: then in @file{~}, then in the normal path (see above).
1.21      crook    1159: 
                   1160: 
                   1161: 
1.29      crook    1162: @comment ----------------------------------------------
                   1163: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
                   1164: @section Leaving Gforth
                   1165: @cindex Gforth - leaving
                   1166: @cindex leaving Gforth
1.21      crook    1167: 
1.30      anton    1168: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
                   1169: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
                   1170: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
                   1171: data are discarded. @xref{Image Files} for ways of saving the state of
                   1172: the system before leaving Gforth.
1.21      crook    1173: 
1.29      crook    1174: doc-bye
1.21      crook    1175: 
1.44    ! crook    1176: 
1.29      crook    1177: @comment ----------------------------------------------
                   1178: @node Command-line editing, Upper and lower case,Leaving Gforth,Gforth Environment
                   1179: @section Command-line editing
                   1180: @cindex command-line editing
1.21      crook    1181: 
1.29      crook    1182: Gforth maintains a history file that records every line that you type to
                   1183: the text interpreter. This file is preserved between sessions, and is
                   1184: used to provide a command-line recall facility; if you type ctrl-P
                   1185: repeatedly you can recall successively older commands from this (or
                   1186: previous) session(s). The full list of command-line editing facilities is:
1.21      crook    1187: 
                   1188: @itemize @bullet
                   1189: @item
1.30      anton    1190: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
1.29      crook    1191: commands from the history buffer.
                   1192: @item
1.30      anton    1193: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
1.29      crook    1194: from the history buffer.
                   1195: @item
1.30      anton    1196: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
1.29      crook    1197: @item
1.30      anton    1198: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
1.29      crook    1199: @item
1.30      anton    1200: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
1.29      crook    1201: closing up the line.
                   1202: @item
1.30      anton    1203: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
1.29      crook    1204: @item
1.30      anton    1205: @kbd{Ctrl-a} to move the cursor to the start of the line.
1.21      crook    1206: @item
1.30      anton    1207: @kbd{Ctrl-e} to move the cursor to the end of the line.
1.21      crook    1208: @item
1.30      anton    1209: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
1.29      crook    1210: line.
1.21      crook    1211: @item
1.30      anton    1212: @key{TAB} to step through all possible full-word completions of the word
1.29      crook    1213: currently being typed.
1.21      crook    1214: @item
1.30      anton    1215: @kbd{Ctrl-d} at the start of the line to terminate Gforth (gracefully,
                   1216: using @code{bye}).
1.21      crook    1217: @end itemize
                   1218: 
1.29      crook    1219: When editing, displayable characters are inserted to the left of the
                   1220: cursor position; the line is always in ``insert'' (as opposed to
                   1221: ``overstrike'') mode.
                   1222: 
                   1223: @cindex history file
                   1224: @cindex @file{.gforth-history}
                   1225: On Unix systems, the history file is @file{~/.gforth-history} by
                   1226: default@footnote{i.e. it is stored in the user's home directory.}. You
                   1227: can find out the name and location of your history file using:
                   1228: 
                   1229: @example 
                   1230: history-file type \ Unix-class systems
1.21      crook    1231: 
1.29      crook    1232: history-file type \ Other systems
                   1233: history-dir  type
1.21      crook    1234: @end example
                   1235: 
1.29      crook    1236: If you enter long definitions by hand, you can use a text editor to
                   1237: paste them out of the history file into a Forth source file for reuse at
                   1238: a later time.
                   1239: 
                   1240: Gforth never trims the size of the history file, so you should do this
                   1241: periodically, if necessary.
                   1242: 
                   1243: @comment this is all defined in history.fs
1.44    ! crook    1244: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
        !          1245: @comment chosen?
1.29      crook    1246: 
                   1247: 
                   1248: 
                   1249: @comment ----------------------------------------------
                   1250: @node Upper and lower case, Environment variables,Command-line editing,Gforth Environment
                   1251: @section Upper and lower case
                   1252: @cindex case-sensitivity
                   1253: @cindex upper and lower case
                   1254: 
1.44    ! crook    1255: Gforth is case-insensitive; you can enter definitions and invoke
1.29      crook    1256: Standard words using upper, lower or mixed case (however,
                   1257: @pxref{core-idef, Implementation-defined options, Implementation-defined
                   1258: options}).
                   1259: 
1.30      anton    1260: ANS Forth only @i{requires} implementations to recognise Standard words
                   1261: when they are typed entirely in upper case. Therefore, a Standard
                   1262: program must use upper case for all Standard words. You can use whatever
                   1263: case you like for words that you define, but in a standard program you
                   1264: have to use the words in the same case that you defined them.
                   1265: 
                   1266: Gforth supports case sensitivity through @code{table}s (case-sensitive
                   1267: wordlists, @pxref{Word Lists}).
                   1268: 
                   1269: Two people have asked how to convert Gforth to case sensitivity; while
                   1270: we think this is a bad idea, you can change all wordlists into tables
                   1271: like this:
1.29      crook    1272: 
1.30      anton    1273: @example
                   1274: ' table-find forth-wordlist wordlist-map @ !
                   1275: @end example
                   1276: 
                   1277: Note that you now have to type the predefined words in the same case
                   1278: that we defined them, which are varying.  You may want to convert them
                   1279: to your favourite case before doing this operation (I won't explain how,
                   1280: because if you are even contemplating to do this, you'd better have
                   1281: enough knowledge of Forth systems to know this already).
1.29      crook    1282: 
                   1283: @comment ----------------------------------------------
                   1284: @node Environment variables, Gforth Files, Upper and lower case,Gforth Environment
                   1285: @section Environment variables
                   1286: @cindex environment variables
1.21      crook    1287: 
1.29      crook    1288: Gforth uses these environment variables:
1.21      crook    1289: 
1.29      crook    1290: @itemize @bullet
                   1291: @item
1.44    ! crook    1292: @cindex @code{GFORTHHIST} -- environment variable
        !          1293: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
1.29      crook    1294: open/create the history file, @file{.gforth-history}. Default:
                   1295: @code{$HOME}.
1.21      crook    1296: 
1.29      crook    1297: @item
1.44    ! crook    1298: @cindex @code{GFORTHPATH} -- environment variable
        !          1299: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
1.29      crook    1300: for Forth source-code files.
1.21      crook    1301: 
1.29      crook    1302: @item
1.44    ! crook    1303: @cindex @code{GFORTH} -- environment variable
        !          1304: @code{GFORTH} -- used by @file{gforthmi} @xref{gforthmi}.
1.26      crook    1305: 
1.29      crook    1306: @item
1.44    ! crook    1307: @cindex @code{GFORTHD} -- environment variable
        !          1308: @code{GFORTHD} -- used by @file{gforthmi} @xref{gforthmi}.
1.21      crook    1309: 
1.29      crook    1310: @item
1.44    ! crook    1311: @cindex @code{TMP}, @code{TEMP} - environment variable
        !          1312: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
        !          1313: location for the history file.
1.29      crook    1314: @end itemize
1.21      crook    1315: 
1.29      crook    1316: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
                   1317: @comment mentioning these.
1.21      crook    1318: 
1.29      crook    1319: All the Gforth environment variables default to sensible values if they
                   1320: are not set.
1.21      crook    1321: 
                   1322: 
1.29      crook    1323: @comment ----------------------------------------------
                   1324: @node Gforth Files, ,Environment variables,Gforth Environment
                   1325: @section Gforth files
                   1326: @cindex Gforth files
1.21      crook    1327: 
1.44    ! crook    1328: When you install Gforth on a Unix system, it installs files in these
        !          1329: locations by default:
1.21      crook    1330: 
1.26      crook    1331: @itemize @bullet
                   1332: @item
1.29      crook    1333: @file{/usr/local/bin/gforth}
                   1334: @item
                   1335: @file{/usr/local/bin/gforthmi}
                   1336: @item
                   1337: @file{/usr/local/man/man1/gforth.1} - man page.
                   1338: @item
                   1339: @file{/usr/local/info} - the Info version of this manual.
                   1340: @item
1.30      anton    1341: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1.29      crook    1342: @item
                   1343: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1.26      crook    1344: @item
1.30      anton    1345: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1.26      crook    1346: @item
1.30      anton    1347: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1.26      crook    1348: @end itemize
1.21      crook    1349: 
1.30      anton    1350: You can select different places for installation by using
                   1351: @code{configure} options (listed with @code{configure --help}).
1.21      crook    1352: 
1.29      crook    1353: @c ******************************************************************
                   1354: @node Introduction, Words, Gforth Environment, Top
                   1355: @comment node-name,     next,           previous, up
                   1356: @chapter An Introduction to ANS Forth
                   1357: @cindex Forth - an introduction
1.21      crook    1358: 
1.29      crook    1359: The primary purpose of this manual is to document Gforth. However, since
                   1360: Forth is not a widely-known language and there is a lack of up-to-date
                   1361: teaching material, it seems worthwhile to provide some introductory
                   1362: material. @xref{Forth-related information} for other sources of Forth-related
                   1363: information.
1.21      crook    1364: 
1.29      crook    1365: The examples in this section should work on any ANS Forth; the
                   1366: output shown was produced using Gforth. Each example attempts to
                   1367: reproduce the exact output that Gforth produces. If you try out the
                   1368: examples (and you should), what you should type is shown @kbd{like this}
                   1369: and Gforth's response is shown @code{like this}. The single exception is
1.30      anton    1370: that, where the example shows @key{RET} it means that you should
1.29      crook    1371: press the ``carriage return'' key. Unfortunately, some output formats for
                   1372: this manual cannot show the difference between @kbd{this} and
                   1373: @code{this} which will make trying out the examples harder (but not
                   1374: impossible).
1.21      crook    1375: 
1.29      crook    1376: Forth is an unusual language. It provides an interactive development
                   1377: environment which includes both an interpreter and compiler. Forth
                   1378: programming style encourages you to break a problem down into many
                   1379: @cindex factoring
                   1380: small fragments (@dfn{factoring}), and then to develop and test each
                   1381: fragment interactively. Forth advocates assert that breaking the
                   1382: edit-compile-test cycle used by conventional programming languages can
                   1383: lead to great productivity improvements.
1.21      crook    1384: 
1.29      crook    1385: @menu
                   1386: * Introducing the Text Interpreter::
                   1387: * Stacks and Postfix notation::
                   1388: * Your first definition::
                   1389: * How does that work?::
                   1390: * Forth is written in Forth::
                   1391: * Review - elements of a Forth system::
                   1392: * Where to go next::
                   1393: * Exercises::
                   1394: @end menu
1.21      crook    1395: 
1.29      crook    1396: @comment ----------------------------------------------
                   1397: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                   1398: @section Introducing the Text Interpreter
                   1399: @cindex text interpreter
                   1400: @cindex outer interpreter
1.21      crook    1401: 
1.30      anton    1402: @c IMO this is too detailed and the pace is too slow for
                   1403: @c an introduction.  If you know German, take a look at
                   1404: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
                   1405: @c to see how I do it - anton 
                   1406: 
1.44    ! crook    1407: @c nac-> Where I have accepted your comments 100% and modified the text
        !          1408: @c accordingly, I have deleted your comments. Elsewhere I have added a
        !          1409: @c response like this to attempt to rationalise what I have done. Of
        !          1410: @c course, this is a very clumsy mechanism for something that would be
        !          1411: @c done far more efficiently over a beer. Please delete any dialogue
        !          1412: @c you consider closed.
        !          1413: 
1.29      crook    1414: When you invoke the Forth image, you will see a startup banner printed
                   1415: and nothing else (if you have Gforth installed on your system, try
1.30      anton    1416: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29      crook    1417: its command line interpreter, which is called the @dfn{Text Interpreter}
                   1418: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
1.30      anton    1419: about the text interpreter as you read through this chapter, but
                   1420: @pxref{The Text Interpreter} for more detail).
1.21      crook    1421: 
1.29      crook    1422: Although it's not obvious, Forth is actually waiting for your
1.30      anton    1423: input. Type a number and press the @key{RET} key:
1.21      crook    1424: 
1.26      crook    1425: @example
1.30      anton    1426: @kbd{45@key{RET}}  ok
1.26      crook    1427: @end example
1.21      crook    1428: 
1.29      crook    1429: Rather than give you a prompt to invite you to input something, the text
                   1430: interpreter prints a status message @i{after} it has processed a line
                   1431: of input. The status message in this case (``@code{ ok}'' followed by
                   1432: carriage-return) indicates that the text interpreter was able to process
                   1433: all of your input successfully. Now type something illegal:
                   1434: 
                   1435: @example
1.30      anton    1436: @kbd{qwer341@key{RET}}
1.29      crook    1437: :1: Undefined word
                   1438: qwer341
                   1439: ^^^^^^^
                   1440: $400D2BA8 Bounce
                   1441: $400DBDA8 no.extensions
                   1442: @end example
1.23      crook    1443: 
1.29      crook    1444: The exact text, other than the ``Undefined word'' may differ slightly on
                   1445: your system, but the effect is the same; when the text interpreter
                   1446: detects an error, it discards any remaining text on a line, resets
1.30      anton    1447: certain internal state and prints an error message. @xref{Error
                   1448: messages} for a detailed description of error messages.
1.23      crook    1449: 
1.29      crook    1450: The text interpreter waits for you to press carriage-return, and then
                   1451: processes your input line. Starting at the beginning of the line, it
                   1452: breaks the line into groups of characters separated by spaces. For each
                   1453: group of characters in turn, it makes two attempts to do something:
1.23      crook    1454: 
1.29      crook    1455: @itemize @bullet
                   1456: @item
1.44    ! crook    1457: @cindex name dictionary
1.29      crook    1458: It tries to treat it as a command. It does this by searching a @dfn{name
                   1459: dictionary}. If the group of characters matches an entry in the name
                   1460: dictionary, the name dictionary provides the text interpreter with
                   1461: information that allows the text interpreter perform some actions. In
                   1462: Forth jargon, we say that the group
                   1463: @cindex word
                   1464: @cindex definition
                   1465: @cindex execution token
                   1466: @cindex xt
                   1467: of characters names a @dfn{word}, that the dictionary search returns an
                   1468: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
                   1469: word, and that the text interpreter executes the xt. Often, the terms
                   1470: @dfn{word} and @dfn{definition} are used interchangeably.
                   1471: @item
                   1472: If the text interpreter fails to find a match in the name dictionary, it
                   1473: tries to treat the group of characters as a number in the current number
                   1474: base (when you start up Forth, the current number base is base 10). If
                   1475: the group of characters legitimately represents a number, the text
                   1476: interpreter pushes the number onto a stack (we'll learn more about that
                   1477: in the next section).
                   1478: @end itemize
1.23      crook    1479: 
1.29      crook    1480: If the text interpreter is unable to do either of these things with any
                   1481: group of characters, it discards the group of characters and the rest of
                   1482: the line, then prints an error message. If the text interpreter reaches
                   1483: the end of the line without error, it prints the status message ``@code{ ok}''
                   1484: followed by carriage-return.
1.21      crook    1485: 
1.29      crook    1486: This is the simplest command we can give to the text interpreter:
1.23      crook    1487: 
                   1488: @example
1.30      anton    1489: @key{RET}  ok
1.23      crook    1490: @end example
1.21      crook    1491: 
1.29      crook    1492: The text interpreter did everything we asked it to do (nothing) without
                   1493: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
                   1494: command:
1.21      crook    1495: 
1.23      crook    1496: @example
1.30      anton    1497: @kbd{12 dup fred dup@key{RET}}
1.29      crook    1498: :1: Undefined word
                   1499: 12 dup fred dup
                   1500:        ^^^^
                   1501: $400D2BA8 Bounce
                   1502: $400DBDA8 no.extensions
1.23      crook    1503: @end example
1.21      crook    1504: 
1.29      crook    1505: When you press the carriage-return key, the text interpreter starts to
                   1506: work its way along the line:
1.21      crook    1507: 
1.29      crook    1508: @itemize @bullet
                   1509: @item
                   1510: When it gets to the space after the @code{2}, it takes the group of
                   1511: characters @code{12} and looks them up in the name
                   1512: dictionary@footnote{We can't tell if it found them or not, but assume
                   1513: for now that it did not}. There is no match for this group of characters
                   1514: in the name dictionary, so it tries to treat them as a number. It is
                   1515: able to do this successfully, so it puts the number, 12, ``on the stack''
                   1516: (whatever that means).
                   1517: @item
                   1518: The text interpreter resumes scanning the line and gets the next group
                   1519: of characters, @code{dup}. It looks it up in the name dictionary and
                   1520: (you'll have to take my word for this) finds it, and executes the word
                   1521: @code{dup} (whatever that means).
                   1522: @item
                   1523: Once again, the text interpreter resumes scanning the line and gets the
                   1524: group of characters @code{fred}. It looks them up in the name
                   1525: dictionary, but can't find them. It tries to treat them as a number, but
                   1526: they don't represent any legal number.
                   1527: @end itemize
1.21      crook    1528: 
1.29      crook    1529: At this point, the text interpreter gives up and prints an error
                   1530: message. The error message shows exactly how far the text interpreter
                   1531: got in processing the line. In particular, it shows that the text
                   1532: interpreter made no attempt to do anything with the final character
                   1533: group, @code{dup}, even though we have good reason to believe that the
                   1534: text interpreter would have no problem looking that word up and
                   1535: executing it a second time.
1.21      crook    1536: 
                   1537: 
1.29      crook    1538: @comment ----------------------------------------------
                   1539: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                   1540: @section Stacks, postfix notation and parameter passing
                   1541: @cindex text interpreter
                   1542: @cindex outer interpreter
1.21      crook    1543: 
1.29      crook    1544: In procedural programming languages (like C and Pascal), the
                   1545: building-block of programs is the @dfn{function} or @dfn{procedure}. These
                   1546: functions or procedures are called with @dfn{explicit parameters}. For
                   1547: example, in C we might write:
1.21      crook    1548: 
1.23      crook    1549: @example
1.29      crook    1550: total = total + new_volume(length,height,depth);
1.23      crook    1551: @end example
1.21      crook    1552: 
1.23      crook    1553: @noindent
1.29      crook    1554: where new_volume is a function-call to another piece of code, and total,
                   1555: length, height and depth are all variables. length, height and depth are
                   1556: parameters to the function-call.
1.21      crook    1557: 
1.29      crook    1558: In Forth, the equivalent of the function or procedure is the
                   1559: @dfn{definition} and parameters are implicitly passed between
                   1560: definitions using a shared stack that is visible to the
                   1561: programmer. Although Forth does support variables, the existence of the
                   1562: stack means that they are used far less often than in most other
                   1563: programming languages. When the text interpreter encounters a number, it
                   1564: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30      anton    1565: actual number is implementation-dependent ...) and the particular stack
1.29      crook    1566: used for any operation is implied unambiguously by the operation being
                   1567: performed. The stack used for all integer operations is called the @dfn{data
                   1568: stack} and, since this is the stack used most commonly, references to
                   1569: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    1570: 
1.29      crook    1571: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    1572: 
1.23      crook    1573: @example
1.30      anton    1574: @kbd{1 2 3@key{RET}}  ok
1.23      crook    1575: @end example
1.21      crook    1576: 
1.29      crook    1577: Then this instructs the text interpreter to placed three numbers on the
                   1578: (data) stack. An analogy for the behaviour of the stack is to take a
                   1579: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
                   1580: the table. The 3 was the last card onto the pile (``last-in'') and if
                   1581: you take a card off the pile then, unless you're prepared to fiddle a
                   1582: bit, the card that you take off will be the 3 (``first-out''). The
                   1583: number that will be first-out of the stack is called the @dfn{top of
                   1584: stack}, which
                   1585: @cindex TOS definition
                   1586: is often abbreviated to @dfn{TOS}.
1.21      crook    1587: 
1.29      crook    1588: To understand how parameters are passed in Forth, consider the
                   1589: behaviour of the definition @code{+} (pronounced ``plus''). You will not
                   1590: be surprised to learn that this definition performs addition. More
                   1591: precisely, it adds two number together and produces a result. Where does
                   1592: it get the two numbers from? It takes the top two numbers off the
                   1593: stack. Where does it place the result? On the stack. You can act-out the
                   1594: behaviour of @code{+} with your playing cards like this:
1.21      crook    1595: 
                   1596: @itemize @bullet
                   1597: @item
1.29      crook    1598: Pick up two cards from the stack on the table
1.21      crook    1599: @item
1.29      crook    1600: Stare at them intently and ask yourself ``what @i{is} the sum of these two
                   1601: numbers''
1.21      crook    1602: @item
1.29      crook    1603: Decide that the answer is 5
1.21      crook    1604: @item
1.29      crook    1605: Shuffle the two cards back into the pack and find a 5
1.21      crook    1606: @item
1.29      crook    1607: Put a 5 on the remaining ace that's on the table.
1.21      crook    1608: @end itemize
                   1609: 
1.29      crook    1610: If you don't have a pack of cards handy but you do have Forth running,
                   1611: you can use the definition @code{.s} to show the current state of the stack,
                   1612: without affecting the stack. Type:
1.21      crook    1613: 
                   1614: @example
1.30      anton    1615: @kbd{clearstack 1 2 3@key{RET}} ok
                   1616: @kbd{.s@key{RET}} <3> 1 2 3  ok
1.23      crook    1617: @end example
                   1618: 
1.29      crook    1619: The text interpreter looks up the word @code{clearstack} and executes
                   1620: it; it tidies up the stack and removes any entries that may have been
                   1621: left on it by earlier examples. The text interpreter pushes each of the
                   1622: three numbers in turn onto the stack. Finally, the text interpreter
                   1623: looks up the word @code{.s} and executes it. The effect of executing
                   1624: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
                   1625: followed by a list of all the items on the stack; the item on the far
                   1626: right-hand side is the TOS.
1.21      crook    1627: 
1.29      crook    1628: You can now type:
1.21      crook    1629: 
1.29      crook    1630: @example
1.30      anton    1631: @kbd{+ .s@key{RET}} <2> 1 5  ok
1.29      crook    1632: @end example
1.21      crook    1633: 
1.29      crook    1634: @noindent
                   1635: which is correct; there are now 2 items on the stack and the result of
                   1636: the addition is 5.
1.23      crook    1637: 
1.29      crook    1638: If you're playing with cards, try doing a second addition: pick up the
                   1639: two cards, work out that their sum is 6, shuffle them into the pack,
                   1640: look for a 6 and place that on the table. You now have just one item on
                   1641: the stack. What happens if you try to do a third addition? Pick up the
                   1642: first card, pick up the second card -- ah! There is no second card. This
                   1643: is called a @dfn{stack underflow} and consitutes an error. If you try to
                   1644: do the same thing with Forth it will report an error (probably a Stack
                   1645: Underflow or an Invalid Memory Address error).
1.23      crook    1646: 
1.29      crook    1647: The opposite situation to a stack underflow is a @dfn{stack overflow},
                   1648: which simply accepts that there is a finite amount of storage space
                   1649: reserved for the stack. To stretch the playing card analogy, if you had
                   1650: enough packs of cards and you piled the cards up on the table, you would
                   1651: eventually be unable to add another card; you'd hit the ceiling. Gforth
                   1652: allows you to set the maximum size of the stacks. In general, the only
                   1653: time that you will get a stack overflow is because a definition has a
                   1654: bug in it and is generating data on the stack uncontrollably.
1.23      crook    1655: 
1.29      crook    1656: There's one final use for the playing card analogy. If you model your
                   1657: stack using a pack of playing cards, the maximum number of items on
                   1658: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   1659: @i{value} of any item on the stack is 13 (the King). In fact, the only
                   1660: possible numbers are positive integer numbers 1 through 13; you can't
                   1661: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   1662: think about some of the cards, you can accommodate different
                   1663: numbers. For example, you could think of the Jack as representing 0,
                   1664: the Queen as representing -1 and the King as representing -2. Your
                   1665: *range* remains unchanged (you can still only represent a total of 13
                   1666: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    1667: 
1.29      crook    1668: In that analogy, the limit was the amount of information that a single
                   1669: stack entry could hold, and Forth has a similar limit. In Forth, the
                   1670: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
                   1671: implementation dependent and affects the maximum value that a stack
                   1672: entry can hold. A Standard Forth provides a cell size of at least
                   1673: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    1674: 
1.29      crook    1675: Forth does not do any type checking for you, so you are free to
                   1676: manipulate and combine stack items in any way you wish. A convenient way
                   1677: of treating stack items is as 2's complement signed integers, and that
                   1678: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    1679: 
1.29      crook    1680: @example
1.30      anton    1681: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
1.29      crook    1682: @end example
1.21      crook    1683: 
1.29      crook    1684: If you use numbers and definitions like @code{+} in order to turn Forth
                   1685: into a great big pocket calculator, you will realise that it's rather
                   1686: different from a normal calculator. Rather than typing 2 + 3 = you had
                   1687: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
                   1688: result). The terminology used to describe this difference is to say that
                   1689: your calculator uses @dfn{Infix Notation} (parameters and operators are
                   1690: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
                   1691: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    1692: 
1.29      crook    1693: Whilst postfix notation might look confusing to begin with, it has
                   1694: several important advantages:
1.21      crook    1695: 
1.23      crook    1696: @itemize @bullet
                   1697: @item
1.29      crook    1698: it is unambiguous
1.23      crook    1699: @item
1.29      crook    1700: it is more concise
1.23      crook    1701: @item
1.29      crook    1702: it fits naturally with a stack-based system
1.23      crook    1703: @end itemize
1.21      crook    1704: 
1.29      crook    1705: To examine these claims in more detail, consider these sums:
1.21      crook    1706: 
1.29      crook    1707: @example
                   1708: 6 + 5 * 4 =
                   1709: 4 * 5 + 6 =
                   1710: @end example
1.21      crook    1711: 
1.29      crook    1712: If you're just learning maths or your maths is very rusty, you will
                   1713: probably come up with the answer 44 for the first and 26 for the
                   1714: second. If you are a bit of a whizz at maths you will remember the
                   1715: @i{convention} that multiplication takes precendence over addition, and
                   1716: you'd come up with the answer 26 both times. To explain the answer 26
                   1717: to someone who got the answer 44, you'd probably rewrite the first sum
                   1718: like this:
1.21      crook    1719: 
1.29      crook    1720: @example
                   1721: 6 + (5 * 4) =
                   1722: @end example
1.21      crook    1723: 
1.29      crook    1724: If what you really wanted was to perform the addition before the
                   1725: multiplication, you would have to use parentheses to force it.
1.21      crook    1726: 
1.29      crook    1727: If you did the first two sums on a pocket calculator you would probably
                   1728: get the right answers, unless you were very cautious and entered them using
                   1729: these keystroke sequences:
1.21      crook    1730: 
1.29      crook    1731: 6 + 5 = * 4 =
                   1732: 4 * 5 = + 6 =
1.21      crook    1733: 
1.29      crook    1734: Postfix notation is unambiguous because the order that the operators
                   1735: are applied is always explicit; that also means that parentheses are
                   1736: never required. The operators are @i{active} (the act of quoting the
                   1737: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    1738: 
1.29      crook    1739: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   1740: equivalent ways:
1.26      crook    1741: 
                   1742: @example
1.29      crook    1743: 6 5 4 * +      or:
                   1744: 5 4 * 6 +
1.26      crook    1745: @end example
1.23      crook    1746: 
1.29      crook    1747: An important thing that you should notice about this notation is that
                   1748: the @i{order} of the numbers does not change; if you want to subtract
                   1749: 2 from 10 you type @code{10 2 -}.
1.1       anton    1750: 
1.29      crook    1751: The reason that Forth uses postfix notation is very simple to explain: it
                   1752: makes the implementation extremely simple, and it follows naturally from
                   1753: using the stack as a mechanism for passing parameters. Another way of
                   1754: thinking about this is to realise that all Forth definitions are
                   1755: @i{active}; they execute as they are encountered by the text
                   1756: interpreter. The result of this is that the syntax of Forth is trivially
                   1757: simple.
1.1       anton    1758: 
                   1759: 
                   1760: 
1.29      crook    1761: @comment ----------------------------------------------
                   1762: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   1763: @section Your first Forth definition
                   1764: @cindex first definition
1.1       anton    1765: 
1.29      crook    1766: Until now, the examples we've seen have been trivial; we've just been
                   1767: using Forth as a bigger-than-pocket calculator. Also, each calculation
                   1768: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
                   1769: again@footnote{That's not quite true. If you press the up-arrow key on
                   1770: your keyboard you should be able to scroll back to any earlier command,
                   1771: edit it and re-enter it.} In this section we'll see how to add new
                   1772: words to Forth's vocabulary.
1.1       anton    1773: 
1.29      crook    1774: The easiest way to create a new word is to use a @dfn{colon
                   1775: definition}. We'll define a few and try them out before worrying too
                   1776: much about how they work. Try typing in these examples; be careful to
                   1777: copy the spaces accurately:
1.1       anton    1778: 
1.29      crook    1779: @example
                   1780: : add-two 2 + . ;
                   1781: : greet ." Hello and welcome" ;
                   1782: : demo 5 add-two ;
                   1783: @end example
1.1       anton    1784: 
1.29      crook    1785: @noindent
                   1786: Now try them out:
1.1       anton    1787: 
1.29      crook    1788: @example
1.30      anton    1789: @kbd{greet@key{RET}} Hello and welcome  ok
                   1790: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
                   1791: @kbd{4 add-two@key{RET}} 6  ok
                   1792: @kbd{demo@key{RET}} 7  ok
                   1793: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
1.29      crook    1794: @end example
1.1       anton    1795: 
1.29      crook    1796: The first new thing that we've introduced here is the pair of words
                   1797: @code{:} and @code{;}. These are used to start and terminate a new
                   1798: definition, respectively. The first word after the @code{:} is the name
                   1799: for the new definition.
1.1       anton    1800: 
1.29      crook    1801: As you can see from the examples, a definition is built up of words that
                   1802: have already been defined; Forth makes no distinction between
                   1803: definitions that existed when you started the system up, and those that
                   1804: you define yourself.
1.1       anton    1805: 
1.29      crook    1806: The examples also introduce the words @code{.} (dot), @code{."}
                   1807: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
                   1808: the stack and displays it. It's like @code{.s} except that it only
                   1809: displays the top item of the stack and it is destructive; after it has
                   1810: executed, the number is no longer on the stack. There is always one
                   1811: space printed after the number, and no spaces before it. Dot-quote
                   1812: defines a string (a sequence of characters) that will be printed when
                   1813: the word is executed. The string can contain any printable characters
                   1814: except @code{"}. A @code{"} has a special function; it is not a Forth
                   1815: word but it acts as a delimiter (the way that delimiters work is
                   1816: described in the next section). Finally, @code{dup} duplicates the value
                   1817: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    1818: 
1.29      crook    1819: We already know that the text interpreter searches through the
                   1820: dictionary to locate names. If you've followed the examples earlier, you
                   1821: will already have a definition called @code{add-two}. Lets try modifying
                   1822: it by typing in a new definition:
1.1       anton    1823: 
1.29      crook    1824: @example
1.30      anton    1825: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
1.29      crook    1826: @end example
1.5       anton    1827: 
1.29      crook    1828: Forth recognised that we were defining a word that already exists, and
                   1829: printed a message to warn us of that fact. Let's try out the new
                   1830: definition:
1.5       anton    1831: 
1.29      crook    1832: @example
1.30      anton    1833: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
1.29      crook    1834: @end example
1.1       anton    1835: 
1.29      crook    1836: @noindent
                   1837: All that we've actually done here, though, is to create a new
                   1838: definition, with a particular name. The fact that there was already a
                   1839: definition with the same name did not make any difference to the way
                   1840: that the new definition was created (except that Forth printed a warning
                   1841: message). The old definition of add-two still exists (try @code{demo}
                   1842: again to see that this is true). Any new definition will use the new
                   1843: definition of @code{add-two}, but old definitions continue to use the
                   1844: version that already existed at the time that they were @code{compiled}.
1.1       anton    1845: 
1.29      crook    1846: Before you go on to the next section, try defining and redefining some
                   1847: words of your own.
1.1       anton    1848: 
1.29      crook    1849: @comment ----------------------------------------------
                   1850: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   1851: @section How does that work?
                   1852: @cindex parsing words
1.1       anton    1853: 
1.30      anton    1854: @c That's pretty deep (IMO way too deep) for an introduction. - anton
                   1855: 
                   1856: @c Is it a good idea to talk about the interpretation semantics of a
                   1857: @c number? We don't have an xt to go along with it. - anton
                   1858: 
                   1859: @c Now that I have eliminated execution semantics, I wonder if it would not
                   1860: @c be better to keep them (or add run-time semantics), to make it easier to
                   1861: @c explain what compilation semantics usually does. - anton
                   1862: 
1.44    ! crook    1863: @c nac-> I removed the term ``default compilation sematics'' from the
        !          1864: @c introductory chapter. Removing ``execution semantics'' was making
        !          1865: @c everything simpler to explain, then I think the use of this term made
        !          1866: @c everything more complex again. I replaced it with ``default
        !          1867: @c semantics'' (which is used elsewhere in the manual) by which I mean
        !          1868: @c ``a definition that has neither the immediate nor the compile-only
        !          1869: @c flag set''. I reworded big chunks of the ``how does that work''
        !          1870: @c section (and, unusually for me, I think I even made it shorter!).  See
        !          1871: @c what you think -- I know I have not addressed your primary concern
        !          1872: @c that it is too heavy-going for an introduction. From what I understood
        !          1873: @c of your course notes it looks as though they might be a good framework. 
        !          1874: @c Things that I've tried to capture here are some things that came as a
        !          1875: @c great revelation here when I first understood them. Also, I like the
        !          1876: @c fact that a very simple code example shows up almost all of the issues
        !          1877: @c that you need to understand to see how Forth works. That's unique and
        !          1878: @c worthwhile to emphasise.
        !          1879: 
1.29      crook    1880: Now we're going to take another look at the definition of @code{add-two}
                   1881: from the previous section. From our knowledge of the way that the text
                   1882: interpreter works, we would have expected this result when we tried to
                   1883: define @code{add-two}:
1.21      crook    1884: 
1.29      crook    1885: @example
1.44    ! crook    1886: @kbd{: add-two 2 + . ;@key{RET}}
1.29      crook    1887:   ^^^^^^^
                   1888: Error: Undefined word
                   1889: @end example
1.28      crook    1890: 
1.29      crook    1891: The reason that this didn't happen is bound up in the way that @code{:}
                   1892: works. The word @code{:} does two special things. The first special
                   1893: thing that it does prevents the text interpreter from ever seeing the
                   1894: characters @code{add-two}. The text interpreter uses a variable called
                   1895: @cindex modifying >IN
1.44    ! crook    1896: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29      crook    1897: input line. When it encounters the word @code{:} it behaves in exactly
                   1898: the same way as it does for any other word; it looks it up in the name
                   1899: dictionary, finds its xt and executes it. When @code{:} executes, it
                   1900: looks at the input buffer, finds the word @code{add-two} and advances the
                   1901: value of @code{>IN} to point past it. It then does some other stuff
                   1902: associated with creating the new definition (including creating an entry
                   1903: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   1904: completes, control returns to the text interpreter, which is oblivious
                   1905: to the fact that it has been tricked into ignoring part of the input
                   1906: line.
1.21      crook    1907: 
1.29      crook    1908: @cindex parsing words
                   1909: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   1910: prevent the text interpreter from acting on the whole of the input line
                   1911: -- are called @dfn{parsing words}.
1.21      crook    1912: 
1.29      crook    1913: @cindex @code{state} - effect on the text interpreter
                   1914: @cindex text interpreter - effect of state
                   1915: The second special thing that @code{:} does is change the value of a
                   1916: variable called @code{state}, which affects the way that the text
                   1917: interpreter behaves. When Gforth starts up, @code{state} has the value
                   1918: 0, and the text interpreter is said to be @dfn{interpreting}. During a
                   1919: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44    ! crook    1920: the text interpreter is said to be @dfn{compiling}.
        !          1921: 
        !          1922: In this example, the text interpreter is compiling when it processes the
        !          1923: string ``@code{2 + . ;}''. It still breaks the string down into
        !          1924: character sequences in the same way. However, instead of pushing the
        !          1925: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
        !          1926: into the definition of @code{add-two} that will make the number @code{2} get
        !          1927: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
        !          1928: the behaviours of @code{+} and @code{.} are also compiled into the
        !          1929: definition.
        !          1930: 
        !          1931: One category of words don't get compiled. These so-called @dfn{immediate
        !          1932: words} get executed (performed @i{now}) regardless of whether the text
        !          1933: interpreter is interpreting or compiling. The word @code{;} is an
        !          1934: immediate word. Rather than being compiled into the definition, it
        !          1935: executes. Its effect is to terminate the current definition, which
        !          1936: includes changing the value of @code{state} back to 0.
        !          1937: 
        !          1938: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
        !          1939: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
        !          1940: definition.
1.28      crook    1941: 
1.30      anton    1942: In Forth, every word or number can be described in terms of two
1.29      crook    1943: properties:
1.28      crook    1944: 
                   1945: @itemize @bullet
                   1946: @item
1.29      crook    1947: @cindex interpretation semantics
1.44    ! crook    1948: Its @dfn{interpretation semantics} describe how it will behave when the
        !          1949: text interpreter encounters it in @dfn{interpret} state. The
        !          1950: interpretation semantics of a word are represented by an @dfn{execution
        !          1951: token}.
1.28      crook    1952: @item
1.29      crook    1953: @cindex compilation semantics
1.44    ! crook    1954: Its @dfn{compilation semantics} describe how it will behave when the
        !          1955: text interpreter encounters it in @dfn{compile} state. The compilation
        !          1956: semantics of a word are represented in an implementation-dependent way;
        !          1957: Gforth uses a @dfn{compilation token}.
1.29      crook    1958: @end itemize
                   1959: 
                   1960: @noindent
                   1961: Numbers are always treated in a fixed way:
                   1962: 
                   1963: @itemize @bullet
1.28      crook    1964: @item
1.44    ! crook    1965: When the number is @dfn{interpreted}, its behaviour is to push the
        !          1966: number onto the stack.
1.28      crook    1967: @item
1.30      anton    1968: When the number is @dfn{compiled}, a piece of code is appended to the
                   1969: current definition that pushes the number when it runs. (In other words,
                   1970: the compilation semantics of a number are to postpone its interpretation
                   1971: semantics until the run-time of the definition that it is being compiled
                   1972: into.)
1.29      crook    1973: @end itemize
                   1974: 
1.44    ! crook    1975: Words don't behave in such a regular way, but most have @i{default
        !          1976: semantics} which means that they behave like this:
1.29      crook    1977: 
                   1978: @itemize @bullet
1.28      crook    1979: @item
1.30      anton    1980: The @dfn{interpretation semantics} of the word are to do something useful.
                   1981: @item
1.29      crook    1982: The @dfn{compilation semantics} of the word are to append its
1.30      anton    1983: @dfn{interpretation semantics} to the current definition (so that its
                   1984: run-time behaviour is to do something useful).
1.28      crook    1985: @end itemize
                   1986: 
1.30      anton    1987: @cindex immediate words
1.44    ! crook    1988: The actual behaviour of any particular word can be controlled by using
        !          1989: the words @code{immediate} and @code{compile-only} when the word is
        !          1990: defined. These words set flags in the name dictionary entry of the most
        !          1991: recently defined word, and these flags are retrieved by the text
        !          1992: interpreter when it finds the word in the name dictionary.
        !          1993: 
        !          1994: A word that is marked as @dfn{immediate} has compilation semantics that
        !          1995: are identical to its interpretation semantics. In other words, it
        !          1996: behaves like this:
1.29      crook    1997: 
                   1998: @itemize @bullet
                   1999: @item
1.30      anton    2000: The @dfn{interpretation semantics} of the word are to do something useful.
1.29      crook    2001: @item
1.30      anton    2002: The @dfn{compilation semantics} of the word are to do something useful
                   2003: (and actually the same thing); i.e., it is executed during compilation.
1.29      crook    2004: @end itemize
1.28      crook    2005: 
1.44    ! crook    2006: Marking a word as @dfn{compile-only} prohibits the text interpreter from
        !          2007: performing the interpretation semantics of the word directly; an attempt
        !          2008: to do so will generate an error. It is never necessary to use
        !          2009: @code{compile-only} (and it is not even part of ANS Forth, though it is
        !          2010: provided by many implementations) but it is good etiquette to apply it
        !          2011: to a word that will not behave correctly (and might have unexpected
        !          2012: side-effects) in interpret state. For example, it is only legal to use
        !          2013: the conditional word @code{IF} within a definition. If you forget this
        !          2014: and try to use it elsewhere, the fact that (in Gforth) it is marked as
        !          2015: @code{compile-only} allows the text interpreter to generate a helpful
        !          2016: error message rather than subjecting you to the consequences of your
        !          2017: folly.
        !          2018: 
1.29      crook    2019: This example shows the difference between an immediate and a
                   2020: non-immediate word:
1.28      crook    2021: 
1.29      crook    2022: @example
                   2023: : show-state state @@ . ;
                   2024: : show-state-now show-state ; immediate
                   2025: : word1 show-state ;
                   2026: : word2 show-state-now ;
1.28      crook    2027: @end example
1.23      crook    2028: 
1.29      crook    2029: The word @code{immediate} after the definition of @code{show-state-now}
                   2030: makes that word an immediate word. These definitions introduce a new
                   2031: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
                   2032: variable, and leaves it on the stack. Therefore, the behaviour of
                   2033: @code{show-state} is to print a number that represents the current value
                   2034: of @code{state}.
1.28      crook    2035: 
1.29      crook    2036: When you execute @code{word1}, it prints the number 0, indicating that
                   2037: the system is interpreting. When the text interpreter compiled the
                   2038: definition of @code{word1}, it encountered @code{show-state} whose
1.30      anton    2039: compilation semantics are to append its interpretation semantics to the
1.29      crook    2040: current definition. When you execute @code{word1}, it performs the
1.30      anton    2041: interpretation semantics of @code{show-state}.  At the time that @code{word1}
1.29      crook    2042: (and therefore @code{show-state}) are executed, the system is
                   2043: interpreting.
1.28      crook    2044: 
1.30      anton    2045: When you pressed @key{RET} after entering the definition of @code{word2},
1.29      crook    2046: you should have seen the number -1 printed, followed by ``@code{
                   2047: ok}''. When the text interpreter compiled the definition of
                   2048: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30      anton    2049: whose compilation semantics are therefore to perform its interpretation
1.29      crook    2050: semantics. It is executed straight away (even before the text
                   2051: interpreter has moved on to process another group of characters; the
                   2052: @code{;} in this example). The effect of executing it are to display the
                   2053: value of @code{state} @i{at the time that the definition of}
                   2054: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
                   2055: system is compiling at this time. If you execute @code{word2} it does
                   2056: nothing at all.
1.28      crook    2057: 
1.29      crook    2058: @cindex @code{."}, how it works
                   2059: Before leaving the subject of immediate words, consider the behaviour of
                   2060: @code{."} in the definition of @code{greet}, in the previous
                   2061: section. This word is both a parsing word and an immediate word. Notice
                   2062: that there is a space between @code{."} and the start of the text
                   2063: @code{Hello and welcome}, but that there is no space between the last
                   2064: letter of @code{welcome} and the @code{"} character. The reason for this
                   2065: is that @code{."} is a Forth word; it must have a space after it so that
                   2066: the text interpreter can identify it. The @code{"} is not a Forth word;
                   2067: it is a @dfn{delimiter}. The examples earlier show that, when the string
                   2068: is displayed, there is neither a space before the @code{H} nor after the
                   2069: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   2070: that @code{greet} is defined. When it executes, its behaviour is to
                   2071: search forward in the input line looking for the delimiter. When it
                   2072: finds the delimiter, it updates @code{>IN} to point past the
                   2073: delimiter. It also compiles some magic code into the definition of
                   2074: @code{greet}; the xt of a run-time routine that prints a text string. It
                   2075: compiles the string @code{Hello and welcome} into memory so that it is
                   2076: available to be printed later. When the text interpreter gains control,
                   2077: the next word it finds in the input stream is @code{;} and so it
                   2078: terminates the definition of @code{greet}.
1.28      crook    2079: 
                   2080: 
                   2081: @comment ----------------------------------------------
1.29      crook    2082: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   2083: @section Forth is written in Forth
                   2084: @cindex structure of Forth programs
                   2085: 
                   2086: When you start up a Forth compiler, a large number of definitions
                   2087: already exist. In Forth, you develop a new application using bottom-up
                   2088: programming techniques to create new definitions that are defined in
                   2089: terms of existing definitions. As you create each definition you can
                   2090: test and debug it interactively.
                   2091: 
                   2092: If you have tried out the examples in this section, you will probably
                   2093: have typed them in by hand; when you leave Gforth, your definitions will
                   2094: be lost. You can avoid this by using a text editor to enter Forth source
                   2095: code into a file, and then loading code from the file using
                   2096: @code{include} (@xref{Forth source files}). A Forth source file is
                   2097: processed by the text interpreter, just as though you had typed it in by
                   2098: hand@footnote{Actually, there are some subtle differences -- see
                   2099: @ref{The Text Interpreter}.}.
                   2100: 
                   2101: Gforth also supports the traditional Forth alternative to using text
                   2102: files for program entry (@xref{Blocks}).
1.28      crook    2103: 
1.29      crook    2104: In common with many, if not most, Forth compilers, most of Gforth is
                   2105: actually written in Forth. All of the @file{.fs} files in the
                   2106: installation directory@footnote{For example,
1.30      anton    2107: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29      crook    2108: study to see examples of Forth programming.
1.28      crook    2109: 
1.29      crook    2110: Gforth maintains a history file that records every line that you type to
                   2111: the text interpreter. This file is preserved between sessions, and is
                   2112: used to provide a command-line recall facility. If you enter long
                   2113: definitions by hand, you can use a text editor to paste them out of the
                   2114: history file into a Forth source file for reuse at a later time
                   2115: (@pxref{Command-line editing} for more information).
1.28      crook    2116: 
                   2117: 
                   2118: @comment ----------------------------------------------
1.29      crook    2119: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
                   2120: @section Review - elements of a Forth system
                   2121: @cindex elements of a Forth system
1.28      crook    2122: 
1.29      crook    2123: To summarise this chapter:
1.28      crook    2124: 
                   2125: @itemize @bullet
                   2126: @item
1.29      crook    2127: Forth programs use @dfn{factoring} to break a problem down into small
                   2128: fragments called @dfn{words} or @dfn{definitions}.
                   2129: @item
                   2130: Forth program development is an interactive process.
                   2131: @item
                   2132: The main command loop that accepts input, and controls both
                   2133: interpretation and compilation, is called the @dfn{text interpreter}
                   2134: (also known as the @dfn{outer interpreter}).
                   2135: @item
                   2136: Forth has a very simple syntax, consisting of words and numbers
                   2137: separated by spaces or carriage-return characters. Any additional syntax
                   2138: is imposed by @dfn{parsing words}.
                   2139: @item
                   2140: Forth uses a stack to pass parameters between words. As a result, it
                   2141: uses postfix notation.
                   2142: @item
                   2143: To use a word that has previously been defined, the text interpreter
                   2144: searches for the word in the @dfn{name dictionary}.
                   2145: @item
1.30      anton    2146: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28      crook    2147: @item
1.29      crook    2148: The text interpreter uses the value of @code{state} to select between
                   2149: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
                   2150: semantics} of a word that it encounters.
1.28      crook    2151: @item
1.30      anton    2152: The relationship between the @dfn{interpretation semantics} and
                   2153: @dfn{compilation semantics} for a word
1.29      crook    2154: depend upon the way in which the word was defined (for example, whether
                   2155: it is an @dfn{immediate} word).
1.28      crook    2156: @item
1.29      crook    2157: Forth definitions can be implemented in Forth (called @dfn{high-level
                   2158: definitions}) or in some other way (usually a lower-level language and
                   2159: as a result often called @dfn{low-level definitions}, @dfn{code
                   2160: definitions} or @dfn{primitives}).
1.28      crook    2161: @item
1.29      crook    2162: Many Forth systems are implemented mainly in Forth.
1.28      crook    2163: @end itemize
                   2164: 
                   2165: 
1.29      crook    2166: @comment ----------------------------------------------
                   2167: @node Where to go next,Exercises,Review - elements of a Forth system, Introduction
                   2168: @section Where To Go Next
                   2169: @cindex where to go next
1.28      crook    2170: 
1.29      crook    2171: Amazing as it may seem, if you have read (and understood) this far, you
                   2172: know almost all the fundamentals about the inner workings of a Forth
                   2173: system. You certainly know enough to be able to read and understand the
                   2174: rest of this manual and the ANS Forth document, to learn more about the
                   2175: facilities that Forth in general and Gforth in particular provide. Even
                   2176: scarier, you know almost enough to implement your own Forth system.
1.30      anton    2177: However, that's not a good idea just yet... better to try writing some
1.29      crook    2178: programs in Gforth.
1.28      crook    2179: 
1.29      crook    2180: Forth has such a rich vocabulary that it can be hard to know where to
                   2181: start in learning it. This section suggests a few sets of words that are
                   2182: enough to write small but useful programs. Use the word index in this
                   2183: document to learn more about each word, then try it out and try to write
                   2184: small definitions using it. Start by experimenting with these words:
1.28      crook    2185: 
                   2186: @itemize @bullet
                   2187: @item
1.29      crook    2188: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
                   2189: @item
                   2190: Comparison: @code{MIN MAX =}
                   2191: @item
                   2192: Logic: @code{AND OR XOR NOT}
                   2193: @item
                   2194: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    2195: @item
1.29      crook    2196: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    2197: @item
1.29      crook    2198: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    2199: @item
1.29      crook    2200: Defining words: @code{: ; CREATE}
1.28      crook    2201: @item
1.29      crook    2202: Memory allocation words: @code{ALLOT ,}
1.28      crook    2203: @item
1.29      crook    2204: Tools: @code{SEE WORDS .S MARKER}
                   2205: @end itemize
                   2206: 
                   2207: When you have mastered those, go on to:
                   2208: 
                   2209: @itemize @bullet
1.28      crook    2210: @item
1.29      crook    2211: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    2212: @item
1.29      crook    2213: Memory access: @code{@@ !}
1.28      crook    2214: @end itemize
1.23      crook    2215: 
1.29      crook    2216: When you have mastered these, there's nothing for it but to read through
                   2217: the whole of this manual and find out what you've missed.
                   2218: 
                   2219: @comment ----------------------------------------------
                   2220: @node Exercises, ,Where to go next, Introduction
                   2221: @section Exercises
                   2222: @cindex exercises
                   2223: 
                   2224: TODO: provide a set of programming excercises linked into the stuff done
                   2225: already and into other sections of the manual. Provide solutions to all
                   2226: the exercises in a .fs file in the distribution.
                   2227: 
                   2228: @c Get some inspiration from Starting Forth and Kelly&Spies.
                   2229: 
                   2230: @c excercises:
                   2231: @c 1. take inches and convert to feet and inches.
                   2232: @c 2. take temperature and convert from fahrenheight to celcius;
                   2233: @c    may need to care about symmetric vs floored??
                   2234: @c 3. take input line and do character substitution
                   2235: @c    to encipher or decipher
                   2236: @c 4. as above but work on a file for in and out
                   2237: @c 5. take input line and convert to pig-latin 
                   2238: @c
                   2239: @c thing of sets of things to exercise then come up with
                   2240: @c problems that need those things.
                   2241: 
                   2242: 
1.26      crook    2243: @c ******************************************************************
1.29      crook    2244: @node Words, Error messages, Introduction, Top
1.1       anton    2245: @chapter Forth Words
1.26      crook    2246: @cindex words
1.1       anton    2247: 
                   2248: @menu
                   2249: * Notation::                    
1.21      crook    2250: * Comments::
                   2251: * Boolean Flags::
1.1       anton    2252: * Arithmetic::                  
                   2253: * Stack Manipulation::          
1.5       anton    2254: * Memory::                      
1.1       anton    2255: * Control Structures::          
                   2256: * Defining Words::              
1.21      crook    2257: * The Text Interpreter::
1.12      anton    2258: * Tokens for Words::            
1.21      crook    2259: * Word Lists::                   
                   2260: * Environmental Queries::
1.12      anton    2261: * Files::                       
                   2262: * Blocks::                      
                   2263: * Other I/O::                   
                   2264: * Programming Tools::           
                   2265: * Assembler and Code Words::    
                   2266: * Threading Words::             
1.26      crook    2267: * Locals::                      
                   2268: * Structures::                  
                   2269: * Object-oriented Forth::       
1.21      crook    2270: * Passing Commands to the OS::
                   2271: * Miscellaneous Words::
1.1       anton    2272: @end menu
                   2273: 
1.21      crook    2274: @node Notation, Comments, Words, Words
1.1       anton    2275: @section Notation
                   2276: @cindex notation of glossary entries
                   2277: @cindex format of glossary entries
                   2278: @cindex glossary notation format
                   2279: @cindex word glossary entry format
                   2280: 
                   2281: The Forth words are described in this section in the glossary notation
                   2282: that has become a de-facto standard for Forth texts, i.e.,
                   2283: 
                   2284: @format
1.29      crook    2285: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    2286: @end format
1.29      crook    2287: @i{Description}
1.1       anton    2288: 
                   2289: @table @var
                   2290: @item word
1.28      crook    2291: The name of the word.
1.1       anton    2292: 
                   2293: @item Stack effect
                   2294: @cindex stack effect
1.29      crook    2295: The stack effect is written in the notation @code{@i{before} --
                   2296: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    2297: stack entries before and after the execution of the word. The rest of
                   2298: the stack is not touched by the word. The top of stack is rightmost,
                   2299: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   2300: uses a separate floating point stack, but a unified stack
1.29      crook    2301: notation. Also, return stack effects are not shown in @i{stack
                   2302: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    2303: the type and/or the function of the item. See below for a discussion of
                   2304: the types.
                   2305: 
                   2306: All words have two stack effects: A compile-time stack effect and a
                   2307: run-time stack effect. The compile-time stack-effect of most words is
1.29      crook    2308: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    2309: this standard behaviour, or the word does other unusual things at
                   2310: compile time, both stack effects are shown; otherwise only the run-time
                   2311: stack effect is shown.
                   2312: 
                   2313: @cindex pronounciation of words
                   2314: @item pronunciation
                   2315: How the word is pronounced.
                   2316: 
                   2317: @cindex wordset
                   2318: @item wordset
1.21      crook    2319: The ANS Forth standard is divided into several word sets. A standard
                   2320: system need not support all of them. Therefore, in theory, the fewer
                   2321: word sets your program uses the more portable it will be. However, we
                   2322: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    2323: all word sets. Words that are not defined in ANS Forth have
1.21      crook    2324: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    2325: describes words that will work in future releases of Gforth;
                   2326: @code{gforth-internal} words are more volatile. Environmental query
                   2327: strings are also displayed like words; you can recognize them by the
1.21      crook    2328: @code{environment} in the word set field.
1.1       anton    2329: 
                   2330: @item Description
                   2331: A description of the behaviour of the word.
                   2332: @end table
                   2333: 
                   2334: @cindex types of stack items
                   2335: @cindex stack item types
                   2336: The type of a stack item is specified by the character(s) the name
                   2337: starts with:
                   2338: 
                   2339: @table @code
                   2340: @item f
                   2341: @cindex @code{f}, stack item type
                   2342: Boolean flags, i.e. @code{false} or @code{true}.
                   2343: @item c
                   2344: @cindex @code{c}, stack item type
                   2345: Char
                   2346: @item w
                   2347: @cindex @code{w}, stack item type
                   2348: Cell, can contain an integer or an address
                   2349: @item n
                   2350: @cindex @code{n}, stack item type
                   2351: signed integer
                   2352: @item u
                   2353: @cindex @code{u}, stack item type
                   2354: unsigned integer
                   2355: @item d
                   2356: @cindex @code{d}, stack item type
                   2357: double sized signed integer
                   2358: @item ud
                   2359: @cindex @code{ud}, stack item type
                   2360: double sized unsigned integer
                   2361: @item r
                   2362: @cindex @code{r}, stack item type
                   2363: Float (on the FP stack)
1.21      crook    2364: @item a-
1.1       anton    2365: @cindex @code{a_}, stack item type
                   2366: Cell-aligned address
1.21      crook    2367: @item c-
1.1       anton    2368: @cindex @code{c_}, stack item type
                   2369: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    2370: @item f-
1.1       anton    2371: @cindex @code{f_}, stack item type
                   2372: Float-aligned address
1.21      crook    2373: @item df-
1.1       anton    2374: @cindex @code{df_}, stack item type
                   2375: Address aligned for IEEE double precision float
1.21      crook    2376: @item sf-
1.1       anton    2377: @cindex @code{sf_}, stack item type
                   2378: Address aligned for IEEE single precision float
                   2379: @item xt
                   2380: @cindex @code{xt}, stack item type
                   2381: Execution token, same size as Cell
                   2382: @item wid
                   2383: @cindex @code{wid}, stack item type
1.21      crook    2384: Word list ID, same size as Cell
1.1       anton    2385: @item f83name
                   2386: @cindex @code{f83name}, stack item type
                   2387: Pointer to a name structure
                   2388: @item "
                   2389: @cindex @code{"}, stack item type
1.12      anton    2390: string in the input stream (not on the stack). The terminating character
                   2391: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    2392: quotes.
                   2393: @end table
                   2394: 
1.21      crook    2395: @node Comments, Boolean Flags, Notation, Words
                   2396: @section Comments
1.26      crook    2397: @cindex comments
1.21      crook    2398: 
1.29      crook    2399: Forth supports two styles of comment; the traditional @i{in-line} comment,
                   2400: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    2401: 
1.44    ! crook    2402: 
1.23      crook    2403: doc-(
1.21      crook    2404: doc-\
1.23      crook    2405: doc-\G
1.21      crook    2406: 
1.44    ! crook    2407: 
1.21      crook    2408: @node Boolean Flags, Arithmetic, Comments, Words
                   2409: @section Boolean Flags
1.26      crook    2410: @cindex Boolean flags
1.21      crook    2411: 
                   2412: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   2413: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    2414: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29      crook    2415: a cell that has @i{any} bit set as @code{true}.
1.21      crook    2416: 
1.44    ! crook    2417: 
1.21      crook    2418: doc-true
                   2419: doc-false
1.29      crook    2420: doc-on
                   2421: doc-off
1.21      crook    2422: 
1.44    ! crook    2423: 
1.21      crook    2424: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    2425: @section Arithmetic
                   2426: @cindex arithmetic words
                   2427: 
                   2428: @cindex division with potentially negative operands
                   2429: Forth arithmetic is not checked, i.e., you will not hear about integer
                   2430: overflow on addition or multiplication, you may hear about division by
                   2431: zero if you are lucky. The operator is written after the operands, but
                   2432: the operands are still in the original order. I.e., the infix @code{2-1}
                   2433: corresponds to @code{2 1 -}. Forth offers a variety of division
                   2434: operators. If you perform division with potentially negative operands,
                   2435: you do not want to use @code{/} or @code{/mod} with its undefined
                   2436: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   2437: former, @pxref{Mixed precision}).
1.26      crook    2438: @comment TODO discuss the different division forms and the std approach
1.1       anton    2439: 
                   2440: @menu
                   2441: * Single precision::            
                   2442: * Bitwise operations::          
1.21      crook    2443: * Double precision::            Double-cell integer arithmetic
                   2444: * Numeric comparison::
1.29      crook    2445: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    2446: * Floating Point::              
                   2447: @end menu
                   2448: 
                   2449: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
                   2450: @subsection Single precision
                   2451: @cindex single precision arithmetic words
                   2452: 
1.21      crook    2453: By default, numbers in Forth are single-precision integers that are 1
1.26      crook    2454: cell in size. They can be signed or unsigned, depending upon how you
1.21      crook    2455: treat them. @xref{Number Conversion} for the rules used by the text
                   2456: interpreter for recognising single-precision integers.
                   2457: 
1.44    ! crook    2458: 
1.1       anton    2459: doc-+
1.21      crook    2460: doc-1+
1.1       anton    2461: doc--
1.21      crook    2462: doc-1-
1.1       anton    2463: doc-*
                   2464: doc-/
                   2465: doc-mod
                   2466: doc-/mod
                   2467: doc-negate
                   2468: doc-abs
                   2469: doc-min
                   2470: doc-max
1.21      crook    2471: doc-d>s
1.27      crook    2472: doc-floored
1.1       anton    2473: 
1.44    ! crook    2474: 
1.21      crook    2475: @node Bitwise operations, Double precision, Single precision, Arithmetic
1.1       anton    2476: @subsection Bitwise operations
                   2477: @cindex bitwise operation words
                   2478: 
1.44    ! crook    2479: 
1.1       anton    2480: doc-and
                   2481: doc-or
                   2482: doc-xor
                   2483: doc-invert
1.21      crook    2484: doc-lshift
                   2485: doc-rshift
1.1       anton    2486: doc-2*
1.21      crook    2487: doc-d2*
1.1       anton    2488: doc-2/
1.21      crook    2489: doc-d2/
                   2490: 
1.44    ! crook    2491: 
1.21      crook    2492: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
                   2493: @subsection Double precision
                   2494: @cindex double precision arithmetic words
                   2495: 
                   2496: @xref{Number Conversion} for the rules used by the text interpreter for
                   2497: recognising double-precision integers.
                   2498: 
                   2499: A double precision number is represented by a cell pair, with the most
1.31      anton    2500: significant cell at the TOS. It is trivial to convert an unsigned
1.26      crook    2501: single to an (unsigned) double; simply push a @code{0} onto the
                   2502: TOS. Since numbers are represented by Gforth using 2's complement
                   2503: arithmetic, converting a signed single to a (signed) double requires
1.31      anton    2504: sign-extension across the most significant cell. This can be achieved
1.26      crook    2505: using @code{s>d}. The moral of the story is that you cannot convert a
                   2506: number without knowing whether it represents an unsigned or a
                   2507: signed number.
1.21      crook    2508: 
1.44    ! crook    2509: 
1.21      crook    2510: doc-s>d
                   2511: doc-d+
                   2512: doc-d-
                   2513: doc-dnegate
                   2514: doc-dabs
                   2515: doc-dmin
                   2516: doc-dmax
                   2517: 
1.44    ! crook    2518: 
1.21      crook    2519: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
                   2520: @subsection Numeric comparison
                   2521: @cindex numeric comparison words
                   2522: 
1.44    ! crook    2523: 
1.28      crook    2524: doc-<
                   2525: doc-<=
                   2526: doc-<>
                   2527: doc-=
                   2528: doc->
                   2529: doc->=
                   2530: 
1.21      crook    2531: doc-0<
1.23      crook    2532: doc-0<=
1.21      crook    2533: doc-0<>
                   2534: doc-0=
1.23      crook    2535: doc-0>
                   2536: doc-0>=
1.28      crook    2537: 
                   2538: doc-u<
                   2539: doc-u<=
1.44    ! crook    2540: @c u<> and u= exist but are the same as <> and =
1.31      anton    2541: @c doc-u<>
                   2542: @c doc-u=
1.28      crook    2543: doc-u>
                   2544: doc-u>=
                   2545: 
                   2546: doc-within
                   2547: 
                   2548: doc-d<
                   2549: doc-d<=
                   2550: doc-d<>
                   2551: doc-d=
                   2552: doc-d>
                   2553: doc-d>=
1.23      crook    2554: 
1.21      crook    2555: doc-d0<
1.23      crook    2556: doc-d0<=
                   2557: doc-d0<>
1.21      crook    2558: doc-d0=
1.23      crook    2559: doc-d0>
                   2560: doc-d0>=
                   2561: 
1.21      crook    2562: doc-du<
1.28      crook    2563: doc-du<=
1.44    ! crook    2564: @c du<> and du= exist but are the same as d<> and d=
1.31      anton    2565: @c doc-du<>
                   2566: @c doc-du=
1.28      crook    2567: doc-du>
                   2568: doc-du>=
1.1       anton    2569: 
1.44    ! crook    2570: 
1.21      crook    2571: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    2572: @subsection Mixed precision
                   2573: @cindex mixed precision arithmetic words
                   2574: 
1.44    ! crook    2575: 
1.1       anton    2576: doc-m+
                   2577: doc-*/
                   2578: doc-*/mod
                   2579: doc-m*
                   2580: doc-um*
                   2581: doc-m*/
                   2582: doc-um/mod
                   2583: doc-fm/mod
                   2584: doc-sm/rem
                   2585: 
1.44    ! crook    2586: 
1.21      crook    2587: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    2588: @subsection Floating Point
                   2589: @cindex floating point arithmetic words
                   2590: 
1.21      crook    2591: @xref{Number Conversion} for the rules used by the text interpreter for
                   2592: recognising floating-point numbers.
1.1       anton    2593: 
1.32      anton    2594: Gforth has a separate floating point
1.26      crook    2595: stack, but the documentation uses the unified notation.
1.1       anton    2596: 
                   2597: @cindex floating-point arithmetic, pitfalls
                   2598: Floating point numbers have a number of unpleasant surprises for the
                   2599: unwary (e.g., floating point addition is not associative) and even a few
                   2600: for the wary. You should not use them unless you know what you are doing
                   2601: or you don't care that the results you get are totally bogus. If you
                   2602: want to learn about the problems of floating point numbers (and how to
                   2603: avoid them), you might start with @cite{David Goldberg, What Every
                   2604: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
1.17      anton    2605: Computing Surveys 23(1):5@minus{}48, March 1991}
                   2606: (@url{http://www.validgh.com/goldberg/paper.ps}).
1.1       anton    2607: 
1.44    ! crook    2608: 
1.21      crook    2609: doc-d>f
                   2610: doc-f>d
1.1       anton    2611: doc-f+
                   2612: doc-f-
                   2613: doc-f*
                   2614: doc-f/
                   2615: doc-fnegate
                   2616: doc-fabs
                   2617: doc-fmax
                   2618: doc-fmin
                   2619: doc-floor
                   2620: doc-fround
                   2621: doc-f**
                   2622: doc-fsqrt
                   2623: doc-fexp
                   2624: doc-fexpm1
                   2625: doc-fln
                   2626: doc-flnp1
                   2627: doc-flog
                   2628: doc-falog
1.32      anton    2629: doc-f2*
                   2630: doc-f2/
                   2631: doc-1/f
                   2632: doc-precision
                   2633: doc-set-precision
                   2634: 
                   2635: @cindex angles in trigonometric operations
                   2636: @cindex trigonometric operations
                   2637: Angles in floating point operations are given in radians (a full circle
                   2638: has 2 pi radians).
                   2639: 
1.1       anton    2640: doc-fsin
                   2641: doc-fcos
                   2642: doc-fsincos
                   2643: doc-ftan
                   2644: doc-fasin
                   2645: doc-facos
                   2646: doc-fatan
                   2647: doc-fatan2
                   2648: doc-fsinh
                   2649: doc-fcosh
                   2650: doc-ftanh
                   2651: doc-fasinh
                   2652: doc-facosh
                   2653: doc-fatanh
1.21      crook    2654: doc-pi
1.28      crook    2655: 
1.32      anton    2656: @cindex equality of floats
                   2657: @cindex floating-point comparisons
1.31      anton    2658: One particular problem with floating-point arithmetic is that comparison
                   2659: for equality often fails when you would expect it to succeed.  For this
                   2660: reason approximate equality is often preferred (but you still have to
                   2661: know what you are doing).  The comparison words are:
                   2662: 
                   2663: doc-f~rel
                   2664: doc-f~abs
                   2665: doc-f=
                   2666: doc-f~
                   2667: doc-f<>
                   2668: 
                   2669: doc-f<
                   2670: doc-f<=
                   2671: doc-f>
                   2672: doc-f>=
                   2673: 
1.21      crook    2674: doc-f0<
1.28      crook    2675: doc-f0<=
                   2676: doc-f0<>
1.21      crook    2677: doc-f0=
1.28      crook    2678: doc-f0>
                   2679: doc-f0>=
                   2680: 
1.1       anton    2681: 
                   2682: @node Stack Manipulation, Memory, Arithmetic, Words
                   2683: @section Stack Manipulation
                   2684: @cindex stack manipulation words
                   2685: 
                   2686: @cindex floating-point stack in the standard
1.21      crook    2687: Gforth maintains a number of separate stacks:
                   2688: 
1.29      crook    2689: @cindex data stack
                   2690: @cindex parameter stack
1.21      crook    2691: @itemize @bullet
                   2692: @item
1.29      crook    2693: A data stack (also known as the @dfn{parameter stack}) -- for
                   2694: characters, cells, addresses, and double cells.
1.21      crook    2695: 
1.29      crook    2696: @cindex floating-point stack
1.21      crook    2697: @item
1.44    ! crook    2698: A floating point stack -- for holding floating point (FP) numbers.
1.21      crook    2699: 
1.29      crook    2700: @cindex return stack
1.21      crook    2701: @item
1.44    ! crook    2702: A return stack -- for holding the return addresses of colon
1.32      anton    2703: definitions and other (non-FP) data.
1.21      crook    2704: 
1.29      crook    2705: @cindex locals stack
1.21      crook    2706: @item
1.44    ! crook    2707: A locals stack -- for holding local variables.
1.21      crook    2708: @end itemize
                   2709: 
1.1       anton    2710: @menu
                   2711: * Data stack::                  
                   2712: * Floating point stack::        
                   2713: * Return stack::                
                   2714: * Locals stack::                
                   2715: * Stack pointer manipulation::  
                   2716: @end menu
                   2717: 
                   2718: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   2719: @subsection Data stack
                   2720: @cindex data stack manipulation words
                   2721: @cindex stack manipulations words, data stack
                   2722: 
1.44    ! crook    2723: 
1.1       anton    2724: doc-drop
                   2725: doc-nip
                   2726: doc-dup
                   2727: doc-over
                   2728: doc-tuck
                   2729: doc-swap
1.21      crook    2730: doc-pick
1.1       anton    2731: doc-rot
                   2732: doc--rot
                   2733: doc-?dup
                   2734: doc-roll
                   2735: doc-2drop
                   2736: doc-2nip
                   2737: doc-2dup
                   2738: doc-2over
                   2739: doc-2tuck
                   2740: doc-2swap
                   2741: doc-2rot
                   2742: 
1.44    ! crook    2743: 
1.1       anton    2744: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   2745: @subsection Floating point stack
                   2746: @cindex floating-point stack manipulation words
                   2747: @cindex stack manipulation words, floating-point stack
                   2748: 
1.32      anton    2749: Whilst every sane Forth has a separate floating-point stack, it is not
                   2750: strictly required; an ANS Forth system could theoretically keep
                   2751: floating-point numbers on the data stack. As an additional difficulty,
                   2752: you don't know how many cells a floating-point number takes. It is
                   2753: reportedly possible to write words in a way that they work also for a
                   2754: unified stack model, but we do not recommend trying it. Instead, just
                   2755: say that your program has an environmental dependency on a separate
                   2756: floating-point stack.
                   2757: 
                   2758: doc-floating-stack
                   2759: 
1.1       anton    2760: doc-fdrop
                   2761: doc-fnip
                   2762: doc-fdup
                   2763: doc-fover
                   2764: doc-ftuck
                   2765: doc-fswap
1.21      crook    2766: doc-fpick
1.1       anton    2767: doc-frot
                   2768: 
1.44    ! crook    2769: 
1.1       anton    2770: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   2771: @subsection Return stack
                   2772: @cindex return stack manipulation words
                   2773: @cindex stack manipulation words, return stack
                   2774: 
1.32      anton    2775: @cindex return stack and locals
                   2776: @cindex locals and return stack
                   2777: A Forth system is allowed to keep local variables on the
                   2778: return stack. This is reasonable, as local variables usually eliminate
                   2779: the need to use the return stack explicitly. So, if you want to produce
                   2780: a standard compliant program and you are using local variables in a
                   2781: word, forget about return stack manipulations in that word (refer to the
                   2782: standard document for the exact rules).
                   2783: 
1.1       anton    2784: doc->r
                   2785: doc-r>
                   2786: doc-r@
                   2787: doc-rdrop
                   2788: doc-2>r
                   2789: doc-2r>
                   2790: doc-2r@
                   2791: doc-2rdrop
                   2792: 
1.44    ! crook    2793: 
1.1       anton    2794: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   2795: @subsection Locals stack
                   2796: 
1.26      crook    2797: @comment TODO
1.21      crook    2798: 
1.1       anton    2799: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   2800: @subsection Stack pointer manipulation
                   2801: @cindex stack pointer manipulation words
                   2802: 
1.44    ! crook    2803: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21      crook    2804: doc-sp0
1.1       anton    2805: doc-sp@
                   2806: doc-sp!
1.21      crook    2807: doc-fp0
1.1       anton    2808: doc-fp@
                   2809: doc-fp!
1.21      crook    2810: doc-rp0
1.1       anton    2811: doc-rp@
                   2812: doc-rp!
1.21      crook    2813: doc-lp0
1.1       anton    2814: doc-lp@
                   2815: doc-lp!
                   2816: 
1.44    ! crook    2817: 
1.1       anton    2818: @node Memory, Control Structures, Stack Manipulation, Words
                   2819: @section Memory
1.26      crook    2820: @cindex memory words
1.1       anton    2821: 
1.32      anton    2822: @menu
                   2823: * Memory model::                
                   2824: * Dictionary allocation::       
                   2825: * Heap Allocation::             
                   2826: * Memory Access::               
                   2827: * Address arithmetic::          
                   2828: * Memory Blocks::               
                   2829: @end menu
                   2830: 
                   2831: @node Memory model, Dictionary allocation, Memory, Memory
                   2832: @subsection ANS Forth and Gforth memory models
                   2833: 
                   2834: @c The ANS Forth description is a mess (e.g., is the heap part of
                   2835: @c the dictionary?), so let's not stick to closely with it.
                   2836: 
                   2837: ANS Forth considers a Forth system as consisting of several memories, of
                   2838: which only @dfn{data space} is managed and accessible with the memory
                   2839: words.  Memory not necessarily in data space includes the stacks, the
                   2840: code (called code space) and the headers (called name space). In Gforth
                   2841: everything is in data space, but the code for the primitives is usually
                   2842: read-only.
                   2843: 
                   2844: Data space is divided into a number of areas: The (data space portion of
                   2845: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
                   2846: refer to the search data structure embodied in word lists and headers,
                   2847: because it is used for looking up names, just as you would in a
                   2848: conventional dictionary.}, the heap, and a number of system-allocated
                   2849: buffers.
                   2850: 
                   2851: In ANS Forth data space is also divided into contiguous regions.  You
                   2852: can only use address arithmetic within a contiguous region, not between
                   2853: them.  Usually each allocation gives you one contiguous region, but the
1.33      anton    2854: dictionary allocation words have additional rules (@pxref{Dictionary
1.32      anton    2855: allocation}).
                   2856: 
                   2857: Gforth provides one big address space, and address arithmetic can be
                   2858: performed between any addresses. However, in the dictionary headers or
                   2859: code are interleaved with data, so almost the only contiguous data space
                   2860: regions there are those described by ANS Forth as contiguous; but you
                   2861: can be sure that the dictionary is allocated towards increasing
                   2862: addresses even between contiguous regions.  The memory order of
                   2863: allocations in the heap is platform-dependent (and possibly different
                   2864: from one run to the next).
                   2865: 
                   2866: @subsubsection ANS Forth dictionary details
                   2867: 
                   2868: This section is just informative, you can skip it if you are in a hurry.
1.27      crook    2869: 
1.29      crook    2870: When you create a colon definition, the text interpreter compiles the
1.32      anton    2871: code for the definition into the code space and compiles the name
                   2872: of the definition into the header space, together with other
1.27      crook    2873: information about the definition (such as its execution token).
                   2874: 
1.44    ! crook    2875: When you create a variable, the execution of @code{Variable} will
1.32      anton    2876: compile some code, assign one cell in data space, and compile the name
                   2877: of the variable into the header space.
1.27      crook    2878: 
                   2879: @cindex memory regions - relationship between them
                   2880: ANS Forth does not specify the relationship between the three memory
                   2881: regions, and specifies that a Standard program must not access code or
                   2882: data space directly -- it may only access data space directly. In
                   2883: addition, the Standard defines what relationships you may and may not
                   2884: rely on when allocating regions in data space. These constraints are
                   2885: simply a reflection of the many diverse techniques that are used to
                   2886: implement Forth systems; understanding and following the requirements of
                   2887: the Standard allows you to write portable programs -- programs that run
                   2888: in the same way on any of these diverse systems. Another way of looking
                   2889: at this is to say that ANS Forth was designed to permit compliant Forth
                   2890: systems to be implemented in many diverse ways.
                   2891: 
                   2892: @cindex memory regions - how they are assigned
1.29      crook    2893: Here are some examples of ways in which name, code and data spaces
                   2894: might be assigned in different Forth implementations:
1.27      crook    2895: 
                   2896: @itemize @bullet
                   2897: @item
                   2898: For a Forth system that runs from RAM under a general-purpose operating
                   2899: system, it can be convenient to interleave name, code and data spaces in
                   2900: a single contiguous memory region. This organisation can be
                   2901: memory-efficient (for example, because the relationship between the name
1.32      anton    2902: dictionary entry and the associated code space entry can be
1.27      crook    2903: implicit, rather than requiring an explicit memory pointer to reference
1.32      anton    2904: from the header space and the code space). This is the
1.27      crook    2905: organisation used by Gforth, as this example@footnote{The addresses
                   2906: in the example have been truncated to fit it onto the page, and the
                   2907: addresses and data shown will not match the output from your system} shows:
                   2908: @example
                   2909: hex
                   2910: variable fred 123456 fred !
                   2911: variable jim abcd jim !
                   2912: : foo + / - ;
                   2913: ' fred 10 - 50 dump 
                   2914: ..80: 5C 46 0E 40  84 66 72 65 - 64 20 20 20  20 20 20 20  \F.@.fred       
                   2915: ..90: D0 9B 04 08  00 00 00 00 - 56 34 12 00  80 46 0E 40  ........V4...F.@
                   2916: ..A0: 83 6A 69 6D  20 20 20 20 - D0 9B 04 08  00 00 00 00  .jim    ........
                   2917: ..B0: CD AB 00 00  9C 46 0E 40 - 83 66 6F 6F  20 20 20 20  .....F.@.foo    
                   2918: ..C0: 80 9B 04 08  00 00 00 00 - E4 2E 05 08  0C 2F 05 08  ............./..
                   2919: @end example
                   2920: 
                   2921: @item
                   2922: For a high-performance system running on a modern RISC processor with a
                   2923: modified Harvard architecture (one that has a unified main memory but
                   2924: separate instruction and data caches), it is desirable to separate
                   2925: processor instructions from processor data. This encourages a high cache
1.32      anton    2926: density and therefore a high cache hit rate. The Forth code space
1.27      crook    2927: is not necessarily made up entirely of processor instructions; its
                   2928: nature is dependent upon the Forth implementation. 
                   2929: 
                   2930: @item
                   2931: A Forth compiler that runs on a segmented 8086 processor could be
                   2932: designed to interleave the name, code and data spaces within a single
                   2933: 64Kbyte segment. A more common implementation choice is to use a
                   2934: separate 64Kbyte segment for each region, which provides more memory
                   2935: overall but provides an address map in which only the data space is
                   2936: accessible.
                   2937: 
                   2938: @item
                   2939: Microprocessors exist that run Forth (or many of the primitives required
                   2940: to implement the Forth virtual machine efficiently) directly. On these
                   2941: processors, the relationship between name, code and data spaces may be
1.32      anton    2942: imposed as a side-effect of the architecture of the processor.
1.27      crook    2943: 
                   2944: @item
                   2945: A Forth compiler that executes from ROM on an embedded system needs its
                   2946: data space separated from the name and code spaces so that the data
                   2947: space can be mapped to a RAM area.
                   2948: 
                   2949: @item 
                   2950: A Forth compiler that runs on an embedded system may have a requirement
                   2951: for a small memory footprint. On such a system it can be useful to
1.32      anton    2952: separate the header space from the data and code spaces; once the
                   2953: application has been compiled, the header space is no longer
1.27      crook    2954: required@footnote{more strictly speaking, most applications can be
1.32      anton    2955: designed so that this is the case}. The header space can be deleted
1.29      crook    2956: entirely, or could be stored in memory on a remote @i{host} system for
1.27      crook    2957: debug and development purposes. In the latter case, the compiler running
1.29      crook    2958: on the @i{target} system could implement a protocol across a
1.32      anton    2959: communication link that would allow it to interrogate the header space.
1.27      crook    2960: @end itemize
                   2961: 
1.32      anton    2962: @node Dictionary allocation, Heap Allocation, Memory model, Memory
                   2963: @subsection Dictionary allocation
1.27      crook    2964: @cindex reserving data space
                   2965: @cindex data space - reserving some
                   2966: 
1.32      anton    2967: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
                   2968: you want to deallocate X, you also deallocate everything
                   2969: allocated after X.
                   2970: 
                   2971: The allocations using the words below are contiguous and grow the region
                   2972: towards increasing addresses.  Other words that allocate dictionary
                   2973: memory of any kind (i.e., defining words including @code{:noname}) end
                   2974: the contiguous region and start a new one.
                   2975: 
                   2976: In ANS Forth only @code{create}d words are guaranteed to produce an
                   2977: address that is the start of the following contiguous region.  In
                   2978: particular, the cell allocated by @code{variable} is not guaranteed to
                   2979: be contiguous with following @code{allot}ed memory.
                   2980: 
                   2981: You can deallocate memory by using @code{allot} with a negative argument
                   2982: (with some restrictions, see @code{allot}). For larger deallocations use
                   2983: @code{marker}.
1.27      crook    2984: 
1.29      crook    2985: 
1.27      crook    2986: doc-here
                   2987: doc-unused
                   2988: doc-allot
                   2989: doc-c,
1.29      crook    2990: doc-f,
1.27      crook    2991: doc-,
                   2992: doc-2,
1.29      crook    2993: @cindex user space
                   2994: doc-udp
                   2995: doc-uallot
1.27      crook    2996: 
1.32      anton    2997: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
                   2998: course you should allocate memory in an aligned way, too. I.e., before
                   2999: allocating allocating a cell, @code{here} must be cell-aligned, etc.
                   3000: The words below align @code{here} if it is not already.  Basically it is
                   3001: only already aligned for a type, if the last allocation was a multiple
                   3002: of the size of this type and if @code{here} was aligned for this type
                   3003: before.
                   3004: 
                   3005: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
                   3006: ANS Forth (@code{maxalign}ed in Gforth).
                   3007: 
                   3008: doc-align
                   3009: doc-falign
                   3010: doc-sfalign
                   3011: doc-dfalign
                   3012: doc-maxalign
                   3013: doc-cfalign
                   3014: 
                   3015: 
                   3016: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
                   3017: @subsection Heap allocation
                   3018: @cindex heap allocation
                   3019: @cindex dynamic allocation of memory
                   3020: @cindex memory-allocation word set
                   3021: 
                   3022: Heap allocation supports deallocation of allocated memory in any
                   3023: order. Dictionary allocation is not affected by it (i.e., it does not
                   3024: end a contiguous region). In Gforth, these words are implemented using
                   3025: the standard C library calls malloc(), free() and resize().
                   3026: 
                   3027: doc-allocate
                   3028: doc-free
                   3029: doc-resize
                   3030: 
1.27      crook    3031: 
1.32      anton    3032: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1       anton    3033: @subsection Memory Access
                   3034: @cindex memory access words
                   3035: 
1.44    ! crook    3036: 
1.1       anton    3037: doc-@
                   3038: doc-!
                   3039: doc-+!
                   3040: doc-c@
                   3041: doc-c!
                   3042: doc-2@
                   3043: doc-2!
                   3044: doc-f@
                   3045: doc-f!
                   3046: doc-sf@
                   3047: doc-sf!
                   3048: doc-df@
                   3049: doc-df!
                   3050: 
1.32      anton    3051: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   3052: @subsection Address arithmetic
1.1       anton    3053: @cindex address arithmetic words
                   3054: 
1.32      anton    3055: Address arithmetic is the foundation on which data structures like
                   3056: arrays, records (@pxref{Structures}) and objects (@pxref{Object-oriented
                   3057: Forth}) are built.
                   3058: 
1.1       anton    3059: ANS Forth does not specify the sizes of the data types. Instead, it
                   3060: offers a number of words for computing sizes and doing address
1.29      crook    3061: arithmetic. Address arithmetic is performed in terms of address units
                   3062: (aus); on most systems the address unit is one byte. Note that a
                   3063: character may have more than one au, so @code{chars} is no noop (on
                   3064: systems where it is a noop, it compiles to nothing).
1.1       anton    3065: 
                   3066: @cindex alignment of addresses for types
                   3067: ANS Forth also defines words for aligning addresses for specific
                   3068: types. Many computers require that accesses to specific data types
                   3069: must only occur at specific addresses; e.g., that cells may only be
                   3070: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   3071: accesses, it can usually perform aligned accesses faster. 
                   3072: 
                   3073: For the performance-conscious: alignment operations are usually only
                   3074: necessary during the definition of a data structure, not during the
                   3075: (more frequent) accesses to it.
                   3076: 
                   3077: ANS Forth defines no words for character-aligning addresses. This is not
                   3078: an oversight, but reflects the fact that addresses that are not
                   3079: char-aligned have no use in the standard and therefore will not be
                   3080: created.
                   3081: 
                   3082: @cindex @code{CREATE} and alignment
1.29      crook    3083: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    3084: are cell-aligned; in addition, Gforth guarantees that these addresses
                   3085: are aligned for all purposes.
                   3086: 
1.26      crook    3087: Note that the ANS Forth word @code{char} has nothing to do with address
                   3088: arithmetic.
1.1       anton    3089: 
1.44    ! crook    3090: 
1.1       anton    3091: doc-chars
                   3092: doc-char+
                   3093: doc-cells
                   3094: doc-cell+
                   3095: doc-cell
                   3096: doc-aligned
                   3097: doc-floats
                   3098: doc-float+
                   3099: doc-float
                   3100: doc-faligned
                   3101: doc-sfloats
                   3102: doc-sfloat+
                   3103: doc-sfaligned
                   3104: doc-dfloats
                   3105: doc-dfloat+
                   3106: doc-dfaligned
                   3107: doc-maxaligned
                   3108: doc-cfaligned
                   3109: doc-address-unit-bits
                   3110: 
1.44    ! crook    3111: 
1.32      anton    3112: @node Memory Blocks,  , Address arithmetic, Memory
1.1       anton    3113: @subsection Memory Blocks
                   3114: @cindex memory block words
1.27      crook    3115: @cindex character strings - moving and copying
                   3116: 
                   3117: Memory blocks often represent character strings; @xref{String Formats}
                   3118: for ways of storing character strings in memory. @xref{Displaying
                   3119: characters and strings} for other string-processing words.
1.1       anton    3120: 
1.32      anton    3121: Some of these words work on address units. Others work on character
                   3122: units (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
                   3123: address. Choose the correct operation depending upon your data type.
1.21      crook    3124: 
                   3125: When copying characters between overlapping memory regions, choose
                   3126: carefully between @code{cmove} and @code{cmove>}.
                   3127: 
1.29      crook    3128: You can only use any of these words @i{portably} to access data space.
1.21      crook    3129: 
1.27      crook    3130: @comment TODO - think the naming of the arguments is wrong for move
1.29      crook    3131: @comment well, really it seems to be the Standard that's wrong; it
                   3132: @comment describes MOVE as a word that requires a CELL-aligned source
                   3133: @comment and destination address but a xtranfer count that need not
                   3134: @comment be a multiple of CELL.
1.44    ! crook    3135: 
1.1       anton    3136: doc-move
                   3137: doc-erase
                   3138: doc-cmove
                   3139: doc-cmove>
                   3140: doc-fill
                   3141: doc-blank
1.21      crook    3142: doc-compare
                   3143: doc-search
1.27      crook    3144: doc--trailing
                   3145: doc-/string
                   3146: 
1.44    ! crook    3147: 
1.27      crook    3148: @comment TODO examples
                   3149: 
1.1       anton    3150: 
1.26      crook    3151: @node Control Structures, Defining Words, Memory, Words
1.1       anton    3152: @section Control Structures
                   3153: @cindex control structures
                   3154: 
1.33      anton    3155: Control structures in Forth cannot be used interpretively, only in a
                   3156: colon definition@footnote{To be precise, they have no interpretation
                   3157: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
                   3158: not like this limitation, but have not seen a satisfying way around it
                   3159: yet, although many schemes have been proposed.
1.1       anton    3160: 
                   3161: @menu
1.33      anton    3162: * Selection::                   IF ... ELSE ... ENDIF
                   3163: * Simple Loops::                BEGIN ...
1.29      crook    3164: * Counted Loops::               DO
                   3165: * Arbitrary control structures::
                   3166: * Calls and returns::
1.1       anton    3167: * Exception Handling::          
                   3168: @end menu
                   3169: 
                   3170: @node Selection, Simple Loops, Control Structures, Control Structures
                   3171: @subsection Selection
                   3172: @cindex selection control structures
                   3173: @cindex control structures for selection
                   3174: 
1.33      anton    3175: @c what's the purpose of all these @i? Maybe we should define a macro
                   3176: @c so we can produce logical markup.  - anton
                   3177: 
1.44    ! crook    3178: @c nac-> When I started working on the manual, a mixture of @i and @var
        !          3179: @c were used inconsistently in code examples and \Glossary entries. These
        !          3180: @c two behave differently in info format so I decided to standardize on @i.
        !          3181: @c Logical markup would be better but texi isn't really upto it, and
        !          3182: @c texi2html just ignores macros.
        !          3183: 
1.1       anton    3184: @cindex @code{IF} control structure
                   3185: @example
1.29      crook    3186: @i{flag}
1.1       anton    3187: IF
1.29      crook    3188:   @i{code}
1.1       anton    3189: ENDIF
                   3190: @end example
1.21      crook    3191: @noindent
1.33      anton    3192: 
1.44    ! crook    3193: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
        !          3194: with any bit set represents truth) @i{code} is executed.
1.33      anton    3195: 
1.1       anton    3196: @example
1.29      crook    3197: @i{flag}
1.1       anton    3198: IF
1.29      crook    3199:   @i{code1}
1.1       anton    3200: ELSE
1.29      crook    3201:   @i{code2}
1.1       anton    3202: ENDIF
                   3203: @end example
                   3204: 
1.44    ! crook    3205: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
        !          3206: executed.
1.33      anton    3207: 
1.1       anton    3208: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   3209: standard, and @code{ENDIF} is not, although it is quite popular. We
                   3210: recommend using @code{ENDIF}, because it is less confusing for people
                   3211: who also know other languages (and is not prone to reinforcing negative
                   3212: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   3213: system that only supplies @code{THEN} is simple:
                   3214: @example
1.21      crook    3215: : ENDIF   POSTPONE THEN ; immediate
1.1       anton    3216: @end example
                   3217: 
                   3218: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   3219: (adv.)}  has the following meanings:
                   3220: @quotation
                   3221: ... 2b: following next after in order ... 3d: as a necessary consequence
                   3222: (if you were there, then you saw them).
                   3223: @end quotation
                   3224: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   3225: and many other programming languages has the meaning 3d.]
                   3226: 
1.21      crook    3227: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    3228: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    3229: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    3230: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   3231: @file{compat/control.fs}.
                   3232: 
                   3233: @cindex @code{CASE} control structure
                   3234: @example
1.29      crook    3235: @i{n}
1.1       anton    3236: CASE
1.29      crook    3237:   @i{n1} OF @i{code1} ENDOF
                   3238:   @i{n2} OF @i{code2} ENDOF
1.1       anton    3239:   @dots{}
                   3240: ENDCASE
                   3241: @end example
                   3242: 
1.29      crook    3243: Executes the first @i{codei}, where the @i{ni} is equal to
                   3244: @i{n}. A default case can be added by simply writing the code after
                   3245: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
1.1       anton    3246: but must not consume it.
                   3247: 
                   3248: @node Simple Loops, Counted Loops, Selection, Control Structures
                   3249: @subsection Simple Loops
                   3250: @cindex simple loops
                   3251: @cindex loops without count 
                   3252: 
                   3253: @cindex @code{WHILE} loop
                   3254: @example
                   3255: BEGIN
1.29      crook    3256:   @i{code1}
                   3257:   @i{flag}
1.1       anton    3258: WHILE
1.29      crook    3259:   @i{code2}
1.1       anton    3260: REPEAT
                   3261: @end example
                   3262: 
1.29      crook    3263: @i{code1} is executed and @i{flag} is computed. If it is true,
                   3264: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    3265: false, execution continues after the @code{REPEAT}.
                   3266: 
                   3267: @cindex @code{UNTIL} loop
                   3268: @example
                   3269: BEGIN
1.29      crook    3270:   @i{code}
                   3271:   @i{flag}
1.1       anton    3272: UNTIL
                   3273: @end example
                   3274: 
1.29      crook    3275: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    3276: 
                   3277: @cindex endless loop
                   3278: @cindex loops, endless
                   3279: @example
                   3280: BEGIN
1.29      crook    3281:   @i{code}
1.1       anton    3282: AGAIN
                   3283: @end example
                   3284: 
                   3285: This is an endless loop.
                   3286: 
                   3287: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   3288: @subsection Counted Loops
                   3289: @cindex counted loops
                   3290: @cindex loops, counted
                   3291: @cindex @code{DO} loops
                   3292: 
                   3293: The basic counted loop is:
                   3294: @example
1.29      crook    3295: @i{limit} @i{start}
1.1       anton    3296: ?DO
1.29      crook    3297:   @i{body}
1.1       anton    3298: LOOP
                   3299: @end example
                   3300: 
1.29      crook    3301: This performs one iteration for every integer, starting from @i{start}
                   3302: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    3303: accessed with @code{i}. For example, the loop:
1.1       anton    3304: @example
                   3305: 10 0 ?DO
                   3306:   i .
                   3307: LOOP
                   3308: @end example
1.21      crook    3309: @noindent
                   3310: prints @code{0 1 2 3 4 5 6 7 8 9}
                   3311: 
1.1       anton    3312: The index of the innermost loop can be accessed with @code{i}, the index
                   3313: of the next loop with @code{j}, and the index of the third loop with
                   3314: @code{k}.
                   3315: 
1.44    ! crook    3316: 
1.1       anton    3317: doc-i
                   3318: doc-j
                   3319: doc-k
                   3320: 
1.44    ! crook    3321: 
1.1       anton    3322: The loop control data are kept on the return stack, so there are some
1.21      crook    3323: restrictions on mixing return stack accesses and counted loop words. In
                   3324: particuler, if you put values on the return stack outside the loop, you
                   3325: cannot read them inside the loop@footnote{well, not in a way that is
                   3326: portable.}. If you put values on the return stack within a loop, you
                   3327: have to remove them before the end of the loop and before accessing the
                   3328: index of the loop.
1.1       anton    3329: 
                   3330: There are several variations on the counted loop:
                   3331: 
1.21      crook    3332: @itemize @bullet
                   3333: @item
                   3334: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   3335: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   3336: 
                   3337: @example
                   3338: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   3339: @end example
                   3340: prints @code{0 1 2 3}
                   3341: 
1.1       anton    3342: 
1.21      crook    3343: @item
                   3344: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   3345: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   3346: return stack so @code{EXIT} can get to its return address. For example:
                   3347: 
                   3348: @example
                   3349: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   3350: @end example
                   3351: prints @code{0 1 2 3}
                   3352: 
                   3353: 
                   3354: @item
1.29      crook    3355: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    3356: (and @code{LOOP} iterates until they become equal by wrap-around
                   3357: arithmetic). This behaviour is usually not what you want. Therefore,
                   3358: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29      crook    3359: @code{?DO}), which do not enter the loop if @i{start} is greater than
                   3360: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    3361: unsigned loop parameters.
                   3362: 
1.21      crook    3363: @item
                   3364: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   3365: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   3366: if you know that the loop is entered in any case. Such knowledge tends
                   3367: to become invalid during maintenance of a program, and then the
                   3368: @code{DO} will make trouble.
                   3369: 
                   3370: @item
1.29      crook    3371: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
                   3372: index by @i{n} instead of by 1. The loop is terminated when the border
                   3373: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    3374: 
1.21      crook    3375: @example
                   3376: 4 0 +DO  i .  2 +LOOP
                   3377: @end example
                   3378: @noindent
                   3379: prints @code{0 2}
                   3380: 
                   3381: @example
                   3382: 4 1 +DO  i .  2 +LOOP
                   3383: @end example
                   3384: @noindent
                   3385: prints @code{1 3}
1.1       anton    3386: 
                   3387: 
                   3388: @cindex negative increment for counted loops
                   3389: @cindex counted loops with negative increment
1.29      crook    3390: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    3391: 
1.21      crook    3392: @example
                   3393: -1 0 ?DO  i .  -1 +LOOP
                   3394: @end example
                   3395: @noindent
                   3396: prints @code{0 -1}
1.1       anton    3397: 
1.21      crook    3398: @example
                   3399: 0 0 ?DO  i .  -1 +LOOP
                   3400: @end example
                   3401: prints nothing.
1.1       anton    3402: 
1.29      crook    3403: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
                   3404: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
                   3405: index by @i{u} each iteration. The loop is terminated when the border
                   3406: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    3407: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   3408: 
1.21      crook    3409: @example
                   3410: -2 0 -DO  i .  1 -LOOP
                   3411: @end example
                   3412: @noindent
                   3413: prints @code{0 -1}
1.1       anton    3414: 
1.21      crook    3415: @example
                   3416: -1 0 -DO  i .  1 -LOOP
                   3417: @end example
                   3418: @noindent
                   3419: prints @code{0}
                   3420: 
                   3421: @example
                   3422: 0 0 -DO  i .  1 -LOOP
                   3423: @end example
                   3424: @noindent
                   3425: prints nothing.
1.1       anton    3426: 
1.21      crook    3427: @end itemize
1.1       anton    3428: 
                   3429: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    3430: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   3431: for these words that uses only standard words is provided in
                   3432: @file{compat/loops.fs}.
1.1       anton    3433: 
                   3434: 
                   3435: @cindex @code{FOR} loops
1.26      crook    3436: Another counted loop is:
1.1       anton    3437: @example
1.29      crook    3438: @i{n}
1.1       anton    3439: FOR
1.29      crook    3440:   @i{body}
1.1       anton    3441: NEXT
                   3442: @end example
                   3443: This is the preferred loop of native code compiler writers who are too
1.26      crook    3444: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29      crook    3445: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
                   3446: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    3447: Forth systems may behave differently, even if they support @code{FOR}
                   3448: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    3449: 
                   3450: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   3451: @subsection Arbitrary control structures
                   3452: @cindex control structures, user-defined
                   3453: 
                   3454: @cindex control-flow stack
                   3455: ANS Forth permits and supports using control structures in a non-nested
                   3456: way. Information about incomplete control structures is stored on the
                   3457: control-flow stack. This stack may be implemented on the Forth data
                   3458: stack, and this is what we have done in Gforth.
                   3459: 
                   3460: @cindex @code{orig}, control-flow stack item
                   3461: @cindex @code{dest}, control-flow stack item
                   3462: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   3463: entry represents a backward branch target. A few words are the basis for
                   3464: building any control structure possible (except control structures that
                   3465: need storage, like calls, coroutines, and backtracking).
                   3466: 
1.44    ! crook    3467: 
1.1       anton    3468: doc-if
                   3469: doc-ahead
                   3470: doc-then
                   3471: doc-begin
                   3472: doc-until
                   3473: doc-again
                   3474: doc-cs-pick
                   3475: doc-cs-roll
                   3476: 
1.44    ! crook    3477: 
1.21      crook    3478: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   3479: manipulate the control-flow stack in a portable way. Without them, you
                   3480: would need to know how many stack items are occupied by a control-flow
                   3481: entry (many systems use one cell. In Gforth they currently take three,
                   3482: but this may change in the future).
                   3483: 
1.1       anton    3484: Some standard control structure words are built from these words:
                   3485: 
1.44    ! crook    3486: 
1.1       anton    3487: doc-else
                   3488: doc-while
                   3489: doc-repeat
                   3490: 
1.44    ! crook    3491: 
        !          3492: @noindent
1.1       anton    3493: Gforth adds some more control-structure words:
                   3494: 
1.44    ! crook    3495: 
1.1       anton    3496: doc-endif
                   3497: doc-?dup-if
                   3498: doc-?dup-0=-if
                   3499: 
1.44    ! crook    3500: 
        !          3501: @noindent
1.1       anton    3502: Counted loop words constitute a separate group of words:
                   3503: 
1.44    ! crook    3504: 
1.1       anton    3505: doc-?do
                   3506: doc-+do
                   3507: doc-u+do
                   3508: doc--do
                   3509: doc-u-do
                   3510: doc-do
                   3511: doc-for
                   3512: doc-loop
                   3513: doc-+loop
                   3514: doc--loop
                   3515: doc-next
                   3516: doc-leave
                   3517: doc-?leave
                   3518: doc-unloop
                   3519: doc-done
                   3520: 
1.44    ! crook    3521: 
1.21      crook    3522: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   3523: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    3524: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   3525: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   3526: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   3527: resolved (by using one of the loop-ending words or @code{DONE}).
                   3528: 
1.44    ! crook    3529: @noindent
1.26      crook    3530: Another group of control structure words are:
1.1       anton    3531: 
1.44    ! crook    3532: 
1.1       anton    3533: doc-case
                   3534: doc-endcase
                   3535: doc-of
                   3536: doc-endof
                   3537: 
1.44    ! crook    3538: 
1.21      crook    3539: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   3540: @code{CS-ROLL}.
1.1       anton    3541: 
                   3542: @subsubsection Programming Style
                   3543: 
                   3544: In order to ensure readability we recommend that you do not create
                   3545: arbitrary control structures directly, but define new control structure
                   3546: words for the control structure you want and use these words in your
1.26      crook    3547: program. For example, instead of writing:
1.1       anton    3548: 
                   3549: @example
1.26      crook    3550: BEGIN
1.1       anton    3551:   ...
1.26      crook    3552: IF [ 1 CS-ROLL ]
1.1       anton    3553:   ...
1.26      crook    3554: AGAIN THEN
1.1       anton    3555: @end example
                   3556: 
1.21      crook    3557: @noindent
1.1       anton    3558: we recommend defining control structure words, e.g.,
                   3559: 
                   3560: @example
1.26      crook    3561: : WHILE ( DEST -- ORIG DEST )
                   3562:  POSTPONE IF
                   3563:  1 CS-ROLL ; immediate
                   3564: 
                   3565: : REPEAT ( orig dest -- )
                   3566:  POSTPONE AGAIN
                   3567:  POSTPONE THEN ; immediate
1.1       anton    3568: @end example
                   3569: 
1.21      crook    3570: @noindent
1.1       anton    3571: and then using these to create the control structure:
                   3572: 
                   3573: @example
1.26      crook    3574: BEGIN
1.1       anton    3575:   ...
1.26      crook    3576: WHILE
1.1       anton    3577:   ...
1.26      crook    3578: REPEAT
1.1       anton    3579: @end example
                   3580: 
                   3581: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   3582: @code{WHILE} are predefined, so in this example it would not be
                   3583: necessary to define them.
                   3584: 
                   3585: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   3586: @subsection Calls and returns
                   3587: @cindex calling a definition
                   3588: @cindex returning from a definition
                   3589: 
1.3       anton    3590: @cindex recursive definitions
                   3591: A definition can be called simply be writing the name of the definition
1.26      crook    3592: to be called. Normally a definition is invisible during its own
1.3       anton    3593: definition. If you want to write a directly recursive definition, you
1.26      crook    3594: can use @code{recursive} to make the current definition visible, or
                   3595: @code{recurse} to call the current definition directly.
1.3       anton    3596: 
1.44    ! crook    3597: 
1.3       anton    3598: doc-recursive
                   3599: doc-recurse
                   3600: 
1.44    ! crook    3601: 
1.21      crook    3602: @comment TODO add example of the two recursion methods
1.12      anton    3603: @quotation
                   3604: @progstyle
                   3605: I prefer using @code{recursive} to @code{recurse}, because calling the
                   3606: definition by name is more descriptive (if the name is well-chosen) than
                   3607: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   3608: implementation, it is much better to read (and think) ``now sort the
                   3609: partitions'' than to read ``now do a recursive call''.
                   3610: @end quotation
1.3       anton    3611: 
1.29      crook    3612: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    3613: 
                   3614: @example
1.28      crook    3615: Defer foo
1.3       anton    3616: 
                   3617: : bar ( ... -- ... )
                   3618:  ... foo ... ;
                   3619: 
                   3620: :noname ( ... -- ... )
                   3621:  ... bar ... ;
                   3622: IS foo
                   3623: @end example
                   3624: 
1.44    ! crook    3625: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33      anton    3626: 
1.26      crook    3627: The current definition returns control to the calling definition when
1.33      anton    3628: the end of the definition is reached or @code{EXIT} is encountered.
1.1       anton    3629: 
                   3630: doc-exit
                   3631: doc-;s
                   3632: 
1.44    ! crook    3633: 
1.1       anton    3634: @node Exception Handling,  , Calls and returns, Control Structures
                   3635: @subsection Exception Handling
1.26      crook    3636: @cindex exceptions
1.1       anton    3637: 
1.26      crook    3638: If your program detects a fatal error condition, the simplest action
                   3639: that it can take is to @code{quit}. This resets the return stack and
                   3640: restarts the text interpreter, but does not print any error message.
1.21      crook    3641: 
1.26      crook    3642: The next stage in severity is to execute @code{abort}, which has the
                   3643: same effect as @code{quit}, with the addition that it resets the data
                   3644: stack.
1.1       anton    3645: 
1.26      crook    3646: A slightly more sophisticated approach is use use @code{abort"}, which
                   3647: compiles a string to be used as an error message and does a conditional
                   3648: @code{abort} at run-time. For example:
1.1       anton    3649: 
1.26      crook    3650: @example
1.30      anton    3651: @kbd{: checker abort" That flag was true" ." A false flag" ;@key{RET}}  ok
                   3652: @kbd{0 checker@key{RET}} A false flag ok
                   3653: @kbd{1 checker@key{RET}}
1.26      crook    3654: :1: That flag was true
                   3655: 1 checker
                   3656:   ^^^^^^^
                   3657: $400D1648 throw 
                   3658: $400E4660
                   3659: @end example
1.1       anton    3660: 
1.26      crook    3661: These simple techniques allow a program to react to a fatal error
                   3662: condition, but they are not exactly user-friendly. The ANS Forth
                   3663: Exception word set provides the pair of words @code{throw} and
                   3664: @code{catch}, which can be used to provide sophisticated error-handling.
1.1       anton    3665: 
1.26      crook    3666: @code{catch} has a similar behaviour to @code{execute}, in that it takes
1.29      crook    3667: an @i{xt} as a parameter and starts execution of the xt. However,
1.26      crook    3668: before passing control to the xt, @code{catch} pushes an
1.29      crook    3669: @dfn{exception frame} onto the @dfn{exception stack}. This exception
1.26      crook    3670: frame is used to restore the system to a known state if a detected error
                   3671: occurs during the execution of the xt. A typical way to use @code{catch}
                   3672: would be:
1.1       anton    3673: 
1.26      crook    3674: @example
                   3675: ... ['] foo catch IF ...
                   3676: @end example
1.1       anton    3677: 
1.33      anton    3678: @c TOS is undefined. - anton
1.44    ! crook    3679: 
        !          3680: @c nac-> TODO -- I need to look at this example again.
        !          3681: 
1.26      crook    3682: Whilst @code{foo} executes, it can call other words to any level of
                   3683: nesting, as usual.  If @code{foo} (and all the words that it calls)
1.33      anton    3684: execute successfully, control will ultimately pass to the word following
                   3685: the @code{catch}, and there will be a 0 at TOS.  However, if any word
                   3686: detects an error, it can terminate the execution of @code{foo} by
                   3687: pushing a non-zero error code onto the stack and then performing a
                   3688: @code{throw}. The execution of @code{throw} will pass control to the
                   3689: word following the @code{catch}, but this time the TOS will hold the
                   3690: error code. Therefore, the @code{IF} in the example can be used to
                   3691: determine whether @code{foo} executed successfully.
1.1       anton    3692: 
1.26      crook    3693: This simple example shows how you can use @code{throw} and @code{catch}
                   3694: to ``take over'' exception handling from the system:
1.1       anton    3695: @example
1.26      crook    3696: : my-div ['] / catch if ." DIVIDE ERROR" else ." OK.. " . then ;
1.1       anton    3697: @end example
                   3698: 
1.26      crook    3699: The next example is more sophisticated and shows a multi-level
                   3700: @code{throw} and @code{catch}. To understand this example, start at the
                   3701: definition of @code{top-level} and work backwards:
                   3702: 
1.1       anton    3703: @example
1.26      crook    3704: : lowest-level ( -- c )
                   3705:     key dup 27 = if
1.44    ! crook    3706:         1 throw \ ESCAPE key pressed
1.26      crook    3707:     else
1.44    ! crook    3708:         ." lowest-level successful" CR
1.26      crook    3709:     then
                   3710: ;
                   3711: 
                   3712: : lower-level ( -- c )
                   3713:     lowest-level
                   3714:     \ at this level consider a CTRL-U to be a fatal error
                   3715:     dup 21 = if \ CTRL-U
1.44    ! crook    3716:         2 throw
1.26      crook    3717:     else
1.44    ! crook    3718:         ." lower-level successful" CR
1.26      crook    3719:     then
                   3720: ;
                   3721: 
                   3722: : low-level ( -- c )
                   3723:     ['] lower-level catch
                   3724:     ?dup if
1.44    ! crook    3725:         \ error occurred - do we recognise it?
        !          3726:         dup 1 = if
        !          3727:             \ ESCAPE key pressed.. pretend it was an E
        !          3728:             [char] E
        !          3729:         else throw \ propogate the error upwards
        !          3730:         then
1.26      crook    3731:     then
                   3732:     ." low-level successfull" CR
                   3733: ;
                   3734: 
                   3735: : top-level ( -- )
                   3736:     CR ['] low-level catch \ CATCH is used like EXECUTE
                   3737:     ?dup if \ error occurred..
1.44    ! crook    3738:         ." Error " . ." occurred - contact your supplier"
1.26      crook    3739:     else
1.44    ! crook    3740:         ." The '" emit ." ' key was pressed" CR
1.26      crook    3741:     then
                   3742: ;
1.1       anton    3743: @end example
                   3744: 
1.26      crook    3745: The ANS Forth document assigns @code{throw} codes thus:
1.1       anton    3746: 
1.26      crook    3747: @itemize @bullet
                   3748: @item
                   3749: codes in the range -1 -- -255 are reserved to be assigned by the
                   3750: Standard. Assignments for codes in the range -1 -- -58 are currently
                   3751: documented in the Standard. In particular, @code{-1 throw} is equivalent
                   3752: to @code{abort} and @code{-2 throw} is equivalent to @code{abort"}.
                   3753: @item
                   3754: codes in the range -256 -- -4095 are reserved to be assigned by the system.
                   3755: @item
                   3756: all other codes may be assigned by programs.
                   3757: @end itemize
1.1       anton    3758: 
1.26      crook    3759: Gforth provides the word @code{exception} as a mechanism for assigning
                   3760: system throw codes to applications. This allows multiple applications to
                   3761: co-exist in memory without any clash of @code{throw} codes. A definition
                   3762: of @code{exception} in ANS Forth is provided in
                   3763: @file{compat/exception.fs}.
1.1       anton    3764: 
1.44    ! crook    3765: 
1.26      crook    3766: doc-quit
                   3767: doc-abort
                   3768: doc-abort"
1.1       anton    3769: 
1.26      crook    3770: doc-catch
1.29      crook    3771: doc-throw
                   3772: doc---exception-exception
                   3773: 
                   3774: 
1.44    ! crook    3775: 
1.29      crook    3776: @c -------------------------------------------------------------
                   3777: @node Defining Words, The Text Interpreter, Control Structures, Words
                   3778: @section Defining Words
                   3779: @cindex defining words
                   3780: 
                   3781: @menu
1.44    ! crook    3782: * CREATE::
        !          3783: * Variables::                   Variables and user variables
        !          3784: * Constants::
        !          3785: * Values::                      Initialised variables
1.29      crook    3786: * Colon Definitions::
1.44    ! crook    3787: * Anonymous Definitions::       Definitions without names
1.29      crook    3788: * User-defined Defining Words::
1.44    ! crook    3789: * Deferred words::              Allow forward references
        !          3790: * Aliases::
1.29      crook    3791: * Supplying names::
                   3792: * Interpretation and Compilation Semantics::
1.44    ! crook    3793: * Combined words::
1.29      crook    3794: @end menu
                   3795: 
1.44    ! crook    3796: @node CREATE, Variables, Defining Words, Defining Words
        !          3797: @subsection @code{CREATE}
1.29      crook    3798: @cindex simple defining words
                   3799: @cindex defining words, simple
                   3800: 
                   3801: Defining words are used to create new entries in the dictionary. The
                   3802: simplest defining word is @code{CREATE}. @code{CREATE} is used like
                   3803: this:
                   3804: 
                   3805: @example
                   3806: CREATE new-word1
                   3807: @end example
                   3808: 
                   3809: @code{CREATE} is a parsing word that generates a dictionary entry for
                   3810: @code{new-word1}. When @code{new-word1} is executed, all that it does is
                   3811: leave an address on the stack. The address represents the value of
                   3812: the data space pointer (@code{HERE}) at the time that @code{new-word1}
                   3813: was defined. Therefore, @code{CREATE} is a way of associating a name
                   3814: with the address of a region of memory.
                   3815: 
1.34      anton    3816: doc-create
                   3817: 
1.29      crook    3818: By extending this example to reserve some memory in data space, we end
                   3819: up with a @i{variable}. Here are two different ways to do it:
                   3820: 
                   3821: @example
                   3822: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
                   3823: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
                   3824: @end example
                   3825: 
                   3826: The variable can be examined and modified using @code{@@} (``fetch'') and
                   3827: @code{!} (``store'') like this:
                   3828: 
                   3829: @example
                   3830: new-word2 @@ .      \ get address, fetch from it and display
                   3831: 1234 new-word2 !   \ new value, get address, store to it
                   3832: @end example
                   3833: 
1.44    ! crook    3834: @cindex arrays
        !          3835: A similar mechanism can be used to create arrays. For example, an
        !          3836: 80-character text input buffer:
1.29      crook    3837: 
                   3838: @example
1.44    ! crook    3839: CREATE text-buf 80 chars allot
        !          3840: 
        !          3841: text-buf 0 chars c@@ \ the 1st character (offset 0)
        !          3842: text-buf 3 chars c@@ \ the 4th character (offset 3)
        !          3843: @end example
1.29      crook    3844: 
1.44    ! crook    3845: You can build arbitrarily complex data structures by allocating
        !          3846: appropriate areas of memory. @xref{Structures} for further discussions
        !          3847: of this, and to learn about some Gforth tools that make it easier.
        !          3848: 
        !          3849: 
        !          3850: @node Variables, Constants, CREATE, Defining Words
        !          3851: @subsection Variables
        !          3852: @cindex variables
        !          3853: 
        !          3854: The previous section showed how a sequence of commands could be used to
        !          3855: generate a variable.  As a final refinement, the whole code sequence can
        !          3856: be wrapped up in a defining word (pre-empting the subject of the next
        !          3857: section), making it easier to create new variables:
        !          3858: 
        !          3859: @example
        !          3860: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
        !          3861: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
        !          3862: 
        !          3863: myvariableX foo \ variable foo starts off with an unknown value
        !          3864: myvariable0 joe \ whilst joe is initialised to 0
1.29      crook    3865: 
                   3866: 45 3 * foo !   \ set foo to 135
                   3867: 1234 joe !     \ set joe to 1234
                   3868: 3 joe +!       \ increment joe by 3.. to 1237
                   3869: @end example
                   3870: 
                   3871: Not surprisingly, there is no need to define @code{myvariable}, since
1.44    ! crook    3872: Forth already has a definition @code{Variable}. ANS Forth does not
        !          3873: require a @code{Variable} to be initialised when it is created (i.e., it
        !          3874: behaves like @code{myvariableX}). In contrast, Gforth's @code{Variable}
        !          3875: initialises the variable to 0 (i.e., it behaves exactly like
        !          3876: @code{myvariable0}). Forth also provides @code{2Variable} and
        !          3877: @code{fvariable} for double and floating-point variables,
        !          3878: respectively -- both are initialised to 0 in Gforth.
1.29      crook    3879: 
1.34      anton    3880: doc-variable
                   3881: doc-2variable
                   3882: doc-fvariable
                   3883: 
1.29      crook    3884: 
                   3885: @cindex user variables
                   3886: @cindex user space
                   3887: The defining word @code{User} behaves in the same way as @code{Variable}.
                   3888: The difference is that it reserves space in @i{user (data) space} rather
                   3889: than normal data space. In a Forth system that has a multi-tasker, each
                   3890: task has its own set of user variables.
                   3891: 
1.34      anton    3892: doc-user
                   3893: 
1.29      crook    3894: @comment TODO is that stuff about user variables strictly correct? Is it
                   3895: @comment just terminal tasks that have user variables?
                   3896: @comment should document tasker.fs (with some examples) elsewhere
                   3897: @comment in this manual, then expand on user space and user variables.
                   3898: 
1.44    ! crook    3899: 
        !          3900: @node Constants, Values, Variables, Defining Words
        !          3901: @subsection Constants
        !          3902: @cindex constants
        !          3903: 
        !          3904: @code{Constant} allows you to declare a fixed value and refer to it by
        !          3905: name. For example:
1.29      crook    3906: 
                   3907: @example
                   3908: 12 Constant INCHES-PER-FOOT
                   3909: 3E+08 fconstant SPEED-O-LIGHT
                   3910: @end example
                   3911: 
                   3912: A @code{Variable} can be both read and written, so its run-time
                   3913: behaviour is to supply an address through which its current value can be
                   3914: manipulated. In contrast, the value of a @code{Constant} cannot be
                   3915: changed once it has been declared@footnote{Well, often it can be -- but
                   3916: not in a Standard, portable way. It's safer to use a @code{Value} (read
                   3917: on).} so it's not necessary to supply the address -- it is more
                   3918: efficient to return the value of the constant directly. That's exactly
                   3919: what happens; the run-time effect of a constant is to put its value on
                   3920: the top of the stack (@ref{User-defined Defining Words} describes one
                   3921: way of implementing @code{Constant}).
                   3922: 
                   3923: Gforth also provides @code{2Constant} and @code{fconstant} for defining
                   3924: double and floating-point constants, respectively.
                   3925: 
1.34      anton    3926: doc-constant
                   3927: doc-2constant
                   3928: doc-fconstant
                   3929: 
                   3930: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44    ! crook    3931: @c nac-> How could that not be true in an ANS Forth? You can't define a
        !          3932: @c constant, use it and then delete the definition of the constant..
        !          3933: @c I agree that it's rather deep, but IMO it is an important difference
        !          3934: @c relative to other programming languages.. often it's annoying: it
        !          3935: @c certainly changes my programming style relative to C.
        !          3936: 
1.29      crook    3937: Constants in Forth behave differently from their equivalents in other
                   3938: programming languages. In other languages, a constant (such as an EQU in
                   3939: assembler or a #define in C) only exists at compile-time; in the
                   3940: executable program the constant has been translated into an absolute
                   3941: number and, unless you are using a symbolic debugger, it's impossible to
                   3942: know what abstract thing that number represents. In Forth a constant has
1.44    ! crook    3943: an entry in the header space and remains there after the code that uses
        !          3944: it has been defined. In fact, it must remain in the dictionary since it
        !          3945: has run-time duties to perform. For example:
1.29      crook    3946: 
                   3947: @example
                   3948: 12 Constant INCHES-PER-FOOT
                   3949: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
                   3950: @end example
                   3951: 
                   3952: @cindex in-lining of constants
                   3953: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
                   3954: associated with the constant @code{INCHES-PER-FOOT}. If you use
                   3955: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
                   3956: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
                   3957: attempt to optimise constants by in-lining them where they are used. You
                   3958: can force Gforth to in-line a constant like this:
                   3959: 
                   3960: @example
                   3961: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
                   3962: @end example
                   3963: 
                   3964: If you use @code{see} to decompile @i{this} version of
                   3965: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.33      anton    3966: longer present. @xref{Interpret/Compile states} and @ref{Literals} on
                   3967: how this works.
1.29      crook    3968: 
                   3969: In-lining constants in this way might improve execution time
                   3970: fractionally, and can ensure that a constant is now only referenced at
                   3971: compile-time. However, the definition of the constant still remains in
                   3972: the dictionary. Some Forth compilers provide a mechanism for controlling
                   3973: a second dictionary for holding transient words such that this second
                   3974: dictionary can be deleted later in order to recover memory
                   3975: space. However, there is no standard way of doing this.
                   3976: 
                   3977: 
1.44    ! crook    3978: @node Values, Colon Definitions, Constants, Defining Words
        !          3979: @subsection Values
        !          3980: @cindex values
1.34      anton    3981: 
1.44    ! crook    3982: A @code{Value} is like a @code{Variable} but with two important
        !          3983: differences:
1.29      crook    3984: 
                   3985: @itemize @bullet
                   3986: @item
1.44    ! crook    3987: A @code{Value} is initialised when it is declared; like a
        !          3988: @code{Constant} but unlike a @code{Variable}.
1.29      crook    3989: @item
1.44    ! crook    3990: A @code{Value} returns its value rather than its address when it is
        !          3991: executed; i.e., it has the same run-time behaviour as @code{Constant}.
1.29      crook    3992: @end itemize
                   3993: 
1.44    ! crook    3994: A @code{Value} needs an additional word, @code{TO} to allow its value to
        !          3995: be changed. Here are some examples:
1.29      crook    3996: 
                   3997: @example
1.44    ! crook    3998: 12 Value APPLES \ Define APPLES with an initial value of 12
        !          3999: 34 TO APPLES    \ Change the value of APPLES. TO is a parsing word
        !          4000: APPLES          \ puts 34 on the top of the stack.
1.29      crook    4001: @end example
                   4002: 
1.44    ! crook    4003: doc-value
        !          4004: doc-to
1.29      crook    4005: 
1.35      anton    4006: 
1.44    ! crook    4007: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
        !          4008: @subsection Colon Definitions
        !          4009: @cindex colon definitions
1.35      anton    4010: 
                   4011: @example
1.44    ! crook    4012: : name ( ... -- ... )
        !          4013:     word1 word2 word3 ;
1.29      crook    4014: @end example
                   4015: 
1.44    ! crook    4016: @noindent
        !          4017: Creates a word called @code{name} that, upon execution, executes
        !          4018: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29      crook    4019: 
1.44    ! crook    4020: The explanation above is somewhat superficial. @xref{Your first
        !          4021: definition} for simple examples of colon definitions, then
        !          4022: @xref{Interpretation and Compilation Semantics} for an in-depth
        !          4023: discussion of some of the issues involved.
1.29      crook    4024: 
1.44    ! crook    4025: doc-:
        !          4026: doc-;
1.1       anton    4027: 
1.34      anton    4028: 
1.44    ! crook    4029: @node Anonymous Definitions, User-defined Defining Words, Colon Definitions, Defining Words
        !          4030: @subsection Anonymous Definitions
        !          4031: @cindex colon definitions
        !          4032: @cindex defining words without name
1.34      anton    4033: 
1.44    ! crook    4034: Sometimes you want to define an @dfn{anonymous word}; a word without a
        !          4035: name. You can do this with:
1.1       anton    4036: 
1.44    ! crook    4037: doc-:noname
1.1       anton    4038: 
1.44    ! crook    4039: This leaves the execution token for the word on the stack after the
        !          4040: closing @code{;}. Here's an example in which a deferred word is
        !          4041: initialised with an @code{xt} from an anonymous colon definition:
1.1       anton    4042: 
1.29      crook    4043: @example
1.44    ! crook    4044: Defer deferred
        !          4045: :noname ( ... -- ... )
        !          4046:   ... ;
        !          4047: IS deferred
1.29      crook    4048: @end example
1.26      crook    4049: 
1.44    ! crook    4050: @noindent
        !          4051: Gforth provides an alternative way of doing this, using two separate
        !          4052: words:
1.27      crook    4053: 
1.44    ! crook    4054: doc-noname
        !          4055: @cindex execution token of last defined word
        !          4056: doc-lastxt
1.1       anton    4057: 
1.44    ! crook    4058: @noindent
        !          4059: The previous example can be rewritten using @code{noname} and
        !          4060: @code{lastxt}:
1.1       anton    4061: 
1.26      crook    4062: @example
1.44    ! crook    4063: Defer deferred
        !          4064: noname : ( ... -- ... )
        !          4065:   ... ;
        !          4066: lastxt IS deferred
1.26      crook    4067: @end example
1.1       anton    4068: 
1.29      crook    4069: @noindent
1.44    ! crook    4070: @code{noname} works with any defining word, not just @code{:}.
        !          4071: 
        !          4072: @code{lastxt} also works when the last word was not defined as
        !          4073: @code{noname}. It also has the useful property that is is valid as soon
        !          4074: as the header for a definition has been built. Thus:
        !          4075: 
        !          4076: @example
        !          4077: lastxt . : foo [ lastxt . ] ; ' foo .
        !          4078: @end example
1.1       anton    4079: 
1.44    ! crook    4080: @noindent
        !          4081: prints 3 numbers; the last two are the same.
1.26      crook    4082: 
1.1       anton    4083: 
1.44    ! crook    4084: @node User-defined Defining Words, Deferred words, Anonymous Definitions, Defining Words
1.26      crook    4085: @subsection User-defined Defining Words
                   4086: @cindex user-defined defining words
                   4087: @cindex defining words, user-defined
1.1       anton    4088: 
1.29      crook    4089: You can create a new defining word by wrapping defining-time code around
                   4090: an existing defining word and putting the sequence in a colon
                   4091: definition. For example, suppose that you have a word @code{stats} that
                   4092: gathers statistics about colon definitions given the @i{xt} of the
                   4093: definition, and you want every colon definition in your application to
                   4094: make a call to @code{stats}. You can define and use a new version of
                   4095: @code{:} like this:
                   4096: 
                   4097: @example
                   4098: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
                   4099:   ... ;  \ other code
                   4100: 
                   4101: : my: : lastxt postpone literal ['] stats compile, ;
                   4102: 
                   4103: my: foo + - ;
                   4104: @end example
                   4105: 
                   4106: When @code{foo} is defined using @code{my:} these steps occur:
                   4107: 
                   4108: @itemize @bullet
                   4109: @item
                   4110: @code{my:} is executed.
                   4111: @item
                   4112: The @code{:} within the definition (the one between @code{my:} and
                   4113: @code{lastxt}) is executed, and does just what it always does; it parses
                   4114: the input stream for a name, builds a dictionary header for the name
                   4115: @code{foo} and switches @code{state} from interpret to compile.
                   4116: @item
                   4117: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
                   4118: being defined -- @code{foo} -- onto the stack.
                   4119: @item
                   4120: The code that was produced by @code{postpone literal} is executed; this
                   4121: causes the value on the stack to be compiled as a literal in the code
                   4122: area of @code{foo}.
                   4123: @item
                   4124: The code @code{['] stats} compiles a literal into the definition of
                   4125: @code{my:}. When @code{compile,} is executed, that literal -- the
                   4126: execution token for @code{stats} -- is layed down in the code area of
                   4127: @code{foo} , following the literal@footnote{Strictly speaking, the
                   4128: mechanism that @code{compile,} uses to convert an @i{xt} into something
                   4129: in the code area is implementation-dependent. A threaded implementation
                   4130: might spit out the execution token directly whilst another
                   4131: implementation might spit out a native code sequence.}.
                   4132: @item
                   4133: At this point, the execution of @code{my:} is complete, and control
                   4134: returns to the text interpreter. The text interpreter is in compile
                   4135: state, so subsequent text @code{+ -} is compiled into the definition of
                   4136: @code{foo} and the @code{;} terminates the definition as always.
                   4137: @end itemize
                   4138: 
                   4139: You can use @code{see} to decompile a word that was defined using
                   4140: @code{my:} and see how it is different from a normal @code{:}
                   4141: definition. For example:
                   4142: 
                   4143: @example
                   4144: : bar + - ;  \ like foo but using : rather than my:
                   4145: see bar
                   4146: : bar
                   4147:   + - ;
                   4148: see foo
                   4149: : foo
                   4150:   107645672 stats + - ;
                   4151: 
                   4152: \ use ' stats . to show that 107645672 is the xt for stats
                   4153: @end example
                   4154: 
                   4155: You can use techniques like this to make new defining words in terms of
                   4156: @i{any} existing defining word.
1.1       anton    4157: 
                   4158: 
1.29      crook    4159: @cindex defining defining words
1.26      crook    4160: @cindex @code{CREATE} ... @code{DOES>}
                   4161: If you want the words defined with your defining words to behave
                   4162: differently from words defined with standard defining words, you can
                   4163: write your defining word like this:
1.1       anton    4164: 
                   4165: @example
1.26      crook    4166: : def-word ( "name" -- )
1.29      crook    4167:     CREATE @i{code1}
1.26      crook    4168: DOES> ( ... -- ... )
1.29      crook    4169:     @i{code2} ;
1.26      crook    4170: 
                   4171: def-word name
1.1       anton    4172: @end example
                   4173: 
1.29      crook    4174: @cindex child words
                   4175: This fragment defines a @dfn{defining word} @code{def-word} and then
                   4176: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
                   4177: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
                   4178: is not executed at this time. The word @code{name} is sometimes called a
                   4179: @dfn{child} of @code{def-word}.
                   4180: 
                   4181: When you execute @code{name}, the address of the body of @code{name} is
                   4182: put on the data stack and @i{code2} is executed (the address of the body
                   4183: of @code{name} is the address @code{HERE} returns immediately after the
                   4184: @code{CREATE}).
                   4185: 
                   4186: @cindex atavism in child words
1.33      anton    4187: You can use @code{def-word} to define a set of child words that behave
1.29      crook    4188: differently, though atavistically; they all have a common run-time
                   4189: behaviour determined by @i{code2}. Typically, the @i{code1} sequence
                   4190: builds a data area in the body of the child word. The structure of the
                   4191: data is common to all children of @code{def-word}, but the data values
                   4192: are specific -- and private -- to each child word. When a child word is
                   4193: executed, the address of its private data area is passed as a parameter
                   4194: on TOS to be used and manipulated@footnote{It is legitimate both to read
                   4195: and write to this data area.} by @i{code2}.
                   4196: 
                   4197: The two fragments of code that make up the defining words act (are
                   4198: executed) at two completely separate times:
1.1       anton    4199: 
1.29      crook    4200: @itemize @bullet
                   4201: @item
                   4202: At @i{define time}, the defining word executes @i{code1} to generate a
                   4203: child word
                   4204: @item
                   4205: At @i{child execution time}, when a child word is invoked, @i{code2}
                   4206: is executed, using parameters (data) that are private and specific to
                   4207: the child word.
                   4208: @end itemize
                   4209: 
1.44    ! crook    4210: Another way of understanding the behaviour of @code{def-word} and
        !          4211: @code{name} is to say that, if you make the following definitions:
1.33      anton    4212: @example
                   4213: : def-word1 ( "name" -- )
                   4214:     CREATE @i{code1} ;
                   4215: 
                   4216: : action1 ( ... -- ... )
                   4217:     @i{code2} ;
                   4218: 
                   4219: def-word1 name1
                   4220: @end example
                   4221: 
1.44    ! crook    4222: @noindent
        !          4223: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    4224: 
1.29      crook    4225: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    4226: 
1.1       anton    4227: @example
1.29      crook    4228: : CONSTANT ( w "name" -- )
                   4229:     CREATE ,
1.26      crook    4230: DOES> ( -- w )
                   4231:     @@ ;
1.1       anton    4232: @end example
                   4233: 
1.29      crook    4234: @comment There is a beautiful description of how this works and what
                   4235: @comment it does in the Forthwrite 100th edition.. as well as an elegant
                   4236: @comment commentary on the Counting Fruits problem.
                   4237: 
                   4238: When you create a constant with @code{5 CONSTANT five}, a set of
                   4239: define-time actions take place; first a new word @code{five} is created,
                   4240: then the value 5 is laid down in the body of @code{five} with
1.44    ! crook    4241: @code{,}. When @code{five} is executed, the address of the body is put on
1.29      crook    4242: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
                   4243: no code of its own; it simply contains a data field and a pointer to the
                   4244: code that follows @code{DOES>} in its defining word. That makes words
                   4245: created in this way very compact.
                   4246: 
                   4247: The final example in this section is intended to remind you that space
                   4248: reserved in @code{CREATE}d words is @i{data} space and therefore can be
                   4249: both read and written by a Standard program@footnote{Exercise: use this
                   4250: example as a starting point for your own implementation of @code{Value}
                   4251: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
                   4252: @code{[']}.}:
                   4253: 
                   4254: @example
                   4255: : foo ( "name" -- )
                   4256:     CREATE -1 ,
                   4257: DOES> ( -- )
1.33      anton    4258:     @@ . ;
1.29      crook    4259: 
                   4260: foo first-word
                   4261: foo second-word
                   4262: 
                   4263: 123 ' first-word >BODY !
                   4264: @end example
                   4265: 
                   4266: If @code{first-word} had been a @code{CREATE}d word, we could simply
                   4267: have executed it to get the address of its data field. However, since it
                   4268: was defined to have @code{DOES>} actions, its execution semantics are to
                   4269: perform those @code{DOES>} actions. To get the address of its data field
                   4270: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
                   4271: translate the xt into the address of the data field.  When you execute
                   4272: @code{first-word}, it will display @code{123}. When you execute
                   4273: @code{second-word} it will display @code{-1}.
1.26      crook    4274: 
                   4275: @cindex stack effect of @code{DOES>}-parts
                   4276: @cindex @code{DOES>}-parts, stack effect
1.29      crook    4277: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    4278: the stack effect of the defined words, not the stack effect of the
                   4279: following code (the following code expects the address of the body on
                   4280: the top of stack, which is not reflected in the stack comment). This is
                   4281: the convention that I use and recommend (it clashes a bit with using
                   4282: locals declarations for stack effect specification, though).
1.1       anton    4283: 
1.26      crook    4284: @subsubsection Applications of @code{CREATE..DOES>}
                   4285: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1       anton    4286: 
1.26      crook    4287: You may wonder how to use this feature. Here are some usage patterns:
1.1       anton    4288: 
1.26      crook    4289: @cindex factoring similar colon definitions
                   4290: When you see a sequence of code occurring several times, and you can
                   4291: identify a meaning, you will factor it out as a colon definition. When
                   4292: you see similar colon definitions, you can factor them using
                   4293: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   4294: that look very similar:
1.1       anton    4295: @example
1.26      crook    4296: : ori, ( reg-target reg-source n -- )
                   4297:     0 asm-reg-reg-imm ;
                   4298: : andi, ( reg-target reg-source n -- )
                   4299:     1 asm-reg-reg-imm ;
1.1       anton    4300: @end example
                   4301: 
1.26      crook    4302: @noindent
                   4303: This could be factored with:
                   4304: @example
                   4305: : reg-reg-imm ( op-code -- )
                   4306:     CREATE ,
                   4307: DOES> ( reg-target reg-source n -- )
                   4308:     @@ asm-reg-reg-imm ;
                   4309: 
                   4310: 0 reg-reg-imm ori,
                   4311: 1 reg-reg-imm andi,
                   4312: @end example
1.1       anton    4313: 
1.26      crook    4314: @cindex currying
                   4315: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   4316: supply a part of the parameters for a word (known as @dfn{currying} in
                   4317: the functional language community). E.g., @code{+} needs two
                   4318: parameters. Creating versions of @code{+} with one parameter fixed can
                   4319: be done like this:
1.1       anton    4320: @example
1.26      crook    4321: : curry+ ( n1 -- )
                   4322:     CREATE ,
                   4323: DOES> ( n2 -- n1+n2 )
                   4324:     @@ + ;
                   4325: 
                   4326:  3 curry+ 3+
                   4327: -2 curry+ 2-
1.1       anton    4328: @end example
                   4329: 
1.26      crook    4330: @subsubsection The gory details of @code{CREATE..DOES>}
                   4331: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    4332: 
1.26      crook    4333: doc-does>
1.1       anton    4334: 
1.26      crook    4335: @cindex @code{DOES>} in a separate definition
                   4336: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   4337: same definition; you can put the @code{DOES>}-part in a separate
1.29      crook    4338: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    4339: @example
                   4340: : does1 
                   4341: DOES> ( ... -- ... )
1.44    ! crook    4342:     ... ;
        !          4343: 
        !          4344: : does2
        !          4345: DOES> ( ... -- ... )
        !          4346:     ... ;
        !          4347: 
        !          4348: : def-word ( ... -- ... )
        !          4349:     create ...
        !          4350:     IF
        !          4351:        does1
        !          4352:     ELSE
        !          4353:        does2
        !          4354:     ENDIF ;
        !          4355: @end example
        !          4356: 
        !          4357: In this example, the selection of whether to use @code{does1} or
        !          4358: @code{does2} is made at compile-time; at the time that the child word is
        !          4359: @code{CREATE}d.
        !          4360: 
        !          4361: @cindex @code{DOES>} in interpretation state
        !          4362: In a standard program you can apply a @code{DOES>}-part only if the last
        !          4363: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
        !          4364: will override the behaviour of the last word defined in any case. In a
        !          4365: standard program, you can use @code{DOES>} only in a colon
        !          4366: definition. In Gforth, you can also use it in interpretation state, in a
        !          4367: kind of one-shot mode; for example:
        !          4368: @example
        !          4369: CREATE name ( ... -- ... )
        !          4370:   @i{initialization}
        !          4371: DOES>
        !          4372:   @i{code} ;
        !          4373: @end example
        !          4374: 
        !          4375: @noindent
        !          4376: is equivalent to the standard:
        !          4377: @example
        !          4378: :noname
        !          4379: DOES>
        !          4380:     @i{code} ;
        !          4381: CREATE name EXECUTE ( ... -- ... )
        !          4382:     @i{initialization}
        !          4383: @end example
        !          4384: 
        !          4385: 
        !          4386: doc->body
        !          4387: 
        !          4388: 
        !          4389: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
        !          4390: @subsection Deferred words
        !          4391: @cindex deferred words
        !          4392: 
        !          4393: The defining word @code{Defer} allows you to define a word by name
        !          4394: without defining its behaviour; the definition of its behaviour is
        !          4395: deferred. Here are two situation where this can be useful:
        !          4396: 
        !          4397: @itemize @bullet
        !          4398: @item
        !          4399: Where you want to allow the behaviour of a word to be altered later, and
        !          4400: for all precompiled references to the word to change when its behaviour
        !          4401: is changed.
        !          4402: @item
        !          4403: For mutual recursion; @xref{Calls and returns}.
        !          4404: @end itemize
        !          4405: 
        !          4406: In the following example, @code{foo} always invokes the version of
        !          4407: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
        !          4408: always invokes the version that prints ``@code{Hello}''. There is no way
        !          4409: of getting @code{foo} to use the later version without re-ordering the
        !          4410: source code and recompiling it.
        !          4411: 
        !          4412: @example
        !          4413: : greet ." Good morning" ;
        !          4414: : foo ... greet ... ;
        !          4415: : greet ." Hello" ;
        !          4416: : bar ... greet ... ;
        !          4417: @end example
        !          4418: 
        !          4419: This problem can be solved by defining @code{greet} as a @code{Defer}red
        !          4420: word. The behaviour of a @code{Defer}red word can be defined and
        !          4421: redefined at any time by using @code{IS} to associate the xt of a
        !          4422: previously-defined word with it. The previous example becomes:
        !          4423: 
        !          4424: @example
        !          4425: Defer greet
        !          4426: : foo ... greet ... ;
        !          4427: : bar ... greet ... ;
        !          4428: : greet1 ." Good morning" ;
        !          4429: : greet2 ." Hello" ;
        !          4430: ' greet2 <IS> greet  \ make greet behave like greet2
        !          4431: @end example
        !          4432: 
        !          4433: A deferred word can be used to improve the statistics-gathering example
        !          4434: from @ref{User-defined Defining Words}; rather than edit the
        !          4435: application's source code to change every @code{:} to a @code{my:}, do
        !          4436: this:
        !          4437: 
        !          4438: @example
        !          4439: : real: : ;     \ retain access to the original
        !          4440: defer :         \ redefine as a deferred word
        !          4441: ' my: IS :      \ use special version of :
        !          4442: \
        !          4443: \ load application here
        !          4444: \
        !          4445: ' real: IS :    \ go back to the original
        !          4446: @end example
        !          4447: 
        !          4448: 
        !          4449: One thing to note is that @code{<IS>} consumes its name when it is
        !          4450: executed.  If you want to specify the name at compile time, use
        !          4451: @code{[IS]}:
        !          4452: 
        !          4453: @example
        !          4454: : set-greet ( xt -- )
        !          4455:   [IS] greet ;
        !          4456: 
        !          4457: ' greet1 set-greet
        !          4458: @end example
        !          4459: 
        !          4460: A deferred word can only inherit default semantics from the xt (because
        !          4461: that is all that an xt can represent -- @pxref{Tokens for Words} for
        !          4462: more discussion of this). However, the semantics of the deferred word
        !          4463: itself can be modified at the time that it is defined. For example:
        !          4464: 
        !          4465: @example
        !          4466: : bar .... ; compile-only
        !          4467: Defer fred immediate
        !          4468: Defer jim
        !          4469: 
        !          4470: ' bar <IS> jim  \ jim has default semantics
        !          4471: ' bar <IS> fred \ fred is immediate
        !          4472: @end example
        !          4473: 
        !          4474: doc-defer
        !          4475: doc-<is>
        !          4476: doc-[is]
        !          4477: doc-is
        !          4478: @comment TODO document these: what's defers [is]
        !          4479: doc-what's
        !          4480: doc-defers
        !          4481: 
        !          4482: @c Use @code{words-deferred} to see a list of deferred words.
        !          4483: 
        !          4484: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
        !          4485: are provided in @file{compat/defer.fs}.
        !          4486: 
        !          4487: 
        !          4488: @node Aliases, Supplying names, Deferred words, Defining Words
        !          4489: @subsection Aliases
        !          4490: @cindex aliases
1.1       anton    4491: 
1.44    ! crook    4492: The defining word @code{Alias} allows you to define a word by name that
        !          4493: has the same behaviour as some other word. Here are two situation where
        !          4494: this can be useful:
1.1       anton    4495: 
1.44    ! crook    4496: @itemize @bullet
        !          4497: @item
        !          4498: When you want access to a word's definition from a different word list
        !          4499: (for an example of this, see the definition of the @code{Root} word list
        !          4500: in the Gforth source).
        !          4501: @item
        !          4502: When you want to create a synonym; a definition that can be known by
        !          4503: either of two names (for example, @code{THEN} and @code{ENDIF} are
        !          4504: aliases).
        !          4505: @end itemize
1.1       anton    4506: 
1.44    ! crook    4507: The word whose behaviour the alias is to inherit is represented by an
        !          4508: xt. Therefore, the alias only inherits default semantics from its
        !          4509: ancestor. The semantics of the alias itself can be modified at the time
        !          4510: that it is defined. For example:
1.1       anton    4511: 
                   4512: @example
1.44    ! crook    4513: : foo ... ; immediate
        !          4514: 
        !          4515: ' foo Alias bar \ bar is not an immediate word
        !          4516: ' foo Alias fooby immediate \ fooby is an immediate word
1.1       anton    4517: @end example
                   4518: 
1.44    ! crook    4519: Words that are aliases have the same xt, different headers in the
        !          4520: dictionary, and consequently different name tokens (@pxref{Tokens for
        !          4521: Words}) and possibly different immediate flags.  An alias can only have
        !          4522: default or immediate compilation semantics; you can define aliases for
        !          4523: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1       anton    4524: 
1.44    ! crook    4525: doc-alias
1.26      crook    4526: 
1.1       anton    4527: 
1.44    ! crook    4528: @node Supplying names, Interpretation and Compilation Semantics, Aliases, Defining Words
1.29      crook    4529: @subsection Supplying the name of a defined word
1.26      crook    4530: @cindex names for defined words
1.44    ! crook    4531: @cindex defining words, name given in a string
1.1       anton    4532: 
1.29      crook    4533: By default, a defining word takes the name for the defined word from the
1.26      crook    4534: input stream. Sometimes you want to supply the name from a string. You
                   4535: can do this with:
1.1       anton    4536: 
1.26      crook    4537: doc-nextname
1.1       anton    4538: 
1.26      crook    4539: For example:
1.1       anton    4540: 
1.26      crook    4541: @example
                   4542: s" foo" nextname create
                   4543: @end example
1.44    ! crook    4544: 
1.26      crook    4545: @noindent
                   4546: is equivalent to:
1.44    ! crook    4547: 
1.26      crook    4548: @example
                   4549: create foo
                   4550: @end example
1.1       anton    4551: 
1.29      crook    4552: @noindent
1.44    ! crook    4553: @code{nextname} works with any defining word, not just @code{:}.
1.1       anton    4554: 
                   4555: 
1.44    ! crook    4556: @node Interpretation and Compilation Semantics, Combined words, Supplying names, Defining Words
1.26      crook    4557: @subsection Interpretation and Compilation Semantics
                   4558: @cindex semantics, interpretation and compilation
1.1       anton    4559: 
1.26      crook    4560: @cindex interpretation semantics
                   4561: The @dfn{interpretation semantics} of a word are what the text
                   4562: interpreter does when it encounters the word in interpret state. It also
                   4563: appears in some other contexts, e.g., the execution token returned by
1.29      crook    4564: @code{' @i{word}} identifies the interpretation semantics of
                   4565: @i{word} (in other words, @code{' @i{word} execute} is equivalent to
                   4566: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    4567: 
1.26      crook    4568: @cindex compilation semantics
                   4569: The @dfn{compilation semantics} of a word are what the text interpreter
                   4570: does when it encounters the word in compile state. It also appears in
1.29      crook    4571: other contexts, e.g, @code{POSTPONE @i{word}} compiles@footnote{In
1.26      crook    4572: standard terminology, ``appends to the current definition''.} the
1.29      crook    4573: compilation semantics of @i{word}.
1.1       anton    4574: 
1.26      crook    4575: @cindex execution semantics
                   4576: The standard also talks about @dfn{execution semantics}. They are used
                   4577: only for defining the interpretation and compilation semantics of many
                   4578: words. By default, the interpretation semantics of a word are to
                   4579: @code{execute} its execution semantics, and the compilation semantics of
                   4580: a word are to @code{compile,} its execution semantics.@footnote{In
                   4581: standard terminology: The default interpretation semantics are its
                   4582: execution semantics; the default compilation semantics are to append its
                   4583: execution semantics to the execution semantics of the current
                   4584: definition.}
                   4585: 
                   4586: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   4587: 
                   4588: @cindex immediate words
                   4589: @cindex compile-only words
                   4590: You can change the semantics of the most-recently defined word:
                   4591: 
1.44    ! crook    4592: 
1.26      crook    4593: doc-immediate
                   4594: doc-compile-only
                   4595: doc-restrict
                   4596: 
1.44    ! crook    4597: 
1.26      crook    4598: Note that ticking (@code{'}) a compile-only word gives an error
                   4599: (``Interpreting a compile-only word'').
1.1       anton    4600: 
1.44    ! crook    4601: 
        !          4602: @node Combined words, ,Interpretation and Compilation Semantics, Defining Words
        !          4603: @subsection Combined Words
        !          4604: @cindex combined words
        !          4605: 
        !          4606: Gforth allows you to define @dfn{combined words} -- words that have an
        !          4607: arbitrary combination of interpretation and compilation semantics.
        !          4608: 
1.1       anton    4609: 
1.26      crook    4610: doc-interpret/compile:
1.1       anton    4611: 
1.44    ! crook    4612: 
1.26      crook    4613: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   4614: recommend that you do not define such words, as cute as they may be:
                   4615: they make it hard to get at both parts of the word in some contexts.
                   4616: E.g., assume you want to get an execution token for the compilation
                   4617: part. Instead, define two words, one that embodies the interpretation
                   4618: part, and one that embodies the compilation part.  Once you have done
                   4619: that, you can define a combined word with @code{interpret/compile:} for
                   4620: the convenience of your users.
1.1       anton    4621: 
1.26      crook    4622: You might try to use this feature to provide an optimizing
                   4623: implementation of the default compilation semantics of a word. For
                   4624: example, by defining:
1.1       anton    4625: @example
1.26      crook    4626: :noname
                   4627:    foo bar ;
                   4628: :noname
                   4629:    POSTPONE foo POSTPONE bar ;
1.29      crook    4630: interpret/compile: opti-foobar
1.1       anton    4631: @end example
1.26      crook    4632: 
1.23      crook    4633: @noindent
1.26      crook    4634: as an optimizing version of:
                   4635: 
1.1       anton    4636: @example
1.26      crook    4637: : foobar
                   4638:     foo bar ;
1.1       anton    4639: @end example
                   4640: 
1.26      crook    4641: Unfortunately, this does not work correctly with @code{[compile]},
                   4642: because @code{[compile]} assumes that the compilation semantics of all
                   4643: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29      crook    4644: opti-foobar} would compile compilation semantics, whereas
                   4645: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    4646: 
1.26      crook    4647: @cindex state-smart words (are a bad idea)
1.29      crook    4648: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    4649: by @code{interpret/compile:} (words are state-smart if they check
                   4650: @code{STATE} during execution). E.g., they would try to code
                   4651: @code{foobar} like this:
1.1       anton    4652: 
1.26      crook    4653: @example
                   4654: : foobar
                   4655:   STATE @@
                   4656:   IF ( compilation state )
                   4657:     POSTPONE foo POSTPONE bar
                   4658:   ELSE
                   4659:     foo bar
                   4660:   ENDIF ; immediate
                   4661: @end example
1.1       anton    4662: 
1.26      crook    4663: Although this works if @code{foobar} is only processed by the text
                   4664: interpreter, it does not work in other contexts (like @code{'} or
                   4665: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   4666: for a state-smart word, not for the interpretation semantics of the
                   4667: original @code{foobar}; when you execute this execution token (directly
                   4668: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   4669: state, the result will not be what you expected (i.e., it will not
                   4670: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   4671: write them@footnote{For a more detailed discussion of this topic, see
                   4672: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
                   4673: Ertl; presented at EuroForth '98 and available from
1.33      anton    4674: @url{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz}}!
1.1       anton    4675: 
1.26      crook    4676: @cindex defining words with arbitrary semantics combinations
                   4677: It is also possible to write defining words that define words with
                   4678: arbitrary combinations of interpretation and compilation semantics. In
                   4679: general, they look like this:
1.1       anton    4680: 
1.26      crook    4681: @example
                   4682: : def-word
                   4683:     create-interpret/compile
1.29      crook    4684:     @i{code1}
1.26      crook    4685: interpretation>
1.29      crook    4686:     @i{code2}
1.26      crook    4687: <interpretation
                   4688: compilation>
1.29      crook    4689:     @i{code3}
1.26      crook    4690: <compilation ;
                   4691: @end example
1.1       anton    4692: 
1.29      crook    4693: For a @i{word} defined with @code{def-word}, the interpretation
                   4694: semantics are to push the address of the body of @i{word} and perform
                   4695: @i{code2}, and the compilation semantics are to push the address of
                   4696: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    4697: can also be defined like this (except that the defined constants don't
                   4698: behave correctly when @code{[compile]}d):
1.1       anton    4699: 
1.26      crook    4700: @example
                   4701: : constant ( n "name" -- )
                   4702:     create-interpret/compile
                   4703:     ,
                   4704: interpretation> ( -- n )
                   4705:     @@
                   4706: <interpretation
                   4707: compilation> ( compilation. -- ; run-time. -- n )
                   4708:     @@ postpone literal
                   4709: <compilation ;
                   4710: @end example
1.1       anton    4711: 
1.44    ! crook    4712: 
1.26      crook    4713: doc-create-interpret/compile
                   4714: doc-interpretation>
                   4715: doc-<interpretation
                   4716: doc-compilation>
                   4717: doc-<compilation
1.1       anton    4718: 
1.44    ! crook    4719: 
1.29      crook    4720: Words defined with @code{interpret/compile:} and
1.26      crook    4721: @code{create-interpret/compile} have an extended header structure that
                   4722: differs from other words; however, unless you try to access them with
                   4723: plain address arithmetic, you should not notice this. Words for
                   4724: accessing the header structure usually know how to deal with this; e.g.,
1.29      crook    4725: @code{'} @i{word} @code{>body} also gives you the body of a word created
                   4726: with @code{create-interpret/compile}.
1.1       anton    4727: 
1.44    ! crook    4728: 
1.27      crook    4729: doc-postpone
1.44    ! crook    4730: 
1.29      crook    4731: @comment TODO -- expand glossary text for POSTPONE
1.27      crook    4732: 
1.26      crook    4733: @c ----------------------------------------------------------
                   4734: @node The Text Interpreter, Tokens for Words, Defining Words, Words
                   4735: @section  The Text Interpreter
                   4736: @cindex interpreter - outer
                   4737: @cindex text interpreter
                   4738: @cindex outer interpreter
1.1       anton    4739: 
1.34      anton    4740: @c Should we really describe all these ugly details?  IMO the text
                   4741: @c interpreter should be much cleaner, but that may not be possible within
                   4742: @c ANS Forth. - anton
1.44    ! crook    4743: @c nac-> I wanted to explain how it works to show how you can exploit
        !          4744: @c it in your own programs. When I was writing a cross-compiler, figuring out
        !          4745: @c some of these gory details was very helpful to me. None of the textbooks
        !          4746: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
        !          4747: @c seems to positively avoid going into too much detail for some of
        !          4748: @c the internals.
1.34      anton    4749: 
1.29      crook    4750: The text interpreter@footnote{This is an expanded version of the
                   4751: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34      anton    4752: that processes input from the current input device. It is also called
                   4753: the outer interpreter, in contrast to the inner interpreter
                   4754: (@pxref{Engine}) which executes the compiled Forth code on interpretive
                   4755: implementations.
1.27      crook    4756: 
1.29      crook    4757: @cindex interpret state
                   4758: @cindex compile state
                   4759: The text interpreter operates in one of two states: @dfn{interpret
                   4760: state} and @dfn{compile state}. The current state is defined by the
                   4761: aptly-named variable, @code{state}.
                   4762: 
                   4763: This section starts by describing how the text interpreter behaves when
                   4764: it is in interpret state, processing input from the user input device --
                   4765: the keyboard. This is the mode that a Forth system is in after it starts
                   4766: up.
                   4767: 
                   4768: @cindex input buffer
                   4769: @cindex terminal input buffer
                   4770: The text interpreter works from an area of memory called the @dfn{input
                   4771: buffer}@footnote{When the text interpreter is processing input from the
                   4772: keyboard, this area of memory is called the @dfn{terminal input buffer}
                   4773: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
                   4774: @code{#TIB}.}, which stores your keyboard input when you press the
1.30      anton    4775: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29      crook    4776: leading spaces (called @dfn{delimiters}) then parses a string (a
                   4777: sequence of non-space characters) until it reaches either a space
                   4778: character or the end of the buffer. Having parsed a string, it makes two
                   4779: attempts to process it:
1.27      crook    4780: 
1.29      crook    4781: @cindex dictionary
1.27      crook    4782: @itemize @bullet
                   4783: @item
1.29      crook    4784: It looks for the string in a @dfn{dictionary} of definitions. If the
                   4785: string is found, the string names a @dfn{definition} (also known as a
                   4786: @dfn{word}) and the dictionary search returns information that allows
                   4787: the text interpreter to perform the word's @dfn{interpretation
                   4788: semantics}. In most cases, this simply means that the word will be
                   4789: executed.
1.27      crook    4790: @item
                   4791: If the string is not found in the dictionary, the text interpreter
1.29      crook    4792: attempts to treat it as a number, using the rules described in
                   4793: @ref{Number Conversion}. If the string represents a legal number in the
                   4794: current radix, the number is pushed onto a parameter stack (the data
                   4795: stack for integers, the floating-point stack for floating-point
                   4796: numbers).
                   4797: @end itemize
                   4798: 
                   4799: If both attempts fail, or if the word is found in the dictionary but has
                   4800: no interpretation semantics@footnote{This happens if the word was
                   4801: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
                   4802: remainder of the input buffer, issues an error message and waits for
                   4803: more input. If one of the attempts succeeds, the text interpreter
                   4804: repeats the parsing process until the whole of the input buffer has been
                   4805: processed, at which point it prints the status message ``@code{ ok}''
                   4806: and waits for more input.
                   4807: 
                   4808: @cindex parse area
                   4809: The text interpreter keeps track of its position in the input buffer by
                   4810: updating a variable called @code{>IN} (pronounced ``to-in''). The value
                   4811: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
                   4812: of the input buffer. The region from offset @code{>IN @@} to the end of
                   4813: the input buffer is called the @dfn{parse area}@footnote{In other words,
                   4814: the text interpreter processes the contents of the input buffer by
                   4815: parsing strings from the parse area until the parse area is empty.}.
                   4816: This example shows how @code{>IN} changes as the text interpreter parses
                   4817: the input buffer:
                   4818: 
                   4819: @example
                   4820: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
                   4821:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
                   4822: 
                   4823: 1 2 3 remaining + remaining . 
                   4824: 
                   4825: : foo 1 2 3 remaining SWAP remaining ;
                   4826: @end example
                   4827: 
                   4828: @noindent
                   4829: The result is:
                   4830: 
                   4831: @example
                   4832: ->+ remaining .<-
                   4833: ->.<-5  ok
                   4834: 
                   4835: ->SWAP remaining ;-<
                   4836: ->;<-  ok
                   4837: @end example
                   4838: 
                   4839: @cindex parsing words
                   4840: The value of @code{>IN} can also be modified by a word in the input
                   4841: buffer that is executed by the text interpreter.  This means that a word
                   4842: can ``trick'' the text interpreter into either skipping a section of the
                   4843: input buffer@footnote{This is how parsing words work.} or into parsing a
                   4844: section twice. For example:
1.27      crook    4845: 
1.29      crook    4846: @example
                   4847: : lat ." <<lat>>" ;
                   4848: : flat ." <<flat>>" >IN DUP @@ 3 - SWAP ! ;
                   4849: @end example
                   4850: 
                   4851: @noindent
                   4852: When @code{flat} is executed, this output is produced@footnote{Exercise
                   4853: for the reader: what would happen if the @code{3} were replaced with
                   4854: @code{4}?}:
                   4855: 
                   4856: @example
                   4857: <<flat>><<lat>>
                   4858: @end example
                   4859: 
                   4860: @noindent
                   4861: Two important notes about the behaviour of the text interpreter:
1.27      crook    4862: 
                   4863: @itemize @bullet
                   4864: @item
                   4865: It processes each input string to completion before parsing additional
1.29      crook    4866: characters from the input buffer.
                   4867: @item
                   4868: It treats the input buffer as a read-only region (and so must your code).
                   4869: @end itemize
                   4870: 
                   4871: @noindent
                   4872: When the text interpreter is in compile state, its behaviour changes in
                   4873: these ways:
                   4874: 
                   4875: @itemize @bullet
                   4876: @item
                   4877: If a parsed string is found in the dictionary, the text interpreter will
                   4878: perform the word's @dfn{compilation semantics}. In most cases, this
                   4879: simply means that the execution semantics of the word will be appended
                   4880: to the current definition.
1.27      crook    4881: @item
1.29      crook    4882: When a number is encountered, it is compiled into the current definition
                   4883: (as a literal) rather than being pushed onto a parameter stack.
                   4884: @item
                   4885: If an error occurs, @code{state} is modified to put the text interpreter
                   4886: back into interpret state.
                   4887: @item
                   4888: Each time a line is entered from the keyboard, Gforth prints
                   4889: ``@code{ compiled}'' rather than `` @code{ok}''.
                   4890: @end itemize
                   4891: 
                   4892: @cindex text interpreter - input sources
                   4893: When the text interpreter is using an input device other than the
                   4894: keyboard, its behaviour changes in these ways:
                   4895: 
                   4896: @itemize @bullet
                   4897: @item
                   4898: When the parse area is empty, the text interpreter attempts to refill
                   4899: the input buffer from the input source. When the input source is
                   4900: exhausted, the input source is set back to the user input device.
                   4901: @item
                   4902: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
                   4903: time the parse area is emptied.
                   4904: @item
                   4905: If an error occurs, the input source is set back to the user input
                   4906: device.
1.27      crook    4907: @end itemize
1.21      crook    4908: 
1.29      crook    4909: @ref{Input Sources} describes this in more detail.
                   4910: 
1.44    ! crook    4911: 
1.26      crook    4912: doc->in
1.27      crook    4913: doc-source
                   4914: 
1.26      crook    4915: doc-tib
                   4916: doc-#tib
1.1       anton    4917: 
1.44    ! crook    4918: 
1.26      crook    4919: @menu
1.29      crook    4920: * Input Sources::
1.26      crook    4921: * Number Conversion::
                   4922: * Interpret/Compile states::
                   4923: * Literals::
                   4924: * Interpreter Directives::
                   4925: @end menu
1.1       anton    4926: 
1.29      crook    4927: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
                   4928: @subsection Input Sources
                   4929: @cindex input sources
                   4930: @cindex text interpreter - input sources
                   4931: 
1.44    ! crook    4932: By default, the text interpreter processes input from the user input
1.29      crook    4933: device (the keyboard) when Forth starts up. The text interpreter can
                   4934: process input from any of these sources:
                   4935: 
                   4936: @itemize @bullet
                   4937: @item
                   4938: The user input device -- the keyboard.
                   4939: @item
                   4940: A file, using the words described in @ref{Forth source files}.
                   4941: @item
                   4942: A block, using the words described in @ref{Blocks}.
                   4943: @item
                   4944: A text string, using @code{evaluate}.
                   4945: @end itemize
                   4946: 
                   4947: A program can identify the current input device from the values of
                   4948: @code{source-id} and @code{blk}.
                   4949: 
1.44    ! crook    4950: 
1.29      crook    4951: doc-source-id
                   4952: doc-blk
                   4953: 
                   4954: doc-save-input
                   4955: doc-restore-input
                   4956: 
                   4957: doc-evaluate
1.1       anton    4958: 
1.29      crook    4959: 
1.44    ! crook    4960: 
1.29      crook    4961: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    4962: @subsection Number Conversion
                   4963: @cindex number conversion
                   4964: @cindex double-cell numbers, input format
                   4965: @cindex input format for double-cell numbers
                   4966: @cindex single-cell numbers, input format
                   4967: @cindex input format for single-cell numbers
                   4968: @cindex floating-point numbers, input format
                   4969: @cindex input format for floating-point numbers
1.1       anton    4970: 
1.29      crook    4971: This section describes the rules that the text interpreter uses when it
                   4972: tries to convert a string into a number.
1.1       anton    4973: 
1.26      crook    4974: Let <digit> represent any character that is a legal digit in the current
1.29      crook    4975: number base@footnote{For example, 0-9 when the number base is decimal or
                   4976: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    4977: 
1.26      crook    4978: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    4979: 
1.29      crook    4980: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
                   4981: in the braces (@i{a} or @i{b} or neither).
1.1       anton    4982: 
1.26      crook    4983: Let * represent any number of instances of the previous character
                   4984: (including none).
1.1       anton    4985: 
1.26      crook    4986: Let any other character represent itself.
1.1       anton    4987: 
1.29      crook    4988: @noindent
1.26      crook    4989: Now, the conversion rules are:
1.21      crook    4990: 
1.26      crook    4991: @itemize @bullet
                   4992: @item
                   4993: A string of the form <digit><digit>* is treated as a single-precision
1.29      crook    4994: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    4995: @item
                   4996: A string of the form -<digit><digit>* is treated as a single-precision
1.29      crook    4997: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    4998: arithmetic. Examples are -45 -5681 -0
                   4999: @item
                   5000: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29      crook    5001: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
                   5002: (all three of these represent the same number).
1.26      crook    5003: @item
                   5004: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29      crook    5005: double-precision (double-cell-sized) negative integer, and is
1.26      crook    5006: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29      crook    5007: -34.65 (all three of these represent the same number).
1.26      crook    5008: @item
1.29      crook    5009: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
                   5010: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35      anton    5011: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29      crook    5012: number) +12.E-4
1.26      crook    5013: @end itemize
1.1       anton    5014: 
1.26      crook    5015: By default, the number base used for integer number conversion is given
1.35      anton    5016: by the contents of the variable @code{base}.  Note that a lot of
                   5017: confusion can result from unexpected values of @code{base}.  If you
                   5018: change @code{base} anywhere, make sure to save the old value and restore
                   5019: it afterwards.  In general I recommend keeping @code{base} decimal, and
                   5020: using the prefixes described below for the popular non-decimal bases.
1.1       anton    5021: 
1.29      crook    5022: doc-dpl
1.26      crook    5023: doc-base
                   5024: doc-hex
                   5025: doc-decimal
1.1       anton    5026: 
1.44    ! crook    5027: 
1.26      crook    5028: @cindex '-prefix for character strings
                   5029: @cindex &-prefix for decimal numbers
                   5030: @cindex %-prefix for binary numbers
                   5031: @cindex $-prefix for hexadecimal numbers
1.35      anton    5032: Gforth allows you to override the value of @code{base} by using a
1.29      crook    5033: prefix@footnote{Some Forth implementations provide a similar scheme by
                   5034: implementing @code{$} etc. as parsing words that process the subsequent
                   5035: number in the input stream and push it onto the stack. For example, see
                   5036: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
                   5037: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
                   5038: is required between the prefix and the number.} before the first digit
                   5039: of an (integer) number. Four prefixes are supported:
1.1       anton    5040: 
1.26      crook    5041: @itemize @bullet
                   5042: @item
1.35      anton    5043: @code{&} -- decimal
1.26      crook    5044: @item
1.35      anton    5045: @code{%} -- binary
1.26      crook    5046: @item
1.35      anton    5047: @code{$} -- hexadecimal
1.26      crook    5048: @item
1.35      anton    5049: @code{'} -- base @code{max-char+1}
1.26      crook    5050: @end itemize
1.1       anton    5051: 
1.26      crook    5052: Here are some examples, with the equivalent decimal number shown after
                   5053: in braces:
1.1       anton    5054: 
1.26      crook    5055: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
                   5056: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
                   5057: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
                   5058: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    5059: 
1.26      crook    5060: @cindex number conversion - traps for the unwary
1.29      crook    5061: @noindent
1.26      crook    5062: Number conversion has a number of traps for the unwary:
1.1       anton    5063: 
1.26      crook    5064: @itemize @bullet
                   5065: @item
                   5066: You cannot determine the current number base using the code sequence
1.35      anton    5067: @code{base @@ .} -- the number base is always 10 in the current number
                   5068: base. Instead, use something like @code{base @@ dec.}
1.26      crook    5069: @item
                   5070: If the number base is set to a value greater than 14 (for example,
                   5071: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   5072: it to be intepreted as either a single-precision integer or a
                   5073: floating-point number (Gforth treats it as an integer). The ambiguity
                   5074: can be resolved by explicitly stating the sign of the mantissa and/or
                   5075: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   5076: ambiguity arises; either representation will be treated as a
                   5077: floating-point number.
                   5078: @item
1.29      crook    5079: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    5080: It is used to specify file types.
                   5081: @item
                   5082: ANS Forth requires the @code{.} of a double-precision number to
                   5083: be the final character in the string. Allowing the @code{.} to be
                   5084: anywhere after the first digit is a Gforth extension.
                   5085: @item
                   5086: The number conversion process does not check for overflow.
                   5087: @item
                   5088: In Gforth, number conversion to floating-point numbers always use base
1.35      anton    5089: 10, irrespective of the value of @code{base}. In ANS Forth,
1.26      crook    5090: conversion to floating-point numbers whilst the value of
1.35      anton    5091: @code{base} is not 10 is an ambiguous condition.
1.26      crook    5092: @end itemize
1.1       anton    5093: 
1.29      crook    5094: @ref{Input} describes words that you can use to read numbers into your
                   5095: programs.
1.1       anton    5096: 
1.26      crook    5097: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
                   5098: @subsection Interpret/Compile states
                   5099: @cindex Interpret/Compile states
1.1       anton    5100: 
1.29      crook    5101: A standard program is not permitted to change @code{state}
                   5102: explicitly. However, it can change @code{state} implicitly, using the
                   5103: words @code{[} and @code{]}. When @code{[} is executed it switches
                   5104: @code{state} to interpret state, and therefore the text interpreter
                   5105: starts interpreting. When @code{]} is executed it switches @code{state}
                   5106: to compile state and therefore the text interpreter starts
1.44    ! crook    5107: compiling. The most common usage for these words is for switching into
        !          5108: interpret state and back from within a colon definition; this technique
        !          5109: can be used to compile a literal (@pxref{Literals} for an example) or
        !          5110: for conditional compilation (@pxref{Interpreter Directives} for an
        !          5111: example).
        !          5112: 
1.35      anton    5113: 
                   5114: @c This is a bad example: It's non-standard, and it's not necessary.
                   5115: @c However, I can't think of a good example for switching into compile
                   5116: @c state when there is no current word (@code{state}-smart words are not a
                   5117: @c good reason).  So maybe we should use an example for switching into
                   5118: @c interpret @code{state} in a colon def. - anton
1.44    ! crook    5119: @c nac-> I agree. I started out by putting in the example, then realised
        !          5120: @c that it was non-ANS, so wrote more words around it. I hope this
        !          5121: @c re-written version is acceptable to you. I do want to keep the example
        !          5122: @c as it is helpful for showing what is and what is not portable, particularly
        !          5123: @c where it outlaws a style in common use.
        !          5124: 
1.35      anton    5125: 
1.44    ! crook    5126: @code{[} and @code{]} also give you the ability to switch into compile
        !          5127: state and back, but we cannot think of any useful Standard application
        !          5128: for this ability. Pre-ANS Forth textbooks have examples like this:
1.29      crook    5129: 
                   5130: @example
                   5131: : AA ." this is A" ;
                   5132: : BB ." this is B" ;
                   5133: : CC ." this is C" ;
                   5134: 
1.44    ! crook    5135: create table ] aa bb cc [
        !          5136: 
1.29      crook    5137: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
                   5138:   cells table + @ execute ;
                   5139: @end example
                   5140: 
1.44    ! crook    5141: This example builds a jump table; @code{0 go} will display ``@code{this
        !          5142: is A}''. Using @code{[} and @code{]} in this example is equivalent to
        !          5143: defining @code{table} like this:
1.29      crook    5144: 
                   5145: @example
1.44    ! crook    5146: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
1.29      crook    5147: @end example
                   5148: 
1.44    ! crook    5149: The problem with this code is that the definition of @code{table} is not
        !          5150: portable -- it @i{compile}s execution tokens into code space. Whilst it
        !          5151: @i{may} work on systems where code space and data space co-incide, the
1.29      crook    5152: Standard only allows data space to be assigned for a @code{CREATE}d
                   5153: word. In addition, the Standard only allows @code{@@} to access data
                   5154: space, whilst this example is using it to access code space. The only
                   5155: portable, Standard way to build this table is to build it in data space,
                   5156: like this:
                   5157: 
                   5158: @example
                   5159: create table ' aa , ' bb , ' cc ,
                   5160: @end example
                   5161: 
1.26      crook    5162: doc-state
                   5163: doc-[
                   5164: doc-]
1.1       anton    5165: 
1.44    ! crook    5166: 
1.26      crook    5167: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
                   5168: @subsection Literals
                   5169: @cindex Literals
1.21      crook    5170: 
1.29      crook    5171: Often, you want to use a number within a colon definition. When you do
                   5172: this, the text interpreter automatically compiles the number as a
                   5173: @i{literal}. A literal is a number whose run-time effect is to be pushed
                   5174: onto the stack.  If you had to do some maths to generate the number, you
                   5175: might write it like this:
                   5176: 
                   5177: @example
                   5178: : HOUR-TO-SEC ( n1 -- n2 )
                   5179:   60 *      \ to minutes
                   5180:   60 * ;    \ to seconds
                   5181: @end example
                   5182: 
                   5183: It is very clear what this definition is doing, but it's inefficient
                   5184: since it is performing 2 multiples at run-time. An alternative would be
                   5185: to write:
                   5186: 
                   5187: @example
                   5188: : HOUR-TO-SEC ( n1 -- n2 )
                   5189:   3600 * ;  \ to seconds
                   5190: @end example
                   5191: 
                   5192: Which does the same thing, and has the advantage of using a single
                   5193: multiply. Ideally, we'd like the efficiency of the second with the
                   5194: readability of the first.
                   5195: 
                   5196: @code{Literal} allows us to achieve that. It takes a number from the
                   5197: stack and lays it down in the current definition just as though the
                   5198: number had been typed directly into the definition. Our first attempt
                   5199: might look like this:
                   5200: 
                   5201: @example
                   5202: 60          \ mins per hour
                   5203: 60 *        \ seconds per minute
                   5204: : HOUR-TO-SEC ( n1 -- n2 )
                   5205:   Literal * ;  \ to seconds
                   5206: @end example
                   5207: 
                   5208: But this produces the error message @code{unstructured}. What happened?
                   5209: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
                   5210: @i{colon-sys} is implementation-defined. In other words, once we start a
                   5211: colon definition we can't portably access anything that was on the stack
                   5212: before the definition began@footnote{@cite{Two Problems in ANS Forth},
                   5213: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
                   5214: some situations where you might want to access stack items above
                   5215: colon-sys, and provides a solution to the problem.}. The correct way of
                   5216: solving this problem in this instance is to use @code{[ ]} like this:
                   5217: 
                   5218: @example
                   5219: : HOUR-TO-SEC ( n1 -- n2 )
                   5220:   [ 60          \ minutes per hour
                   5221:     60 * ]      \ seconds per minute
                   5222:   LITERAL * ;   \ to seconds
                   5223: @end example
1.23      crook    5224: 
1.44    ! crook    5225: 
1.26      crook    5226: doc-literal
                   5227: doc-]L
                   5228: doc-2literal
                   5229: doc-fliteral
1.1       anton    5230: 
1.44    ! crook    5231: 
1.29      crook    5232: @node Interpreter Directives, , Literals, The Text Interpreter
1.26      crook    5233: @subsection Interpreter Directives
                   5234: @cindex interpreter directives
1.1       anton    5235: 
1.29      crook    5236: These words are usually used in interpret state; typically to control
                   5237: which parts of a source file are processed by the text
1.26      crook    5238: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   5239: supplements these with a rich set of immediate control structure words
                   5240: to compensate for the fact that the non-immediate versions can only be
1.29      crook    5241: used in compile state (@pxref{Control Structures}). Typical usages:
                   5242: 
                   5243: @example
                   5244: FALSE Constant ASSEMBLER
                   5245: .
                   5246: .
                   5247: ASSEMBLER [IF]
                   5248: : ASSEMBLER-FEATURE
                   5249:   ...
                   5250: ;
                   5251: [ENDIF]
                   5252: .
                   5253: .
                   5254: : SEE
                   5255:   ... \ general-purpose SEE code
                   5256:   [ ASSEMBLER [IF] ]
                   5257:   ... \ assembler-specific SEE code
                   5258:   [ [ENDIF] ]
                   5259: ;
                   5260: @end example
1.1       anton    5261: 
1.44    ! crook    5262: 
1.26      crook    5263: doc-[IF]
                   5264: doc-[ELSE]
                   5265: doc-[THEN]
                   5266: doc-[ENDIF]
1.1       anton    5267: 
1.26      crook    5268: doc-[IFDEF]
                   5269: doc-[IFUNDEF]
1.1       anton    5270: 
1.26      crook    5271: doc-[?DO]
                   5272: doc-[DO]
                   5273: doc-[FOR]
                   5274: doc-[LOOP]
                   5275: doc-[+LOOP]
                   5276: doc-[NEXT]
1.1       anton    5277: 
1.26      crook    5278: doc-[BEGIN]
                   5279: doc-[UNTIL]
                   5280: doc-[AGAIN]
                   5281: doc-[WHILE]
                   5282: doc-[REPEAT]
1.1       anton    5283: 
1.27      crook    5284: 
                   5285: 
1.44    ! crook    5286: 
1.26      crook    5287: @c -------------------------------------------------------------
                   5288: @node Tokens for Words, Word Lists, The Text Interpreter, Words
                   5289: @section Tokens for Words
                   5290: @cindex tokens for words
1.1       anton    5291: 
1.28      crook    5292: This section describes the creation and use of tokens that represent
1.29      crook    5293: words.
                   5294: 
1.32      anton    5295: Named words have information stored in their header space entries to
1.29      crook    5296: indicate any non-default semantics (@pxref{Interpretation and
                   5297: Compilation Semantics}). The semantics can be modified, using
                   5298: @code{immediate} and/or @code{compile-only}, at the time that the words
1.32      anton    5299: are defined. Unnamed words have (by definition) no header space
1.29      crook    5300: entry, and therefore must have default semantics.
1.21      crook    5301: 
1.26      crook    5302: Named words have interpretation and compilation semantics. Unnamed words
                   5303: just have execution semantics.
1.21      crook    5304: 
1.29      crook    5305: @cindex xt
                   5306: @cindex execution token
                   5307: The execution semantics of an unnamed word are represented by an
                   5308: @dfn{execution token} (@i{xt}). As explained in @ref{Supplying names},
                   5309: the execution token of the last word defined can be produced with
                   5310: @code{lastxt}.
                   5311: 
                   5312: The interpretation semantics of a named word are also represented by an
                   5313: execution token. You can produce the execution token using @code{'} or
                   5314: @code{[']}. A simple example shows the difference between the two:
1.21      crook    5315: 
1.29      crook    5316: @example
                   5317: : greet ( -- )   ." Hello" ;
1.36      anton    5318: : foo ( -- xt )  ['] greet execute ; \ ['] parses greet at compile-time
                   5319: : bar ( -- )     ' execute ; \  '  parses at run-time
1.1       anton    5320: 
1.29      crook    5321: \ the next four lines all do the same thing
1.36      anton    5322: foo
                   5323: bar greet
1.29      crook    5324: greet
                   5325: ' greet EXECUTE
                   5326: @end example
1.1       anton    5327: 
1.29      crook    5328: An execution token occupies one cell.
1.26      crook    5329: @cindex code field address
                   5330: @cindex CFA
1.29      crook    5331: In Gforth, the abstract data type @i{execution token} is implemented
1.26      crook    5332: as a code field address (CFA).
                   5333: @comment TODO note that the standard does not say what it represents..
                   5334: @comment and you cannot necessarily compile it in all Forths (eg native
                   5335: @comment compilers?).
1.1       anton    5336: 
1.29      crook    5337: For literals, use @code{'} in interpreted code and @code{[']} in
                   5338: compiled code. Gforth's @code{'} and @code{[']} behave somewhat
                   5339: unusually by complaining about compile-only words. To get the execution
                   5340: token for a compile-only word @i{name}, use @code{COMP' @i{name} DROP}
                   5341: or @code{[COMP'] @i{name} DROP}.
1.1       anton    5342: 
1.26      crook    5343: @cindex compilation token
1.29      crook    5344: The compilation semantics of a named word are represented by a
                   5345: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
                   5346: @i{xt} is an execution token. The compilation semantics represented by
                   5347: the compilation token can be performed with @code{execute}, which
                   5348: consumes the whole compilation token, with an additional stack effect
                   5349: determined by the represented compilation semantics.
                   5350: 
                   5351: At present, the @i{w} part of a compilation token is an execution token,
                   5352: and the @i{xt} part represents either @code{execute} or
                   5353: @code{compile,}@footnote{Depending upon the compilation semantics of the
                   5354: word. If the word has default compilation semantics, the @i{xt} will
1.36      anton    5355: represent @code{compile,}. Otherwise (e.g., for immediate words), the
                   5356: @i{xt} will represent @code{execute}.}. However, don't rely on that
                   5357: knowledge, unless necessary; future versions of Gforth may introduce
                   5358: unusual compilation tokens (e.g., a compilation token that represents
                   5359: the compilation semantics of a literal).
1.1       anton    5360: 
1.26      crook    5361: You can compile the compilation semantics with @code{postpone,}. I.e.,
1.29      crook    5362: @code{COMP' @i{word} postpone,} is equivalent to @code{postpone
                   5363: @i{word}}.
1.21      crook    5364: 
1.26      crook    5365: @cindex name token
                   5366: @cindex name field address
                   5367: @cindex NFA
1.29      crook    5368: Named words are also represented by the @dfn{name token}, (@i{nt}). In
                   5369: Gforth, the abstract data type @emph{name token} is implemented as a
                   5370: name field address (NFA).
                   5371: 
1.44    ! crook    5372: 
1.29      crook    5373: doc-execute
                   5374: doc-compile,
                   5375: doc-[']
                   5376: doc-'
                   5377: doc-[comp']
                   5378: doc-comp'
                   5379: doc-postpone,
1.1       anton    5380: 
1.26      crook    5381: doc-find-name
                   5382: doc-name>int
                   5383: doc-name?int
                   5384: doc-name>comp
                   5385: doc-name>string
1.1       anton    5386: 
1.44    ! crook    5387: 
1.26      crook    5388: @c -------------------------------------------------------------
                   5389: @node Word Lists, Environmental Queries, Tokens for Words, Words
                   5390: @section Word Lists
                   5391: @cindex word lists
1.32      anton    5392: @cindex header space
1.1       anton    5393: 
1.36      anton    5394: A wordlist is a list of named words; you can add new words and look up
                   5395: words by name (and you can remove words in a restricted way with
                   5396: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
                   5397: 
                   5398: @cindex search order stack
                   5399: The text interpreter searches the wordlists present in the search order
                   5400: (a stack of wordlists), from the top to the bottom.  Within each
                   5401: wordlist, the search starts conceptually at the newest word; i.e., if
                   5402: two words in a wordlist have the same name, the newer word is found.
1.1       anton    5403: 
1.26      crook    5404: @cindex compilation word list
1.36      anton    5405: New words are added to the @dfn{compilation wordlist} (aka current
                   5406: wordlist).
1.1       anton    5407: 
1.36      anton    5408: @cindex wid
                   5409: A word list is identified by a cell-sized word list identifier (@i{wid})
                   5410: in much the same way as a file is identified by a file handle. The
                   5411: numerical value of the wid has no (portable) meaning, and might change
                   5412: from session to session.
1.1       anton    5413: 
1.29      crook    5414: The ANS Forth ``Search order'' word set is intended to provide a set of
                   5415: low-level tools that allow various different schemes to be
1.26      crook    5416: implemented. Gforth provides @code{vocabulary}, a traditional Forth
                   5417: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
                   5418: Standard Forth.
1.1       anton    5419: 
1.27      crook    5420: @comment TODO: locals section refers to here, saying that every word list (aka
                   5421: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.1       anton    5422: 
1.27      crook    5423: @comment the thisone- prefix is used to pick out the true definition of a
                   5424: @comment word from the source files, rather than some alias.
1.44    ! crook    5425: 
1.26      crook    5426: doc-forth-wordlist
                   5427: doc-definitions
                   5428: doc-get-current
                   5429: doc-set-current
                   5430: doc-get-order
1.27      crook    5431: doc---thisone-set-order
1.26      crook    5432: doc-wordlist
1.30      anton    5433: doc-table
1.36      anton    5434: doc-push-order
                   5435: doc-previous
1.26      crook    5436: doc-also
1.27      crook    5437: doc---thisone-forth
1.26      crook    5438: doc-only
1.27      crook    5439: doc---thisone-order
1.15      anton    5440: 
1.26      crook    5441: doc-find
                   5442: doc-search-wordlist
1.15      anton    5443: 
1.26      crook    5444: doc-words
                   5445: doc-vlist
1.44    ! crook    5446: @c doc-words-deferred
1.1       anton    5447: 
1.26      crook    5448: doc-mappedwordlist
                   5449: doc-root
                   5450: doc-vocabulary
                   5451: doc-seal
                   5452: doc-vocs
                   5453: doc-current
                   5454: doc-context
1.1       anton    5455: 
1.44    ! crook    5456: 
1.26      crook    5457: @menu
                   5458: * Why use word lists?::
                   5459: * Word list examples::
                   5460: @end menu
                   5461: 
                   5462: @node Why use word lists?, Word list examples, Word Lists, Word Lists
                   5463: @subsection Why use word lists?
                   5464: @cindex word lists - why use them?
                   5465: 
1.29      crook    5466: Here are some reasons for using multiple word lists:
1.26      crook    5467: 
                   5468: @itemize @bullet
                   5469: @item
1.32      anton    5470: To improve compilation speed by reducing the number of header space
1.26      crook    5471: entries that must be searched. This is achieved by creating a new
                   5472: word list that contains all of the definitions that are used in the
                   5473: definition of a Forth system but which would not usually be used by
                   5474: programs running on that system. That word list would be on the search
                   5475: list when the Forth system was compiled but would be removed from the
                   5476: search list for normal operation. This can be a useful technique for
                   5477: low-performance systems (for example, 8-bit processors in embedded
                   5478: systems) but is unlikely to be necessary in high-performance desktop
                   5479: systems.
                   5480: @item
                   5481: To prevent a set of words from being used outside the context in which
                   5482: they are valid. Two classic examples of this are an integrated editor
                   5483: (all of the edit commands are defined in a separate word list; the
                   5484: search order is set to the editor word list when the editor is invoked;
                   5485: the old search order is restored when the editor is terminated) and an
                   5486: integrated assembler (the op-codes for the machine are defined in a
                   5487: separate word list which is used when a @code{CODE} word is defined).
                   5488: @item
                   5489: To prevent a name-space clash between multiple definitions with the same
                   5490: name. For example, when building a cross-compiler you might have a word
                   5491: @code{IF} that generates conditional code for your target system. By
                   5492: placing this definition in a different word list you can control whether
                   5493: the host system's @code{IF} or the target system's @code{IF} get used in
                   5494: any particular context by controlling the order of the word lists on the
                   5495: search order stack.
                   5496: @end itemize
1.1       anton    5497: 
1.26      crook    5498: @node Word list examples, ,Why use word lists?, Word Lists
                   5499: @subsection Word list examples
                   5500: @cindex word lists - examples
1.1       anton    5501: 
1.26      crook    5502: Here is an example of creating and using a new wordlist using ANS
                   5503: Forth Standard words:
1.1       anton    5504: 
                   5505: @example
1.26      crook    5506: wordlist constant my-new-words-wordlist
                   5507: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
1.21      crook    5508: 
1.26      crook    5509: \ add it to the search order
                   5510: also my-new-words
1.21      crook    5511: 
1.26      crook    5512: \ alternatively, add it to the search order and make it
                   5513: \ the compilation word list
                   5514: also my-new-words definitions
                   5515: \ type "order" to see the problem
1.21      crook    5516: @end example
                   5517: 
1.26      crook    5518: The problem with this example is that @code{order} has no way to
                   5519: associate the name @code{my-new-words} with the wid of the word list (in
                   5520: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   5521: that has no associated name). There is no Standard way of associating a
                   5522: name with a wid.
                   5523: 
                   5524: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   5525: associates a name with a wid:
1.21      crook    5526: 
1.26      crook    5527: @example
                   5528: vocabulary my-new-words
1.21      crook    5529: 
1.26      crook    5530: \ add it to the search order
                   5531: my-new-words
1.21      crook    5532: 
1.26      crook    5533: \ alternatively, add it to the search order and make it
                   5534: \ the compilation word list
                   5535: my-new-words definitions
                   5536: \ type "order" to see that the problem is solved
                   5537: @end example
1.23      crook    5538: 
1.26      crook    5539: @c -------------------------------------------------------------
                   5540: @node Environmental Queries, Files, Word Lists, Words
                   5541: @section Environmental Queries
                   5542: @cindex environmental queries
1.21      crook    5543: 
1.26      crook    5544: ANS Forth introduced the idea of ``environmental queries'' as a way
                   5545: for a program running on a system to determine certain characteristics of the system.
                   5546: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    5547: 
1.32      anton    5548: The Standard requires that the header space used for environmental queries
                   5549: be distinct from the header space used for definitions.
1.21      crook    5550: 
1.26      crook    5551: Typically, environmental queries are supported by creating a set of
1.29      crook    5552: definitions in a word list that is @i{only} used during environmental
1.26      crook    5553: queries; that is what Gforth does. There is no Standard way of adding
                   5554: definitions to the set of recognised environmental queries, but any
                   5555: implementation that supports the loading of optional word sets must have
                   5556: some mechanism for doing this (after loading the word set, the
                   5557: associated environmental query string must return @code{true}). In
                   5558: Gforth, the word list used to honour environmental queries can be
                   5559: manipulated just like any other word list.
1.21      crook    5560: 
1.44    ! crook    5561: 
1.26      crook    5562: doc-environment?
                   5563: doc-environment-wordlist
1.21      crook    5564: 
1.26      crook    5565: doc-gforth
                   5566: doc-os-class
1.21      crook    5567: 
1.44    ! crook    5568: 
1.26      crook    5569: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   5570: returning two items on the stack, querying it using @code{environment?}
                   5571: will return an additional item; the @code{true} flag that shows that the
                   5572: string was recognised.
1.21      crook    5573: 
1.26      crook    5574: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    5575: 
1.26      crook    5576: Here are some examples of using environmental queries:
1.21      crook    5577: 
1.26      crook    5578: @example
                   5579: s" address-unit-bits" environment? 0=
                   5580: [IF]
                   5581:      cr .( environmental attribute address-units-bits unknown... ) cr
                   5582: [THEN]
1.21      crook    5583: 
1.26      crook    5584: s" block" environment? [IF] DROP include block.fs [THEN]
1.21      crook    5585: 
1.26      crook    5586: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
1.21      crook    5587: 
1.26      crook    5588: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   5589:                         [ELSE] .( Not Gforth..) [THEN]
                   5590: @end example
1.21      crook    5591: 
                   5592: 
1.26      crook    5593: Here is an example of adding a definition to the environment word list:
1.21      crook    5594: 
1.26      crook    5595: @example
                   5596: get-current environment-wordlist set-current
                   5597: true constant block
                   5598: true constant block-ext
                   5599: set-current
                   5600: @end example
1.21      crook    5601: 
1.26      crook    5602: You can see what definitions are in the environment word list like this:
1.21      crook    5603: 
1.26      crook    5604: @example
                   5605: get-order 1+ environment-wordlist swap set-order words previous
                   5606: @end example
1.21      crook    5607: 
                   5608: 
1.26      crook    5609: @c -------------------------------------------------------------
                   5610: @node Files, Blocks, Environmental Queries, Words
                   5611: @section Files
1.28      crook    5612: @cindex files
                   5613: @cindex I/O - file-handling
1.21      crook    5614: 
1.26      crook    5615: Gforth provides facilities for accessing files that are stored in the
                   5616: host operating system's file-system. Files that are processed by Gforth
                   5617: can be divided into two categories:
1.21      crook    5618: 
1.23      crook    5619: @itemize @bullet
                   5620: @item
1.29      crook    5621: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    5622: @item
1.29      crook    5623: Files that are processed by some other program (@dfn{general files}).
1.26      crook    5624: @end itemize
                   5625: 
                   5626: @menu
                   5627: * Forth source files::
                   5628: * General files::         
                   5629: * Search Paths::                 
                   5630: * Forth Search Paths::    
                   5631: * General Search Paths::        
                   5632: @end menu
                   5633: 
1.21      crook    5634: 
1.26      crook    5635: @c -------------------------------------------------------------
                   5636: @node Forth source files, General files, Files, Files
                   5637: @subsection Forth source files
                   5638: @cindex including files
                   5639: @cindex Forth source files
1.21      crook    5640: 
1.26      crook    5641: The simplest way to interpret the contents of a file is to use one of
                   5642: these two formats:
1.21      crook    5643: 
1.26      crook    5644: @example
                   5645: include mysource.fs
                   5646: s" mysource.fs" included
                   5647: @end example
1.21      crook    5648: 
1.26      crook    5649: Sometimes you want to include a file only if it is not included already
                   5650: (by, say, another source file). In that case, you can use one of these
                   5651: fomats:
1.21      crook    5652: 
1.26      crook    5653: @example
                   5654: require mysource.fs
                   5655: needs mysource.fs
                   5656: s" mysource.fs" required
                   5657: @end example
1.21      crook    5658: 
1.26      crook    5659: @cindex stack effect of included files
                   5660: @cindex including files, stack effect
                   5661: I recommend that you write your source files such that interpreting them
                   5662: does not change the stack. This allows using these files with
                   5663: @code{required} and friends without complications. For example:
1.21      crook    5664: 
1.26      crook    5665: @example
                   5666: 1 require foo.fs drop
                   5667: @end example
1.21      crook    5668: 
1.44    ! crook    5669: 
1.26      crook    5670: doc-include-file
                   5671: doc-included
1.28      crook    5672: doc-included?
1.26      crook    5673: doc-include
                   5674: doc-required
                   5675: doc-require
                   5676: doc-needs
1.28      crook    5677: doc-init-included-files
1.21      crook    5678: 
1.44    ! crook    5679: 
1.26      crook    5680: A definition in ANS Forth for @code{required} is provided in
                   5681: @file{compat/required.fs}.
1.21      crook    5682: 
1.26      crook    5683: @c -------------------------------------------------------------
                   5684: @node General files, Search Paths, Forth source files, Files
                   5685: @subsection General files
                   5686: @cindex general files
                   5687: @cindex file-handling
1.21      crook    5688: 
1.26      crook    5689: Files are opened/created by name and type. The following types are
                   5690: recognised:
1.1       anton    5691: 
1.44    ! crook    5692: 
1.26      crook    5693: doc-r/o
                   5694: doc-r/w
                   5695: doc-w/o
                   5696: doc-bin
1.1       anton    5697: 
1.44    ! crook    5698: 
1.26      crook    5699: When a file is opened/created, it returns a file identifier,
1.29      crook    5700: @i{wfileid} that is used for all other file commands. All file
                   5701: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    5702: successful operation and an implementation-defined non-zero value in the
                   5703: case of an error.
1.21      crook    5704: 
1.44    ! crook    5705: 
1.26      crook    5706: doc-open-file
                   5707: doc-create-file
1.21      crook    5708: 
1.26      crook    5709: doc-close-file
                   5710: doc-delete-file
                   5711: doc-rename-file
                   5712: doc-read-file
                   5713: doc-read-line
                   5714: doc-write-file
                   5715: doc-write-line
                   5716: doc-emit-file
                   5717: doc-flush-file
1.21      crook    5718: 
1.26      crook    5719: doc-file-status
                   5720: doc-file-position
                   5721: doc-reposition-file
                   5722: doc-file-size
                   5723: doc-resize-file
1.21      crook    5724: 
1.44    ! crook    5725: 
1.26      crook    5726: @c ---------------------------------------------------------
                   5727: @node Search Paths, Forth Search Paths, General files, Files
                   5728: @subsection Search Paths
                   5729: @cindex path for @code{included}
                   5730: @cindex file search path
                   5731: @cindex @code{include} search path
                   5732: @cindex search path for files
1.21      crook    5733: 
1.26      crook    5734: If you specify an absolute filename (i.e., a filename starting with
                   5735: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   5736: @samp{C:...})) for @code{included} and friends, that file is included
                   5737: just as you would expect.
1.21      crook    5738: 
1.26      crook    5739: For relative filenames, Gforth uses a search path similar to Forth's
                   5740: search order (@pxref{Word Lists}). It tries to find the given filename
                   5741: in the directories present in the path, and includes the first one it
                   5742: finds. There are separate search paths for Forth source files and
                   5743: general files.
1.21      crook    5744: 
1.26      crook    5745: If the search path contains the directory @file{.} (as it should), this
                   5746: refers to the directory that the present file was @code{included}
                   5747: from. This allows files to include other files relative to their own
                   5748: position (irrespective of the current working directory or the absolute
                   5749: position).  This feature is essential for libraries consisting of
                   5750: several files, where a file may include other files from the library.
                   5751: It corresponds to @code{#include "..."} in C. If the current input
                   5752: source is not a file, @file{.} refers to the directory of the innermost
                   5753: file being included, or, if there is no file being included, to the
                   5754: current working directory.
1.21      crook    5755: 
1.26      crook    5756: Use @file{~+} to refer to the current working directory (as in the
                   5757: @code{bash}).
1.1       anton    5758: 
1.26      crook    5759: If the filename starts with @file{./}, the search path is not searched
                   5760: (just as with absolute filenames), and the @file{.} has the same meaning
                   5761: as described above.
1.1       anton    5762: 
1.26      crook    5763: @c ---------------------------------------------------------
                   5764: @node Forth Search Paths, General Search Paths, Search Paths, Files
                   5765: @subsubsection Forth Search Paths
1.28      crook    5766: @cindex search path control - Forth
1.5       anton    5767: 
1.26      crook    5768: The search path is initialized when you start Gforth (@pxref{Invoking
                   5769: Gforth}). You can display it and change it using these words:
1.5       anton    5770: 
1.44    ! crook    5771: 
1.26      crook    5772: doc-.fpath
                   5773: doc-fpath+
                   5774: doc-fpath=
                   5775: doc-open-fpath-file
1.5       anton    5776: 
1.44    ! crook    5777: 
        !          5778: @noindent
1.26      crook    5779: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    5780: 
1.26      crook    5781: @example
                   5782: fpath= /usr/lib/forth/|./
                   5783: require timer.fs
                   5784: @end example
1.5       anton    5785: 
1.26      crook    5786: @c ---------------------------------------------------------
                   5787: @node General Search Paths,  , Forth Search Paths, Files
                   5788: @subsubsection General Search Paths
                   5789: @cindex search path control - for user applications
1.5       anton    5790: 
1.26      crook    5791: Your application may need to search files in several directories, like
                   5792: @code{included} does. To facilitate this, Gforth allows you to define
                   5793: and use your own search paths, by providing generic equivalents of the
                   5794: Forth search path words:
1.5       anton    5795: 
1.44    ! crook    5796: 
1.26      crook    5797: doc-.path
                   5798: doc-path+
                   5799: doc-path=
                   5800: doc-open-path-file
1.5       anton    5801: 
1.44    ! crook    5802: 
1.26      crook    5803: Here's an example of creating a search path:
1.5       anton    5804: 
1.26      crook    5805: @example
                   5806: \ Make a buffer for the path:
                   5807: create mypath   100 chars ,     \ maximum length (is checked)
                   5808:                 0 ,             \ real len
                   5809:                 100 chars allot \ space for path
                   5810: @end example
1.5       anton    5811: 
1.26      crook    5812: @c -------------------------------------------------------------
                   5813: @node Blocks, Other I/O, Files, Words
                   5814: @section Blocks
1.28      crook    5815: @cindex I/O - blocks
                   5816: @cindex blocks
                   5817: 
                   5818: When you run Gforth on a modern desk-top computer, it runs under the
                   5819: control of an operating system which provides certain services.  One of
                   5820: these services is @var{file services}, which allows Forth source code
                   5821: and data to be stored in files and read into Gforth (@pxref{Files}).
                   5822: 
                   5823: Traditionally, Forth has been an important programming language on
                   5824: systems where it has interfaced directly to the underlying hardware with
                   5825: no intervening operating system. Forth provides a mechanism, called
1.29      crook    5826: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    5827: 
                   5828: A block is a 1024-byte data area, which can be used to hold data or
                   5829: Forth source code. No structure is imposed on the contents of the
                   5830: block. A block is identified by its number; blocks are numbered
                   5831: contiguously from 1 to an implementation-defined maximum.
                   5832: 
                   5833: A typical system that used blocks but no operating system might use a
                   5834: single floppy-disk drive for mass storage, with the disks formatted to
                   5835: provide 256-byte sectors. Blocks would be implemented by assigning the
                   5836: first four sectors of the disk to block 1, the second four sectors to
                   5837: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   5838: would not contain any file system information, just the set of blocks.
                   5839: 
1.29      crook    5840: @cindex blocks file
1.28      crook    5841: On systems that do provide file services, blocks are typically
1.29      crook    5842: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    5843: file}.  The size of the blocks file will be an exact multiple of 1024
                   5844: bytes, corresponding to the number of blocks it contains. This is the
                   5845: mechanism that Gforth uses.
                   5846: 
1.29      crook    5847: @cindex @file{blocks.fb}
1.28      crook    5848: Only 1 blocks file can be open at a time. If you use block words without
                   5849: having specified a blocks file, Gforth defaults to the blocks file
                   5850: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
                   5851: locate a blocks file (@pxref{Forth Search Paths}).
                   5852: 
1.29      crook    5853: @cindex block buffers
1.28      crook    5854: When you read and write blocks under program control, Gforth uses a
1.29      crook    5855: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    5856: not used when you use @code{load} to interpret the contents of a block.
                   5857: 
                   5858: The behaviour of the block buffers is directly analagous to that of a
                   5859: cache. Each block buffer has three states:
                   5860: 
                   5861: @itemize @bullet
                   5862: @item
                   5863: Unassigned
                   5864: @item
                   5865: Assigned-clean
                   5866: @item
                   5867: Assigned-dirty
                   5868: @end itemize
                   5869: 
1.29      crook    5870: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    5871: block, the block (specified by its block number) must be assigned to a
                   5872: block buffer.
                   5873: 
                   5874: The assignment of a block to a block buffer is performed by @code{block}
                   5875: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   5876: contents of a block. Use @code{buffer} when you don't care about the
                   5877: existing contents of the block@footnote{The ANS Forth definition of
1.35      anton    5878: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28      crook    5879: with the particular block is already stored in a block buffer due to an
                   5880: earlier @code{block} command, @code{buffer} will return that block
                   5881: buffer and the existing contents of the block will be
                   5882: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29      crook    5883: block buffer for the block.}.
1.28      crook    5884: 
                   5885: Once a block has been assigned to a block buffer, the block buffer state
1.29      crook    5886: becomes @i{assigned-clean}. Data can now be manipulated within the
1.28      crook    5887: block buffer.
                   5888: 
                   5889: When the contents of a block buffer is changed it is necessary,
                   5890: @i{before calling} @code{block} @i{or} @code{buffer} @i{again}, to
                   5891: either abandon the changes (by doing nothing) or commit the changes,
                   5892: using @code{update}. Using @code{update} does not change the blocks
1.29      crook    5893: file; it simply changes a block buffer's state to @i{assigned-dirty}.
1.28      crook    5894: 
1.29      crook    5895: The word @code{flush} causes all @i{assigned-dirty} blocks to be
1.28      crook    5896: written back to the blocks file on disk. Leaving Gforth using @code{bye}
                   5897: also causes a @code{flush} to be performed.
                   5898: 
1.29      crook    5899: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    5900: algorithm to assign a block buffer to a block. That means that any
                   5901: particular block can only be assigned to one specific block buffer,
1.29      crook    5902: called (for the particular operation) the @i{victim buffer}. If the
                   5903: victim buffer is @i{unassigned} or @i{assigned-clean} it can be
                   5904: allocated to the new block immediately. If it is @i{assigned-dirty}
1.28      crook    5905: its current contents must be written out to disk before it can be
                   5906: allocated to the new block.
                   5907: 
                   5908: Although no structure is imposed on the contents of a block, it is
                   5909: traditional to display the contents as 16 lines each of 64 characters.  A
                   5910: block provides a single, continuous stream of input (for example, it
                   5911: acts as a single parse area) -- there are no end-of-line characters
                   5912: within a block, and no end-of-file character at the end of a
                   5913: block. There are two consequences of this:
1.26      crook    5914: 
1.28      crook    5915: @itemize @bullet
                   5916: @item
                   5917: The last character of one line wraps straight into the first character
                   5918: of the following line
                   5919: @item
                   5920: The word @code{\} -- comment to end of line -- requires special
                   5921: treatment; in the context of a block it causes all characters until the
                   5922: end of the current 64-character ``line'' to be ignored.
                   5923: @end itemize
                   5924: 
                   5925: In Gforth, when you use @code{block} with a non-existent block number,
                   5926: the current block file will be extended to the appropriate size and the
                   5927: block buffer will be initialised with spaces.
                   5928: 
1.29      crook    5929: Gforth doesn't encourage the use of blocks; the mechanism is only
                   5930: provided for backward compatibility -- ANS Forth requires blocks to be
                   5931: available when files are.
1.28      crook    5932: 
                   5933: Common techniques that are used when working with blocks include:
                   5934: 
                   5935: @itemize @bullet
                   5936: @item
                   5937: A screen editor that allows you to edit blocks without leaving the Forth
                   5938: environment.
                   5939: @item
                   5940: Shadow screens; where every code block has an associated block
                   5941: containing comments (for example: code in odd block numbers, comments in
                   5942: even block numbers). Typically, the block editor provides a convenient
                   5943: mechanism to toggle between code and comments.
                   5944: @item
                   5945: Load blocks; a single block (typically block 1) contains a number of
                   5946: @code{thru} commands which @code{load} the whole of the application.
                   5947: @end itemize
1.26      crook    5948: 
1.29      crook    5949: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
                   5950: integrated into a Forth programming environment.
1.26      crook    5951: 
                   5952: @comment TODO what about errors on open-blocks?
1.44    ! crook    5953: 
1.26      crook    5954: doc-open-blocks
                   5955: doc-use
                   5956: doc-get-block-fid
                   5957: doc-block-position
1.28      crook    5958: 
                   5959: doc-scr
                   5960: doc-list
                   5961: 
                   5962: doc---block-block
                   5963: doc-buffer
                   5964: 
1.26      crook    5965: doc-update
1.28      crook    5966: doc-updated?
1.26      crook    5967: doc-save-buffers
                   5968: doc-empty-buffers
                   5969: doc-empty-buffer
                   5970: doc-flush
1.28      crook    5971: 
1.26      crook    5972: doc-load
                   5973: doc-thru
                   5974: doc-+load
                   5975: doc-+thru
1.44    ! crook    5976: doc---gforth--->
1.26      crook    5977: doc-block-included
                   5978: 
1.44    ! crook    5979: 
1.26      crook    5980: @c -------------------------------------------------------------
                   5981: @node Other I/O, Programming Tools, Blocks, Words
                   5982: @section Other I/O
1.28      crook    5983: @cindex I/O - keyboard and display
1.26      crook    5984: 
                   5985: @menu
                   5986: * Simple numeric output::       Predefined formats
                   5987: * Formatted numeric output::    Formatted (pictured) output
                   5988: * String Formats::              How Forth stores strings in memory
                   5989: * Displaying characters and strings:: Other stuff
                   5990: * Input::                       Input
                   5991: @end menu
                   5992: 
                   5993: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   5994: @subsection Simple numeric output
1.28      crook    5995: @cindex numeric output - simple/free-format
1.5       anton    5996: 
1.26      crook    5997: The simplest output functions are those that display numbers from the
                   5998: data or floating-point stacks. Floating-point output is always displayed
                   5999: using base 10. Numbers displayed from the data stack use the value stored
                   6000: in @code{base}.
1.5       anton    6001: 
1.44    ! crook    6002: 
1.26      crook    6003: doc-.
                   6004: doc-dec.
                   6005: doc-hex.
                   6006: doc-u.
                   6007: doc-.r
                   6008: doc-u.r
                   6009: doc-d.
                   6010: doc-ud.
                   6011: doc-d.r
                   6012: doc-ud.r
                   6013: doc-f.
                   6014: doc-fe.
                   6015: doc-fs.
1.5       anton    6016: 
1.44    ! crook    6017: 
1.26      crook    6018: Examples of printing the number 1234.5678E23 in the different floating-point output
                   6019: formats are shown below:
1.5       anton    6020: 
                   6021: @example
1.26      crook    6022: f. 123456779999999000000000000.
                   6023: fe. 123.456779999999E24
                   6024: fs. 1.23456779999999E26
1.5       anton    6025: @end example
                   6026: 
                   6027: 
1.26      crook    6028: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   6029: @subsection Formatted numeric output
1.28      crook    6030: @cindex formatted numeric output
1.26      crook    6031: @cindex pictured numeric output
1.28      crook    6032: @cindex numeric output - formatted
1.26      crook    6033: 
1.29      crook    6034: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    6035: output} for formatted printing of integers.  In this technique, digits
                   6036: are extracted from the number (using the current output radix defined by
                   6037: @code{base}), converted to ASCII codes and appended to a string that is
                   6038: built in a scratch-pad area of memory (@pxref{core-idef,
                   6039: Implementation-defined options, Implementation-defined
                   6040: options}). Arbitrary characters can be appended to the string during the
                   6041: extraction process. The completed string is specified by an address
                   6042: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   6043: under program control.
1.5       anton    6044: 
1.26      crook    6045: All of the words described in the previous section for simple numeric
                   6046: output are implemented in Gforth using pictured numeric output.
1.5       anton    6047: 
1.26      crook    6048: Three important things to remember about Pictured Numeric Output:
1.5       anton    6049: 
1.26      crook    6050: @itemize @bullet
                   6051: @item
1.28      crook    6052: It always operates on double-precision numbers; to display a
                   6053: single-precision number, convert it first (@pxref{Double precision} for
                   6054: ways of doing this).
1.26      crook    6055: @item
1.28      crook    6056: It always treats the double-precision number as though it were
                   6057: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    6058: @item
                   6059: The string is built up from right to left; least significant digit first.
                   6060: @end itemize
1.5       anton    6061: 
1.44    ! crook    6062: 
1.26      crook    6063: doc-<#
                   6064: doc-#
                   6065: doc-#s
                   6066: doc-hold
                   6067: doc-sign
                   6068: doc-#>
1.5       anton    6069: 
1.26      crook    6070: doc-represent
1.5       anton    6071: 
1.44    ! crook    6072: 
        !          6073: @noindent
1.26      crook    6074: Here are some examples of using pictured numeric output:
1.5       anton    6075: 
                   6076: @example
1.26      crook    6077: : my-u. ( u -- )
                   6078:   \ Simplest use of pns.. behaves like Standard u. 
                   6079:   0              \ convert to unsigned double
                   6080:   <#             \ start conversion
                   6081:   #s             \ convert all digits
                   6082:   #>             \ complete conversion
                   6083:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    6084: 
1.26      crook    6085: : cents-only ( u -- )
                   6086:   0              \ convert to unsigned double
                   6087:   <#             \ start conversion
                   6088:   # #            \ convert two least-significant digits
                   6089:   #>             \ complete conversion, discard other digits
                   6090:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    6091: 
1.26      crook    6092: : dollars-and-cents ( u -- )
                   6093:   0              \ convert to unsigned double
                   6094:   <#             \ start conversion
                   6095:   # #            \ convert two least-significant digits
                   6096:   [char] . hold  \ insert decimal point
                   6097:   #s             \ convert remaining digits
                   6098:   [char] $ hold  \ append currency symbol
                   6099:   #>             \ complete conversion
                   6100:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    6101: 
1.26      crook    6102: : my-. ( n -- )
                   6103:   \ handling negatives.. behaves like Standard .
                   6104:   s>d            \ convert to signed double
                   6105:   swap over dabs \ leave sign byte followed by unsigned double
                   6106:   <#             \ start conversion
                   6107:   #s             \ convert all digits
                   6108:   rot sign       \ get at sign byte, append "-" if needed
                   6109:   #>             \ complete conversion
                   6110:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    6111: 
1.26      crook    6112: : account. ( n -- )
                   6113:   \ accountants don't like minus signs, they use braces
                   6114:   \ for negative numbers
                   6115:   s>d            \ convert to signed double
                   6116:   swap over dabs \ leave sign byte followed by unsigned double
                   6117:   <#             \ start conversion
                   6118:   2 pick         \ get copy of sign byte
                   6119:   0< IF [char] ) hold THEN \ right-most character of output
                   6120:   #s             \ convert all digits
                   6121:   rot            \ get at sign byte
                   6122:   0< IF [char] ( hold THEN
                   6123:   #>             \ complete conversion
                   6124:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    6125: @end example
                   6126: 
1.26      crook    6127: Here are some examples of using these words:
1.5       anton    6128: 
                   6129: @example
1.26      crook    6130: 1 my-u. 1
                   6131: hex -1 my-u. decimal FFFFFFFF
                   6132: 1 cents-only 01
                   6133: 1234 cents-only 34
                   6134: 2 dollars-and-cents $0.02
                   6135: 1234 dollars-and-cents $12.34
                   6136: 123 my-. 123
                   6137: -123 my. -123
                   6138: 123 account. 123
                   6139: -456 account. (456)
1.5       anton    6140: @end example
                   6141: 
                   6142: 
1.26      crook    6143: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   6144: @subsection String Formats
1.27      crook    6145: @cindex strings - see character strings
                   6146: @cindex character strings - formats
1.28      crook    6147: @cindex I/O - see character strings
1.26      crook    6148: 
1.27      crook    6149: Forth commonly uses two different methods for representing character
                   6150: strings:
1.26      crook    6151: 
                   6152: @itemize @bullet
                   6153: @item
                   6154: @cindex address of counted string
1.29      crook    6155: As a @dfn{counted string}, represented by a @i{c-addr}. The char
                   6156: addressed by @i{c-addr} contains a character-count, @i{n}, of the
                   6157: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    6158: memory.
                   6159: @item
1.29      crook    6160: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
                   6161: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    6162: first byte of the string.
                   6163: @end itemize
                   6164: 
                   6165: ANS Forth encourages the use of the second format when representing
                   6166: strings on the stack, whilst conceeding that the counted string format
                   6167: remains useful as a way of storing strings in memory.
                   6168: 
1.44    ! crook    6169: 
1.26      crook    6170: doc-count
                   6171: 
1.44    ! crook    6172: 
1.26      crook    6173: @xref{Memory Blocks} for words that move, copy and search
                   6174: for strings. @xref{Displaying characters and strings,} for words that
                   6175: display characters and strings.
                   6176: 
                   6177: 
                   6178: @node Displaying characters and strings, Input, String Formats, Other I/O
                   6179: @subsection Displaying characters and strings
1.27      crook    6180: @cindex characters - compiling and displaying
                   6181: @cindex character strings - compiling and displaying
1.26      crook    6182: 
                   6183: This section starts with a glossary of Forth words and ends with a set
                   6184: of examples.
                   6185: 
1.44    ! crook    6186: 
1.26      crook    6187: doc-bl
                   6188: doc-space
                   6189: doc-spaces
                   6190: doc-emit
                   6191: doc-toupper
                   6192: doc-."
                   6193: doc-.(
                   6194: doc-type
1.44    ! crook    6195: doc-typewhite
1.26      crook    6196: doc-cr
1.27      crook    6197: @cindex cursor control
1.26      crook    6198: doc-at-xy
                   6199: doc-page
                   6200: doc-s"
                   6201: doc-c"
                   6202: doc-char
                   6203: doc-[char]
                   6204: doc-sliteral
                   6205: 
1.44    ! crook    6206: 
        !          6207: @noindent
1.26      crook    6208: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    6209: 
                   6210: @example
1.26      crook    6211: .( text-1)
                   6212: : my-word
                   6213:   ." text-2" cr
                   6214:   .( text-3)
                   6215: ;
                   6216: 
                   6217: ." text-4"
                   6218: 
                   6219: : my-char
                   6220:   [char] ALPHABET emit
                   6221:   char emit
                   6222: ;
1.5       anton    6223: @end example
                   6224: 
1.26      crook    6225: When you load this code into Gforth, the following output is generated:
1.5       anton    6226: 
1.26      crook    6227: @example
1.30      anton    6228: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26      crook    6229: @end example
1.5       anton    6230: 
1.26      crook    6231: @itemize @bullet
                   6232: @item
                   6233: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   6234: is an immediate word; it behaves in the same way whether it is used inside
                   6235: or outside a colon definition.
                   6236: @item
                   6237: Message @code{text-4} is displayed because of Gforth's added interpretation
                   6238: semantics for @code{."}.
                   6239: @item
1.29      crook    6240: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    6241: performs the compilation semantics for @code{."} within the definition of
                   6242: @code{my-word}.
                   6243: @end itemize
1.5       anton    6244: 
1.26      crook    6245: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    6246: 
1.26      crook    6247: @example
1.30      anton    6248: @kbd{my-word @key{RET}} text-2
1.26      crook    6249:  ok
1.30      anton    6250: @kbd{my-char fred @key{RET}} Af ok
                   6251: @kbd{my-char jim @key{RET}} Aj ok
1.26      crook    6252: @end example
1.5       anton    6253: 
                   6254: @itemize @bullet
                   6255: @item
1.26      crook    6256: Message @code{text-2} is displayed because of the run-time behaviour of
                   6257: @code{."}.
                   6258: @item
                   6259: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   6260: on the stack at run-time. @code{emit} always displays the character
                   6261: when @code{my-char} is executed.
                   6262: @item
                   6263: @code{char} parses a string at run-time and the second @code{emit} displays
                   6264: the first character of the string.
1.5       anton    6265: @item
1.26      crook    6266: If you type @code{see my-char} you can see that @code{[char]} discarded
                   6267: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   6268: definition of @code{my-char}.
1.5       anton    6269: @end itemize
                   6270: 
                   6271: 
                   6272: 
1.26      crook    6273: @node Input, , Displaying characters and strings, Other I/O
                   6274: @subsection Input
                   6275: @cindex input
1.28      crook    6276: @cindex I/O - see input
                   6277: @cindex parsing a string
1.5       anton    6278: 
1.27      crook    6279: @xref{String Formats} for ways of storing character strings in memory.
1.5       anton    6280: 
1.27      crook    6281: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29      crook    6282: @comment then index them
1.27      crook    6283: 
1.44    ! crook    6284: 
1.27      crook    6285: doc-key
                   6286: doc-key?
1.26      crook    6287: doc->number
                   6288: doc->float
                   6289: doc-accept
1.27      crook    6290: doc-pad
                   6291: doc-parse
                   6292: doc-word
                   6293: doc-sword
1.44    ! crook    6294: doc-(name)
1.27      crook    6295: doc-refill
                   6296: @comment obsolescent words..
                   6297: doc-convert
1.26      crook    6298: doc-query
                   6299: doc-expect
1.27      crook    6300: doc-span
1.5       anton    6301: 
                   6302: 
1.44    ! crook    6303: 
1.5       anton    6304: @c -------------------------------------------------------------
1.26      crook    6305: @node Programming Tools, Assembler and Code Words, Other I/O, Words
                   6306: @section Programming Tools
                   6307: @cindex programming tools
1.12      anton    6308: 
                   6309: @menu
1.26      crook    6310: * Debugging::                   Simple and quick.
                   6311: * Assertions::                  Making your programs self-checking.
                   6312: * Singlestep Debugger::                Executing your program word by word.
1.5       anton    6313: @end menu
                   6314: 
1.26      crook    6315: @node Debugging, Assertions, Programming Tools, Programming Tools
                   6316: @subsection Debugging
                   6317: @cindex debugging
1.5       anton    6318: 
1.26      crook    6319: Languages with a slow edit/compile/link/test development loop tend to
                   6320: require sophisticated tracing/stepping debuggers to facilate
                   6321: productive debugging.
1.5       anton    6322: 
1.26      crook    6323: A much better (faster) way in fast-compiling languages is to add
                   6324: printing code at well-selected places, let the program run, look at
                   6325: the output, see where things went wrong, add more printing code, etc.,
                   6326: until the bug is found.
1.5       anton    6327: 
1.26      crook    6328: The simple debugging aids provided in @file{debugs.fs}
                   6329: are meant to support this style of debugging. In addition, there are
                   6330: words for non-destructively inspecting the stack and memory:
1.5       anton    6331: 
1.44    ! crook    6332: 
1.26      crook    6333: doc-.s
                   6334: doc-f.s
1.5       anton    6335: 
1.44    ! crook    6336: 
1.29      crook    6337: There is a word @code{.r} but it does @i{not} display the return
1.26      crook    6338: stack! It is used for formatted numeric output.
1.5       anton    6339: 
1.44    ! crook    6340: 
1.26      crook    6341: doc-depth
                   6342: doc-fdepth
                   6343: doc-clearstack
                   6344: doc-?
                   6345: doc-dump
1.5       anton    6346: 
1.44    ! crook    6347: 
1.26      crook    6348: The word @code{~~} prints debugging information (by default the source
                   6349: location and the stack contents). It is easy to insert. If you use Emacs
                   6350: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   6351: query-replace them with nothing). The deferred words
                   6352: @code{printdebugdata} and @code{printdebugline} control the output of
                   6353: @code{~~}. The default source location output format works well with
                   6354: Emacs' compilation mode, so you can step through the program at the
                   6355: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   6356: is that you can step in any direction and you know where the crash has
                   6357: happened or where the strange data has occurred).
1.5       anton    6358: 
1.26      crook    6359: The default actions of @code{~~} clobber the contents of the pictured
                   6360: numeric output string, so you should not use @code{~~}, e.g., between
                   6361: @code{<#} and @code{#>}.
1.5       anton    6362: 
1.44    ! crook    6363: 
1.26      crook    6364: doc-~~
                   6365: doc-printdebugdata
                   6366: doc-printdebugline
1.5       anton    6367: 
1.26      crook    6368: doc-see
                   6369: doc-marker
1.5       anton    6370: 
1.44    ! crook    6371: 
1.26      crook    6372: Here's an example of using @code{marker} at the start of a source file
                   6373: that you are debugging; it ensures that you only ever have one copy of
                   6374: the file's definitions compiled at any time:
1.5       anton    6375: 
1.26      crook    6376: @example
                   6377: [IFDEF] my-code
                   6378:     my-code
                   6379: [ENDIF]
1.5       anton    6380: 
1.26      crook    6381: marker my-code
1.28      crook    6382: init-included-files
1.5       anton    6383: 
1.26      crook    6384: \ .. definitions start here
                   6385: \ .
                   6386: \ .
                   6387: \ end
                   6388: @end example
1.5       anton    6389: 
                   6390: 
                   6391: 
1.26      crook    6392: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
                   6393: @subsection Assertions
                   6394: @cindex assertions
1.5       anton    6395: 
1.26      crook    6396: It is a good idea to make your programs self-checking, especially if you
                   6397: make an assumption that may become invalid during maintenance (for
                   6398: example, that a certain field of a data structure is never zero). Gforth
1.29      crook    6399: supports @dfn{assertions} for this purpose. They are used like this:
1.23      crook    6400: 
1.26      crook    6401: @example
1.29      crook    6402: assert( @i{flag} )
1.26      crook    6403: @end example
1.23      crook    6404: 
1.26      crook    6405: The code between @code{assert(} and @code{)} should compute a flag, that
                   6406: should be true if everything is alright and false otherwise. It should
                   6407: not change anything else on the stack. The overall stack effect of the
                   6408: assertion is @code{( -- )}. E.g.
1.23      crook    6409: 
1.26      crook    6410: @example
                   6411: assert( 1 1 + 2 = ) \ what we learn in school
                   6412: assert( dup 0<> ) \ assert that the top of stack is not zero
                   6413: assert( false ) \ this code should not be reached
                   6414: @end example
1.23      crook    6415: 
1.26      crook    6416: The need for assertions is different at different times. During
                   6417: debugging, we want more checking, in production we sometimes care more
                   6418: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   6419: becomes a comment. Depending on the importance of an assertion and the
                   6420: time it takes to check it, you may want to turn off some assertions and
                   6421: keep others turned on. Gforth provides several levels of assertions for
                   6422: this purpose:
1.23      crook    6423: 
1.44    ! crook    6424: 
1.26      crook    6425: doc-assert0(
                   6426: doc-assert1(
                   6427: doc-assert2(
                   6428: doc-assert3(
                   6429: doc-assert(
                   6430: doc-)
1.23      crook    6431: 
1.44    ! crook    6432: 
1.26      crook    6433: The variable @code{assert-level} specifies the highest assertions that
                   6434: are turned on. I.e., at the default @code{assert-level} of one,
                   6435: @code{assert0(} and @code{assert1(} assertions perform checking, while
                   6436: @code{assert2(} and @code{assert3(} assertions are treated as comments.
                   6437: 
                   6438: The value of @code{assert-level} is evaluated at compile-time, not at
                   6439: run-time. Therefore you cannot turn assertions on or off at run-time;
                   6440: you have to set the @code{assert-level} appropriately before compiling a
                   6441: piece of code. You can compile different pieces of code at different
                   6442: @code{assert-level}s (e.g., a trusted library at level 1 and
                   6443: newly-written code at level 3).
1.23      crook    6444: 
1.44    ! crook    6445: 
1.26      crook    6446: doc-assert-level
1.23      crook    6447: 
1.44    ! crook    6448: 
1.26      crook    6449: If an assertion fails, a message compatible with Emacs' compilation mode
                   6450: is produced and the execution is aborted (currently with @code{ABORT"}.
                   6451: If there is interest, we will introduce a special throw code. But if you
                   6452: intend to @code{catch} a specific condition, using @code{throw} is
                   6453: probably more appropriate than an assertion).
1.23      crook    6454: 
1.26      crook    6455: Definitions in ANS Forth for these assertion words are provided
                   6456: in @file{compat/assert.fs}.
1.23      crook    6457: 
                   6458: 
1.26      crook    6459: @node Singlestep Debugger, , Assertions, Programming Tools
                   6460: @subsection Singlestep Debugger
                   6461: @cindex singlestep Debugger
                   6462: @cindex debugging Singlestep
                   6463: @cindex @code{dbg}
                   6464: @cindex @code{BREAK:}
                   6465: @cindex @code{BREAK"}
1.23      crook    6466: 
1.26      crook    6467: When you create a new word there's often the need to check whether it
                   6468: behaves correctly or not. You can do this by typing @code{dbg
                   6469: badword}. A debug session might look like this:
1.23      crook    6470: 
1.26      crook    6471: @example
                   6472: : badword 0 DO i . LOOP ;  ok
                   6473: 2 dbg badword 
                   6474: : badword  
                   6475: Scanning code...
1.23      crook    6476: 
1.26      crook    6477: Nesting debugger ready!
1.23      crook    6478: 
1.26      crook    6479: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   6480: 400D4740  8049F68 DO             -> [ 0 ] 
                   6481: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   6482: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   6483: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   6484: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   6485: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   6486: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   6487: 400D4758  804B384 ;              ->  ok
                   6488: @end example
1.23      crook    6489: 
1.26      crook    6490: Each line displayed is one step. You always have to hit return to
                   6491: execute the next word that is displayed. If you don't want to execute
                   6492: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   6493: an overview what keys are available:
1.23      crook    6494: 
1.26      crook    6495: @table @i
1.23      crook    6496: 
1.30      anton    6497: @item @key{RET}
1.26      crook    6498: Next; Execute the next word.
1.23      crook    6499: 
1.26      crook    6500: @item n
                   6501: Nest; Single step through next word.
1.5       anton    6502: 
1.26      crook    6503: @item u
                   6504: Unnest; Stop debugging and execute rest of word. If we got to this word
                   6505: with nest, continue debugging with the calling word.
1.5       anton    6506: 
1.26      crook    6507: @item d
                   6508: Done; Stop debugging and execute rest.
1.5       anton    6509: 
1.26      crook    6510: @item s
                   6511: Stop; Abort immediately.
1.5       anton    6512: 
1.26      crook    6513: @end table
1.5       anton    6514: 
1.26      crook    6515: Debugging large application with this mechanism is very difficult, because
                   6516: you have to nest very deeply into the program before the interesting part
                   6517: begins. This takes a lot of time. 
1.5       anton    6518: 
1.26      crook    6519: To do it more directly put a @code{BREAK:} command into your source code.
                   6520: When program execution reaches @code{BREAK:} the single step debugger is
                   6521: invoked and you have all the features described above.
1.23      crook    6522: 
1.26      crook    6523: If you have more than one part to debug it is useful to know where the
                   6524: program has stopped at the moment. You can do this by the 
                   6525: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   6526: string is typed out when the ``breakpoint'' is reached.
                   6527: 
1.44    ! crook    6528: 
1.26      crook    6529: doc-dbg
                   6530: doc-BREAK:
                   6531: doc-BREAK"
                   6532: 
                   6533: 
1.44    ! crook    6534: 
1.26      crook    6535: @c -------------------------------------------------------------
                   6536: @node Assembler and Code Words, Threading Words, Programming Tools, Words
                   6537: @section Assembler and Code Words
                   6538: @cindex assembler
                   6539: @cindex code words
1.5       anton    6540: 
1.26      crook    6541: Gforth provides some words for defining primitives (words written in
1.29      crook    6542: machine code), and for defining the machine-code equivalent of
1.26      crook    6543: @code{DOES>}-based defining words. However, the machine-independent
                   6544: nature of Gforth poses a few problems: First of all, Gforth runs on
                   6545: several architectures, so it can provide no standard assembler. What's
                   6546: worse is that the register allocation not only depends on the processor,
                   6547: but also on the @code{gcc} version and options used.
1.5       anton    6548: 
1.29      crook    6549: The words that Gforth offers encapsulate some system dependences (e.g.,
                   6550: the header structure), so a system-independent assembler may be used in
1.26      crook    6551: Gforth. If you do not have an assembler, you can compile machine code
1.29      crook    6552: directly with @code{,} and @code{c,}@footnote{This isn't portable,
                   6553: because these words emit stuff in @i{data} space; it works because
                   6554: Gforth has unified code/data spaces. Assembler isn't likely to be
                   6555: portable anyway.}.
1.5       anton    6556: 
1.44    ! crook    6557: 
1.26      crook    6558: doc-assembler
                   6559: doc-code
                   6560: doc-end-code
                   6561: doc-;code
                   6562: doc-flush-icache
1.5       anton    6563: 
1.44    ! crook    6564: 
1.26      crook    6565: If @code{flush-icache} does not work correctly, @code{code} words
                   6566: etc. will not work (reliably), either.
1.5       anton    6567: 
1.29      crook    6568: The typical usage of these @code{code} words can be shown most easily by
                   6569: analogy to the equivalent high-level defining words:
                   6570: 
                   6571: @example
                   6572: : foo                                        code foo
                   6573:    <high-level Forth words>                        <assembler>
                   6574: ;                                            end-code
                   6575: 
                   6576: : bar                                        : bar
                   6577:    <high-level Forth words>                     <high-level Forth words>
                   6578:    CREATE                                       CREATE
                   6579:       <high-level Forth words>                     <high-level Forth words>
                   6580:    DOES>                                        ;code
                   6581:       <high-level Forth words>                     <assembler>
                   6582: ;                                            end-code
                   6583: @end example
                   6584: 
1.26      crook    6585: @code{flush-icache} is always present. The other words are rarely used
                   6586: and reside in @code{code.fs}, which is usually not loaded. You can load
                   6587: it with @code{require code.fs}.
1.5       anton    6588: 
1.26      crook    6589: @cindex registers of the inner interpreter
                   6590: In the assembly code you will want to refer to the inner interpreter's
                   6591: registers (e.g., the data stack pointer) and you may want to use other
                   6592: registers for temporary storage. Unfortunately, the register allocation
                   6593: is installation-dependent.
1.5       anton    6594: 
1.26      crook    6595: The easiest solution is to use explicit register declarations
                   6596: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
                   6597: GNU C Manual}) for all of the inner interpreter's registers: You have to
                   6598: compile Gforth with @code{-DFORCE_REG} (configure option
                   6599: @code{--enable-force-reg}) and the appropriate declarations must be
                   6600: present in the @code{machine.h} file (see @code{mips.h} for an example;
                   6601: you can find a full list of all declarable register symbols with
                   6602: @code{grep register engine.c}). If you give explicit registers to all
                   6603: variables that are declared at the beginning of @code{engine()}, you
                   6604: should be able to use the other caller-saved registers for temporary
                   6605: storage. Alternatively, you can use the @code{gcc} option
                   6606: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
                   6607: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
                   6608: (however, this restriction on register allocation may slow Gforth
                   6609: significantly).
1.5       anton    6610: 
1.26      crook    6611: If this solution is not viable (e.g., because @code{gcc} does not allow
                   6612: you to explicitly declare all the registers you need), you have to find
                   6613: out by looking at the code where the inner interpreter's registers
                   6614: reside and which registers can be used for temporary storage. You can
                   6615: get an assembly listing of the engine's code with @code{make engine.s}.
1.5       anton    6616: 
1.26      crook    6617: In any case, it is good practice to abstract your assembly code from the
                   6618: actual register allocation. E.g., if the data stack pointer resides in
                   6619: register @code{$17}, create an alias for this register called @code{sp},
                   6620: and use that in your assembly code.
1.5       anton    6621: 
1.26      crook    6622: @cindex code words, portable
                   6623: Another option for implementing normal and defining words efficiently
                   6624: is to add the desired functionality to the source of Gforth. For normal
                   6625: words you just have to edit @file{primitives} (@pxref{Automatic
                   6626: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
                   6627: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
                   6628: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.5       anton    6629: 
                   6630: 
1.26      crook    6631: @c -------------------------------------------------------------
                   6632: @node Threading Words, Locals, Assembler and Code Words, Words
                   6633: @section Threading Words
                   6634: @cindex threading words
1.5       anton    6635: 
1.26      crook    6636: @cindex code address
                   6637: These words provide access to code addresses and other threading stuff
                   6638: in Gforth (and, possibly, other interpretive Forths). It more or less
                   6639: abstracts away the differences between direct and indirect threading
                   6640: (and, for direct threading, the machine dependences). However, at
                   6641: present this wordset is still incomplete. It is also pretty low-level;
                   6642: some day it will hopefully be made unnecessary by an internals wordset
                   6643: that abstracts implementation details away completely.
1.5       anton    6644: 
1.44    ! crook    6645: 
1.26      crook    6646: doc-threading-method
                   6647: doc->code-address
                   6648: doc->does-code
                   6649: doc-code-address!
                   6650: doc-does-code!
                   6651: doc-does-handler!
                   6652: doc-/does-handler
1.5       anton    6653: 
1.44    ! crook    6654: 
1.26      crook    6655: The code addresses produced by various defining words are produced by
                   6656: the following words:
1.5       anton    6657: 
1.44    ! crook    6658: 
1.26      crook    6659: doc-docol:
                   6660: doc-docon:
                   6661: doc-dovar:
                   6662: doc-douser:
                   6663: doc-dodefer:
                   6664: doc-dofield:
1.5       anton    6665: 
1.44    ! crook    6666: 
1.26      crook    6667: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
                   6668: with @code{>does-code}. If the word was defined in that way, the value
                   6669: returned is non-zero and identifies the @code{DOES>} used by the
                   6670: defining word.
                   6671: @comment TODO should that be ``identifies the xt of the DOES> ??''
1.5       anton    6672: 
1.26      crook    6673: @c -------------------------------------------------------------
                   6674: @node Locals, Structures, Threading Words, Words
                   6675: @section Locals
                   6676: @cindex locals
1.5       anton    6677: 
1.26      crook    6678: Local variables can make Forth programming more enjoyable and Forth
                   6679: programs easier to read. Unfortunately, the locals of ANS Forth are
                   6680: laden with restrictions. Therefore, we provide not only the ANS Forth
                   6681: locals wordset, but also our own, more powerful locals wordset (we
                   6682: implemented the ANS Forth locals wordset through our locals wordset).
1.5       anton    6683: 
1.26      crook    6684: The ideas in this section have also been published in the paper
                   6685: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
                   6686: at EuroForth '94; it is available at
                   6687: @*@url{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
1.5       anton    6688: 
1.26      crook    6689: @menu
                   6690: * Gforth locals::               
                   6691: * ANS Forth locals::            
                   6692: @end menu
1.5       anton    6693: 
1.26      crook    6694: @node Gforth locals, ANS Forth locals, Locals, Locals
                   6695: @subsection Gforth locals
                   6696: @cindex Gforth locals
                   6697: @cindex locals, Gforth style
1.5       anton    6698: 
1.26      crook    6699: Locals can be defined with
1.5       anton    6700: 
                   6701: @example
1.26      crook    6702: @{ local1 local2 ... -- comment @}
                   6703: @end example
                   6704: or
                   6705: @example
                   6706: @{ local1 local2 ... @}
1.5       anton    6707: @end example
                   6708: 
1.26      crook    6709: E.g.,
1.5       anton    6710: @example
1.26      crook    6711: : max @{ n1 n2 -- n3 @}
                   6712:  n1 n2 > if
                   6713:    n1
                   6714:  else
                   6715:    n2
                   6716:  endif ;
1.5       anton    6717: @end example
                   6718: 
1.26      crook    6719: The similarity of locals definitions with stack comments is intended. A
                   6720: locals definition often replaces the stack comment of a word. The order
                   6721: of the locals corresponds to the order in a stack comment and everything
                   6722: after the @code{--} is really a comment.
1.5       anton    6723: 
1.26      crook    6724: This similarity has one disadvantage: It is too easy to confuse locals
                   6725: declarations with stack comments, causing bugs and making them hard to
                   6726: find. However, this problem can be avoided by appropriate coding
                   6727: conventions: Do not use both notations in the same program. If you do,
                   6728: they should be distinguished using additional means, e.g. by position.
                   6729: 
                   6730: @cindex types of locals
                   6731: @cindex locals types
                   6732: The name of the local may be preceded by a type specifier, e.g.,
                   6733: @code{F:} for a floating point value:
                   6734: 
                   6735: @example
                   6736: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   6737: \ complex multiplication
                   6738:  Ar Br f* Ai Bi f* f-
                   6739:  Ar Bi f* Ai Br f* f+ ;
                   6740: @end example
                   6741: 
                   6742: @cindex flavours of locals
                   6743: @cindex locals flavours
                   6744: @cindex value-flavoured locals
                   6745: @cindex variable-flavoured locals
                   6746: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   6747: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   6748: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   6749: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   6750: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   6751: produces its address (which becomes invalid when the variable's scope is
                   6752: left). E.g., the standard word @code{emit} can be defined in terms of
                   6753: @code{type} like this:
1.5       anton    6754: 
                   6755: @example
1.26      crook    6756: : emit @{ C^ char* -- @}
                   6757:     char* 1 type ;
1.5       anton    6758: @end example
                   6759: 
1.26      crook    6760: @cindex default type of locals
                   6761: @cindex locals, default type
                   6762: A local without type specifier is a @code{W:} local. Both flavours of
                   6763: locals are initialized with values from the data or FP stack.
1.5       anton    6764: 
1.26      crook    6765: Currently there is no way to define locals with user-defined data
                   6766: structures, but we are working on it.
1.5       anton    6767: 
1.26      crook    6768: Gforth allows defining locals everywhere in a colon definition. This
                   6769: poses the following questions:
1.5       anton    6770: 
1.26      crook    6771: @menu
                   6772: * Where are locals visible by name?::  
                   6773: * How long do locals live?::    
                   6774: * Programming Style::           
                   6775: * Implementation::              
                   6776: @end menu
1.5       anton    6777: 
1.26      crook    6778: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   6779: @subsubsection Where are locals visible by name?
                   6780: @cindex locals visibility
                   6781: @cindex visibility of locals
                   6782: @cindex scope of locals
1.5       anton    6783: 
1.26      crook    6784: Basically, the answer is that locals are visible where you would expect
                   6785: it in block-structured languages, and sometimes a little longer. If you
                   6786: want to restrict the scope of a local, enclose its definition in
                   6787: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    6788: 
1.44    ! crook    6789: 
1.26      crook    6790: doc-scope
                   6791: doc-endscope
1.5       anton    6792: 
1.44    ! crook    6793: 
1.26      crook    6794: These words behave like control structure words, so you can use them
                   6795: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   6796: arbitrary ways.
1.5       anton    6797: 
1.26      crook    6798: If you want a more exact answer to the visibility question, here's the
                   6799: basic principle: A local is visible in all places that can only be
                   6800: reached through the definition of the local@footnote{In compiler
                   6801: construction terminology, all places dominated by the definition of the
                   6802: local.}. In other words, it is not visible in places that can be reached
                   6803: without going through the definition of the local. E.g., locals defined
                   6804: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   6805: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   6806: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.5       anton    6807: 
1.26      crook    6808: The reasoning behind this solution is: We want to have the locals
                   6809: visible as long as it is meaningful. The user can always make the
                   6810: visibility shorter by using explicit scoping. In a place that can
                   6811: only be reached through the definition of a local, the meaning of a
                   6812: local name is clear. In other places it is not: How is the local
                   6813: initialized at the control flow path that does not contain the
                   6814: definition? Which local is meant, if the same name is defined twice in
                   6815: two independent control flow paths?
1.5       anton    6816: 
1.26      crook    6817: This should be enough detail for nearly all users, so you can skip the
                   6818: rest of this section. If you really must know all the gory details and
                   6819: options, read on.
1.5       anton    6820: 
1.26      crook    6821: In order to implement this rule, the compiler has to know which places
                   6822: are unreachable. It knows this automatically after @code{AHEAD},
                   6823: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   6824: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   6825: compiler that the control flow never reaches that place. If
                   6826: @code{UNREACHABLE} is not used where it could, the only consequence is
                   6827: that the visibility of some locals is more limited than the rule above
                   6828: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   6829: lie to the compiler), buggy code will be produced.
1.5       anton    6830: 
1.44    ! crook    6831: 
1.26      crook    6832: doc-unreachable
1.5       anton    6833: 
1.44    ! crook    6834: 
1.26      crook    6835: Another problem with this rule is that at @code{BEGIN}, the compiler
                   6836: does not know which locals will be visible on the incoming
                   6837: back-edge. All problems discussed in the following are due to this
                   6838: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   6839: loops as examples; the discussion also applies to @code{?DO} and other
                   6840: loops). Perhaps the most insidious example is:
1.5       anton    6841: @example
1.26      crook    6842: AHEAD
                   6843: BEGIN
                   6844:   x
                   6845: [ 1 CS-ROLL ] THEN
                   6846:   @{ x @}
                   6847:   ...
                   6848: UNTIL
                   6849: @end example
1.5       anton    6850: 
1.26      crook    6851: This should be legal according to the visibility rule. The use of
                   6852: @code{x} can only be reached through the definition; but that appears
                   6853: textually below the use.
1.5       anton    6854: 
1.26      crook    6855: From this example it is clear that the visibility rules cannot be fully
                   6856: implemented without major headaches. Our implementation treats common
                   6857: cases as advertised and the exceptions are treated in a safe way: The
                   6858: compiler makes a reasonable guess about the locals visible after a
                   6859: @code{BEGIN}; if it is too pessimistic, the
                   6860: user will get a spurious error about the local not being defined; if the
                   6861: compiler is too optimistic, it will notice this later and issue a
                   6862: warning. In the case above the compiler would complain about @code{x}
                   6863: being undefined at its use. You can see from the obscure examples in
                   6864: this section that it takes quite unusual control structures to get the
                   6865: compiler into trouble, and even then it will often do fine.
1.5       anton    6866: 
1.26      crook    6867: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   6868: is that all locals visible before the @code{BEGIN} will also be
                   6869: visible after the @code{BEGIN}. This guess is valid for all loops that
                   6870: are entered only through the @code{BEGIN}, in particular, for normal
                   6871: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   6872: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   6873: compiler. When the branch to the @code{BEGIN} is finally generated by
                   6874: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   6875: warns the user if it was too optimistic:
                   6876: @example
                   6877: IF
                   6878:   @{ x @}
                   6879: BEGIN
                   6880:   \ x ? 
                   6881: [ 1 cs-roll ] THEN
                   6882:   ...
                   6883: UNTIL
1.5       anton    6884: @end example
                   6885: 
1.26      crook    6886: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   6887: optimistically assumes that it lives until the @code{THEN}. It notices
                   6888: this difference when it compiles the @code{UNTIL} and issues a
                   6889: warning. The user can avoid the warning, and make sure that @code{x}
                   6890: is not used in the wrong area by using explicit scoping:
                   6891: @example
                   6892: IF
                   6893:   SCOPE
                   6894:   @{ x @}
                   6895:   ENDSCOPE
                   6896: BEGIN
                   6897: [ 1 cs-roll ] THEN
                   6898:   ...
                   6899: UNTIL
                   6900: @end example
1.5       anton    6901: 
1.26      crook    6902: Since the guess is optimistic, there will be no spurious error messages
                   6903: about undefined locals.
1.5       anton    6904: 
1.26      crook    6905: If the @code{BEGIN} is not reachable from above (e.g., after
                   6906: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   6907: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   6908: defined later. Therefore, the compiler assumes that no locals are
                   6909: visible after the @code{BEGIN}. However, the user can use
                   6910: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   6911: visible at the BEGIN as at the point where the top control-flow stack
                   6912: item was created.
1.5       anton    6913: 
1.44    ! crook    6914: 
1.26      crook    6915: doc-assume-live
1.5       anton    6916: 
1.44    ! crook    6917: 
        !          6918: @noindent
1.26      crook    6919: E.g.,
1.5       anton    6920: @example
1.26      crook    6921: @{ x @}
                   6922: AHEAD
                   6923: ASSUME-LIVE
                   6924: BEGIN
                   6925:   x
                   6926: [ 1 CS-ROLL ] THEN
                   6927:   ...
                   6928: UNTIL
1.5       anton    6929: @end example
                   6930: 
1.26      crook    6931: Other cases where the locals are defined before the @code{BEGIN} can be
                   6932: handled by inserting an appropriate @code{CS-ROLL} before the
                   6933: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   6934: behind the @code{ASSUME-LIVE}).
1.5       anton    6935: 
1.26      crook    6936: Cases where locals are defined after the @code{BEGIN} (but should be
                   6937: visible immediately after the @code{BEGIN}) can only be handled by
                   6938: rearranging the loop. E.g., the ``most insidious'' example above can be
                   6939: arranged into:
1.5       anton    6940: @example
1.26      crook    6941: BEGIN
                   6942:   @{ x @}
                   6943:   ... 0=
                   6944: WHILE
                   6945:   x
                   6946: REPEAT
1.5       anton    6947: @end example
                   6948: 
1.26      crook    6949: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
                   6950: @subsubsection How long do locals live?
                   6951: @cindex locals lifetime
                   6952: @cindex lifetime of locals
1.5       anton    6953: 
1.26      crook    6954: The right answer for the lifetime question would be: A local lives at
                   6955: least as long as it can be accessed. For a value-flavoured local this
                   6956: means: until the end of its visibility. However, a variable-flavoured
                   6957: local could be accessed through its address far beyond its visibility
                   6958: scope. Ultimately, this would mean that such locals would have to be
                   6959: garbage collected. Since this entails un-Forth-like implementation
                   6960: complexities, I adopted the same cowardly solution as some other
                   6961: languages (e.g., C): The local lives only as long as it is visible;
                   6962: afterwards its address is invalid (and programs that access it
                   6963: afterwards are erroneous).
1.5       anton    6964: 
1.26      crook    6965: @node Programming Style, Implementation, How long do locals live?, Gforth locals
                   6966: @subsubsection Programming Style
                   6967: @cindex locals programming style
                   6968: @cindex programming style, locals
1.5       anton    6969: 
1.26      crook    6970: The freedom to define locals anywhere has the potential to change
                   6971: programming styles dramatically. In particular, the need to use the
                   6972: return stack for intermediate storage vanishes. Moreover, all stack
                   6973: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   6974: determined arguments) can be eliminated: If the stack items are in the
                   6975: wrong order, just write a locals definition for all of them; then
                   6976: write the items in the order you want.
1.5       anton    6977: 
1.26      crook    6978: This seems a little far-fetched and eliminating stack manipulations is
                   6979: unlikely to become a conscious programming objective. Still, the number
                   6980: of stack manipulations will be reduced dramatically if local variables
                   6981: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
                   6982: a traditional implementation of @code{max}).
1.5       anton    6983: 
1.26      crook    6984: This shows one potential benefit of locals: making Forth programs more
                   6985: readable. Of course, this benefit will only be realized if the
                   6986: programmers continue to honour the principle of factoring instead of
                   6987: using the added latitude to make the words longer.
1.5       anton    6988: 
1.26      crook    6989: @cindex single-assignment style for locals
                   6990: Using @code{TO} can and should be avoided.  Without @code{TO},
                   6991: every value-flavoured local has only a single assignment and many
                   6992: advantages of functional languages apply to Forth. I.e., programs are
                   6993: easier to analyse, to optimize and to read: It is clear from the
                   6994: definition what the local stands for, it does not turn into something
                   6995: different later.
1.5       anton    6996: 
1.26      crook    6997: E.g., a definition using @code{TO} might look like this:
1.5       anton    6998: @example
1.26      crook    6999: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   7000:  u1 u2 min 0
                   7001:  ?do
                   7002:    addr1 c@@ addr2 c@@ -
                   7003:    ?dup-if
                   7004:      unloop exit
                   7005:    then
                   7006:    addr1 char+ TO addr1
                   7007:    addr2 char+ TO addr2
                   7008:  loop
                   7009:  u1 u2 - ;
1.5       anton    7010: @end example
1.26      crook    7011: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   7012: every loop iteration. @code{strcmp} is a typical example of the
                   7013: readability problems of using @code{TO}. When you start reading
                   7014: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   7015: string. Only near the end of the loop you realize that it is something
                   7016: else.
1.5       anton    7017: 
1.26      crook    7018: This can be avoided by defining two locals at the start of the loop that
                   7019: are initialized with the right value for the current iteration.
1.5       anton    7020: @example
1.26      crook    7021: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   7022:  addr1 addr2
                   7023:  u1 u2 min 0 
                   7024:  ?do @{ s1 s2 @}
                   7025:    s1 c@@ s2 c@@ -
                   7026:    ?dup-if
                   7027:      unloop exit
                   7028:    then
                   7029:    s1 char+ s2 char+
                   7030:  loop
                   7031:  2drop
                   7032:  u1 u2 - ;
1.5       anton    7033: @end example
1.26      crook    7034: Here it is clear from the start that @code{s1} has a different value
                   7035: in every loop iteration.
1.5       anton    7036: 
1.26      crook    7037: @node Implementation,  , Programming Style, Gforth locals
                   7038: @subsubsection Implementation
                   7039: @cindex locals implementation
                   7040: @cindex implementation of locals
1.5       anton    7041: 
1.26      crook    7042: @cindex locals stack
                   7043: Gforth uses an extra locals stack. The most compelling reason for
                   7044: this is that the return stack is not float-aligned; using an extra stack
                   7045: also eliminates the problems and restrictions of using the return stack
                   7046: as locals stack. Like the other stacks, the locals stack grows toward
                   7047: lower addresses. A few primitives allow an efficient implementation:
1.5       anton    7048: 
1.44    ! crook    7049: 
1.26      crook    7050: doc-@local#
                   7051: doc-f@local#
                   7052: doc-laddr#
                   7053: doc-lp+!#
                   7054: doc-lp!
                   7055: doc->l
                   7056: doc-f>l
1.5       anton    7057: 
1.44    ! crook    7058: 
1.26      crook    7059: In addition to these primitives, some specializations of these
                   7060: primitives for commonly occurring inline arguments are provided for
                   7061: efficiency reasons, e.g., @code{@@local0} as specialization of
                   7062: @code{@@local#} for the inline argument 0. The following compiling words
                   7063: compile the right specialized version, or the general version, as
                   7064: appropriate:
1.6       pazsan   7065: 
1.44    ! crook    7066: 
1.26      crook    7067: doc-compile-@local
                   7068: doc-compile-f@local
                   7069: doc-compile-lp+!
1.12      anton    7070: 
1.44    ! crook    7071: 
1.26      crook    7072: Combinations of conditional branches and @code{lp+!#} like
                   7073: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   7074: is taken) are provided for efficiency and correctness in loops.
1.6       pazsan   7075: 
1.26      crook    7076: A special area in the dictionary space is reserved for keeping the
                   7077: local variable names. @code{@{} switches the dictionary pointer to this
                   7078: area and @code{@}} switches it back and generates the locals
                   7079: initializing code. @code{W:} etc.@ are normal defining words. This
                   7080: special area is cleared at the start of every colon definition.
1.6       pazsan   7081: 
1.26      crook    7082: @cindex word list for defining locals
                   7083: A special feature of Gforth's dictionary is used to implement the
                   7084: definition of locals without type specifiers: every word list (aka
                   7085: vocabulary) has its own methods for searching
                   7086: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   7087: with a special search method: When it is searched for a word, it
                   7088: actually creates that word using @code{W:}. @code{@{} changes the search
                   7089: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   7090: and then the word list for defining locals without type specifiers.
1.12      anton    7091: 
1.26      crook    7092: The lifetime rules support a stack discipline within a colon
                   7093: definition: The lifetime of a local is either nested with other locals
                   7094: lifetimes or it does not overlap them.
1.6       pazsan   7095: 
1.26      crook    7096: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   7097: pointer manipulation is generated. Between control structure words
                   7098: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   7099: is the simplest of the other three control flow words. It has to
                   7100: restore the locals stack depth of the corresponding @code{BEGIN}
                   7101: before branching. The code looks like this:
                   7102: @format
                   7103: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   7104: @code{branch} <begin>
                   7105: @end format
1.6       pazsan   7106: 
1.26      crook    7107: @code{UNTIL} is a little more complicated: If it branches back, it
                   7108: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   7109: the locals stack must not be changed. The compiler generates the
                   7110: following code:
                   7111: @format
                   7112: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   7113: @end format
                   7114: The locals stack pointer is only adjusted if the branch is taken.
1.6       pazsan   7115: 
1.26      crook    7116: @code{THEN} can produce somewhat inefficient code:
                   7117: @format
                   7118: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   7119: <orig target>:
                   7120: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   7121: @end format
                   7122: The second @code{lp+!#} adjusts the locals stack pointer from the
1.29      crook    7123: level at the @i{orig} point to the level after the @code{THEN}. The
1.26      crook    7124: first @code{lp+!#} adjusts the locals stack pointer from the current
                   7125: level to the level at the orig point, so the complete effect is an
                   7126: adjustment from the current level to the right level after the
                   7127: @code{THEN}.
1.6       pazsan   7128: 
1.26      crook    7129: @cindex locals information on the control-flow stack
                   7130: @cindex control-flow stack items, locals information
                   7131: In a conventional Forth implementation a dest control-flow stack entry
                   7132: is just the target address and an orig entry is just the address to be
                   7133: patched. Our locals implementation adds a word list to every orig or dest
                   7134: item. It is the list of locals visible (or assumed visible) at the point
                   7135: described by the entry. Our implementation also adds a tag to identify
                   7136: the kind of entry, in particular to differentiate between live and dead
                   7137: (reachable and unreachable) orig entries.
1.6       pazsan   7138: 
1.26      crook    7139: A few unusual operations have to be performed on locals word lists:
1.6       pazsan   7140: 
1.44    ! crook    7141: 
1.26      crook    7142: doc-common-list
                   7143: doc-sub-list?
                   7144: doc-list-size
1.6       pazsan   7145: 
1.44    ! crook    7146: 
1.26      crook    7147: Several features of our locals word list implementation make these
                   7148: operations easy to implement: The locals word lists are organised as
                   7149: linked lists; the tails of these lists are shared, if the lists
                   7150: contain some of the same locals; and the address of a name is greater
                   7151: than the address of the names behind it in the list.
1.6       pazsan   7152: 
1.26      crook    7153: Another important implementation detail is the variable
                   7154: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   7155: determine if they can be reached directly or only through the branch
                   7156: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   7157: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   7158: definition, by @code{BEGIN} and usually by @code{THEN}.
1.6       pazsan   7159: 
1.26      crook    7160: Counted loops are similar to other loops in most respects, but
                   7161: @code{LEAVE} requires special attention: It performs basically the same
                   7162: service as @code{AHEAD}, but it does not create a control-flow stack
                   7163: entry. Therefore the information has to be stored elsewhere;
                   7164: traditionally, the information was stored in the target fields of the
                   7165: branches created by the @code{LEAVE}s, by organizing these fields into a
                   7166: linked list. Unfortunately, this clever trick does not provide enough
                   7167: space for storing our extended control flow information. Therefore, we
                   7168: introduce another stack, the leave stack. It contains the control-flow
                   7169: stack entries for all unresolved @code{LEAVE}s.
1.6       pazsan   7170: 
1.26      crook    7171: Local names are kept until the end of the colon definition, even if
                   7172: they are no longer visible in any control-flow path. In a few cases
                   7173: this may lead to increased space needs for the locals name area, but
                   7174: usually less than reclaiming this space would cost in code size.
1.6       pazsan   7175: 
                   7176: 
1.26      crook    7177: @node ANS Forth locals,  , Gforth locals, Locals
                   7178: @subsection ANS Forth locals
                   7179: @cindex locals, ANS Forth style
1.6       pazsan   7180: 
1.26      crook    7181: The ANS Forth locals wordset does not define a syntax for locals, but
                   7182: words that make it possible to define various syntaxes. One of the
                   7183: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   7184: wordset, i.e.:
1.6       pazsan   7185: 
                   7186: @example
1.26      crook    7187: @{ local1 local2 ... -- comment @}
1.6       pazsan   7188: @end example
1.23      crook    7189: @noindent
1.26      crook    7190: or
1.6       pazsan   7191: @example
1.26      crook    7192: @{ local1 local2 ... @}
1.6       pazsan   7193: @end example
                   7194: 
1.26      crook    7195: The order of the locals corresponds to the order in a stack comment. The
                   7196: restrictions are:
1.6       pazsan   7197: 
                   7198: @itemize @bullet
                   7199: @item
1.26      crook    7200: Locals can only be cell-sized values (no type specifiers are allowed).
1.6       pazsan   7201: @item
1.26      crook    7202: Locals can be defined only outside control structures.
1.6       pazsan   7203: @item
1.26      crook    7204: Locals can interfere with explicit usage of the return stack. For the
                   7205: exact (and long) rules, see the standard. If you don't use return stack
                   7206: accessing words in a definition using locals, you will be all right. The
                   7207: purpose of this rule is to make locals implementation on the return
                   7208: stack easier.
1.6       pazsan   7209: @item
1.26      crook    7210: The whole definition must be in one line.
                   7211: @end itemize
1.6       pazsan   7212: 
1.44    ! crook    7213: Locals defined in this way behave like @code{VALUE}s
        !          7214: (@xref{Values}). I.e., they are initialized from the stack. Using their
1.26      crook    7215: name produces their value. Their value can be changed using @code{TO}.
1.6       pazsan   7216: 
1.26      crook    7217: Since this syntax is supported by Gforth directly, you need not do
                   7218: anything to use it. If you want to port a program using this syntax to
                   7219: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   7220: syntax on the other system.
1.6       pazsan   7221: 
1.26      crook    7222: Note that a syntax shown in the standard, section A.13 looks
                   7223: similar, but is quite different in having the order of locals
                   7224: reversed. Beware!
1.6       pazsan   7225: 
1.26      crook    7226: The ANS Forth locals wordset itself consists of a word:
1.6       pazsan   7227: 
1.44    ! crook    7228: 
1.26      crook    7229: doc-(local)
1.6       pazsan   7230: 
1.44    ! crook    7231: 
1.26      crook    7232: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
                   7233: awful that we strongly recommend not to use it. We have implemented this
                   7234: syntax to make porting to Gforth easy, but do not document it here. The
                   7235: problem with this syntax is that the locals are defined in an order
                   7236: reversed with respect to the standard stack comment notation, making
                   7237: programs harder to read, and easier to misread and miswrite. The only
                   7238: merit of this syntax is that it is easy to implement using the ANS Forth
                   7239: locals wordset.
1.7       pazsan   7240: 
                   7241: 
1.26      crook    7242: @c ----------------------------------------------------------
                   7243: @node Structures, Object-oriented Forth, Locals, Words
                   7244: @section  Structures
                   7245: @cindex structures
                   7246: @cindex records
1.7       pazsan   7247: 
1.26      crook    7248: This section presents the structure package that comes with Gforth. A
                   7249: version of the package implemented in ANS Forth is available in
                   7250: @file{compat/struct.fs}. This package was inspired by a posting on
                   7251: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   7252: possibly John Hayes). A version of this section has been published in
                   7253: ???. Marcel Hendrix provided helpful comments.
1.7       pazsan   7254: 
1.26      crook    7255: @menu
                   7256: * Why explicit structure support?::  
                   7257: * Structure Usage::             
                   7258: * Structure Naming Convention::  
                   7259: * Structure Implementation::    
                   7260: * Structure Glossary::          
                   7261: @end menu
1.7       pazsan   7262: 
1.26      crook    7263: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   7264: @subsection Why explicit structure support?
1.7       pazsan   7265: 
1.26      crook    7266: @cindex address arithmetic for structures
                   7267: @cindex structures using address arithmetic
                   7268: If we want to use a structure containing several fields, we could simply
                   7269: reserve memory for it, and access the fields using address arithmetic
1.32      anton    7270: (@pxref{Address arithmetic}). As an example, consider a structure with
1.26      crook    7271: the following fields
1.7       pazsan   7272: 
1.26      crook    7273: @table @code
                   7274: @item a
                   7275: is a float
                   7276: @item b
                   7277: is a cell
                   7278: @item c
                   7279: is a float
                   7280: @end table
1.7       pazsan   7281: 
1.26      crook    7282: Given the (float-aligned) base address of the structure we get the
                   7283: address of the field
1.13      pazsan   7284: 
1.26      crook    7285: @table @code
                   7286: @item a
                   7287: without doing anything further.
                   7288: @item b
                   7289: with @code{float+}
                   7290: @item c
                   7291: with @code{float+ cell+ faligned}
                   7292: @end table
1.13      pazsan   7293: 
1.26      crook    7294: It is easy to see that this can become quite tiring. 
1.13      pazsan   7295: 
1.26      crook    7296: Moreover, it is not very readable, because seeing a
                   7297: @code{cell+} tells us neither which kind of structure is
                   7298: accessed nor what field is accessed; we have to somehow infer the kind
                   7299: of structure, and then look up in the documentation, which field of
                   7300: that structure corresponds to that offset.
1.13      pazsan   7301: 
1.26      crook    7302: Finally, this kind of address arithmetic also causes maintenance
                   7303: troubles: If you add or delete a field somewhere in the middle of the
                   7304: structure, you have to find and change all computations for the fields
                   7305: afterwards.
1.13      pazsan   7306: 
1.26      crook    7307: So, instead of using @code{cell+} and friends directly, how
                   7308: about storing the offsets in constants:
1.13      pazsan   7309: 
                   7310: @example
1.26      crook    7311: 0 constant a-offset
                   7312: 0 float+ constant b-offset
                   7313: 0 float+ cell+ faligned c-offset
1.13      pazsan   7314: @end example
                   7315: 
1.26      crook    7316: Now we can get the address of field @code{x} with @code{x-offset
                   7317: +}. This is much better in all respects. Of course, you still
                   7318: have to change all later offset definitions if you add a field. You can
                   7319: fix this by declaring the offsets in the following way:
1.13      pazsan   7320: 
                   7321: @example
1.26      crook    7322: 0 constant a-offset
                   7323: a-offset float+ constant b-offset
                   7324: b-offset cell+ faligned constant c-offset
1.13      pazsan   7325: @end example
                   7326: 
1.26      crook    7327: Since we always use the offsets with @code{+}, we could use a defining
                   7328: word @code{cfield} that includes the @code{+} in the action of the
                   7329: defined word:
1.8       pazsan   7330: 
                   7331: @example
1.26      crook    7332: : cfield ( n "name" -- )
                   7333:     create ,
                   7334: does> ( name execution: addr1 -- addr2 )
                   7335:     @@ + ;
1.13      pazsan   7336: 
1.26      crook    7337: 0 cfield a
                   7338: 0 a float+ cfield b
                   7339: 0 b cell+ faligned cfield c
1.13      pazsan   7340: @end example
                   7341: 
1.26      crook    7342: Instead of @code{x-offset +}, we now simply write @code{x}.
                   7343: 
                   7344: The structure field words now can be used quite nicely. However,
                   7345: their definition is still a bit cumbersome: We have to repeat the
                   7346: name, the information about size and alignment is distributed before
                   7347: and after the field definitions etc.  The structure package presented
                   7348: here addresses these problems.
                   7349: 
                   7350: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   7351: @subsection Structure Usage
                   7352: @cindex structure usage
1.13      pazsan   7353: 
1.26      crook    7354: @cindex @code{field} usage
                   7355: @cindex @code{struct} usage
                   7356: @cindex @code{end-struct} usage
                   7357: You can define a structure for a (data-less) linked list with:
1.13      pazsan   7358: @example
1.26      crook    7359: struct
                   7360:     cell% field list-next
                   7361: end-struct list%
1.13      pazsan   7362: @end example
                   7363: 
1.26      crook    7364: With the address of the list node on the stack, you can compute the
                   7365: address of the field that contains the address of the next node with
                   7366: @code{list-next}. E.g., you can determine the length of a list
                   7367: with:
1.13      pazsan   7368: 
                   7369: @example
1.26      crook    7370: : list-length ( list -- n )
                   7371: \ "list" is a pointer to the first element of a linked list
                   7372: \ "n" is the length of the list
                   7373:     0 BEGIN ( list1 n1 )
                   7374:         over
                   7375:     WHILE ( list1 n1 )
                   7376:         1+ swap list-next @@ swap
                   7377:     REPEAT
                   7378:     nip ;
1.13      pazsan   7379: @end example
                   7380: 
1.26      crook    7381: You can reserve memory for a list node in the dictionary with
                   7382: @code{list% %allot}, which leaves the address of the list node on the
                   7383: stack. For the equivalent allocation on the heap you can use @code{list%
                   7384: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   7385: use @code{list% %allocate}). You can get the the size of a list
                   7386: node with @code{list% %size} and its alignment with @code{list%
                   7387: %alignment}.
1.13      pazsan   7388: 
1.26      crook    7389: Note that in ANS Forth the body of a @code{create}d word is
                   7390: @code{aligned} but not necessarily @code{faligned};
                   7391: therefore, if you do a:
1.13      pazsan   7392: @example
1.26      crook    7393: create @emph{name} foo% %allot
1.8       pazsan   7394: @end example
                   7395: 
1.26      crook    7396: @noindent
                   7397: then the memory alloted for @code{foo%} is
                   7398: guaranteed to start at the body of @code{@emph{name}} only if
                   7399: @code{foo%} contains only character, cell and double fields.
1.20      pazsan   7400: 
1.26      crook    7401: @cindex strcutures containing structures
                   7402: You can include a structure @code{foo%} as a field of
                   7403: another structure, like this:
1.20      pazsan   7404: @example
1.26      crook    7405: struct
                   7406: ...
                   7407:     foo% field ...
                   7408: ...
                   7409: end-struct ...
1.20      pazsan   7410: @end example
                   7411: 
1.26      crook    7412: @cindex structure extension
                   7413: @cindex extended records
                   7414: Instead of starting with an empty structure, you can extend an
                   7415: existing structure. E.g., a plain linked list without data, as defined
                   7416: above, is hardly useful; You can extend it to a linked list of integers,
                   7417: like this:@footnote{This feature is also known as @emph{extended
                   7418: records}. It is the main innovation in the Oberon language; in other
                   7419: words, adding this feature to Modula-2 led Wirth to create a new
                   7420: language, write a new compiler etc.  Adding this feature to Forth just
                   7421: required a few lines of code.}
1.20      pazsan   7422: 
                   7423: @example
1.26      crook    7424: list%
                   7425:     cell% field intlist-int
                   7426: end-struct intlist%
1.20      pazsan   7427: @end example
                   7428: 
1.26      crook    7429: @code{intlist%} is a structure with two fields:
                   7430: @code{list-next} and @code{intlist-int}.
1.20      pazsan   7431: 
1.26      crook    7432: @cindex structures containing arrays
                   7433: You can specify an array type containing @emph{n} elements of
                   7434: type @code{foo%} like this:
1.20      pazsan   7435: 
                   7436: @example
1.26      crook    7437: foo% @emph{n} *
1.20      pazsan   7438: @end example
                   7439: 
1.26      crook    7440: You can use this array type in any place where you can use a normal
                   7441: type, e.g., when defining a @code{field}, or with
                   7442: @code{%allot}.
1.20      pazsan   7443: 
1.26      crook    7444: @cindex first field optimization
                   7445: The first field is at the base address of a structure and the word
                   7446: for this field (e.g., @code{list-next}) actually does not change
                   7447: the address on the stack. You may be tempted to leave it away in the
                   7448: interest of run-time and space efficiency. This is not necessary,
                   7449: because the structure package optimizes this case and compiling such
                   7450: words does not generate any code. So, in the interest of readability
                   7451: and maintainability you should include the word for the field when
                   7452: accessing the field.
1.20      pazsan   7453: 
1.26      crook    7454: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   7455: @subsection Structure Naming Convention
                   7456: @cindex structure naming convention
1.20      pazsan   7457: 
1.26      crook    7458: The field names that come to (my) mind are often quite generic, and,
                   7459: if used, would cause frequent name clashes. E.g., many structures
                   7460: probably contain a @code{counter} field. The structure names
                   7461: that come to (my) mind are often also the logical choice for the names
                   7462: of words that create such a structure.
1.20      pazsan   7463: 
1.26      crook    7464: Therefore, I have adopted the following naming conventions: 
1.20      pazsan   7465: 
1.26      crook    7466: @itemize @bullet
                   7467: @cindex field naming convention
                   7468: @item
                   7469: The names of fields are of the form
                   7470: @code{@emph{struct}-@emph{field}}, where
                   7471: @code{@emph{struct}} is the basic name of the structure, and
                   7472: @code{@emph{field}} is the basic name of the field. You can
                   7473: think of field words as converting the (address of the)
                   7474: structure into the (address of the) field.
1.20      pazsan   7475: 
1.26      crook    7476: @cindex structure naming convention
                   7477: @item
                   7478: The names of structures are of the form
                   7479: @code{@emph{struct}%}, where
                   7480: @code{@emph{struct}} is the basic name of the structure.
                   7481: @end itemize
1.20      pazsan   7482: 
1.26      crook    7483: This naming convention does not work that well for fields of extended
                   7484: structures; e.g., the integer list structure has a field
                   7485: @code{intlist-int}, but has @code{list-next}, not
                   7486: @code{intlist-next}.
1.20      pazsan   7487: 
1.26      crook    7488: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   7489: @subsection Structure Implementation
                   7490: @cindex structure implementation
                   7491: @cindex implementation of structures
1.20      pazsan   7492: 
1.26      crook    7493: The central idea in the implementation is to pass the data about the
                   7494: structure being built on the stack, not in some global
                   7495: variable. Everything else falls into place naturally once this design
                   7496: decision is made.
1.20      pazsan   7497: 
1.26      crook    7498: The type description on the stack is of the form @emph{align
                   7499: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   7500: very simple.
1.20      pazsan   7501: 
1.26      crook    7502: @code{field} is a defining word that uses @code{Create}
                   7503: and @code{DOES>}. The body of the field contains the offset
                   7504: of the field, and the normal @code{DOES>} action is simply:
1.20      pazsan   7505: 
                   7506: @example
1.26      crook    7507: @ +
1.20      pazsan   7508: @end example
                   7509: 
1.23      crook    7510: @noindent
1.26      crook    7511: i.e., add the offset to the address, giving the stack effect
1.29      crook    7512: @i{addr1 -- addr2} for a field.
1.20      pazsan   7513: 
1.26      crook    7514: @cindex first field optimization, implementation
                   7515: This simple structure is slightly complicated by the optimization
                   7516: for fields with offset 0, which requires a different
                   7517: @code{DOES>}-part (because we cannot rely on there being
                   7518: something on the stack if such a field is invoked during
                   7519: compilation). Therefore, we put the different @code{DOES>}-parts
                   7520: in separate words, and decide which one to invoke based on the
                   7521: offset. For a zero offset, the field is basically a noop; it is
                   7522: immediate, and therefore no code is generated when it is compiled.
1.20      pazsan   7523: 
1.26      crook    7524: @node Structure Glossary,  , Structure Implementation, Structures
                   7525: @subsection Structure Glossary
                   7526: @cindex structure glossary
1.20      pazsan   7527: 
1.44    ! crook    7528: 
1.26      crook    7529: doc-%align
                   7530: doc-%alignment
                   7531: doc-%alloc
                   7532: doc-%allocate
                   7533: doc-%allot
                   7534: doc-cell%
                   7535: doc-char%
                   7536: doc-dfloat%
                   7537: doc-double%
                   7538: doc-end-struct
                   7539: doc-field
                   7540: doc-float%
                   7541: doc-naligned
                   7542: doc-sfloat%
                   7543: doc-%size
                   7544: doc-struct
1.23      crook    7545: 
1.44    ! crook    7546: 
1.26      crook    7547: @c -------------------------------------------------------------
                   7548: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
                   7549: @section Object-oriented Forth
1.20      pazsan   7550: 
1.26      crook    7551: Gforth comes with three packages for object-oriented programming:
                   7552: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   7553: is preloaded, so you have to @code{include} them before use. The most
                   7554: important differences between these packages (and others) are discussed
                   7555: in @ref{Comparison with other object models}. All packages are written
                   7556: in ANS Forth and can be used with any other ANS Forth.
1.20      pazsan   7557: 
1.26      crook    7558: @menu
                   7559: * Why object-oriented programming?::
                   7560: * Object-Oriented Terminology::
                   7561: * Objects::
                   7562: * OOF::
                   7563: * Mini-OOF::
                   7564: * Comparison with other object models::  
                   7565: @end menu
1.20      pazsan   7566: 
1.23      crook    7567: 
1.26      crook    7568: @node Why object-oriented programming?, Object-Oriented Terminology, , Object-oriented Forth
                   7569: @subsubsection Why object-oriented programming?
                   7570: @cindex object-oriented programming motivation
                   7571: @cindex motivation for object-oriented programming
1.23      crook    7572: 
1.26      crook    7573: Often we have to deal with several data structures (@emph{objects}),
                   7574: that have to be treated similarly in some respects, but differently in
                   7575: others. Graphical objects are the textbook example: circles, triangles,
                   7576: dinosaurs, icons, and others, and we may want to add more during program
                   7577: development. We want to apply some operations to any graphical object,
                   7578: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   7579: has to do something different for every kind of object.
                   7580: @comment TODO add some other operations eg perimeter, area
                   7581: @comment and tie in to concrete examples later..
1.23      crook    7582: 
1.26      crook    7583: We could implement @code{draw} as a big @code{CASE}
                   7584: control structure that executes the appropriate code depending on the
                   7585: kind of object to be drawn. This would be not be very elegant, and,
                   7586: moreover, we would have to change @code{draw} every time we add
                   7587: a new kind of graphical object (say, a spaceship).
1.23      crook    7588: 
1.26      crook    7589: What we would rather do is: When defining spaceships, we would tell
                   7590: the system: ``Here's how you @code{draw} a spaceship; you figure
                   7591: out the rest''.
1.23      crook    7592: 
1.26      crook    7593: This is the problem that all systems solve that (rightfully) call
                   7594: themselves object-oriented; the object-oriented packages presented here
                   7595: solve this problem (and not much else).
                   7596: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.23      crook    7597: 
1.26      crook    7598: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
                   7599: @subsubsection Object-Oriented Terminology
                   7600: @cindex object-oriented terminology
                   7601: @cindex terminology for object-oriented programming
1.23      crook    7602: 
1.26      crook    7603: This section is mainly for reference, so you don't have to understand
                   7604: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   7605: short:
1.23      crook    7606: 
1.26      crook    7607: @table @emph
                   7608: @cindex class
                   7609: @item class
                   7610: a data structure definition with some extras.
1.23      crook    7611: 
1.26      crook    7612: @cindex object
                   7613: @item object
                   7614: an instance of the data structure described by the class definition.
1.23      crook    7615: 
1.26      crook    7616: @cindex instance variables
                   7617: @item instance variables
                   7618: fields of the data structure.
1.23      crook    7619: 
1.26      crook    7620: @cindex selector
                   7621: @cindex method selector
                   7622: @cindex virtual function
                   7623: @item selector
                   7624: (or @emph{method selector}) a word (e.g.,
                   7625: @code{draw}) that performs an operation on a variety of data
                   7626: structures (classes). A selector describes @emph{what} operation to
                   7627: perform. In C++ terminology: a (pure) virtual function.
1.23      crook    7628: 
1.26      crook    7629: @cindex method
                   7630: @item method
                   7631: the concrete definition that performs the operation
                   7632: described by the selector for a specific class. A method specifies
                   7633: @emph{how} the operation is performed for a specific class.
1.23      crook    7634: 
1.26      crook    7635: @cindex selector invocation
                   7636: @cindex message send
                   7637: @cindex invoking a selector
                   7638: @item selector invocation
                   7639: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   7640: is used for determining which method is used. In Smalltalk terminology:
                   7641: a message (consisting of the selector and the other arguments) is sent
                   7642: to the object.
1.1       anton    7643: 
1.26      crook    7644: @cindex receiving object
                   7645: @item receiving object
                   7646: the object used for determining the method executed by a selector
                   7647: invocation. In the @file{objects.fs} model, it is the object that is on
                   7648: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   7649: the Smalltalk @emph{message} terminology.)
1.1       anton    7650: 
1.26      crook    7651: @cindex child class
                   7652: @cindex parent class
                   7653: @cindex inheritance
                   7654: @item child class
                   7655: a class that has (@emph{inherits}) all properties (instance variables,
                   7656: selectors, methods) from a @emph{parent class}. In Smalltalk
                   7657: terminology: The subclass inherits from the superclass. In C++
                   7658: terminology: The derived class inherits from the base class.
1.1       anton    7659: 
1.26      crook    7660: @end table
1.21      crook    7661: 
1.26      crook    7662: @c If you wonder about the message sending terminology, it comes from
                   7663: @c a time when each object had it's own task and objects communicated via
                   7664: @c message passing; eventually the Smalltalk developers realized that
                   7665: @c they can do most things through simple (indirect) calls. They kept the
                   7666: @c terminology.
1.1       anton    7667: 
                   7668: 
1.26      crook    7669: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   7670: @subsection The @file{objects.fs} model
                   7671: @cindex objects
                   7672: @cindex object-oriented programming
1.1       anton    7673: 
1.26      crook    7674: @cindex @file{objects.fs}
                   7675: @cindex @file{oof.fs}
1.1       anton    7676: 
1.37      anton    7677: This section describes the @file{objects.fs} package. This material also
                   7678: has been published in @cite{Yet Another Forth Objects Package} by Anton
                   7679: Ertl and appeared in Forth Dimensions 19(2), pages 37--43
                   7680: (@url{http://www.complang.tuwien.ac.at/forth/objects/objects.html}).
1.26      crook    7681: @c McKewan's and Zsoter's packages
1.1       anton    7682: 
1.26      crook    7683: This section assumes that you have read @ref{Structures}.
1.1       anton    7684: 
1.26      crook    7685: The techniques on which this model is based have been used to implement
                   7686: the parser generator, Gray, and have also been used in Gforth for
                   7687: implementing the various flavours of word lists (hashed or not,
                   7688: case-sensitive or not, special-purpose word lists for locals etc.).
1.1       anton    7689: 
                   7690: 
1.26      crook    7691: @menu
                   7692: * Properties of the Objects model::  
                   7693: * Basic Objects Usage::         
1.37      anton    7694: * The Objects base class::      
1.26      crook    7695: * Creating objects::            
                   7696: * Object-Oriented Programming Style::  
                   7697: * Class Binding::               
                   7698: * Method conveniences::         
                   7699: * Classes and Scoping::         
1.37      anton    7700: * Dividing classes::            
1.26      crook    7701: * Object Interfaces::           
                   7702: * Objects Implementation::      
                   7703: * Objects Glossary::            
                   7704: @end menu
1.1       anton    7705: 
1.26      crook    7706: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
                   7707: and Bernd Paysan helped me with the related works section.
1.1       anton    7708: 
1.26      crook    7709: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   7710: @subsubsection Properties of the @file{objects.fs} model
                   7711: @cindex @file{objects.fs} properties
1.1       anton    7712: 
1.26      crook    7713: @itemize @bullet
                   7714: @item
                   7715: It is straightforward to pass objects on the stack. Passing
                   7716: selectors on the stack is a little less convenient, but possible.
1.1       anton    7717: 
1.26      crook    7718: @item
                   7719: Objects are just data structures in memory, and are referenced by their
                   7720: address. You can create words for objects with normal defining words
                   7721: like @code{constant}. Likewise, there is no difference between instance
                   7722: variables that contain objects and those that contain other data.
1.1       anton    7723: 
1.26      crook    7724: @item
                   7725: Late binding is efficient and easy to use.
1.21      crook    7726: 
1.26      crook    7727: @item
                   7728: It avoids parsing, and thus avoids problems with state-smartness
                   7729: and reduced extensibility; for convenience there are a few parsing
                   7730: words, but they have non-parsing counterparts. There are also a few
                   7731: defining words that parse. This is hard to avoid, because all standard
                   7732: defining words parse (except @code{:noname}); however, such
                   7733: words are not as bad as many other parsing words, because they are not
                   7734: state-smart.
1.21      crook    7735: 
1.26      crook    7736: @item
                   7737: It does not try to incorporate everything. It does a few things and does
                   7738: them well (IMO). In particular, this model was not designed to support
                   7739: information hiding (although it has features that may help); you can use
                   7740: a separate package for achieving this.
1.21      crook    7741: 
1.26      crook    7742: @item
                   7743: It is layered; you don't have to learn and use all features to use this
                   7744: model. Only a few features are necessary (@xref{Basic Objects Usage},
                   7745: @xref{The Objects base class}, @xref{Creating objects}.), the others
                   7746: are optional and independent of each other.
1.21      crook    7747: 
1.26      crook    7748: @item
                   7749: An implementation in ANS Forth is available.
1.21      crook    7750: 
1.26      crook    7751: @end itemize
1.21      crook    7752: 
                   7753: 
1.26      crook    7754: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   7755: @subsubsection Basic @file{objects.fs} Usage
                   7756: @cindex basic objects usage
                   7757: @cindex objects, basic usage
1.21      crook    7758: 
1.26      crook    7759: You can define a class for graphical objects like this:
1.21      crook    7760: 
1.26      crook    7761: @cindex @code{class} usage
                   7762: @cindex @code{end-class} usage
                   7763: @cindex @code{selector} usage
                   7764: @example
                   7765: object class \ "object" is the parent class
                   7766:   selector draw ( x y graphical -- )
                   7767: end-class graphical
                   7768: @end example
1.21      crook    7769: 
1.26      crook    7770: This code defines a class @code{graphical} with an
                   7771: operation @code{draw}.  We can perform the operation
                   7772: @code{draw} on any @code{graphical} object, e.g.:
1.21      crook    7773: 
1.26      crook    7774: @example
                   7775: 100 100 t-rex draw
                   7776: @end example
1.21      crook    7777: 
1.26      crook    7778: @noindent
                   7779: where @code{t-rex} is a word (say, a constant) that produces a
                   7780: graphical object.
1.21      crook    7781: 
1.29      crook    7782: @comment TODO add a 2nd operation eg perimeter.. and use for
1.26      crook    7783: @comment a concrete example
1.21      crook    7784: 
1.26      crook    7785: @cindex abstract class
                   7786: How do we create a graphical object? With the present definitions,
                   7787: we cannot create a useful graphical object. The class
                   7788: @code{graphical} describes graphical objects in general, but not
                   7789: any concrete graphical object type (C++ users would call it an
                   7790: @emph{abstract class}); e.g., there is no method for the selector
                   7791: @code{draw} in the class @code{graphical}.
1.21      crook    7792: 
1.26      crook    7793: For concrete graphical objects, we define child classes of the
                   7794: class @code{graphical}, e.g.:
1.21      crook    7795: 
1.26      crook    7796: @cindex @code{overrides} usage
                   7797: @cindex @code{field} usage in class definition
                   7798: @example
                   7799: graphical class \ "graphical" is the parent class
                   7800:   cell% field circle-radius
1.21      crook    7801: 
1.26      crook    7802: :noname ( x y circle -- )
                   7803:   circle-radius @@ draw-circle ;
                   7804: overrides draw
1.21      crook    7805: 
1.26      crook    7806: :noname ( n-radius circle -- )
                   7807:   circle-radius ! ;
                   7808: overrides construct
1.21      crook    7809: 
1.26      crook    7810: end-class circle
1.21      crook    7811: @end example
                   7812: 
1.26      crook    7813: Here we define a class @code{circle} as a child of @code{graphical},
                   7814: with field @code{circle-radius} (which behaves just like a field
                   7815: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   7816: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   7817: defined in @code{object}, the parent class of @code{graphical}).
1.21      crook    7818: 
1.26      crook    7819: Now we can create a circle on the heap (i.e.,
                   7820: @code{allocate}d memory) with:
1.21      crook    7821: 
1.26      crook    7822: @cindex @code{heap-new} usage
1.21      crook    7823: @example
1.26      crook    7824: 50 circle heap-new constant my-circle
                   7825: @end example
1.21      crook    7826: 
1.26      crook    7827: @noindent
                   7828: @code{heap-new} invokes @code{construct}, thus
                   7829: initializing the field @code{circle-radius} with 50. We can draw
                   7830: this new circle at (100,100) with:
1.21      crook    7831: 
1.26      crook    7832: @example
                   7833: 100 100 my-circle draw
1.21      crook    7834: @end example
                   7835: 
1.26      crook    7836: @cindex selector invocation, restrictions
                   7837: @cindex class definition, restrictions
                   7838: Note: You can only invoke a selector if the object on the TOS
                   7839: (the receiving object) belongs to the class where the selector was
                   7840: defined or one of its descendents; e.g., you can invoke
                   7841: @code{draw} only for objects belonging to @code{graphical}
                   7842: or its descendents (e.g., @code{circle}).  Immediately before
                   7843: @code{end-class}, the search order has to be the same as
                   7844: immediately after @code{class}.
1.21      crook    7845: 
1.26      crook    7846: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   7847: @subsubsection The @file{object.fs} base class
                   7848: @cindex @code{object} class
1.21      crook    7849: 
1.26      crook    7850: When you define a class, you have to specify a parent class.  So how do
                   7851: you start defining classes? There is one class available from the start:
                   7852: @code{object}. It is ancestor for all classes and so is the
                   7853: only class that has no parent. It has two selectors: @code{construct}
                   7854: and @code{print}.
1.21      crook    7855: 
1.26      crook    7856: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   7857: @subsubsection Creating objects
                   7858: @cindex creating objects
                   7859: @cindex object creation
                   7860: @cindex object allocation options
1.21      crook    7861: 
1.26      crook    7862: @cindex @code{heap-new} discussion
                   7863: @cindex @code{dict-new} discussion
                   7864: @cindex @code{construct} discussion
                   7865: You can create and initialize an object of a class on the heap with
                   7866: @code{heap-new} ( ... class -- object ) and in the dictionary
                   7867: (allocation with @code{allot}) with @code{dict-new} (
                   7868: ... class -- object ). Both words invoke @code{construct}, which
                   7869: consumes the stack items indicated by "..." above.
1.21      crook    7870: 
1.26      crook    7871: @cindex @code{init-object} discussion
                   7872: @cindex @code{class-inst-size} discussion
                   7873: If you want to allocate memory for an object yourself, you can get its
                   7874: alignment and size with @code{class-inst-size 2@@} ( class --
                   7875: align size ). Once you have memory for an object, you can initialize
                   7876: it with @code{init-object} ( ... class object -- );
                   7877: @code{construct} does only a part of the necessary work.
1.21      crook    7878: 
1.26      crook    7879: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   7880: @subsubsection Object-Oriented Programming Style
                   7881: @cindex object-oriented programming style
1.21      crook    7882: 
1.26      crook    7883: This section is not exhaustive.
1.1       anton    7884: 
1.26      crook    7885: @cindex stack effects of selectors
                   7886: @cindex selectors and stack effects
                   7887: In general, it is a good idea to ensure that all methods for the
                   7888: same selector have the same stack effect: when you invoke a selector,
                   7889: you often have no idea which method will be invoked, so, unless all
                   7890: methods have the same stack effect, you will not know the stack effect
                   7891: of the selector invocation.
1.21      crook    7892: 
1.26      crook    7893: One exception to this rule is methods for the selector
                   7894: @code{construct}. We know which method is invoked, because we
                   7895: specify the class to be constructed at the same place. Actually, I
                   7896: defined @code{construct} as a selector only to give the users a
                   7897: convenient way to specify initialization. The way it is used, a
                   7898: mechanism different from selector invocation would be more natural
                   7899: (but probably would take more code and more space to explain).
1.21      crook    7900: 
1.26      crook    7901: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   7902: @subsubsection Class Binding
                   7903: @cindex class binding
                   7904: @cindex early binding
1.21      crook    7905: 
1.26      crook    7906: @cindex late binding
                   7907: Normal selector invocations determine the method at run-time depending
                   7908: on the class of the receiving object. This run-time selection is called
1.29      crook    7909: @i{late binding}.
1.21      crook    7910: 
1.26      crook    7911: Sometimes it's preferable to invoke a different method. For example,
                   7912: you might want to use the simple method for @code{print}ing
                   7913: @code{object}s instead of the possibly long-winded @code{print} method
                   7914: of the receiver class. You can achieve this by replacing the invocation
                   7915: of @code{print} with:
1.21      crook    7916: 
1.26      crook    7917: @cindex @code{[bind]} usage
                   7918: @example
                   7919: [bind] object print
1.21      crook    7920: @end example
                   7921: 
1.26      crook    7922: @noindent
                   7923: in compiled code or:
1.21      crook    7924: 
1.26      crook    7925: @cindex @code{bind} usage
1.21      crook    7926: @example
1.26      crook    7927: bind object print
1.21      crook    7928: @end example
                   7929: 
1.26      crook    7930: @cindex class binding, alternative to
                   7931: @noindent
                   7932: in interpreted code. Alternatively, you can define the method with a
                   7933: name (e.g., @code{print-object}), and then invoke it through the
                   7934: name. Class binding is just a (often more convenient) way to achieve
                   7935: the same effect; it avoids name clutter and allows you to invoke
                   7936: methods directly without naming them first.
                   7937: 
                   7938: @cindex superclass binding
                   7939: @cindex parent class binding
                   7940: A frequent use of class binding is this: When we define a method
                   7941: for a selector, we often want the method to do what the selector does
                   7942: in the parent class, and a little more. There is a special word for
                   7943: this purpose: @code{[parent]}; @code{[parent]
                   7944: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   7945: selector}}, where @code{@emph{parent}} is the parent
                   7946: class of the current class. E.g., a method definition might look like:
1.21      crook    7947: 
1.26      crook    7948: @cindex @code{[parent]} usage
1.21      crook    7949: @example
1.26      crook    7950: :noname
                   7951:   dup [parent] foo \ do parent's foo on the receiving object
                   7952:   ... \ do some more
                   7953: ; overrides foo
1.21      crook    7954: @end example
                   7955: 
1.26      crook    7956: @cindex class binding as optimization
                   7957: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   7958: March 1997), Andrew McKewan presents class binding as an optimization
                   7959: technique. I recommend not using it for this purpose unless you are in
                   7960: an emergency. Late binding is pretty fast with this model anyway, so the
                   7961: benefit of using class binding is small; the cost of using class binding
                   7962: where it is not appropriate is reduced maintainability.
1.21      crook    7963: 
1.26      crook    7964: While we are at programming style questions: You should bind
                   7965: selectors only to ancestor classes of the receiving object. E.g., say,
                   7966: you know that the receiving object is of class @code{foo} or its
                   7967: descendents; then you should bind only to @code{foo} and its
                   7968: ancestors.
1.21      crook    7969: 
1.26      crook    7970: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   7971: @subsubsection Method conveniences
                   7972: @cindex method conveniences
1.1       anton    7973: 
1.26      crook    7974: In a method you usually access the receiving object pretty often.  If
                   7975: you define the method as a plain colon definition (e.g., with
                   7976: @code{:noname}), you may have to do a lot of stack
                   7977: gymnastics. To avoid this, you can define the method with @code{m:
                   7978: ... ;m}. E.g., you could define the method for
                   7979: @code{draw}ing a @code{circle} with
1.20      pazsan   7980: 
1.26      crook    7981: @cindex @code{this} usage
                   7982: @cindex @code{m:} usage
                   7983: @cindex @code{;m} usage
                   7984: @example
                   7985: m: ( x y circle -- )
                   7986:   ( x y ) this circle-radius @@ draw-circle ;m
                   7987: @end example
1.20      pazsan   7988: 
1.26      crook    7989: @cindex @code{exit} in @code{m: ... ;m}
                   7990: @cindex @code{exitm} discussion
                   7991: @cindex @code{catch} in @code{m: ... ;m}
                   7992: When this method is executed, the receiver object is removed from the
                   7993: stack; you can access it with @code{this} (admittedly, in this
                   7994: example the use of @code{m: ... ;m} offers no advantage). Note
                   7995: that I specify the stack effect for the whole method (i.e. including
                   7996: the receiver object), not just for the code between @code{m:}
                   7997: and @code{;m}. You cannot use @code{exit} in
                   7998: @code{m:...;m}; instead, use
                   7999: @code{exitm}.@footnote{Moreover, for any word that calls
                   8000: @code{catch} and was defined before loading
                   8001: @code{objects.fs}, you have to redefine it like I redefined
                   8002: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.20      pazsan   8003: 
1.26      crook    8004: @cindex @code{inst-var} usage
                   8005: You will frequently use sequences of the form @code{this
                   8006: @emph{field}} (in the example above: @code{this
                   8007: circle-radius}). If you use the field only in this way, you can
                   8008: define it with @code{inst-var} and eliminate the
                   8009: @code{this} before the field name. E.g., the @code{circle}
                   8010: class above could also be defined with:
1.20      pazsan   8011: 
1.26      crook    8012: @example
                   8013: graphical class
                   8014:   cell% inst-var radius
1.20      pazsan   8015: 
1.26      crook    8016: m: ( x y circle -- )
                   8017:   radius @@ draw-circle ;m
                   8018: overrides draw
1.20      pazsan   8019: 
1.26      crook    8020: m: ( n-radius circle -- )
                   8021:   radius ! ;m
                   8022: overrides construct
1.12      anton    8023: 
1.26      crook    8024: end-class circle
                   8025: @end example
1.12      anton    8026: 
1.26      crook    8027: @code{radius} can only be used in @code{circle} and its
                   8028: descendent classes and inside @code{m:...;m}.
1.12      anton    8029: 
1.26      crook    8030: @cindex @code{inst-value} usage
                   8031: You can also define fields with @code{inst-value}, which is
                   8032: to @code{inst-var} what @code{value} is to
                   8033: @code{variable}.  You can change the value of such a field with
                   8034: @code{[to-inst]}.  E.g., we could also define the class
                   8035: @code{circle} like this:
1.12      anton    8036: 
1.26      crook    8037: @example
                   8038: graphical class
                   8039:   inst-value radius
1.12      anton    8040: 
1.26      crook    8041: m: ( x y circle -- )
                   8042:   radius draw-circle ;m
                   8043: overrides draw
1.12      anton    8044: 
1.26      crook    8045: m: ( n-radius circle -- )
                   8046:   [to-inst] radius ;m
                   8047: overrides construct
1.21      crook    8048: 
1.26      crook    8049: end-class circle
1.12      anton    8050: @end example
                   8051: 
1.38      anton    8052: Finally, you can define named methods with @code{:m}.  One use of this
                   8053: feature is the definition of words that occur only in one class and are
                   8054: not intended to be overridden, but which still need method context
                   8055: (e.g., for accessing @code{inst-var}s).  Another use is for methods that
                   8056: would be bound frequently, if defined anonymously.
                   8057: 
1.12      anton    8058: 
1.37      anton    8059: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
1.26      crook    8060: @subsubsection Classes and Scoping
                   8061: @cindex classes and scoping
                   8062: @cindex scoping and classes
1.12      anton    8063: 
1.26      crook    8064: Inheritance is frequent, unlike structure extension. This exacerbates
                   8065: the problem with the field name convention (@pxref{Structure Naming
                   8066: Convention}): One always has to remember in which class the field was
                   8067: originally defined; changing a part of the class structure would require
                   8068: changes for renaming in otherwise unaffected code.
1.12      anton    8069: 
1.26      crook    8070: @cindex @code{inst-var} visibility
                   8071: @cindex @code{inst-value} visibility
                   8072: To solve this problem, I added a scoping mechanism (which was not in my
                   8073: original charter): A field defined with @code{inst-var} (or
                   8074: @code{inst-value}) is visible only in the class where it is defined and in
                   8075: the descendent classes of this class.  Using such fields only makes
                   8076: sense in @code{m:}-defined methods in these classes anyway.
1.12      anton    8077: 
1.26      crook    8078: This scoping mechanism allows us to use the unadorned field name,
                   8079: because name clashes with unrelated words become much less likely.
1.12      anton    8080: 
1.26      crook    8081: @cindex @code{protected} discussion
                   8082: @cindex @code{private} discussion
                   8083: Once we have this mechanism, we can also use it for controlling the
                   8084: visibility of other words: All words defined after
                   8085: @code{protected} are visible only in the current class and its
                   8086: descendents. @code{public} restores the compilation
                   8087: (i.e. @code{current}) word list that was in effect before. If you
                   8088: have several @code{protected}s without an intervening
                   8089: @code{public} or @code{set-current}, @code{public}
                   8090: will restore the compilation word list in effect before the first of
                   8091: these @code{protected}s.
1.12      anton    8092: 
1.37      anton    8093: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
                   8094: @subsubsection Dividing classes
                   8095: @cindex Dividing classes
                   8096: @cindex @code{methods}...@code{end-methods}
                   8097: 
                   8098: You may want to do the definition of methods separate from the
                   8099: definition of the class, its selectors, fields, and instance variables,
                   8100: i.e., separate the implementation from the definition.  You can do this
                   8101: in the following way:
                   8102: 
                   8103: @example
                   8104: graphical class
                   8105:   inst-value radius
                   8106: end-class circle
                   8107: 
                   8108: ... \ do some other stuff
                   8109: 
                   8110: circle methods \ now we are ready
                   8111: 
                   8112: m: ( x y circle -- )
                   8113:   radius draw-circle ;m
                   8114: overrides draw
                   8115: 
                   8116: m: ( n-radius circle -- )
                   8117:   [to-inst] radius ;m
                   8118: overrides construct
                   8119: 
                   8120: end-methods
                   8121: @end example
                   8122: 
                   8123: You can use several @code{methods}...@code{end-methods} sections.  The
                   8124: only things you can do to the class in these sections are: defining
                   8125: methods, and overriding the class's selectors.  You must not define new
                   8126: selectors or fields.
                   8127: 
                   8128: Note that you often have to override a selector before using it.  In
                   8129: particular, you usually have to override @code{construct} with a new
                   8130: method before you can invoke @code{heap-new} and friends.  E.g., you
                   8131: must not create a circle before the @code{overrides construct} sequence
                   8132: in the example above.
                   8133: 
                   8134: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
1.26      crook    8135: @subsubsection Object Interfaces
                   8136: @cindex object interfaces
                   8137: @cindex interfaces for objects
1.12      anton    8138: 
1.26      crook    8139: In this model you can only call selectors defined in the class of the
                   8140: receiving objects or in one of its ancestors. If you call a selector
                   8141: with a receiving object that is not in one of these classes, the
                   8142: result is undefined; if you are lucky, the program crashes
                   8143: immediately.
1.12      anton    8144: 
1.26      crook    8145: @cindex selectors common to hardly-related classes
                   8146: Now consider the case when you want to have a selector (or several)
                   8147: available in two classes: You would have to add the selector to a
                   8148: common ancestor class, in the worst case to @code{object}. You
                   8149: may not want to do this, e.g., because someone else is responsible for
                   8150: this ancestor class.
1.12      anton    8151: 
1.26      crook    8152: The solution for this problem is interfaces. An interface is a
                   8153: collection of selectors. If a class implements an interface, the
                   8154: selectors become available to the class and its descendents. A class
                   8155: can implement an unlimited number of interfaces. For the problem
                   8156: discussed above, we would define an interface for the selector(s), and
                   8157: both classes would implement the interface.
1.12      anton    8158: 
1.26      crook    8159: As an example, consider an interface @code{storage} for
                   8160: writing objects to disk and getting them back, and a class
                   8161: @code{foo} that implements it. The code would look like this:
1.12      anton    8162: 
1.26      crook    8163: @cindex @code{interface} usage
                   8164: @cindex @code{end-interface} usage
                   8165: @cindex @code{implementation} usage
                   8166: @example
                   8167: interface
                   8168:   selector write ( file object -- )
                   8169:   selector read1 ( file object -- )
                   8170: end-interface storage
1.12      anton    8171: 
1.26      crook    8172: bar class
                   8173:   storage implementation
1.12      anton    8174: 
1.26      crook    8175: ... overrides write
1.37      anton    8176: ... overrides read1
1.26      crook    8177: ...
                   8178: end-class foo
1.12      anton    8179: @end example
                   8180: 
1.26      crook    8181: @noindent
1.29      crook    8182: (I would add a word @code{read} @i{( file -- object )} that uses
1.26      crook    8183: @code{read1} internally, but that's beyond the point illustrated
                   8184: here.)
1.12      anton    8185: 
1.26      crook    8186: Note that you cannot use @code{protected} in an interface; and
                   8187: of course you cannot define fields.
1.12      anton    8188: 
1.26      crook    8189: In the Neon model, all selectors are available for all classes;
                   8190: therefore it does not need interfaces. The price you pay in this model
                   8191: is slower late binding, and therefore, added complexity to avoid late
                   8192: binding.
1.12      anton    8193: 
1.26      crook    8194: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   8195: @subsubsection @file{objects.fs} Implementation
                   8196: @cindex @file{objects.fs} implementation
1.12      anton    8197: 
1.26      crook    8198: @cindex @code{object-map} discussion
                   8199: An object is a piece of memory, like one of the data structures
                   8200: described with @code{struct...end-struct}. It has a field
                   8201: @code{object-map} that points to the method map for the object's
                   8202: class.
1.12      anton    8203: 
1.26      crook    8204: @cindex method map
                   8205: @cindex virtual function table
                   8206: The @emph{method map}@footnote{This is Self terminology; in C++
                   8207: terminology: virtual function table.} is an array that contains the
1.29      crook    8208: execution tokens (@i{xt}s) of the methods for the object's class. Each
1.26      crook    8209: selector contains an offset into a method map.
1.12      anton    8210: 
1.26      crook    8211: @cindex @code{selector} implementation, class
                   8212: @code{selector} is a defining word that uses
                   8213: @code{CREATE} and @code{DOES>}. The body of the
1.44    ! crook    8214: selector contains the offset; the @code{DOES>} action for a
1.26      crook    8215: class selector is, basically:
1.21      crook    8216: 
1.26      crook    8217: @example
                   8218: ( object addr ) @@ over object-map @@ + @@ execute
                   8219: @end example
1.12      anton    8220: 
1.26      crook    8221: Since @code{object-map} is the first field of the object, it
                   8222: does not generate any code. As you can see, calling a selector has a
                   8223: small, constant cost.
1.12      anton    8224: 
1.26      crook    8225: @cindex @code{current-interface} discussion
                   8226: @cindex class implementation and representation
                   8227: A class is basically a @code{struct} combined with a method
                   8228: map. During the class definition the alignment and size of the class
                   8229: are passed on the stack, just as with @code{struct}s, so
                   8230: @code{field} can also be used for defining class
                   8231: fields. However, passing more items on the stack would be
                   8232: inconvenient, so @code{class} builds a data structure in memory,
                   8233: which is accessed through the variable
                   8234: @code{current-interface}. After its definition is complete, the
                   8235: class is represented on the stack by a pointer (e.g., as parameter for
                   8236: a child class definition).
1.1       anton    8237: 
1.26      crook    8238: A new class starts off with the alignment and size of its parent,
                   8239: and a copy of the parent's method map. Defining new fields extends the
                   8240: size and alignment; likewise, defining new selectors extends the
1.29      crook    8241: method map. @code{overrides} just stores a new @i{xt} in the method
1.26      crook    8242: map at the offset given by the selector.
1.20      pazsan   8243: 
1.26      crook    8244: @cindex class binding, implementation
1.29      crook    8245: Class binding just gets the @i{xt} at the offset given by the selector
1.26      crook    8246: from the class's method map and @code{compile,}s (in the case of
                   8247: @code{[bind]}) it.
1.21      crook    8248: 
1.26      crook    8249: @cindex @code{this} implementation
                   8250: @cindex @code{catch} and @code{this}
                   8251: @cindex @code{this} and @code{catch}
                   8252: I implemented @code{this} as a @code{value}. At the
                   8253: start of an @code{m:...;m} method the old @code{this} is
                   8254: stored to the return stack and restored at the end; and the object on
                   8255: the TOS is stored @code{TO this}. This technique has one
                   8256: disadvantage: If the user does not leave the method via
                   8257: @code{;m}, but via @code{throw} or @code{exit},
                   8258: @code{this} is not restored (and @code{exit} may
                   8259: crash). To deal with the @code{throw} problem, I have redefined
                   8260: @code{catch} to save and restore @code{this}; the same
                   8261: should be done with any word that can catch an exception. As for
                   8262: @code{exit}, I simply forbid it (as a replacement, there is
                   8263: @code{exitm}).
1.21      crook    8264: 
1.26      crook    8265: @cindex @code{inst-var} implementation
                   8266: @code{inst-var} is just the same as @code{field}, with
                   8267: a different @code{DOES>} action:
                   8268: @example
                   8269: @@ this +
                   8270: @end example
                   8271: Similar for @code{inst-value}.
1.21      crook    8272: 
1.26      crook    8273: @cindex class scoping implementation
                   8274: Each class also has a word list that contains the words defined with
                   8275: @code{inst-var} and @code{inst-value}, and its protected
                   8276: words. It also has a pointer to its parent. @code{class} pushes
                   8277: the word lists of the class and all its ancestors onto the search order stack,
                   8278: and @code{end-class} drops them.
1.21      crook    8279: 
1.26      crook    8280: @cindex interface implementation
                   8281: An interface is like a class without fields, parent and protected
                   8282: words; i.e., it just has a method map. If a class implements an
                   8283: interface, its method map contains a pointer to the method map of the
                   8284: interface. The positive offsets in the map are reserved for class
                   8285: methods, therefore interface map pointers have negative
                   8286: offsets. Interfaces have offsets that are unique throughout the
                   8287: system, unlike class selectors, whose offsets are only unique for the
                   8288: classes where the selector is available (invokable).
1.21      crook    8289: 
1.26      crook    8290: This structure means that interface selectors have to perform one
                   8291: indirection more than class selectors to find their method. Their body
                   8292: contains the interface map pointer offset in the class method map, and
                   8293: the method offset in the interface method map. The
                   8294: @code{does>} action for an interface selector is, basically:
1.21      crook    8295: 
                   8296: @example
1.26      crook    8297: ( object selector-body )
                   8298: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   8299: swap object-map @@ + @@ ( object selector-body map )
                   8300: swap selector-offset @@ + @@ execute
1.21      crook    8301: @end example
                   8302: 
1.26      crook    8303: where @code{object-map} and @code{selector-offset} are
                   8304: first fields and generate no code.
                   8305: 
                   8306: As a concrete example, consider the following code:
1.21      crook    8307: 
1.26      crook    8308: @example
                   8309: interface
                   8310:   selector if1sel1
                   8311:   selector if1sel2
                   8312: end-interface if1
1.21      crook    8313: 
1.26      crook    8314: object class
                   8315:   if1 implementation
                   8316:   selector cl1sel1
                   8317:   cell% inst-var cl1iv1
1.21      crook    8318: 
1.26      crook    8319: ' m1 overrides construct
                   8320: ' m2 overrides if1sel1
                   8321: ' m3 overrides if1sel2
                   8322: ' m4 overrides cl1sel2
                   8323: end-class cl1
1.21      crook    8324: 
1.26      crook    8325: create obj1 object dict-new drop
                   8326: create obj2 cl1    dict-new drop
                   8327: @end example
1.21      crook    8328: 
1.26      crook    8329: The data structure created by this code (including the data structure
                   8330: for @code{object}) is shown in the <a
                   8331: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
1.29      crook    8332: @comment TODO add this diagram..
1.21      crook    8333: 
1.26      crook    8334: @node Objects Glossary,  , Objects Implementation, Objects
                   8335: @subsubsection @file{objects.fs} Glossary
                   8336: @cindex @file{objects.fs} Glossary
1.21      crook    8337: 
1.44    ! crook    8338: 
1.26      crook    8339: doc---objects-bind
                   8340: doc---objects-<bind>
                   8341: doc---objects-bind'
                   8342: doc---objects-[bind]
                   8343: doc---objects-class
                   8344: doc---objects-class->map
                   8345: doc---objects-class-inst-size
                   8346: doc---objects-class-override!
                   8347: doc---objects-construct
                   8348: doc---objects-current'
                   8349: doc---objects-[current]
                   8350: doc---objects-current-interface
                   8351: doc---objects-dict-new
                   8352: doc---objects-drop-order
                   8353: doc---objects-end-class
                   8354: doc---objects-end-class-noname
                   8355: doc---objects-end-interface
                   8356: doc---objects-end-interface-noname
1.37      anton    8357: doc---objects-end-methods
1.26      crook    8358: doc---objects-exitm
                   8359: doc---objects-heap-new
                   8360: doc---objects-implementation
                   8361: doc---objects-init-object
                   8362: doc---objects-inst-value
                   8363: doc---objects-inst-var
                   8364: doc---objects-interface
1.38      anton    8365: doc---objects-m:
                   8366: doc---objects-:m
1.26      crook    8367: doc---objects-;m
                   8368: doc---objects-method
1.37      anton    8369: doc---objects-methods
1.26      crook    8370: doc---objects-object
                   8371: doc---objects-overrides
                   8372: doc---objects-[parent]
                   8373: doc---objects-print
                   8374: doc---objects-protected
                   8375: doc---objects-public
                   8376: doc---objects-push-order
                   8377: doc---objects-selector
                   8378: doc---objects-this
                   8379: doc---objects-<to-inst>
                   8380: doc---objects-[to-inst]
                   8381: doc---objects-to-this
                   8382: doc---objects-xt-new
1.21      crook    8383: 
1.44    ! crook    8384: 
1.26      crook    8385: @c -------------------------------------------------------------
                   8386: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   8387: @subsection The @file{oof.fs} model
                   8388: @cindex oof
                   8389: @cindex object-oriented programming
1.21      crook    8390: 
1.26      crook    8391: @cindex @file{objects.fs}
                   8392: @cindex @file{oof.fs}
1.21      crook    8393: 
1.26      crook    8394: This section describes the @file{oof.fs} package.
1.21      crook    8395: 
1.26      crook    8396: The package described in this section has been used in bigFORTH since 1991, and
                   8397: used for two large applications: a chromatographic system used to
                   8398: create new medicaments, and a graphic user interface library (MINOS).
1.21      crook    8399: 
1.26      crook    8400: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   8401: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   8402: 10(2), 1994.
1.21      crook    8403: 
1.26      crook    8404: @menu
                   8405: * Properties of the OOF model::
                   8406: * Basic OOF Usage::
                   8407: * The OOF base class::
                   8408: * Class Declaration::
                   8409: * Class Implementation::
                   8410: @end menu
1.21      crook    8411: 
1.26      crook    8412: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   8413: @subsubsection Properties of the @file{oof.fs} model
                   8414: @cindex @file{oof.fs} properties
1.21      crook    8415: 
1.26      crook    8416: @itemize @bullet
                   8417: @item
                   8418: This model combines object oriented programming with information
                   8419: hiding. It helps you writing large application, where scoping is
                   8420: necessary, because it provides class-oriented scoping.
1.21      crook    8421: 
1.26      crook    8422: @item
                   8423: Named objects, object pointers, and object arrays can be created,
                   8424: selector invocation uses the ``object selector'' syntax. Selector invocation
                   8425: to objects and/or selectors on the stack is a bit less convenient, but
                   8426: possible.
1.21      crook    8427: 
1.26      crook    8428: @item
                   8429: Selector invocation and instance variable usage of the active object is
                   8430: straightforward, since both make use of the active object.
1.21      crook    8431: 
1.26      crook    8432: @item
                   8433: Late binding is efficient and easy to use.
1.21      crook    8434: 
1.26      crook    8435: @item
                   8436: State-smart objects parse selectors. However, extensibility is provided
                   8437: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.21      crook    8438: 
                   8439: @item
1.26      crook    8440: An implementation in ANS Forth is available.
                   8441: 
1.21      crook    8442: @end itemize
                   8443: 
                   8444: 
1.26      crook    8445: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   8446: @subsubsection Basic @file{oof.fs} Usage
                   8447: @cindex @file{oof.fs} usage
                   8448: 
                   8449: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.21      crook    8450: 
1.26      crook    8451: You can define a class for graphical objects like this:
1.21      crook    8452: 
1.26      crook    8453: @cindex @code{class} usage
                   8454: @cindex @code{class;} usage
                   8455: @cindex @code{method} usage
                   8456: @example
                   8457: object class graphical \ "object" is the parent class
                   8458:   method draw ( x y graphical -- )
                   8459: class;
                   8460: @end example
1.21      crook    8461: 
1.26      crook    8462: This code defines a class @code{graphical} with an
                   8463: operation @code{draw}.  We can perform the operation
                   8464: @code{draw} on any @code{graphical} object, e.g.:
1.21      crook    8465: 
1.26      crook    8466: @example
                   8467: 100 100 t-rex draw
                   8468: @end example
1.21      crook    8469: 
1.26      crook    8470: @noindent
                   8471: where @code{t-rex} is an object or object pointer, created with e.g.
                   8472: @code{graphical : t-rex}.
1.21      crook    8473: 
1.26      crook    8474: @cindex abstract class
                   8475: How do we create a graphical object? With the present definitions,
                   8476: we cannot create a useful graphical object. The class
                   8477: @code{graphical} describes graphical objects in general, but not
                   8478: any concrete graphical object type (C++ users would call it an
                   8479: @emph{abstract class}); e.g., there is no method for the selector
                   8480: @code{draw} in the class @code{graphical}.
1.21      crook    8481: 
1.26      crook    8482: For concrete graphical objects, we define child classes of the
                   8483: class @code{graphical}, e.g.:
1.21      crook    8484: 
                   8485: @example
1.26      crook    8486: graphical class circle \ "graphical" is the parent class
                   8487:   cell var circle-radius
                   8488: how:
                   8489:   : draw ( x y -- )
                   8490:     circle-radius @@ draw-circle ;
                   8491: 
                   8492:   : init ( n-radius -- (
                   8493:     circle-radius ! ;
                   8494: class;
                   8495: @end example
                   8496: 
                   8497: Here we define a class @code{circle} as a child of @code{graphical},
                   8498: with a field @code{circle-radius}; it defines new methods for the
                   8499: selectors @code{draw} and @code{init} (@code{init} is defined in
                   8500: @code{object}, the parent class of @code{graphical}).
1.21      crook    8501: 
1.26      crook    8502: Now we can create a circle in the dictionary with:
1.21      crook    8503: 
1.26      crook    8504: @example
                   8505: 50 circle : my-circle
1.21      crook    8506: @end example
                   8507: 
1.26      crook    8508: @noindent
                   8509: @code{:} invokes @code{init}, thus initializing the field
                   8510: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   8511: with:
1.21      crook    8512: 
                   8513: @example
1.26      crook    8514: 100 100 my-circle draw
1.21      crook    8515: @end example
                   8516: 
1.26      crook    8517: @cindex selector invocation, restrictions
                   8518: @cindex class definition, restrictions
                   8519: Note: You can only invoke a selector if the receiving object belongs to
                   8520: the class where the selector was defined or one of its descendents;
                   8521: e.g., you can invoke @code{draw} only for objects belonging to
                   8522: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   8523: mechanism will check if you try to invoke a selector that is not
                   8524: defined in this class hierarchy, so you'll get an error at compilation
                   8525: time.
                   8526: 
                   8527: 
                   8528: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   8529: @subsubsection The @file{oof.fs} base class
                   8530: @cindex @file{oof.fs} base class
                   8531: 
                   8532: When you define a class, you have to specify a parent class.  So how do
                   8533: you start defining classes? There is one class available from the start:
                   8534: @code{object}. You have to use it as ancestor for all classes. It is the
                   8535: only class that has no parent. Classes are also objects, except that
                   8536: they don't have instance variables; class manipulation such as
                   8537: inheritance or changing definitions of a class is handled through
                   8538: selectors of the class @code{object}.
                   8539: 
                   8540: @code{object} provides a number of selectors:
                   8541: 
1.21      crook    8542: @itemize @bullet
                   8543: @item
1.26      crook    8544: @code{class} for subclassing, @code{definitions} to add definitions
                   8545: later on, and @code{class?} to get type informations (is the class a
                   8546: subclass of the class passed on the stack?).
1.44    ! crook    8547: 
1.26      crook    8548: doc---object-class
                   8549: doc---object-definitions
                   8550: doc---object-class?
                   8551: 
1.44    ! crook    8552: 
1.21      crook    8553: @item
1.26      crook    8554: @code{init} and @code{dispose} as constructor and destructor of the
                   8555: object. @code{init} is invocated after the object's memory is allocated,
                   8556: while @code{dispose} also handles deallocation. Thus if you redefine
                   8557: @code{dispose}, you have to call the parent's dispose with @code{super
                   8558: dispose}, too.
1.44    ! crook    8559: 
1.26      crook    8560: doc---object-init
                   8561: doc---object-dispose
                   8562: 
1.44    ! crook    8563: 
1.21      crook    8564: @item
1.26      crook    8565: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   8566: @code{[]} to create named and unnamed objects and object arrays or
                   8567: object pointers.
1.44    ! crook    8568: 
1.26      crook    8569: doc---object-new
                   8570: doc---object-new[]
                   8571: doc---object-:
                   8572: doc---object-ptr
                   8573: doc---object-asptr
                   8574: doc---object-[]
1.21      crook    8575: 
1.44    ! crook    8576: 
1.26      crook    8577: @item
                   8578: @code{::} and @code{super} for explicit scoping. You should use explicit
                   8579: scoping only for super classes or classes with the same set of instance
                   8580: variables. Explicitly-scoped selectors use early binding.
1.44    ! crook    8581: 
1.26      crook    8582: doc---object-::
                   8583: doc---object-super
1.21      crook    8584: 
1.44    ! crook    8585: 
1.26      crook    8586: @item
                   8587: @code{self} to get the address of the object
1.44    ! crook    8588: 
1.26      crook    8589: doc---object-self
1.21      crook    8590: 
1.44    ! crook    8591: 
1.21      crook    8592: @item
1.26      crook    8593: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   8594: pointers and instance defers.
1.44    ! crook    8595: 
1.26      crook    8596: doc---object-bind
                   8597: doc---object-bound
                   8598: doc---object-link
                   8599: doc---object-is
                   8600: 
1.44    ! crook    8601: 
1.21      crook    8602: @item
1.26      crook    8603: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   8604: form the stack, and @code{postpone} to generate selector invocation code.
1.44    ! crook    8605: 
1.26      crook    8606: doc---object-'
                   8607: doc---object-postpone
                   8608: 
1.44    ! crook    8609: 
1.21      crook    8610: @item
1.26      crook    8611: @code{with} and @code{endwith} to select the active object from the
                   8612: stack, and enable its scope. Using @code{with} and @code{endwith}
                   8613: also allows you to create code using selector @code{postpone} without being
                   8614: trapped by the state-smart objects.
1.44    ! crook    8615: 
1.26      crook    8616: doc---object-with
                   8617: doc---object-endwith
                   8618: 
1.44    ! crook    8619: 
1.21      crook    8620: @end itemize
                   8621: 
1.26      crook    8622: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   8623: @subsubsection Class Declaration
                   8624: @cindex class declaration
                   8625: 
                   8626: @itemize @bullet
                   8627: @item
                   8628: Instance variables
1.44    ! crook    8629: 
1.26      crook    8630: doc---oof-var
1.21      crook    8631: 
1.44    ! crook    8632: 
1.26      crook    8633: @item
                   8634: Object pointers
1.44    ! crook    8635: 
1.26      crook    8636: doc---oof-ptr
                   8637: doc---oof-asptr
1.21      crook    8638: 
1.44    ! crook    8639: 
1.26      crook    8640: @item
                   8641: Instance defers
1.44    ! crook    8642: 
1.26      crook    8643: doc---oof-defer
1.21      crook    8644: 
1.44    ! crook    8645: 
1.26      crook    8646: @item
                   8647: Method selectors
1.44    ! crook    8648: 
1.26      crook    8649: doc---oof-early
                   8650: doc---oof-method
1.21      crook    8651: 
1.44    ! crook    8652: 
1.26      crook    8653: @item
                   8654: Class-wide variables
1.44    ! crook    8655: 
1.26      crook    8656: doc---oof-static
1.21      crook    8657: 
1.44    ! crook    8658: 
1.26      crook    8659: @item
                   8660: End declaration
1.44    ! crook    8661: 
1.26      crook    8662: doc---oof-how:
                   8663: doc---oof-class;
1.21      crook    8664: 
1.44    ! crook    8665: 
1.26      crook    8666: @end itemize
1.21      crook    8667: 
1.26      crook    8668: @c -------------------------------------------------------------
                   8669: @node Class Implementation,  , Class Declaration, OOF
                   8670: @subsubsection Class Implementation
                   8671: @cindex class implementation
1.21      crook    8672: 
1.26      crook    8673: @c -------------------------------------------------------------
                   8674: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   8675: @subsection The @file{mini-oof.fs} model
                   8676: @cindex mini-oof
1.1       anton    8677: 
1.26      crook    8678: Gforth's third object oriented Forth package is a 12-liner. It uses a
                   8679: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
                   8680: and reduces to the bare minimum of features. This is based on a posting
                   8681: of Bernd Paysan in comp.arch.
1.1       anton    8682: 
                   8683: @menu
1.26      crook    8684: * Basic Mini-OOF Usage::
                   8685: * Mini-OOF Example::
                   8686: * Mini-OOF Implementation::
1.1       anton    8687: @end menu
                   8688: 
1.26      crook    8689: @c -------------------------------------------------------------
                   8690: @node Basic Mini-OOF Usage, Mini-OOF Example, , Mini-OOF
                   8691: @subsubsection Basic @file{mini-oof.fs} Usage
                   8692: @cindex mini-oof usage
1.1       anton    8693: 
1.28      crook    8694: There is a base class (@code{class}, which allocates one cell for the
                   8695: object pointer) plus seven other words: to define a method, a variable,
                   8696: a class; to end a class, to resolve binding, to allocate an object and
                   8697: to compile a class method.
1.26      crook    8698: @comment TODO better description of the last one
1.1       anton    8699: 
1.44    ! crook    8700: 
1.26      crook    8701: doc-object
                   8702: doc-method
                   8703: doc-var
                   8704: doc-class
                   8705: doc-end-class
                   8706: doc-defines
                   8707: doc-new
                   8708: doc-::
1.1       anton    8709: 
1.21      crook    8710: 
1.44    ! crook    8711: 
1.26      crook    8712: @c -------------------------------------------------------------
                   8713: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   8714: @subsubsection Mini-OOF Example
                   8715: @cindex mini-oof example
1.21      crook    8716: 
1.26      crook    8717: A short example shows how to use this package. This example, in slightly
                   8718: extended form, is supplied as @file{moof-exm.fs}
1.29      crook    8719: @comment TODO could flesh this out with some comments from the Forthwrite article
1.21      crook    8720: 
1.26      crook    8721: @example
                   8722: object class
                   8723:   method init
                   8724:   method draw
                   8725: end-class graphical
                   8726: @end example
1.21      crook    8727: 
1.26      crook    8728: This code defines a class @code{graphical} with an
                   8729: operation @code{draw}.  We can perform the operation
                   8730: @code{draw} on any @code{graphical} object, e.g.:
1.1       anton    8731: 
1.26      crook    8732: @example
                   8733: 100 100 t-rex draw
                   8734: @end example
1.1       anton    8735: 
1.26      crook    8736: where @code{t-rex} is an object or object pointer, created with e.g.
                   8737: @code{graphical new Constant t-rex}.
1.1       anton    8738: 
1.26      crook    8739: For concrete graphical objects, we define child classes of the
                   8740: class @code{graphical}, e.g.:
1.21      crook    8741: 
                   8742: @example
1.26      crook    8743: graphical class
                   8744:   cell var circle-radius
                   8745: end-class circle \ "graphical" is the parent class
1.21      crook    8746: 
1.26      crook    8747: :noname ( x y -- )
                   8748:   circle-radius @@ draw-circle ; circle defines draw
                   8749: :noname ( r -- )
                   8750:   circle-radius ! ; circle defines init
1.21      crook    8751: @end example
                   8752: 
1.26      crook    8753: There is no implicit init method, so we have to define one. The creation
                   8754: code of the object now has to call init explicitely.
1.21      crook    8755: 
1.26      crook    8756: @example
                   8757: circle new Constant my-circle
                   8758: 50 my-circle init
                   8759: @end example
1.21      crook    8760: 
1.26      crook    8761: It is also possible to add a function to create named objects with
                   8762: automatic call of @code{init}, given that all objects have @code{init}
                   8763: on the same place:
1.1       anton    8764: 
                   8765: @example
1.26      crook    8766: : new: ( .. o "name" -- )
                   8767:     new dup Constant init ;
                   8768: 80 circle new: large-circle
1.1       anton    8769: @end example
                   8770: 
1.26      crook    8771: We can draw this new circle at (100,100) with:
1.1       anton    8772: 
                   8773: @example
1.26      crook    8774: 100 100 my-circle draw
1.1       anton    8775: @end example
                   8776: 
1.26      crook    8777: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
                   8778: @subsubsection @file{mini-oof.fs} Implementation
1.1       anton    8779: 
1.26      crook    8780: Object-oriented systems with late binding typically use a
                   8781: ``vtable''-approach: the first variable in each object is a pointer to a
                   8782: table, which contains the methods as function pointers. The vtable
                   8783: may also contain other information.
1.1       anton    8784: 
1.26      crook    8785: So first, let's declare methods:
1.1       anton    8786: 
1.26      crook    8787: @example
                   8788: : method ( m v -- m' v ) Create  over , swap cell+ swap
                   8789:   DOES> ( ... o -- ... ) @ over @ + @ execute ;
                   8790: @end example
1.1       anton    8791: 
1.26      crook    8792: During method declaration, the number of methods and instance
                   8793: variables is on the stack (in address units). @code{method} creates
                   8794: one method and increments the method number. To execute a method, it
                   8795: takes the object, fetches the vtable pointer, adds the offset, and
1.29      crook    8796: executes the @i{xt} stored there. Each method takes the object it is
1.26      crook    8797: invoked from as top of stack parameter. The method itself should
                   8798: consume that object.
1.1       anton    8799: 
1.26      crook    8800: Now, we also have to declare instance variables
1.21      crook    8801: 
1.26      crook    8802: @example
                   8803: : var ( m v size -- m v' ) Create  over , +
                   8804:   DOES> ( o -- addr ) @ + ;
                   8805: @end example
1.21      crook    8806: 
1.26      crook    8807: As before, a word is created with the current offset. Instance
                   8808: variables can have different sizes (cells, floats, doubles, chars), so
                   8809: all we do is take the size and add it to the offset. If your machine
                   8810: has alignment restrictions, put the proper @code{aligned} or
                   8811: @code{faligned} before the variable, to adjust the variable
                   8812: offset. That's why it is on the top of stack.
1.2       jwilke   8813: 
1.26      crook    8814: We need a starting point (the base object) and some syntactic sugar:
1.21      crook    8815: 
1.26      crook    8816: @example
                   8817: Create object  1 cells , 2 cells ,
                   8818: : class ( class -- class methods vars ) dup 2@ ;
                   8819: @end example
1.21      crook    8820: 
1.26      crook    8821: For inheritance, the vtable of the parent object has to be
                   8822: copied when a new, derived class is declared. This gives all the
                   8823: methods of the parent class, which can be overridden, though.
1.21      crook    8824: 
1.2       jwilke   8825: @example
1.26      crook    8826: : end-class  ( class methods vars -- )
                   8827:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   8828:   cell+ dup cell+ r> rot @ 2 cells /string move ;
                   8829: @end example
                   8830: 
                   8831: The first line creates the vtable, initialized with
                   8832: @code{noop}s. The second line is the inheritance mechanism, it
                   8833: copies the xts from the parent vtable.
1.2       jwilke   8834: 
1.26      crook    8835: We still have no way to define new methods, let's do that now:
1.2       jwilke   8836: 
1.26      crook    8837: @example
                   8838: : defines ( xt class -- ) ' >body @ + ! ;
1.2       jwilke   8839: @end example
                   8840: 
1.26      crook    8841: To allocate a new object, we need a word, too:
1.2       jwilke   8842: 
1.26      crook    8843: @example
                   8844: : new ( class -- o )  here over @ allot swap over ! ;
                   8845: @end example
1.2       jwilke   8846: 
1.26      crook    8847: Sometimes derived classes want to access the method of the
                   8848: parent object. There are two ways to achieve this with Mini-OOF:
                   8849: first, you could use named words, and second, you could look up the
                   8850: vtable of the parent object.
1.2       jwilke   8851: 
1.26      crook    8852: @example
                   8853: : :: ( class "name" -- ) ' >body @ + @ compile, ;
                   8854: @end example
1.2       jwilke   8855: 
                   8856: 
1.26      crook    8857: Nothing can be more confusing than a good example, so here is
                   8858: one. First let's declare a text object (called
                   8859: @code{button}), that stores text and position:
1.2       jwilke   8860: 
1.26      crook    8861: @example
                   8862: object class
                   8863:   cell var text
                   8864:   cell var len
                   8865:   cell var x
                   8866:   cell var y
                   8867:   method init
                   8868:   method draw
                   8869: end-class button
                   8870: @end example
1.2       jwilke   8871: 
1.26      crook    8872: @noindent
                   8873: Now, implement the two methods, @code{draw} and @code{init}:
1.2       jwilke   8874: 
1.26      crook    8875: @example
                   8876: :noname ( o -- )
                   8877:  >r r@ x @ r@ y @ at-xy  r@ text @ r> len @ type ;
                   8878:  button defines draw
                   8879: :noname ( addr u o -- )
                   8880:  >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
                   8881:  button defines init
                   8882: @end example
1.2       jwilke   8883: 
1.26      crook    8884: @noindent
                   8885: To demonstrate inheritance, we define a class @code{bold-button}, with no
                   8886: new data and no new methods:
1.2       jwilke   8887: 
1.26      crook    8888: @example
                   8889: button class
                   8890: end-class bold-button
1.1       anton    8891: 
1.26      crook    8892: : bold   27 emit ." [1m" ;
                   8893: : normal 27 emit ." [0m" ;
                   8894: @end example
1.1       anton    8895: 
1.26      crook    8896: @noindent
                   8897: The class @code{bold-button} has a different draw method to
                   8898: @code{button}, but the new method is defined in terms of the draw method
                   8899: for @code{button}:
1.1       anton    8900: 
1.26      crook    8901: @example
                   8902: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   8903: @end example
1.1       anton    8904: 
1.26      crook    8905: @noindent
                   8906: Finally, create two objects and apply methods:
1.1       anton    8907: 
1.26      crook    8908: @example
                   8909: button new Constant foo
                   8910: s" thin foo" foo init
                   8911: page
                   8912: foo draw
                   8913: bold-button new Constant bar
                   8914: s" fat bar" bar init
                   8915: 1 bar y !
                   8916: bar draw
                   8917: @end example
1.1       anton    8918: 
                   8919: 
1.26      crook    8920: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
                   8921: @subsubsection Comparison with other object models
                   8922: @cindex comparison of object models
                   8923: @cindex object models, comparison
1.1       anton    8924: 
1.26      crook    8925: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   8926: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   8927: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   8928: relation of the object models described here to two well-known and two
                   8929: closely-related (by the use of method maps) models.
1.1       anton    8930: 
1.26      crook    8931: @cindex Neon model
                   8932: The most popular model currently seems to be the Neon model (see
                   8933: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   8934: 1997) by Andrew McKewan) but this model has a number of limitations
                   8935: @footnote{A longer version of this critique can be
                   8936: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   8937: Dimensions, May 1997) by Anton Ertl.}:
1.1       anton    8938: 
1.26      crook    8939: @itemize @bullet
                   8940: @item
                   8941: It uses a @code{@emph{selector
                   8942: object}} syntax, which makes it unnatural to pass objects on the
                   8943: stack.
1.1       anton    8944: 
1.26      crook    8945: @item
                   8946: It requires that the selector parses the input stream (at
                   8947: compile time); this leads to reduced extensibility and to bugs that are+
                   8948: hard to find.
1.1       anton    8949: 
1.26      crook    8950: @item
                   8951: It allows using every selector to every object;
                   8952: this eliminates the need for classes, but makes it harder to create
                   8953: efficient implementations. 
                   8954: @end itemize
1.1       anton    8955: 
1.26      crook    8956: @cindex Pountain's object-oriented model
                   8957: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   8958: Press, London, 1987) by Dick Pountain. However, it is not really about
                   8959: object-oriented programming, because it hardly deals with late
                   8960: binding. Instead, it focuses on features like information hiding and
                   8961: overloading that are characteristic of modular languages like Ada (83).
1.1       anton    8962: 
1.26      crook    8963: @cindex Zsoter's object-oriented model
                   8964: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1) 1996, pages 31-35)
                   8965: Andras Zsoter describes a model that makes heavy use of an active object
                   8966: (like @code{this} in @file{objects.fs}): The active object is not only
                   8967: used for accessing all fields, but also specifies the receiving object
                   8968: of every selector invocation; you have to change the active object
                   8969: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
                   8970: changes more or less implicitly at @code{m: ... ;m}. Such a change at
                   8971: the method entry point is unnecessary with the Zsoter's model, because
                   8972: the receiving object is the active object already. On the other hand, the explicit
                   8973: change is absolutely necessary in that model, because otherwise no one
                   8974: could ever change the active object. An ANS Forth implementation of this
                   8975: model is available at @url{http://www.forth.org/fig/oopf.html}.
1.1       anton    8976: 
1.26      crook    8977: @cindex @file{oof.fs}, differences to other models
                   8978: The @file{oof.fs} model combines information hiding and overloading
                   8979: resolution (by keeping names in various word lists) with object-oriented
                   8980: programming. It sets the active object implicitly on method entry, but
                   8981: also allows explicit changing (with @code{>o...o>} or with
                   8982: @code{with...endwith}). It uses parsing and state-smart objects and
                   8983: classes for resolving overloading and for early binding: the object or
                   8984: class parses the selector and determines the method from this. If the
                   8985: selector is not parsed by an object or class, it performs a call to the
                   8986: selector for the active object (late binding), like Zsoter's model.
                   8987: Fields are always accessed through the active object. The big
                   8988: disadvantage of this model is the parsing and the state-smartness, which
                   8989: reduces extensibility and increases the opportunities for subtle bugs;
                   8990: essentially, you are only safe if you never tick or @code{postpone} an
                   8991: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.1       anton    8992: 
1.26      crook    8993: @cindex @file{mini-oof.fs}, differences to other models
                   8994: The @file{mini-oof.fs} model is quite similar to a very stripped-down version of
                   8995: the @file{objects.fs} model, but syntactically it is a mixture of the @file{objects.fs} and
                   8996: @file{oof.fs} models.
1.1       anton    8997: 
1.26      crook    8998: @c -------------------------------------------------------------
                   8999: @node Passing Commands to the OS, Miscellaneous Words, Object-oriented Forth, Words
1.21      crook    9000: @section Passing Commands to the Operating System
                   9001: @cindex operating system - passing commands
                   9002: @cindex shell commands
                   9003: 
                   9004: Gforth allows you to pass an arbitrary string to the host operating
                   9005: system shell (if such a thing exists) for execution.
                   9006: 
1.44    ! crook    9007: 
1.21      crook    9008: doc-sh
                   9009: doc-system
                   9010: doc-$?
1.23      crook    9011: doc-getenv
1.21      crook    9012: 
1.44    ! crook    9013: 
1.26      crook    9014: @c -------------------------------------------------------------
1.21      crook    9015: @node Miscellaneous Words,  , Passing Commands to the OS, Words
                   9016: @section Miscellaneous Words
                   9017: @cindex miscellaneous words
                   9018: 
1.29      crook    9019: @comment TODO find homes for these
                   9020: 
1.26      crook    9021: These section lists the ANS Forth words that are not documented
1.21      crook    9022: elsewhere in this manual. Ultimately, they all need proper homes.
                   9023: 
1.44    ! crook    9024: 
1.21      crook    9025: doc-ms
                   9026: doc-time&date
1.27      crook    9027: 
1.44    ! crook    9028: 
        !          9029: 
1.21      crook    9030: doc-[compile]
                   9031: 
1.44    ! crook    9032: 
1.26      crook    9033: The following ANS Forth words are not currently supported by Gforth 
1.27      crook    9034: (@pxref{ANS conformance}):
1.21      crook    9035: 
                   9036: @code{EDITOR} 
                   9037: @code{EMIT?} 
                   9038: @code{FORGET} 
                   9039: 
1.24      anton    9040: @c ******************************************************************
                   9041: @node Error messages, Tools, Words, Top
                   9042: @chapter Error messages
                   9043: @cindex error messages
                   9044: @cindex backtrace
                   9045: 
                   9046: A typical Gforth error message looks like this:
                   9047: 
                   9048: @example
                   9049: in file included from :-1
                   9050: in file included from ./yyy.fs:1
                   9051: ./xxx.fs:4: Invalid memory address
                   9052: bar
                   9053: ^^^
1.25      anton    9054: $400E664C @@
                   9055: $400E6664 foo
1.24      anton    9056: @end example
                   9057: 
                   9058: The message identifying the error is @code{Invalid memory address}.  The
                   9059: error happened when text-interpreting line 4 of the file
                   9060: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
                   9061: word on the line where the error happened, is pointed out (with
                   9062: @code{^^^}).
                   9063: 
                   9064: The file containing the error was included in line 1 of @file{./yyy.fs},
                   9065: and @file{yyy.fs} was included from a non-file (in this case, by giving
                   9066: @file{yyy.fs} as command-line parameter to Gforth).
                   9067: 
                   9068: At the end of the error message you find a return stack dump that can be
                   9069: interpreted as a backtrace (possibly empty). On top you find the top of
                   9070: the return stack when the @code{throw} happened, and at the bottom you
                   9071: find the return stack entry just above the return stack of the topmost
                   9072: text interpreter.
                   9073: 
                   9074: To the right of most return stack entries you see a guess for the word
                   9075: that pushed that return stack entry as its return address. This gives a
                   9076: backtrace. In our case we see that @code{bar} called @code{foo}, and
                   9077: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
                   9078: address} exception).
                   9079: 
                   9080: Note that the backtrace is not perfect: We don't know which return stack
                   9081: entries are return addresses (so we may get false positives); and in
                   9082: some cases (e.g., for @code{abort"}) we cannot determine from the return
                   9083: address the word that pushed the return address, so for some return
                   9084: addresses you see no names in the return stack dump.
1.25      anton    9085: 
                   9086: @cindex @code{catch} and backtraces
                   9087: The return stack dump represents the return stack at the time when a
                   9088: specific @code{throw} was executed.  In programs that make use of
                   9089: @code{catch}, it is not necessarily clear which @code{throw} should be
                   9090: used for the return stack dump (e.g., consider one @code{throw} that
                   9091: indicates an error, which is caught, and during recovery another error
1.42      anton    9092: happens; which @code{throw} should be used for the stack dump?).  Gforth
1.25      anton    9093: presents the return stack dump for the first @code{throw} after the last
                   9094: executed (not returned-to) @code{catch}; this works well in the usual
                   9095: case.
                   9096: 
                   9097: @cindex @code{gforth-fast} and backtraces
                   9098: @cindex @code{gforth-fast}, difference from @code{gforth}
                   9099: @cindex backtraces with @code{gforth-fast}
                   9100: @cindex return stack dump with @code{gforth-fast}
                   9101: @code{gforth} is able to do a return stack dump for throws generated
                   9102: from primitives (e.g., invalid memory address, stack empty etc.);
                   9103: @code{gforth-fast} is only able to do a return stack dump from a
                   9104: directly called @code{throw} (including @code{abort} etc.).  This is the
1.30      anton    9105: only difference (apart from a speed factor of between 1.15 (K6-2) and
                   9106: 1.6 (21164A)) between @code{gforth} and @code{gforth-fast}.  Given an
                   9107: exception caused by a primitive in @code{gforth-fast}, you will
                   9108: typically see no return stack dump at all; however, if the exception is
                   9109: caught by @code{catch} (e.g., for restoring some state), and then
                   9110: @code{throw}n again, the return stack dump will be for the first such
                   9111: @code{throw}.
1.2       jwilke   9112: 
1.5       anton    9113: @c ******************************************************************
1.24      anton    9114: @node Tools, ANS conformance, Error messages, Top
1.1       anton    9115: @chapter Tools
                   9116: 
                   9117: @menu
                   9118: * ANS Report::                  Report the words used, sorted by wordset.
                   9119: @end menu
                   9120: 
                   9121: See also @ref{Emacs and Gforth}.
                   9122: 
                   9123: @node ANS Report,  , Tools, Tools
                   9124: @section @file{ans-report.fs}: Report the words used, sorted by wordset
                   9125: @cindex @file{ans-report.fs}
                   9126: @cindex report the words used in your program
                   9127: @cindex words used in your program
                   9128: 
                   9129: If you want to label a Forth program as ANS Forth Program, you must
                   9130: document which wordsets the program uses; for extension wordsets, it is
                   9131: helpful to list the words the program requires from these wordsets
                   9132: (because Forth systems are allowed to provide only some words of them).
                   9133: 
                   9134: The @file{ans-report.fs} tool makes it easy for you to determine which
                   9135: words from which wordset and which non-ANS words your application
                   9136: uses. You simply have to include @file{ans-report.fs} before loading the
                   9137: program you want to check. After loading your program, you can get the
                   9138: report with @code{print-ans-report}. A typical use is to run this as
                   9139: batch job like this:
                   9140: @example
                   9141: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
                   9142: @end example
                   9143: 
                   9144: The output looks like this (for @file{compat/control.fs}):
                   9145: @example
                   9146: The program uses the following words
                   9147: from CORE :
                   9148: : POSTPONE THEN ; immediate ?dup IF 0= 
                   9149: from BLOCK-EXT :
                   9150: \ 
                   9151: from FILE :
                   9152: ( 
                   9153: @end example
                   9154: 
                   9155: @subsection Caveats
                   9156: 
                   9157: Note that @file{ans-report.fs} just checks which words are used, not whether
                   9158: they are used in an ANS Forth conforming way!
                   9159: 
                   9160: Some words are defined in several wordsets in the
                   9161: standard. @file{ans-report.fs} reports them for only one of the
                   9162: wordsets, and not necessarily the one you expect. It depends on usage
                   9163: which wordset is the right one to specify. E.g., if you only use the
                   9164: compilation semantics of @code{S"}, it is a Core word; if you also use
                   9165: its interpretation semantics, it is a File word.
                   9166: 
                   9167: @c ******************************************************************
                   9168: @node ANS conformance, Model, Tools, Top
                   9169: @chapter ANS conformance
                   9170: @cindex ANS conformance of Gforth
                   9171: 
                   9172: To the best of our knowledge, Gforth is an
                   9173: 
                   9174: ANS Forth System
                   9175: @itemize @bullet
                   9176: @item providing the Core Extensions word set
                   9177: @item providing the Block word set
                   9178: @item providing the Block Extensions word set
                   9179: @item providing the Double-Number word set
                   9180: @item providing the Double-Number Extensions word set
                   9181: @item providing the Exception word set
                   9182: @item providing the Exception Extensions word set
                   9183: @item providing the Facility word set
1.40      anton    9184: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1       anton    9185: @item providing the File Access word set
                   9186: @item providing the File Access Extensions word set
                   9187: @item providing the Floating-Point word set
                   9188: @item providing the Floating-Point Extensions word set
                   9189: @item providing the Locals word set
                   9190: @item providing the Locals Extensions word set
                   9191: @item providing the Memory-Allocation word set
                   9192: @item providing the Memory-Allocation Extensions word set (that one's easy)
                   9193: @item providing the Programming-Tools word set
                   9194: @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
                   9195: @item providing the Search-Order word set
                   9196: @item providing the Search-Order Extensions word set
                   9197: @item providing the String word set
                   9198: @item providing the String Extensions word set (another easy one)
                   9199: @end itemize
                   9200: 
                   9201: @cindex system documentation
                   9202: In addition, ANS Forth systems are required to document certain
                   9203: implementation choices. This chapter tries to meet these
                   9204: requirements. In many cases it gives a way to ask the system for the
                   9205: information instead of providing the information directly, in
                   9206: particular, if the information depends on the processor, the operating
                   9207: system or the installation options chosen, or if they are likely to
                   9208: change during the maintenance of Gforth.
                   9209: 
                   9210: @comment The framework for the rest has been taken from pfe.
                   9211: 
                   9212: @menu
                   9213: * The Core Words::              
                   9214: * The optional Block word set::  
                   9215: * The optional Double Number word set::  
                   9216: * The optional Exception word set::  
                   9217: * The optional Facility word set::  
                   9218: * The optional File-Access word set::  
                   9219: * The optional Floating-Point word set::  
                   9220: * The optional Locals word set::  
                   9221: * The optional Memory-Allocation word set::  
                   9222: * The optional Programming-Tools word set::  
                   9223: * The optional Search-Order word set::  
                   9224: @end menu
                   9225: 
                   9226: 
                   9227: @c =====================================================================
                   9228: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
                   9229: @comment  node-name,  next,  previous,  up
                   9230: @section The Core Words
                   9231: @c =====================================================================
                   9232: @cindex core words, system documentation
                   9233: @cindex system documentation, core words
                   9234: 
                   9235: @menu
                   9236: * core-idef::                   Implementation Defined Options                   
                   9237: * core-ambcond::                Ambiguous Conditions                
                   9238: * core-other::                  Other System Documentation                  
                   9239: @end menu
                   9240: 
                   9241: @c ---------------------------------------------------------------------
                   9242: @node core-idef, core-ambcond, The Core Words, The Core Words
                   9243: @subsection Implementation Defined Options
                   9244: @c ---------------------------------------------------------------------
                   9245: @cindex core words, implementation-defined options
                   9246: @cindex implementation-defined options, core words
                   9247: 
                   9248: 
                   9249: @table @i
                   9250: @item (Cell) aligned addresses:
                   9251: @cindex cell-aligned addresses
                   9252: @cindex aligned addresses
                   9253: processor-dependent. Gforth's alignment words perform natural alignment
                   9254: (e.g., an address aligned for a datum of size 8 is divisible by
                   9255: 8). Unaligned accesses usually result in a @code{-23 THROW}.
                   9256: 
                   9257: @item @code{EMIT} and non-graphic characters:
                   9258: @cindex @code{EMIT} and non-graphic characters
                   9259: @cindex non-graphic characters and @code{EMIT}
                   9260: The character is output using the C library function (actually, macro)
                   9261: @code{putc}.
                   9262: 
                   9263: @item character editing of @code{ACCEPT} and @code{EXPECT}:
                   9264: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
                   9265: @cindex editing in @code{ACCEPT} and @code{EXPECT}
                   9266: @cindex @code{ACCEPT}, editing
                   9267: @cindex @code{EXPECT}, editing
                   9268: This is modeled on the GNU readline library (@pxref{Readline
                   9269: Interaction, , Command Line Editing, readline, The GNU Readline
                   9270: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
                   9271: producing a full word completion every time you type it (instead of
1.28      crook    9272: producing the common prefix of all completions). @xref{Command-line editing}.
1.1       anton    9273: 
                   9274: @item character set:
                   9275: @cindex character set
                   9276: The character set of your computer and display device. Gforth is
                   9277: 8-bit-clean (but some other component in your system may make trouble).
                   9278: 
                   9279: @item Character-aligned address requirements:
                   9280: @cindex character-aligned address requirements
                   9281: installation-dependent. Currently a character is represented by a C
                   9282: @code{unsigned char}; in the future we might switch to @code{wchar_t}
                   9283: (Comments on that requested).
                   9284: 
                   9285: @item character-set extensions and matching of names:
                   9286: @cindex character-set extensions and matching of names
1.26      crook    9287: @cindex case-sensitivity for name lookup
                   9288: @cindex name lookup, case-sensitivity
                   9289: @cindex locale and case-sensitivity
1.21      crook    9290: Any character except the ASCII NUL character can be used in a
1.1       anton    9291: name. Matching is case-insensitive (except in @code{TABLE}s). The
                   9292: matching is performed using the C function @code{strncasecmp}, whose
                   9293: function is probably influenced by the locale. E.g., the @code{C} locale
                   9294: does not know about accents and umlauts, so they are matched
                   9295: case-sensitively in that locale. For portability reasons it is best to
                   9296: write programs such that they work in the @code{C} locale. Then one can
                   9297: use libraries written by a Polish programmer (who might use words
                   9298: containing ISO Latin-2 encoded characters) and by a French programmer
                   9299: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
                   9300: funny results for some of the words (which ones, depends on the font you
                   9301: are using)). Also, the locale you prefer may not be available in other
                   9302: operating systems. Hopefully, Unicode will solve these problems one day.
                   9303: 
                   9304: @item conditions under which control characters match a space delimiter:
                   9305: @cindex space delimiters
                   9306: @cindex control characters as delimiters
                   9307: If @code{WORD} is called with the space character as a delimiter, all
                   9308: white-space characters (as identified by the C macro @code{isspace()})
                   9309: are delimiters. @code{PARSE}, on the other hand, treats space like other
1.44    ! crook    9310: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
1.1       anton    9311: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
                   9312: interpreter (aka text interpreter) by default, treats all white-space
                   9313: characters as delimiters.
                   9314: 
1.26      crook    9315: @item format of the control-flow stack:
                   9316: @cindex control-flow stack, format
                   9317: The data stack is used as control-flow stack. The size of a control-flow
1.1       anton    9318: stack item in cells is given by the constant @code{cs-item-size}. At the
                   9319: time of this writing, an item consists of a (pointer to a) locals list
                   9320: (third), an address in the code (second), and a tag for identifying the
                   9321: item (TOS). The following tags are used: @code{defstart},
                   9322: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
                   9323: @code{scopestart}.
                   9324: 
                   9325: @item conversion of digits > 35
                   9326: @cindex digits > 35
                   9327: The characters @code{[\]^_'} are the digits with the decimal value
                   9328: 36@minus{}41. There is no way to input many of the larger digits.
                   9329: 
                   9330: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
                   9331: @cindex @code{EXPECT}, display after end of input
                   9332: @cindex @code{ACCEPT}, display after end of input
                   9333: The cursor is moved to the end of the entered string. If the input is
                   9334: terminated using the @kbd{Return} key, a space is typed.
                   9335: 
                   9336: @item exception abort sequence of @code{ABORT"}:
                   9337: @cindex exception abort sequence of @code{ABORT"}
                   9338: @cindex @code{ABORT"}, exception abort sequence
                   9339: The error string is stored into the variable @code{"error} and a
                   9340: @code{-2 throw} is performed.
                   9341: 
                   9342: @item input line terminator:
                   9343: @cindex input line terminator
                   9344: @cindex line terminator on input
1.26      crook    9345: @cindex newline character on input
1.1       anton    9346: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
                   9347: lines. One of these characters is typically produced when you type the
                   9348: @kbd{Enter} or @kbd{Return} key.
                   9349: 
                   9350: @item maximum size of a counted string:
                   9351: @cindex maximum size of a counted string
                   9352: @cindex counted string, maximum size
                   9353: @code{s" /counted-string" environment? drop .}. Currently 255 characters
                   9354: on all ports, but this may change.
                   9355: 
                   9356: @item maximum size of a parsed string:
                   9357: @cindex maximum size of a parsed string
                   9358: @cindex parsed string, maximum size
                   9359: Given by the constant @code{/line}. Currently 255 characters.
                   9360: 
                   9361: @item maximum size of a definition name, in characters:
                   9362: @cindex maximum size of a definition name, in characters
                   9363: @cindex name, maximum length
                   9364: 31
                   9365: 
                   9366: @item maximum string length for @code{ENVIRONMENT?}, in characters:
                   9367: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
                   9368: @cindex @code{ENVIRONMENT?} string length, maximum
                   9369: 31
                   9370: 
                   9371: @item method of selecting the user input device:
                   9372: @cindex user input device, method of selecting
                   9373: The user input device is the standard input. There is currently no way to
                   9374: change it from within Gforth. However, the input can typically be
                   9375: redirected in the command line that starts Gforth.
                   9376: 
                   9377: @item method of selecting the user output device:
                   9378: @cindex user output device, method of selecting
                   9379: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10      anton    9380: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
                   9381: output when the user output device is a terminal, otherwise the output
                   9382: is buffered.
1.1       anton    9383: 
                   9384: @item methods of dictionary compilation:
                   9385: What are we expected to document here?
                   9386: 
                   9387: @item number of bits in one address unit:
                   9388: @cindex number of bits in one address unit
                   9389: @cindex address unit, size in bits
                   9390: @code{s" address-units-bits" environment? drop .}. 8 in all current
                   9391: ports.
                   9392: 
                   9393: @item number representation and arithmetic:
                   9394: @cindex number representation and arithmetic
                   9395: Processor-dependent. Binary two's complement on all current ports.
                   9396: 
                   9397: @item ranges for integer types:
                   9398: @cindex ranges for integer types
                   9399: @cindex integer types, ranges
                   9400: Installation-dependent. Make environmental queries for @code{MAX-N},
                   9401: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
                   9402: unsigned (and positive) types is 0. The lower bound for signed types on
                   9403: two's complement and one's complement machines machines can be computed
                   9404: by adding 1 to the upper bound.
                   9405: 
                   9406: @item read-only data space regions:
                   9407: @cindex read-only data space regions
                   9408: @cindex data-space, read-only regions
                   9409: The whole Forth data space is writable.
                   9410: 
                   9411: @item size of buffer at @code{WORD}:
                   9412: @cindex size of buffer at @code{WORD}
                   9413: @cindex @code{WORD} buffer size
                   9414: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   9415: shared with the pictured numeric output string. If overwriting
                   9416: @code{PAD} is acceptable, it is as large as the remaining dictionary
                   9417: space, although only as much can be sensibly used as fits in a counted
                   9418: string.
                   9419: 
                   9420: @item size of one cell in address units:
                   9421: @cindex cell size
                   9422: @code{1 cells .}.
                   9423: 
                   9424: @item size of one character in address units:
                   9425: @cindex char size
                   9426: @code{1 chars .}. 1 on all current ports.
                   9427: 
                   9428: @item size of the keyboard terminal buffer:
                   9429: @cindex size of the keyboard terminal buffer
                   9430: @cindex terminal buffer, size
                   9431: Varies. You can determine the size at a specific time using @code{lp@@
                   9432: tib - .}. It is shared with the locals stack and TIBs of files that
                   9433: include the current file. You can change the amount of space for TIBs
                   9434: and locals stack at Gforth startup with the command line option
                   9435: @code{-l}.
                   9436: 
                   9437: @item size of the pictured numeric output buffer:
                   9438: @cindex size of the pictured numeric output buffer
                   9439: @cindex pictured numeric output buffer, size
                   9440: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   9441: shared with @code{WORD}.
                   9442: 
                   9443: @item size of the scratch area returned by @code{PAD}:
                   9444: @cindex size of the scratch area returned by @code{PAD}
                   9445: @cindex @code{PAD} size
                   9446: The remainder of dictionary space. @code{unused pad here - - .}.
                   9447: 
                   9448: @item system case-sensitivity characteristics:
                   9449: @cindex case-sensitivity characteristics
1.26      crook    9450: Dictionary searches are case-insensitive (except in
1.1       anton    9451: @code{TABLE}s). However, as explained above under @i{character-set
                   9452: extensions}, the matching for non-ASCII characters is determined by the
                   9453: locale you are using. In the default @code{C} locale all non-ASCII
                   9454: characters are matched case-sensitively.
                   9455: 
                   9456: @item system prompt:
                   9457: @cindex system prompt
                   9458: @cindex prompt
                   9459: @code{ ok} in interpret state, @code{ compiled} in compile state.
                   9460: 
                   9461: @item division rounding:
                   9462: @cindex division rounding
                   9463: installation dependent. @code{s" floored" environment? drop .}. We leave
                   9464: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
                   9465: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
                   9466: 
                   9467: @item values of @code{STATE} when true:
                   9468: @cindex @code{STATE} values
                   9469: -1.
                   9470: 
                   9471: @item values returned after arithmetic overflow:
                   9472: On two's complement machines, arithmetic is performed modulo
                   9473: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   9474: arithmetic (with appropriate mapping for signed types). Division by zero
                   9475: typically results in a @code{-55 throw} (Floating-point unidentified
                   9476: fault), although a @code{-10 throw} (divide by zero) would be more
                   9477: appropriate.
                   9478: 
                   9479: @item whether the current definition can be found after @t{DOES>}:
                   9480: @cindex @t{DOES>}, visibility of current definition
                   9481: No.
                   9482: 
                   9483: @end table
                   9484: 
                   9485: @c ---------------------------------------------------------------------
                   9486: @node core-ambcond, core-other, core-idef, The Core Words
                   9487: @subsection Ambiguous conditions
                   9488: @c ---------------------------------------------------------------------
                   9489: @cindex core words, ambiguous conditions
                   9490: @cindex ambiguous conditions, core words
                   9491: 
                   9492: @table @i
                   9493: 
                   9494: @item a name is neither a word nor a number:
                   9495: @cindex name not found
1.26      crook    9496: @cindex undefined word
1.1       anton    9497: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
                   9498: preserves the data and FP stack, so you don't lose more work than
                   9499: necessary.
                   9500: 
                   9501: @item a definition name exceeds the maximum length allowed:
1.26      crook    9502: @cindex word name too long
1.1       anton    9503: @code{-19 throw} (Word name too long)
                   9504: 
                   9505: @item addressing a region not inside the various data spaces of the forth system:
                   9506: @cindex Invalid memory address
1.32      anton    9507: The stacks, code space and header space are accessible. Machine code space is
1.1       anton    9508: typically readable. Accessing other addresses gives results dependent on
                   9509: the operating system. On decent systems: @code{-9 throw} (Invalid memory
                   9510: address).
                   9511: 
                   9512: @item argument type incompatible with parameter:
1.26      crook    9513: @cindex argument type mismatch
1.1       anton    9514: This is usually not caught. Some words perform checks, e.g., the control
                   9515: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
                   9516: mismatch).
                   9517: 
                   9518: @item attempting to obtain the execution token of a word with undefined execution semantics:
                   9519: @cindex Interpreting a compile-only word, for @code{'} etc.
                   9520: @cindex execution token of words with undefined execution semantics
                   9521: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
                   9522: get an execution token for @code{compile-only-error} (which performs a
                   9523: @code{-14 throw} when executed).
                   9524: 
                   9525: @item dividing by zero:
                   9526: @cindex dividing by zero
                   9527: @cindex floating point unidentified fault, integer division
1.24      anton    9528: On better platforms, this produces a @code{-10 throw} (Division by
                   9529: zero); on other systems, this typically results in a @code{-55 throw}
                   9530: (Floating-point unidentified fault).
1.1       anton    9531: 
                   9532: @item insufficient data stack or return stack space:
                   9533: @cindex insufficient data stack or return stack space
                   9534: @cindex stack overflow
1.26      crook    9535: @cindex address alignment exception, stack overflow
1.1       anton    9536: @cindex Invalid memory address, stack overflow
                   9537: Depending on the operating system, the installation, and the invocation
                   9538: of Gforth, this is either checked by the memory management hardware, or
1.24      anton    9539: it is not checked. If it is checked, you typically get a @code{-3 throw}
                   9540: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
                   9541: throw} (Invalid memory address) (depending on the platform and how you
                   9542: achieved the overflow) as soon as the overflow happens. If it is not
                   9543: checked, overflows typically result in mysterious illegal memory
                   9544: accesses, producing @code{-9 throw} (Invalid memory address) or
                   9545: @code{-23 throw} (Address alignment exception); they might also destroy
                   9546: the internal data structure of @code{ALLOCATE} and friends, resulting in
                   9547: various errors in these words.
1.1       anton    9548: 
                   9549: @item insufficient space for loop control parameters:
                   9550: @cindex insufficient space for loop control parameters
                   9551: like other return stack overflows.
                   9552: 
                   9553: @item insufficient space in the dictionary:
                   9554: @cindex insufficient space in the dictionary
                   9555: @cindex dictionary overflow
1.12      anton    9556: If you try to allot (either directly with @code{allot}, or indirectly
                   9557: with @code{,}, @code{create} etc.) more memory than available in the
                   9558: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
                   9559: to access memory beyond the end of the dictionary, the results are
                   9560: similar to stack overflows.
1.1       anton    9561: 
                   9562: @item interpreting a word with undefined interpretation semantics:
                   9563: @cindex interpreting a word with undefined interpretation semantics
                   9564: @cindex Interpreting a compile-only word
                   9565: For some words, we have defined interpretation semantics. For the
                   9566: others: @code{-14 throw} (Interpreting a compile-only word).
                   9567: 
                   9568: @item modifying the contents of the input buffer or a string literal:
                   9569: @cindex modifying the contents of the input buffer or a string literal
                   9570: These are located in writable memory and can be modified.
                   9571: 
                   9572: @item overflow of the pictured numeric output string:
                   9573: @cindex overflow of the pictured numeric output string
                   9574: @cindex pictured numeric output string, overflow
1.24      anton    9575: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1       anton    9576: 
                   9577: @item parsed string overflow:
                   9578: @cindex parsed string overflow
                   9579: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
                   9580: 
                   9581: @item producing a result out of range:
                   9582: @cindex result out of range
                   9583: On two's complement machines, arithmetic is performed modulo
                   9584: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   9585: arithmetic (with appropriate mapping for signed types). Division by zero
1.24      anton    9586: typically results in a @code{-10 throw} (divide by zero) or @code{-55
                   9587: throw} (floating point unidentified fault). @code{convert} and
                   9588: @code{>number} currently overflow silently.
1.1       anton    9589: 
                   9590: @item reading from an empty data or return stack:
                   9591: @cindex stack empty
                   9592: @cindex stack underflow
1.24      anton    9593: @cindex return stack underflow
1.1       anton    9594: The data stack is checked by the outer (aka text) interpreter after
                   9595: every word executed. If it has underflowed, a @code{-4 throw} (Stack
                   9596: underflow) is performed. Apart from that, stacks may be checked or not,
1.24      anton    9597: depending on operating system, installation, and invocation. If they are
                   9598: caught by a check, they typically result in @code{-4 throw} (Stack
                   9599: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
                   9600: (Invalid memory address), depending on the platform and which stack
                   9601: underflows and by how much. Note that even if the system uses checking
                   9602: (through the MMU), your program may have to underflow by a significant
                   9603: number of stack items to trigger the reaction (the reason for this is
                   9604: that the MMU, and therefore the checking, works with a page-size
                   9605: granularity).  If there is no checking, the symptoms resulting from an
                   9606: underflow are similar to those from an overflow.  Unbalanced return
                   9607: stack errors result in a variaty of symptoms, including @code{-9 throw}
                   9608: (Invalid memory address) and Illegal Instruction (typically @code{-260
                   9609: throw}).
1.1       anton    9610: 
                   9611: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
                   9612: @cindex unexpected end of the input buffer
                   9613: @cindex zero-length string as a name
                   9614: @cindex Attempt to use zero-length string as a name
                   9615: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
                   9616: use zero-length string as a name). Words like @code{'} probably will not
                   9617: find what they search. Note that it is possible to create zero-length
                   9618: names with @code{nextname} (should it not?).
                   9619: 
                   9620: @item @code{>IN} greater than input buffer:
                   9621: @cindex @code{>IN} greater than input buffer
                   9622: The next invocation of a parsing word returns a string with length 0.
                   9623: 
                   9624: @item @code{RECURSE} appears after @code{DOES>}:
                   9625: @cindex @code{RECURSE} appears after @code{DOES>}
                   9626: Compiles a recursive call to the defining word, not to the defined word.
                   9627: 
                   9628: @item argument input source different than current input source for @code{RESTORE-INPUT}:
                   9629: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26      crook    9630: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1       anton    9631: @cindex @code{RESTORE-INPUT}, Argument type mismatch
                   9632: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
                   9633: the end of the file was reached), its source-id may be
                   9634: reused. Therefore, restoring an input source specification referencing a
                   9635: closed file may lead to unpredictable results instead of a @code{-12
                   9636: THROW}.
                   9637: 
                   9638: In the future, Gforth may be able to restore input source specifications
                   9639: from other than the current input source.
                   9640: 
                   9641: @item data space containing definitions gets de-allocated:
                   9642: @cindex data space containing definitions gets de-allocated
                   9643: Deallocation with @code{allot} is not checked. This typically results in
                   9644: memory access faults or execution of illegal instructions.
                   9645: 
                   9646: @item data space read/write with incorrect alignment:
                   9647: @cindex data space read/write with incorrect alignment
                   9648: @cindex alignment faults
1.26      crook    9649: @cindex address alignment exception
1.1       anton    9650: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12      anton    9651: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1       anton    9652: alignment turned on, incorrect alignment results in a @code{-9 throw}
                   9653: (Invalid memory address). There are reportedly some processors with
1.12      anton    9654: alignment restrictions that do not report violations.
1.1       anton    9655: 
                   9656: @item data space pointer not properly aligned, @code{,}, @code{C,}:
                   9657: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
                   9658: Like other alignment errors.
                   9659: 
                   9660: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
                   9661: Like other stack underflows.
                   9662: 
                   9663: @item loop control parameters not available:
                   9664: @cindex loop control parameters not available
                   9665: Not checked. The counted loop words simply assume that the top of return
                   9666: stack items are loop control parameters and behave accordingly.
                   9667: 
                   9668: @item most recent definition does not have a name (@code{IMMEDIATE}):
                   9669: @cindex most recent definition does not have a name (@code{IMMEDIATE})
                   9670: @cindex last word was headerless
                   9671: @code{abort" last word was headerless"}.
                   9672: 
                   9673: @item name not defined by @code{VALUE} used by @code{TO}:
                   9674: @cindex name not defined by @code{VALUE} used by @code{TO}
                   9675: @cindex @code{TO} on non-@code{VALUE}s
                   9676: @cindex Invalid name argument, @code{TO}
                   9677: @code{-32 throw} (Invalid name argument) (unless name is a local or was
                   9678: defined by @code{CONSTANT}; in the latter case it just changes the constant).
                   9679: 
                   9680: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
                   9681: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26      crook    9682: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1       anton    9683: @code{-13 throw} (Undefined word)
                   9684: 
                   9685: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
                   9686: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
                   9687: Gforth behaves as if they were of the same type. I.e., you can predict
                   9688: the behaviour by interpreting all parameters as, e.g., signed.
                   9689: 
                   9690: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
                   9691: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
                   9692: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
                   9693: compilation semantics of @code{TO}.
                   9694: 
                   9695: @item String longer than a counted string returned by @code{WORD}:
1.26      crook    9696: @cindex string longer than a counted string returned by @code{WORD}
1.1       anton    9697: @cindex @code{WORD}, string overflow
                   9698: Not checked. The string will be ok, but the count will, of course,
                   9699: contain only the least significant bits of the length.
                   9700: 
                   9701: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
                   9702: @cindex @code{LSHIFT}, large shift counts
                   9703: @cindex @code{RSHIFT}, large shift counts
                   9704: Processor-dependent. Typical behaviours are returning 0 and using only
                   9705: the low bits of the shift count.
                   9706: 
                   9707: @item word not defined via @code{CREATE}:
                   9708: @cindex @code{>BODY} of non-@code{CREATE}d words
                   9709: @code{>BODY} produces the PFA of the word no matter how it was defined.
                   9710: 
                   9711: @cindex @code{DOES>} of non-@code{CREATE}d words
                   9712: @code{DOES>} changes the execution semantics of the last defined word no
                   9713: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
                   9714: @code{CREATE , DOES>}.
                   9715: 
                   9716: @item words improperly used outside @code{<#} and @code{#>}:
                   9717: Not checked. As usual, you can expect memory faults.
                   9718: 
                   9719: @end table
                   9720: 
                   9721: 
                   9722: @c ---------------------------------------------------------------------
                   9723: @node core-other,  , core-ambcond, The Core Words
                   9724: @subsection Other system documentation
                   9725: @c ---------------------------------------------------------------------
                   9726: @cindex other system documentation, core words
                   9727: @cindex core words, other system documentation
                   9728: 
                   9729: @table @i
                   9730: @item nonstandard words using @code{PAD}:
                   9731: @cindex @code{PAD} use by nonstandard words
                   9732: None.
                   9733: 
                   9734: @item operator's terminal facilities available:
                   9735: @cindex operator's terminal facilities available
                   9736: After processing the command line, Gforth goes into interactive mode,
                   9737: and you can give commands to Gforth interactively. The actual facilities
                   9738: available depend on how you invoke Gforth.
                   9739: 
                   9740: @item program data space available:
                   9741: @cindex program data space available
                   9742: @cindex data space available
                   9743: @code{UNUSED .} gives the remaining dictionary space. The total
                   9744: dictionary space can be specified with the @code{-m} switch
                   9745: (@pxref{Invoking Gforth}) when Gforth starts up.
                   9746: 
                   9747: @item return stack space available:
                   9748: @cindex return stack space available
                   9749: You can compute the total return stack space in cells with
                   9750: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
                   9751: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
                   9752: 
                   9753: @item stack space available:
                   9754: @cindex stack space available
                   9755: You can compute the total data stack space in cells with
                   9756: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
                   9757: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
                   9758: 
                   9759: @item system dictionary space required, in address units:
                   9760: @cindex system dictionary space required, in address units
                   9761: Type @code{here forthstart - .} after startup. At the time of this
                   9762: writing, this gives 80080 (bytes) on a 32-bit system.
                   9763: @end table
                   9764: 
                   9765: 
                   9766: @c =====================================================================
                   9767: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
                   9768: @section The optional Block word set
                   9769: @c =====================================================================
                   9770: @cindex system documentation, block words
                   9771: @cindex block words, system documentation
                   9772: 
                   9773: @menu
                   9774: * block-idef::                  Implementation Defined Options
                   9775: * block-ambcond::               Ambiguous Conditions               
                   9776: * block-other::                 Other System Documentation                 
                   9777: @end menu
                   9778: 
                   9779: 
                   9780: @c ---------------------------------------------------------------------
                   9781: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
                   9782: @subsection Implementation Defined Options
                   9783: @c ---------------------------------------------------------------------
                   9784: @cindex implementation-defined options, block words
                   9785: @cindex block words, implementation-defined options
                   9786: 
                   9787: @table @i
                   9788: @item the format for display by @code{LIST}:
                   9789: @cindex @code{LIST} display format
                   9790: First the screen number is displayed, then 16 lines of 64 characters,
                   9791: each line preceded by the line number.
                   9792: 
                   9793: @item the length of a line affected by @code{\}:
                   9794: @cindex length of a line affected by @code{\}
                   9795: @cindex @code{\}, line length in blocks
                   9796: 64 characters.
                   9797: @end table
                   9798: 
                   9799: 
                   9800: @c ---------------------------------------------------------------------
                   9801: @node block-ambcond, block-other, block-idef, The optional Block word set
                   9802: @subsection Ambiguous conditions
                   9803: @c ---------------------------------------------------------------------
                   9804: @cindex block words, ambiguous conditions
                   9805: @cindex ambiguous conditions, block words
                   9806: 
                   9807: @table @i
                   9808: @item correct block read was not possible:
                   9809: @cindex block read not possible
                   9810: Typically results in a @code{throw} of some OS-derived value (between
                   9811: -512 and -2048). If the blocks file was just not long enough, blanks are
                   9812: supplied for the missing portion.
                   9813: 
                   9814: @item I/O exception in block transfer:
                   9815: @cindex I/O exception in block transfer
                   9816: @cindex block transfer, I/O exception
                   9817: Typically results in a @code{throw} of some OS-derived value (between
                   9818: -512 and -2048).
                   9819: 
                   9820: @item invalid block number:
                   9821: @cindex invalid block number
                   9822: @cindex block number invalid
                   9823: @code{-35 throw} (Invalid block number)
                   9824: 
                   9825: @item a program directly alters the contents of @code{BLK}:
                   9826: @cindex @code{BLK}, altering @code{BLK}
                   9827: The input stream is switched to that other block, at the same
                   9828: position. If the storing to @code{BLK} happens when interpreting
                   9829: non-block input, the system will get quite confused when the block ends.
                   9830: 
                   9831: @item no current block buffer for @code{UPDATE}:
                   9832: @cindex @code{UPDATE}, no current block buffer
                   9833: @code{UPDATE} has no effect.
                   9834: 
                   9835: @end table
                   9836: 
                   9837: @c ---------------------------------------------------------------------
                   9838: @node block-other,  , block-ambcond, The optional Block word set
                   9839: @subsection Other system documentation
                   9840: @c ---------------------------------------------------------------------
                   9841: @cindex other system documentation, block words
                   9842: @cindex block words, other system documentation
                   9843: 
                   9844: @table @i
                   9845: @item any restrictions a multiprogramming system places on the use of buffer addresses:
                   9846: No restrictions (yet).
                   9847: 
                   9848: @item the number of blocks available for source and data:
                   9849: depends on your disk space.
                   9850: 
                   9851: @end table
                   9852: 
                   9853: 
                   9854: @c =====================================================================
                   9855: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
                   9856: @section The optional Double Number word set
                   9857: @c =====================================================================
                   9858: @cindex system documentation, double words
                   9859: @cindex double words, system documentation
                   9860: 
                   9861: @menu
                   9862: * double-ambcond::              Ambiguous Conditions              
                   9863: @end menu
                   9864: 
                   9865: 
                   9866: @c ---------------------------------------------------------------------
                   9867: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
                   9868: @subsection Ambiguous conditions
                   9869: @c ---------------------------------------------------------------------
                   9870: @cindex double words, ambiguous conditions
                   9871: @cindex ambiguous conditions, double words
                   9872: 
                   9873: @table @i
1.29      crook    9874: @item @i{d} outside of range of @i{n} in @code{D>S}:
                   9875: @cindex @code{D>S}, @i{d} out of range of @i{n} 
                   9876: The least significant cell of @i{d} is produced.
1.1       anton    9877: 
                   9878: @end table
                   9879: 
                   9880: 
                   9881: @c =====================================================================
                   9882: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
                   9883: @section The optional Exception word set
                   9884: @c =====================================================================
                   9885: @cindex system documentation, exception words
                   9886: @cindex exception words, system documentation
                   9887: 
                   9888: @menu
                   9889: * exception-idef::              Implementation Defined Options              
                   9890: @end menu
                   9891: 
                   9892: 
                   9893: @c ---------------------------------------------------------------------
                   9894: @node exception-idef,  , The optional Exception word set, The optional Exception word set
                   9895: @subsection Implementation Defined Options
                   9896: @c ---------------------------------------------------------------------
                   9897: @cindex implementation-defined options, exception words
                   9898: @cindex exception words, implementation-defined options
                   9899: 
                   9900: @table @i
                   9901: @item @code{THROW}-codes used in the system:
                   9902: @cindex @code{THROW}-codes used in the system
                   9903: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29      crook    9904: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1       anton    9905: codes -512@minus{}-2047 are used for OS errors (for file and memory
                   9906: allocation operations). The mapping from OS error numbers to throw codes
                   9907: is -512@minus{}@code{errno}. One side effect of this mapping is that
                   9908: undefined OS errors produce a message with a strange number; e.g.,
                   9909: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
                   9910: @end table
                   9911: 
                   9912: @c =====================================================================
                   9913: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
                   9914: @section The optional Facility word set
                   9915: @c =====================================================================
                   9916: @cindex system documentation, facility words
                   9917: @cindex facility words, system documentation
                   9918: 
                   9919: @menu
                   9920: * facility-idef::               Implementation Defined Options               
                   9921: * facility-ambcond::            Ambiguous Conditions            
                   9922: @end menu
                   9923: 
                   9924: 
                   9925: @c ---------------------------------------------------------------------
                   9926: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
                   9927: @subsection Implementation Defined Options
                   9928: @c ---------------------------------------------------------------------
                   9929: @cindex implementation-defined options, facility words
                   9930: @cindex facility words, implementation-defined options
                   9931: 
                   9932: @table @i
                   9933: @item encoding of keyboard events (@code{EKEY}):
                   9934: @cindex keyboard events, encoding in @code{EKEY}
                   9935: @cindex @code{EKEY}, encoding of keyboard events
1.40      anton    9936: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41      anton    9937: Other keys are encoded with the constants @code{k-left}, @code{k-right},
                   9938: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
                   9939: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
                   9940: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40      anton    9941: 
1.1       anton    9942: 
                   9943: @item duration of a system clock tick:
                   9944: @cindex duration of a system clock tick
                   9945: @cindex clock tick duration
                   9946: System dependent. With respect to @code{MS}, the time is specified in
                   9947: microseconds. How well the OS and the hardware implement this, is
                   9948: another question.
                   9949: 
                   9950: @item repeatability to be expected from the execution of @code{MS}:
                   9951: @cindex repeatability to be expected from the execution of @code{MS}
                   9952: @cindex @code{MS}, repeatability to be expected
                   9953: System dependent. On Unix, a lot depends on load. If the system is
                   9954: lightly loaded, and the delay is short enough that Gforth does not get
                   9955: swapped out, the performance should be acceptable. Under MS-DOS and
                   9956: other single-tasking systems, it should be good.
                   9957: 
                   9958: @end table
                   9959: 
                   9960: 
                   9961: @c ---------------------------------------------------------------------
                   9962: @node facility-ambcond,  , facility-idef, The optional Facility word set
                   9963: @subsection Ambiguous conditions
                   9964: @c ---------------------------------------------------------------------
                   9965: @cindex facility words, ambiguous conditions
                   9966: @cindex ambiguous conditions, facility words
                   9967: 
                   9968: @table @i
                   9969: @item @code{AT-XY} can't be performed on user output device:
                   9970: @cindex @code{AT-XY} can't be performed on user output device
                   9971: Largely terminal dependent. No range checks are done on the arguments.
                   9972: No errors are reported. You may see some garbage appearing, you may see
                   9973: simply nothing happen.
                   9974: 
                   9975: @end table
                   9976: 
                   9977: 
                   9978: @c =====================================================================
                   9979: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
                   9980: @section The optional File-Access word set
                   9981: @c =====================================================================
                   9982: @cindex system documentation, file words
                   9983: @cindex file words, system documentation
                   9984: 
                   9985: @menu
                   9986: * file-idef::                   Implementation Defined Options
                   9987: * file-ambcond::                Ambiguous Conditions                
                   9988: @end menu
                   9989: 
                   9990: @c ---------------------------------------------------------------------
                   9991: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
                   9992: @subsection Implementation Defined Options
                   9993: @c ---------------------------------------------------------------------
                   9994: @cindex implementation-defined options, file words
                   9995: @cindex file words, implementation-defined options
                   9996: 
                   9997: @table @i
                   9998: @item file access methods used:
                   9999: @cindex file access methods used
                   10000: @code{R/O}, @code{R/W} and @code{BIN} work as you would
                   10001: expect. @code{W/O} translates into the C file opening mode @code{w} (or
                   10002: @code{wb}): The file is cleared, if it exists, and created, if it does
                   10003: not (with both @code{open-file} and @code{create-file}).  Under Unix
                   10004: @code{create-file} creates a file with 666 permissions modified by your
                   10005: umask.
                   10006: 
                   10007: @item file exceptions:
                   10008: @cindex file exceptions
                   10009: The file words do not raise exceptions (except, perhaps, memory access
                   10010: faults when you pass illegal addresses or file-ids).
                   10011: 
                   10012: @item file line terminator:
                   10013: @cindex file line terminator
                   10014: System-dependent. Gforth uses C's newline character as line
                   10015: terminator. What the actual character code(s) of this are is
                   10016: system-dependent.
                   10017: 
                   10018: @item file name format:
                   10019: @cindex file name format
                   10020: System dependent. Gforth just uses the file name format of your OS.
                   10021: 
                   10022: @item information returned by @code{FILE-STATUS}:
                   10023: @cindex @code{FILE-STATUS}, returned information
                   10024: @code{FILE-STATUS} returns the most powerful file access mode allowed
                   10025: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
                   10026: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
                   10027: along with the returned mode.
                   10028: 
                   10029: @item input file state after an exception when including source:
                   10030: @cindex exception when including source
                   10031: All files that are left via the exception are closed.
                   10032: 
1.29      crook    10033: @item @i{ior} values and meaning:
                   10034: @cindex @i{ior} values and meaning
                   10035: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    10036: intended as throw codes. They typically are in the range
                   10037: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    10038: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    10039: 
                   10040: @item maximum depth of file input nesting:
                   10041: @cindex maximum depth of file input nesting
                   10042: @cindex file input nesting, maximum depth
                   10043: limited by the amount of return stack, locals/TIB stack, and the number
                   10044: of open files available. This should not give you troubles.
                   10045: 
                   10046: @item maximum size of input line:
                   10047: @cindex maximum size of input line
                   10048: @cindex input line size, maximum
                   10049: @code{/line}. Currently 255.
                   10050: 
                   10051: @item methods of mapping block ranges to files:
                   10052: @cindex mapping block ranges to files
                   10053: @cindex files containing blocks
                   10054: @cindex blocks in files
                   10055: By default, blocks are accessed in the file @file{blocks.fb} in the
                   10056: current working directory. The file can be switched with @code{USE}.
                   10057: 
                   10058: @item number of string buffers provided by @code{S"}:
                   10059: @cindex @code{S"}, number of string buffers
                   10060: 1
                   10061: 
                   10062: @item size of string buffer used by @code{S"}:
                   10063: @cindex @code{S"}, size of string buffer
                   10064: @code{/line}. currently 255.
                   10065: 
                   10066: @end table
                   10067: 
                   10068: @c ---------------------------------------------------------------------
                   10069: @node file-ambcond,  , file-idef, The optional File-Access word set
                   10070: @subsection Ambiguous conditions
                   10071: @c ---------------------------------------------------------------------
                   10072: @cindex file words, ambiguous conditions
                   10073: @cindex ambiguous conditions, file words
                   10074: 
                   10075: @table @i
                   10076: @item attempting to position a file outside its boundaries:
                   10077: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
                   10078: @code{REPOSITION-FILE} is performed as usual: Afterwards,
                   10079: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
                   10080: 
                   10081: @item attempting to read from file positions not yet written:
                   10082: @cindex reading from file positions not yet written
                   10083: End-of-file, i.e., zero characters are read and no error is reported.
                   10084: 
1.29      crook    10085: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
                   10086: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
1.1       anton    10087: An appropriate exception may be thrown, but a memory fault or other
                   10088: problem is more probable.
                   10089: 
1.29      crook    10090: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
                   10091: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
                   10092: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
                   10093: The @i{ior} produced by the operation, that discovered the problem, is
1.1       anton    10094: thrown.
                   10095: 
                   10096: @item named file cannot be opened (@code{INCLUDED}):
                   10097: @cindex @code{INCLUDED}, named file cannot be opened
1.29      crook    10098: The @i{ior} produced by @code{open-file} is thrown.
1.1       anton    10099: 
                   10100: @item requesting an unmapped block number:
                   10101: @cindex unmapped block numbers
                   10102: There are no unmapped legal block numbers. On some operating systems,
                   10103: writing a block with a large number may overflow the file system and
                   10104: have an error message as consequence.
                   10105: 
                   10106: @item using @code{source-id} when @code{blk} is non-zero:
                   10107: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
                   10108: @code{source-id} performs its function. Typically it will give the id of
                   10109: the source which loaded the block. (Better ideas?)
                   10110: 
                   10111: @end table
                   10112: 
                   10113: 
                   10114: @c =====================================================================
                   10115: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
                   10116: @section The optional Floating-Point word set
                   10117: @c =====================================================================
                   10118: @cindex system documentation, floating-point words
                   10119: @cindex floating-point words, system documentation
                   10120: 
                   10121: @menu
                   10122: * floating-idef::               Implementation Defined Options
                   10123: * floating-ambcond::            Ambiguous Conditions            
                   10124: @end menu
                   10125: 
                   10126: 
                   10127: @c ---------------------------------------------------------------------
                   10128: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
                   10129: @subsection Implementation Defined Options
                   10130: @c ---------------------------------------------------------------------
                   10131: @cindex implementation-defined options, floating-point words
                   10132: @cindex floating-point words, implementation-defined options
                   10133: 
                   10134: @table @i
                   10135: @item format and range of floating point numbers:
                   10136: @cindex format and range of floating point numbers
                   10137: @cindex floating point numbers, format and range
                   10138: System-dependent; the @code{double} type of C.
                   10139: 
1.29      crook    10140: @item results of @code{REPRESENT} when @i{float} is out of range:
                   10141: @cindex  @code{REPRESENT}, results when @i{float} is out of range
1.1       anton    10142: System dependent; @code{REPRESENT} is implemented using the C library
                   10143: function @code{ecvt()} and inherits its behaviour in this respect.
                   10144: 
                   10145: @item rounding or truncation of floating-point numbers:
                   10146: @cindex rounding of floating-point numbers
                   10147: @cindex truncation of floating-point numbers
                   10148: @cindex floating-point numbers, rounding or truncation
                   10149: System dependent; the rounding behaviour is inherited from the hosting C
                   10150: compiler. IEEE-FP-based (i.e., most) systems by default round to
                   10151: nearest, and break ties by rounding to even (i.e., such that the last
                   10152: bit of the mantissa is 0).
                   10153: 
                   10154: @item size of floating-point stack:
                   10155: @cindex floating-point stack size
                   10156: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
                   10157: the floating-point stack (in floats). You can specify this on startup
                   10158: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
                   10159: 
                   10160: @item width of floating-point stack:
                   10161: @cindex floating-point stack width 
                   10162: @code{1 floats}.
                   10163: 
                   10164: @end table
                   10165: 
                   10166: 
                   10167: @c ---------------------------------------------------------------------
                   10168: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
                   10169: @subsection Ambiguous conditions
                   10170: @c ---------------------------------------------------------------------
                   10171: @cindex floating-point words, ambiguous conditions
                   10172: @cindex ambiguous conditions, floating-point words
                   10173: 
                   10174: @table @i
                   10175: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
                   10176: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
                   10177: System-dependent. Typically results in a @code{-23 THROW} like other
                   10178: alignment violations.
                   10179: 
                   10180: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
                   10181: @cindex @code{f@@} used with an address that is not float aligned
                   10182: @cindex @code{f!} used with an address that is not float aligned
                   10183: System-dependent. Typically results in a @code{-23 THROW} like other
                   10184: alignment violations.
                   10185: 
                   10186: @item floating-point result out of range:
                   10187: @cindex floating-point result out of range
                   10188: System-dependent. Can result in a @code{-55 THROW} (Floating-point
                   10189: unidentified fault), or can produce a special value representing, e.g.,
                   10190: Infinity.
                   10191: 
                   10192: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
                   10193: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
                   10194: System-dependent. Typically results in an alignment fault like other
                   10195: alignment violations.
                   10196: 
1.35      anton    10197: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
                   10198: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1       anton    10199: The floating-point number is converted into decimal nonetheless.
                   10200: 
                   10201: @item Both arguments are equal to zero (@code{FATAN2}):
                   10202: @cindex @code{FATAN2}, both arguments are equal to zero
                   10203: System-dependent. @code{FATAN2} is implemented using the C library
                   10204: function @code{atan2()}.
                   10205: 
1.29      crook    10206: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
                   10207: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
                   10208: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1       anton    10209: because of small errors and the tan will be a very large (or very small)
                   10210: but finite number.
                   10211: 
1.29      crook    10212: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
                   10213: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1       anton    10214: The result is rounded to the nearest float.
                   10215: 
                   10216: @item dividing by zero:
                   10217: @cindex dividing by zero, floating-point
                   10218: @cindex floating-point dividing by zero
                   10219: @cindex floating-point unidentified fault, FP divide-by-zero
                   10220: @code{-55 throw} (Floating-point unidentified fault)
                   10221: 
                   10222: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
                   10223: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
                   10224: System dependent. On IEEE-FP based systems the number is converted into
                   10225: an infinity.
                   10226: 
1.29      crook    10227: @item @i{float}<1 (@code{FACOSH}):
                   10228: @cindex @code{FACOSH}, @i{float}<1
1.1       anton    10229: @cindex floating-point unidentified fault, @code{FACOSH}
                   10230: @code{-55 throw} (Floating-point unidentified fault)
                   10231: 
1.29      crook    10232: @item @i{float}=<-1 (@code{FLNP1}):
                   10233: @cindex @code{FLNP1}, @i{float}=<-1
1.1       anton    10234: @cindex floating-point unidentified fault, @code{FLNP1}
                   10235: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29      crook    10236: negative infinity is typically produced for @i{float}=-1.
1.1       anton    10237: 
1.29      crook    10238: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
                   10239: @cindex @code{FLN}, @i{float}=<0
                   10240: @cindex @code{FLOG}, @i{float}=<0
1.1       anton    10241: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
                   10242: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29      crook    10243: negative infinity is typically produced for @i{float}=0.
1.1       anton    10244: 
1.29      crook    10245: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
                   10246: @cindex @code{FASINH}, @i{float}<0
                   10247: @cindex @code{FSQRT}, @i{float}<0
1.1       anton    10248: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
                   10249: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
                   10250: produces values for these inputs on my Linux box (Bug in the C library?)
                   10251: 
1.29      crook    10252: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
                   10253: @cindex @code{FACOS}, |@i{float}|>1
                   10254: @cindex @code{FASIN}, |@i{float}|>1
                   10255: @cindex @code{FATANH}, |@i{float}|>1
1.1       anton    10256: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
                   10257: @code{-55 throw} (Floating-point unidentified fault).
                   10258: 
1.29      crook    10259: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
                   10260: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1       anton    10261: @cindex floating-point unidentified fault, @code{F>D}
                   10262: @code{-55 throw} (Floating-point unidentified fault).
                   10263: 
                   10264: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
                   10265: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
                   10266: This does not happen.
                   10267: @end table
                   10268: 
                   10269: @c =====================================================================
                   10270: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
                   10271: @section The optional Locals word set
                   10272: @c =====================================================================
                   10273: @cindex system documentation, locals words
                   10274: @cindex locals words, system documentation
                   10275: 
                   10276: @menu
                   10277: * locals-idef::                 Implementation Defined Options                 
                   10278: * locals-ambcond::              Ambiguous Conditions              
                   10279: @end menu
                   10280: 
                   10281: 
                   10282: @c ---------------------------------------------------------------------
                   10283: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
                   10284: @subsection Implementation Defined Options
                   10285: @c ---------------------------------------------------------------------
                   10286: @cindex implementation-defined options, locals words
                   10287: @cindex locals words, implementation-defined options
                   10288: 
                   10289: @table @i
                   10290: @item maximum number of locals in a definition:
                   10291: @cindex maximum number of locals in a definition
                   10292: @cindex locals, maximum number in a definition
                   10293: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
                   10294: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
                   10295: characters. The number of locals in a definition is bounded by the size
                   10296: of locals-buffer, which contains the names of the locals.
                   10297: 
                   10298: @end table
                   10299: 
                   10300: 
                   10301: @c ---------------------------------------------------------------------
                   10302: @node locals-ambcond,  , locals-idef, The optional Locals word set
                   10303: @subsection Ambiguous conditions
                   10304: @c ---------------------------------------------------------------------
                   10305: @cindex locals words, ambiguous conditions
                   10306: @cindex ambiguous conditions, locals words
                   10307: 
                   10308: @table @i
                   10309: @item executing a named local in interpretation state:
                   10310: @cindex local in interpretation state
                   10311: @cindex Interpreting a compile-only word, for a local
                   10312: Locals have no interpretation semantics. If you try to perform the
                   10313: interpretation semantics, you will get a @code{-14 throw} somewhere
                   10314: (Interpreting a compile-only word). If you perform the compilation
                   10315: semantics, the locals access will be compiled (irrespective of state).
                   10316: 
1.29      crook    10317: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1       anton    10318: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
                   10319: @cindex @code{TO} on non-@code{VALUE}s and non-locals
                   10320: @cindex Invalid name argument, @code{TO}
                   10321: @code{-32 throw} (Invalid name argument)
                   10322: 
                   10323: @end table
                   10324: 
                   10325: 
                   10326: @c =====================================================================
                   10327: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
                   10328: @section The optional Memory-Allocation word set
                   10329: @c =====================================================================
                   10330: @cindex system documentation, memory-allocation words
                   10331: @cindex memory-allocation words, system documentation
                   10332: 
                   10333: @menu
                   10334: * memory-idef::                 Implementation Defined Options                 
                   10335: @end menu
                   10336: 
                   10337: 
                   10338: @c ---------------------------------------------------------------------
                   10339: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
                   10340: @subsection Implementation Defined Options
                   10341: @c ---------------------------------------------------------------------
                   10342: @cindex implementation-defined options, memory-allocation words
                   10343: @cindex memory-allocation words, implementation-defined options
                   10344: 
                   10345: @table @i
1.29      crook    10346: @item values and meaning of @i{ior}:
                   10347: @cindex  @i{ior} values and meaning
                   10348: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    10349: intended as throw codes. They typically are in the range
                   10350: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    10351: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    10352: 
                   10353: @end table
                   10354: 
                   10355: @c =====================================================================
                   10356: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
                   10357: @section The optional Programming-Tools word set
                   10358: @c =====================================================================
                   10359: @cindex system documentation, programming-tools words
                   10360: @cindex programming-tools words, system documentation
                   10361: 
                   10362: @menu
                   10363: * programming-idef::            Implementation Defined Options            
                   10364: * programming-ambcond::         Ambiguous Conditions         
                   10365: @end menu
                   10366: 
                   10367: 
                   10368: @c ---------------------------------------------------------------------
                   10369: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
                   10370: @subsection Implementation Defined Options
                   10371: @c ---------------------------------------------------------------------
                   10372: @cindex implementation-defined options, programming-tools words
                   10373: @cindex programming-tools words, implementation-defined options
                   10374: 
                   10375: @table @i
                   10376: @item ending sequence for input following @code{;CODE} and @code{CODE}:
                   10377: @cindex @code{;CODE} ending sequence
                   10378: @cindex @code{CODE} ending sequence
                   10379: @code{END-CODE}
                   10380: 
                   10381: @item manner of processing input following @code{;CODE} and @code{CODE}:
                   10382: @cindex @code{;CODE}, processing input
                   10383: @cindex @code{CODE}, processing input
                   10384: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
                   10385: the input is processed by the text interpreter, (starting) in interpret
                   10386: state.
                   10387: 
                   10388: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
                   10389: @cindex @code{ASSEMBLER}, search order capability
                   10390: The ANS Forth search order word set.
                   10391: 
                   10392: @item source and format of display by @code{SEE}:
                   10393: @cindex @code{SEE}, source and format of output
                   10394: The source for @code{see} is the intermediate code used by the inner
                   10395: interpreter.  The current @code{see} tries to output Forth source code
                   10396: as well as possible.
                   10397: 
                   10398: @end table
                   10399: 
                   10400: @c ---------------------------------------------------------------------
                   10401: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
                   10402: @subsection Ambiguous conditions
                   10403: @c ---------------------------------------------------------------------
                   10404: @cindex programming-tools words, ambiguous conditions
                   10405: @cindex ambiguous conditions, programming-tools words
                   10406: 
                   10407: @table @i
                   10408: 
1.21      crook    10409: @item deleting the compilation word list (@code{FORGET}):
                   10410: @cindex @code{FORGET}, deleting the compilation word list
1.1       anton    10411: Not implemented (yet).
                   10412: 
1.29      crook    10413: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
                   10414: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
                   10415: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1       anton    10416: @cindex control-flow stack underflow
                   10417: This typically results in an @code{abort"} with a descriptive error
                   10418: message (may change into a @code{-22 throw} (Control structure mismatch)
                   10419: in the future). You may also get a memory access error. If you are
                   10420: unlucky, this ambiguous condition is not caught.
                   10421: 
1.29      crook    10422: @item @i{name} can't be found (@code{FORGET}):
                   10423: @cindex @code{FORGET}, @i{name} can't be found
1.1       anton    10424: Not implemented (yet).
                   10425: 
1.29      crook    10426: @item @i{name} not defined via @code{CREATE}:
                   10427: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1       anton    10428: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
                   10429: the execution semantics of the last defined word no matter how it was
                   10430: defined.
                   10431: 
                   10432: @item @code{POSTPONE} applied to @code{[IF]}:
                   10433: @cindex @code{POSTPONE} applied to @code{[IF]}
                   10434: @cindex @code{[IF]} and @code{POSTPONE}
                   10435: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
                   10436: equivalent to @code{[IF]}.
                   10437: 
                   10438: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
                   10439: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
                   10440: Continue in the same state of conditional compilation in the next outer
                   10441: input source. Currently there is no warning to the user about this.
                   10442: 
                   10443: @item removing a needed definition (@code{FORGET}):
                   10444: @cindex @code{FORGET}, removing a needed definition
                   10445: Not implemented (yet).
                   10446: 
                   10447: @end table
                   10448: 
                   10449: 
                   10450: @c =====================================================================
                   10451: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
                   10452: @section The optional Search-Order word set
                   10453: @c =====================================================================
                   10454: @cindex system documentation, search-order words
                   10455: @cindex search-order words, system documentation
                   10456: 
                   10457: @menu
                   10458: * search-idef::                 Implementation Defined Options                 
                   10459: * search-ambcond::              Ambiguous Conditions              
                   10460: @end menu
                   10461: 
                   10462: 
                   10463: @c ---------------------------------------------------------------------
                   10464: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
                   10465: @subsection Implementation Defined Options
                   10466: @c ---------------------------------------------------------------------
                   10467: @cindex implementation-defined options, search-order words
                   10468: @cindex search-order words, implementation-defined options
                   10469: 
                   10470: @table @i
                   10471: @item maximum number of word lists in search order:
                   10472: @cindex maximum number of word lists in search order
                   10473: @cindex search order, maximum depth
                   10474: @code{s" wordlists" environment? drop .}. Currently 16.
                   10475: 
                   10476: @item minimum search order:
                   10477: @cindex minimum search order
                   10478: @cindex search order, minimum
                   10479: @code{root root}.
                   10480: 
                   10481: @end table
                   10482: 
                   10483: @c ---------------------------------------------------------------------
                   10484: @node search-ambcond,  , search-idef, The optional Search-Order word set
                   10485: @subsection Ambiguous conditions
                   10486: @c ---------------------------------------------------------------------
                   10487: @cindex search-order words, ambiguous conditions
                   10488: @cindex ambiguous conditions, search-order words
                   10489: 
                   10490: @table @i
1.21      crook    10491: @item changing the compilation word list (during compilation):
                   10492: @cindex changing the compilation word list (during compilation)
                   10493: @cindex compilation word list, change before definition ends
                   10494: The word is entered into the word list that was the compilation word list
1.1       anton    10495: at the start of the definition. Any changes to the name field (e.g.,
                   10496: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
                   10497: are applied to the latest defined word (as reported by @code{last} or
1.21      crook    10498: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1       anton    10499: 
                   10500: @item search order empty (@code{previous}):
                   10501: @cindex @code{previous}, search order empty
1.26      crook    10502: @cindex vocstack empty, @code{previous}
1.1       anton    10503: @code{abort" Vocstack empty"}.
                   10504: 
                   10505: @item too many word lists in search order (@code{also}):
                   10506: @cindex @code{also}, too many word lists in search order
1.26      crook    10507: @cindex vocstack full, @code{also}
1.1       anton    10508: @code{abort" Vocstack full"}.
                   10509: 
                   10510: @end table
                   10511: 
                   10512: @c ***************************************************************
                   10513: @node Model, Integrating Gforth, ANS conformance, Top
                   10514: @chapter Model
                   10515: 
                   10516: This chapter has yet to be written. It will contain information, on
                   10517: which internal structures you can rely.
                   10518: 
                   10519: @c ***************************************************************
                   10520: @node Integrating Gforth, Emacs and Gforth, Model, Top
                   10521: @chapter Integrating Gforth into C programs
                   10522: 
                   10523: This is not yet implemented.
                   10524: 
                   10525: Several people like to use Forth as scripting language for applications
                   10526: that are otherwise written in C, C++, or some other language.
                   10527: 
                   10528: The Forth system ATLAST provides facilities for embedding it into
                   10529: applications; unfortunately it has several disadvantages: most
                   10530: importantly, it is not based on ANS Forth, and it is apparently dead
                   10531: (i.e., not developed further and not supported). The facilities
1.21      crook    10532: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1       anton    10533: making the switch should not be hard.
                   10534: 
                   10535: We also tried to design the interface such that it can easily be
                   10536: implemented by other Forth systems, so that we may one day arrive at a
                   10537: standardized interface. Such a standard interface would allow you to
                   10538: replace the Forth system without having to rewrite C code.
                   10539: 
                   10540: You embed the Gforth interpreter by linking with the library
                   10541: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
                   10542: global symbols in this library that belong to the interface, have the
                   10543: prefix @code{forth_}. (Global symbols that are used internally have the
                   10544: prefix @code{gforth_}).
                   10545: 
                   10546: You can include the declarations of Forth types and the functions and
                   10547: variables of the interface with @code{#include <forth.h>}.
                   10548: 
                   10549: Types.
                   10550: 
                   10551: Variables.
                   10552: 
                   10553: Data and FP Stack pointer. Area sizes.
                   10554: 
                   10555: functions.
                   10556: 
                   10557: forth_init(imagefile)
                   10558: forth_evaluate(string) exceptions?
                   10559: forth_goto(address) (or forth_execute(xt)?)
                   10560: forth_continue() (a corountining mechanism)
                   10561: 
                   10562: Adding primitives.
                   10563: 
                   10564: No checking.
                   10565: 
                   10566: Signals?
                   10567: 
                   10568: Accessing the Stacks
                   10569: 
1.26      crook    10570: @c ******************************************************************
1.1       anton    10571: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
                   10572: @chapter Emacs and Gforth
                   10573: @cindex Emacs and Gforth
                   10574: 
                   10575: @cindex @file{gforth.el}
                   10576: @cindex @file{forth.el}
                   10577: @cindex Rydqvist, Goran
                   10578: @cindex comment editing commands
                   10579: @cindex @code{\}, editing with Emacs
                   10580: @cindex debug tracer editing commands
                   10581: @cindex @code{~~}, removal with Emacs
                   10582: @cindex Forth mode in Emacs
                   10583: Gforth comes with @file{gforth.el}, an improved version of
                   10584: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26      crook    10585: improvements are:
                   10586: 
                   10587: @itemize @bullet
                   10588: @item
                   10589: A better (but still not perfect) handling of indentation.
                   10590: @item
                   10591: Comment paragraph filling (@kbd{M-q})
                   10592: @item
                   10593: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
                   10594: @item
                   10595: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41      anton    10596: @item
                   10597: Support of the @code{info-lookup} feature for looking up the
                   10598: documentation of a word.
1.26      crook    10599: @end itemize
                   10600: 
                   10601: I left the stuff I do not use alone, even though some of it only makes
                   10602: sense for TILE. To get a description of these features, enter Forth mode
                   10603: and type @kbd{C-h m}.
1.1       anton    10604: 
                   10605: @cindex source location of error or debugging output in Emacs
                   10606: @cindex error output, finding the source location in Emacs
                   10607: @cindex debugging output, finding the source location in Emacs
                   10608: In addition, Gforth supports Emacs quite well: The source code locations
                   10609: given in error messages, debugging output (from @code{~~}) and failed
                   10610: assertion messages are in the right format for Emacs' compilation mode
                   10611: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
                   10612: Manual}) so the source location corresponding to an error or other
                   10613: message is only a few keystrokes away (@kbd{C-x `} for the next error,
                   10614: @kbd{C-c C-c} for the error under the cursor).
                   10615: 
                   10616: @cindex @file{TAGS} file
                   10617: @cindex @file{etags.fs}
                   10618: @cindex viewing the source of a word in Emacs
1.43      anton    10619: @cindex @code{require}, placement in files
                   10620: @cindex @code{include}, placement in files
                   10621: Also, if you @code{require} @file{etags.fs}, a new @file{TAGS} file will
1.26      crook    10622: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1       anton    10623: contains the definitions of all words defined afterwards. You can then
                   10624: find the source for a word using @kbd{M-.}. Note that emacs can use
                   10625: several tags files at the same time (e.g., one for the Gforth sources
                   10626: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
                   10627: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
                   10628: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43      anton    10629: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
                   10630: with @file{etags.fs}, you should avoid putting definitions both before
                   10631: and after @code{require} etc., otherwise you will see the same file
                   10632: visited several times by commands like @code{tags-search}.
1.1       anton    10633: 
1.41      anton    10634: @cindex viewing the documentation of a word in Emacs
                   10635: @cindex context-sensitive help
                   10636: Moreover, for words documented in this manual, you can look up the
                   10637: glossary entry quickly by using @kbd{C-h TAB}
                   10638: (@code{info-lookup-symbol}, see @pxref{Documentation, ,Documentation
                   10639: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
1.42      anton    10640: later and does not work for words containing @code{:}.
1.41      anton    10641: 
                   10642: 
1.1       anton    10643: @cindex @file{.emacs}
                   10644: To get all these benefits, add the following lines to your @file{.emacs}
                   10645: file:
                   10646: 
                   10647: @example
                   10648: (autoload 'forth-mode "gforth.el")
                   10649: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
                   10650: @end example
                   10651: 
1.26      crook    10652: @c ******************************************************************
1.1       anton    10653: @node Image Files, Engine, Emacs and Gforth, Top
                   10654: @chapter Image Files
1.26      crook    10655: @cindex image file
                   10656: @cindex @file{.fi} files
1.1       anton    10657: @cindex precompiled Forth code
                   10658: @cindex dictionary in persistent form
                   10659: @cindex persistent form of dictionary
                   10660: 
                   10661: An image file is a file containing an image of the Forth dictionary,
                   10662: i.e., compiled Forth code and data residing in the dictionary.  By
                   10663: convention, we use the extension @code{.fi} for image files.
                   10664: 
                   10665: @menu
1.18      anton    10666: * Image Licensing Issues::      Distribution terms for images.
                   10667: * Image File Background::       Why have image files?
1.29      crook    10668: * Non-Relocatable Image Files::   don't always work.
1.18      anton    10669: * Data-Relocatable Image Files::  are better.
1.29      crook    10670: * Fully Relocatable Image Files:: better yet.
1.18      anton    10671: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.29      crook    10672: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.18      anton    10673: * Modifying the Startup Sequence::  and turnkey applications.
1.1       anton    10674: @end menu
                   10675: 
1.18      anton    10676: @node Image Licensing Issues, Image File Background, Image Files, Image Files
                   10677: @section Image Licensing Issues
                   10678: @cindex license for images
                   10679: @cindex image license
                   10680: 
                   10681: An image created with @code{gforthmi} (@pxref{gforthmi}) or
                   10682: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
                   10683: original image; i.e., according to copyright law it is a derived work of
                   10684: the original image.
                   10685: 
                   10686: Since Gforth is distributed under the GNU GPL, the newly created image
                   10687: falls under the GNU GPL, too. In particular, this means that if you
                   10688: distribute the image, you have to make all of the sources for the image
                   10689: available, including those you wrote.  For details see @ref{License, ,
                   10690: GNU General Public License (Section 3)}.
                   10691: 
                   10692: If you create an image with @code{cross} (@pxref{cross.fs}), the image
                   10693: contains only code compiled from the sources you gave it; if none of
                   10694: these sources is under the GPL, the terms discussed above do not apply
                   10695: to the image. However, if your image needs an engine (a gforth binary)
                   10696: that is under the GPL, you should make sure that you distribute both in
                   10697: a way that is at most a @emph{mere aggregation}, if you don't want the
                   10698: terms of the GPL to apply to the image.
                   10699: 
                   10700: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1       anton    10701: @section Image File Background
                   10702: @cindex image file background
                   10703: 
                   10704: Our Forth system consists not only of primitives, but also of
                   10705: definitions written in Forth. Since the Forth compiler itself belongs to
                   10706: those definitions, it is not possible to start the system with the
                   10707: primitives and the Forth source alone. Therefore we provide the Forth
1.26      crook    10708: code as an image file in nearly executable form. When Gforth starts up,
                   10709: a C routine loads the image file into memory, optionally relocates the
                   10710: addresses, then sets up the memory (stacks etc.) according to
                   10711: information in the image file, and (finally) starts executing Forth
                   10712: code.
1.1       anton    10713: 
                   10714: The image file variants represent different compromises between the
                   10715: goals of making it easy to generate image files and making them
                   10716: portable.
                   10717: 
                   10718: @cindex relocation at run-time
1.26      crook    10719: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1       anton    10720: run-time. This avoids many of the complications discussed below (image
                   10721: files are data relocatable without further ado), but costs performance
                   10722: (one addition per memory access).
                   10723: 
                   10724: @cindex relocation at load-time
1.26      crook    10725: By contrast, the Gforth loader performs relocation at image load time. The
                   10726: loader also has to replace tokens that represent primitive calls with the
1.1       anton    10727: appropriate code-field addresses (or code addresses in the case of
                   10728: direct threading).
                   10729: 
                   10730: There are three kinds of image files, with different degrees of
                   10731: relocatability: non-relocatable, data-relocatable, and fully relocatable
                   10732: image files.
                   10733: 
                   10734: @cindex image file loader
                   10735: @cindex relocating loader
                   10736: @cindex loader for image files
                   10737: These image file variants have several restrictions in common; they are
                   10738: caused by the design of the image file loader:
                   10739: 
                   10740: @itemize @bullet
                   10741: @item
                   10742: There is only one segment; in particular, this means, that an image file
                   10743: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26      crook    10744: them). The contents of the stacks are not represented, either.
1.1       anton    10745: 
                   10746: @item
                   10747: The only kinds of relocation supported are: adding the same offset to
                   10748: all cells that represent data addresses; and replacing special tokens
                   10749: with code addresses or with pieces of machine code.
                   10750: 
                   10751: If any complex computations involving addresses are performed, the
                   10752: results cannot be represented in the image file. Several applications that
                   10753: use such computations come to mind:
                   10754: @itemize @minus
                   10755: @item
                   10756: Hashing addresses (or data structures which contain addresses) for table
                   10757: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
                   10758: purpose, you will have no problem, because the hash tables are
                   10759: recomputed automatically when the system is started. If you use your own
                   10760: hash tables, you will have to do something similar.
                   10761: 
                   10762: @item
                   10763: There's a cute implementation of doubly-linked lists that uses
                   10764: @code{XOR}ed addresses. You could represent such lists as singly-linked
                   10765: in the image file, and restore the doubly-linked representation on
                   10766: startup.@footnote{In my opinion, though, you should think thrice before
                   10767: using a doubly-linked list (whatever implementation).}
                   10768: 
                   10769: @item
                   10770: The code addresses of run-time routines like @code{docol:} cannot be
                   10771: represented in the image file (because their tokens would be replaced by
                   10772: machine code in direct threaded implementations). As a workaround,
                   10773: compute these addresses at run-time with @code{>code-address} from the
                   10774: executions tokens of appropriate words (see the definitions of
                   10775: @code{docol:} and friends in @file{kernel.fs}).
                   10776: 
                   10777: @item
                   10778: On many architectures addresses are represented in machine code in some
                   10779: shifted or mangled form. You cannot put @code{CODE} words that contain
                   10780: absolute addresses in this form in a relocatable image file. Workarounds
                   10781: are representing the address in some relative form (e.g., relative to
                   10782: the CFA, which is present in some register), or loading the address from
                   10783: a place where it is stored in a non-mangled form.
                   10784: @end itemize
                   10785: @end itemize
                   10786: 
                   10787: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
                   10788: @section Non-Relocatable Image Files
                   10789: @cindex non-relocatable image files
1.26      crook    10790: @cindex image file, non-relocatable
1.1       anton    10791: 
                   10792: These files are simple memory dumps of the dictionary. They are specific
                   10793: to the executable (i.e., @file{gforth} file) they were created
                   10794: with. What's worse, they are specific to the place on which the
                   10795: dictionary resided when the image was created. Now, there is no
                   10796: guarantee that the dictionary will reside at the same place the next
                   10797: time you start Gforth, so there's no guarantee that a non-relocatable
                   10798: image will work the next time (Gforth will complain instead of crashing,
                   10799: though).
                   10800: 
                   10801: You can create a non-relocatable image file with
                   10802: 
1.44    ! crook    10803: 
1.1       anton    10804: doc-savesystem
                   10805: 
1.44    ! crook    10806: 
1.1       anton    10807: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
                   10808: @section Data-Relocatable Image Files
                   10809: @cindex data-relocatable image files
1.26      crook    10810: @cindex image file, data-relocatable
1.1       anton    10811: 
                   10812: These files contain relocatable data addresses, but fixed code addresses
                   10813: (instead of tokens). They are specific to the executable (i.e.,
                   10814: @file{gforth} file) they were created with. For direct threading on some
                   10815: architectures (e.g., the i386), data-relocatable images do not work. You
                   10816: get a data-relocatable image, if you use @file{gforthmi} with a
                   10817: Gforth binary that is not doubly indirect threaded (@pxref{Fully
                   10818: Relocatable Image Files}).
                   10819: 
                   10820: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
                   10821: @section Fully Relocatable Image Files
                   10822: @cindex fully relocatable image files
1.26      crook    10823: @cindex image file, fully relocatable
1.1       anton    10824: 
                   10825: @cindex @file{kern*.fi}, relocatability
                   10826: @cindex @file{gforth.fi}, relocatability
                   10827: These image files have relocatable data addresses, and tokens for code
                   10828: addresses. They can be used with different binaries (e.g., with and
                   10829: without debugging) on the same machine, and even across machines with
                   10830: the same data formats (byte order, cell size, floating point
                   10831: format). However, they are usually specific to the version of Gforth
                   10832: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
                   10833: are fully relocatable.
                   10834: 
                   10835: There are two ways to create a fully relocatable image file:
                   10836: 
                   10837: @menu
1.29      crook    10838: * gforthmi::                    The normal way
1.1       anton    10839: * cross.fs::                    The hard way
                   10840: @end menu
                   10841: 
                   10842: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
                   10843: @subsection @file{gforthmi}
                   10844: @cindex @file{comp-i.fs}
                   10845: @cindex @file{gforthmi}
                   10846: 
                   10847: You will usually use @file{gforthmi}. If you want to create an
1.29      crook    10848: image @i{file} that contains everything you would load by invoking
                   10849: Gforth with @code{gforth @i{options}}, you simply say:
1.1       anton    10850: @example
1.29      crook    10851: gforthmi @i{file} @i{options}
1.1       anton    10852: @end example
                   10853: 
                   10854: E.g., if you want to create an image @file{asm.fi} that has the file
                   10855: @file{asm.fs} loaded in addition to the usual stuff, you could do it
                   10856: like this:
                   10857: 
                   10858: @example
                   10859: gforthmi asm.fi asm.fs
                   10860: @end example
                   10861: 
1.27      crook    10862: @file{gforthmi} is implemented as a sh script and works like this: It
                   10863: produces two non-relocatable images for different addresses and then
                   10864: compares them. Its output reflects this: first you see the output (if
                   10865: any) of the two Gforth invocations that produce the nonrelocatable image
                   10866: files, then you see the output of the comparing program: It displays the
                   10867: offset used for data addresses and the offset used for code addresses;
1.1       anton    10868: moreover, for each cell that cannot be represented correctly in the
1.44    ! crook    10869: image files, it displays a line like this:
1.1       anton    10870: 
                   10871: @example
                   10872:      78DC         BFFFFA50         BFFFFA40
                   10873: @end example
                   10874: 
                   10875: This means that at offset $78dc from @code{forthstart}, one input image
                   10876: contains $bffffa50, and the other contains $bffffa40. Since these cells
                   10877: cannot be represented correctly in the output image, you should examine
                   10878: these places in the dictionary and verify that these cells are dead
                   10879: (i.e., not read before they are written).
1.39      anton    10880: 
                   10881: @cindex --application, @code{gforthmi} option
                   10882: If you insert the option @code{--application} in front of the image file
                   10883: name, you will get an image that uses the @code{--appl-image} option
                   10884: instead of the @code{--image-file} option (@pxref{Invoking
                   10885: Gforth}). When you execute such an image on Unix (by typing the image
                   10886: name as command), the Gforth engine will pass all options to the image
                   10887: instead of trying to interpret them as engine options.
1.1       anton    10888: 
1.27      crook    10889: If you type @file{gforthmi} with no arguments, it prints some usage
                   10890: instructions.
                   10891: 
1.1       anton    10892: @cindex @code{savesystem} during @file{gforthmi}
                   10893: @cindex @code{bye} during @file{gforthmi}
                   10894: @cindex doubly indirect threaded code
1.44    ! crook    10895: @cindex environment variables
        !          10896: @cindex @code{GFORTHD} -- environment variable
        !          10897: @cindex @code{GFORTH} -- environment variable
1.1       anton    10898: @cindex @code{gforth-ditc}
1.29      crook    10899: There are a few wrinkles: After processing the passed @i{options}, the
1.1       anton    10900: words @code{savesystem} and @code{bye} must be visible. A special doubly
                   10901: indirect threaded version of the @file{gforth} executable is used for
                   10902: creating the nonrelocatable images; you can pass the exact filename of
                   10903: this executable through the environment variable @code{GFORTHD}
                   10904: (default: @file{gforth-ditc}); if you pass a version that is not doubly
                   10905: indirect threaded, you will not get a fully relocatable image, but a
1.27      crook    10906: data-relocatable image (because there is no code address offset). The
                   10907: normal @file{gforth} executable is used for creating the relocatable
                   10908: image; you can pass the exact filename of this executable through the
                   10909: environment variable @code{GFORTH}.
1.1       anton    10910: 
                   10911: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
                   10912: @subsection @file{cross.fs}
                   10913: @cindex @file{cross.fs}
                   10914: @cindex cross-compiler
                   10915: @cindex metacompiler
                   10916: 
                   10917: You can also use @code{cross}, a batch compiler that accepts a Forth-like
                   10918: programming language. This @code{cross} language has to be documented
                   10919: yet.
                   10920: 
                   10921: @cindex target compiler
                   10922: @code{cross} also allows you to create image files for machines with
                   10923: different data sizes and data formats than the one used for generating
                   10924: the image file. You can also use it to create an application image that
                   10925: does not contain a Forth compiler. These features are bought with
                   10926: restrictions and inconveniences in programming. E.g., addresses have to
                   10927: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
                   10928: order to make the code relocatable.
                   10929: 
                   10930: 
                   10931: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
                   10932: @section Stack and Dictionary Sizes
                   10933: @cindex image file, stack and dictionary sizes
                   10934: @cindex dictionary size default
                   10935: @cindex stack size default
                   10936: 
                   10937: If you invoke Gforth with a command line flag for the size
                   10938: (@pxref{Invoking Gforth}), the size you specify is stored in the
                   10939: dictionary. If you save the dictionary with @code{savesystem} or create
                   10940: an image with @file{gforthmi}, this size will become the default
                   10941: for the resulting image file. E.g., the following will create a
1.21      crook    10942: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1       anton    10943: 
                   10944: @example
                   10945: gforthmi gforth.fi -m 1M
                   10946: @end example
                   10947: 
                   10948: In other words, if you want to set the default size for the dictionary
                   10949: and the stacks of an image, just invoke @file{gforthmi} with the
                   10950: appropriate options when creating the image.
                   10951: 
                   10952: @cindex stack size, cache-friendly
                   10953: Note: For cache-friendly behaviour (i.e., good performance), you should
                   10954: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
                   10955: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
                   10956: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
                   10957: 
                   10958: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
                   10959: @section Running Image Files
                   10960: @cindex running image files
                   10961: @cindex invoking image files
                   10962: @cindex image file invocation
                   10963: 
                   10964: @cindex -i, invoke image file
                   10965: @cindex --image file, invoke image file
1.29      crook    10966: You can invoke Gforth with an image file @i{image} instead of the
1.1       anton    10967: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
                   10968: @example
1.29      crook    10969: gforth -i @i{image}
1.1       anton    10970: @end example
                   10971: 
                   10972: @cindex executable image file
1.26      crook    10973: @cindex image file, executable
1.1       anton    10974: If your operating system supports starting scripts with a line of the
                   10975: form @code{#! ...}, you just have to type the image file name to start
                   10976: Gforth with this image file (note that the file extension @code{.fi} is
1.29      crook    10977: just a convention). I.e., to run Gforth with the image file @i{image},
                   10978: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27      crook    10979: This works because every @code{.fi} file starts with a line of this
                   10980: format:
                   10981: 
                   10982: @example
                   10983: #! /usr/local/bin/gforth-0.4.0 -i
                   10984: @end example
                   10985: 
                   10986: The file and pathname for the Gforth engine specified on this line is
                   10987: the specific Gforth executable that it was built against; i.e. the value
                   10988: of the environment variable @code{GFORTH} at the time that
                   10989: @file{gforthmi} was executed.
1.1       anton    10990: 
1.27      crook    10991: You can make use of the same shell capability to make a Forth source
                   10992: file into an executable. For example, if you place this text in a file:
1.26      crook    10993: 
                   10994: @example
                   10995: #! /usr/local/bin/gforth
                   10996: 
                   10997: ." Hello, world" CR
                   10998: bye
                   10999: @end example
                   11000: 
                   11001: @noindent
1.27      crook    11002: and then make the file executable (chmod +x in Unix), you can run it
1.26      crook    11003: directly from the command line. The sequence @code{#!} is used in two
                   11004: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29      crook    11005: system@footnote{The Unix kernel actually recognises two types of files:
                   11006: executable files and files of data, where the data is processed by an
                   11007: interpreter that is specified on the ``interpreter line'' -- the first
                   11008: line of the file, starting with the sequence #!. There may be a small
                   11009: limit (e.g., 32) on the number of characters that may be specified on
                   11010: the interpreter line.} secondly it is treated as a comment character by
                   11011: Gforth. Because of the second usage, a space is required between
                   11012: @code{#!} and the path to the executable.
1.27      crook    11013: 
                   11014: The disadvantage of this latter technique, compared with using
                   11015: @file{gforthmi}, is that it is slower; the Forth source code is compiled
                   11016: on-the-fly, each time the program is invoked.
                   11017: 
1.26      crook    11018: 
1.1       anton    11019: doc-#!
                   11020: 
1.44    ! crook    11021: 
1.1       anton    11022: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
                   11023: @section Modifying the Startup Sequence
                   11024: @cindex startup sequence for image file
                   11025: @cindex image file initialization sequence
                   11026: @cindex initialization sequence of image file
                   11027: 
                   11028: You can add your own initialization to the startup sequence through the
1.26      crook    11029: deferred word @code{'cold}. @code{'cold} is invoked just before the
                   11030: image-specific command line processing (by default, loading files and
                   11031: evaluating (@code{-e}) strings) starts.
1.1       anton    11032: 
                   11033: A sequence for adding your initialization usually looks like this:
                   11034: 
                   11035: @example
                   11036: :noname
                   11037:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
                   11038:     ... \ your stuff
                   11039: ; IS 'cold
                   11040: @end example
                   11041: 
                   11042: @cindex turnkey image files
1.26      crook    11043: @cindex image file, turnkey applications
1.1       anton    11044: You can make a turnkey image by letting @code{'cold} execute a word
                   11045: (your turnkey application) that never returns; instead, it exits Gforth
                   11046: via @code{bye} or @code{throw}.
                   11047: 
                   11048: @cindex command-line arguments, access
                   11049: @cindex arguments on the command line, access
                   11050: You can access the (image-specific) command-line arguments through the
1.26      crook    11051: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1       anton    11052: access to @code{argv}.
                   11053: 
1.26      crook    11054: If @code{'cold} exits normally, Gforth processes the command-line
                   11055: arguments as files to be loaded and strings to be evaluated.  Therefore,
                   11056: @code{'cold} should remove the arguments it has used in this case.
                   11057: 
1.44    ! crook    11058: 
        !          11059: 
1.26      crook    11060: doc-'cold
1.1       anton    11061: doc-argc
                   11062: doc-argv
                   11063: doc-arg
                   11064: 
                   11065: 
1.44    ! crook    11066: 
1.1       anton    11067: @c ******************************************************************
1.13      pazsan   11068: @node Engine, Binding to System Library, Image Files, Top
1.1       anton    11069: @chapter Engine
                   11070: @cindex engine
                   11071: @cindex virtual machine
                   11072: 
1.26      crook    11073: Reading this chapter is not necessary for programming with Gforth. It
1.1       anton    11074: may be helpful for finding your way in the Gforth sources.
                   11075: 
                   11076: The ideas in this section have also been published in the papers
                   11077: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
                   11078: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
                   11079: Ertl, presented at EuroForth '93; the latter is available at
                   11080: @*@url{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
                   11081: 
                   11082: @menu
                   11083: * Portability::                 
                   11084: * Threading::                   
                   11085: * Primitives::                  
                   11086: * Performance::                 
                   11087: @end menu
                   11088: 
                   11089: @node Portability, Threading, Engine, Engine
                   11090: @section Portability
                   11091: @cindex engine portability
                   11092: 
1.26      crook    11093: An important goal of the Gforth Project is availability across a wide
                   11094: range of personal machines. fig-Forth, and, to a lesser extent, F83,
                   11095: achieved this goal by manually coding the engine in assembly language
                   11096: for several then-popular processors. This approach is very
                   11097: labor-intensive and the results are short-lived due to progress in
                   11098: computer architecture.
1.1       anton    11099: 
                   11100: @cindex C, using C for the engine
                   11101: Others have avoided this problem by coding in C, e.g., Mitch Bradley
                   11102: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
                   11103: particularly popular for UNIX-based Forths due to the large variety of
                   11104: architectures of UNIX machines. Unfortunately an implementation in C
                   11105: does not mix well with the goals of efficiency and with using
                   11106: traditional techniques: Indirect or direct threading cannot be expressed
                   11107: in C, and switch threading, the fastest technique available in C, is
                   11108: significantly slower. Another problem with C is that it is very
                   11109: cumbersome to express double integer arithmetic.
                   11110: 
                   11111: @cindex GNU C for the engine
                   11112: @cindex long long
                   11113: Fortunately, there is a portable language that does not have these
                   11114: limitations: GNU C, the version of C processed by the GNU C compiler
                   11115: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
                   11116: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
                   11117: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
                   11118: threading possible, its @code{long long} type (@pxref{Long Long, ,
                   11119: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
                   11120: double numbers@footnote{Unfortunately, long longs are not implemented
                   11121: properly on all machines (e.g., on alpha-osf1, long longs are only 64
                   11122: bits, the same size as longs (and pointers), but they should be twice as
1.4       anton    11123: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1       anton    11124: C Manual}). So, we had to implement doubles in C after all. Still, on
                   11125: most machines we can use long longs and achieve better performance than
                   11126: with the emulation package.}. GNU C is available for free on all
                   11127: important (and many unimportant) UNIX machines, VMS, 80386s running
                   11128: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
                   11129: on all these machines.
                   11130: 
                   11131: Writing in a portable language has the reputation of producing code that
                   11132: is slower than assembly. For our Forth engine we repeatedly looked at
                   11133: the code produced by the compiler and eliminated most compiler-induced
                   11134: inefficiencies by appropriate changes in the source code.
                   11135: 
                   11136: @cindex explicit register declarations
                   11137: @cindex --enable-force-reg, configuration flag
                   11138: @cindex -DFORCE_REG
                   11139: However, register allocation cannot be portably influenced by the
                   11140: programmer, leading to some inefficiencies on register-starved
                   11141: machines. We use explicit register declarations (@pxref{Explicit Reg
                   11142: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
                   11143: improve the speed on some machines. They are turned on by using the
                   11144: configuration flag @code{--enable-force-reg} (@code{gcc} switch
                   11145: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
                   11146: machine, but also on the compiler version: On some machines some
                   11147: compiler versions produce incorrect code when certain explicit register
                   11148: declarations are used. So by default @code{-DFORCE_REG} is not used.
                   11149: 
                   11150: @node Threading, Primitives, Portability, Engine
                   11151: @section Threading
                   11152: @cindex inner interpreter implementation
                   11153: @cindex threaded code implementation
                   11154: 
                   11155: @cindex labels as values
                   11156: GNU C's labels as values extension (available since @code{gcc-2.0},
                   11157: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29      crook    11158: makes it possible to take the address of @i{label} by writing
                   11159: @code{&&@i{label}}.  This address can then be used in a statement like
                   11160: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1       anton    11161: @code{goto x}.
                   11162: 
1.26      crook    11163: @cindex @code{NEXT}, indirect threaded
1.1       anton    11164: @cindex indirect threaded inner interpreter
                   11165: @cindex inner interpreter, indirect threaded
1.26      crook    11166: With this feature an indirect threaded @code{NEXT} looks like:
1.1       anton    11167: @example
                   11168: cfa = *ip++;
                   11169: ca = *cfa;
                   11170: goto *ca;
                   11171: @end example
                   11172: @cindex instruction pointer
                   11173: For those unfamiliar with the names: @code{ip} is the Forth instruction
                   11174: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
                   11175: execution token and points to the code field of the next word to be
                   11176: executed; The @code{ca} (code address) fetched from there points to some
                   11177: executable code, e.g., a primitive or the colon definition handler
                   11178: @code{docol}.
                   11179: 
1.26      crook    11180: @cindex @code{NEXT}, direct threaded
1.1       anton    11181: @cindex direct threaded inner interpreter
                   11182: @cindex inner interpreter, direct threaded
                   11183: Direct threading is even simpler:
                   11184: @example
                   11185: ca = *ip++;
                   11186: goto *ca;
                   11187: @end example
                   11188: 
                   11189: Of course we have packaged the whole thing neatly in macros called
1.26      crook    11190: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1       anton    11191: 
                   11192: @menu
                   11193: * Scheduling::                  
                   11194: * Direct or Indirect Threaded?::  
                   11195: * DOES>::                       
                   11196: @end menu
                   11197: 
                   11198: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
                   11199: @subsection Scheduling
                   11200: @cindex inner interpreter optimization
                   11201: 
                   11202: There is a little complication: Pipelined and superscalar processors,
                   11203: i.e., RISC and some modern CISC machines can process independent
                   11204: instructions while waiting for the results of an instruction. The
                   11205: compiler usually reorders (schedules) the instructions in a way that
                   11206: achieves good usage of these delay slots. However, on our first tries
                   11207: the compiler did not do well on scheduling primitives. E.g., for
                   11208: @code{+} implemented as
                   11209: @example
                   11210: n=sp[0]+sp[1];
                   11211: sp++;
                   11212: sp[0]=n;
                   11213: NEXT;
                   11214: @end example
1.26      crook    11215: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
1.1       anton    11216: scheduling. After a little thought the problem becomes clear: The
1.21      crook    11217: compiler cannot know that @code{sp} and @code{ip} point to different
                   11218: addresses (and the version of @code{gcc} we used would not know it even
                   11219: if it was possible), so it could not move the load of the cfa above the
                   11220: store to the TOS. Indeed the pointers could be the same, if code on or
                   11221: very near the top of stack were executed. In the interest of speed we
                   11222: chose to forbid this probably unused ``feature'' and helped the compiler
1.26      crook    11223: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
1.21      crook    11224: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1       anton    11225: @example
                   11226: n=sp[0]+sp[1];
                   11227: sp++;
                   11228: NEXT_P1;
                   11229: sp[0]=n;
                   11230: NEXT_P2;
                   11231: @end example
                   11232: This can be scheduled optimally by the compiler.
                   11233: 
                   11234: This division can be turned off with the switch @code{-DCISC_NEXT}. This
                   11235: switch is on by default on machines that do not profit from scheduling
                   11236: (e.g., the 80386), in order to preserve registers.
                   11237: 
                   11238: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
                   11239: @subsection Direct or Indirect Threaded?
                   11240: @cindex threading, direct or indirect?
                   11241: 
                   11242: @cindex -DDIRECT_THREADED
                   11243: Both! After packaging the nasty details in macro definitions we
                   11244: realized that we could switch between direct and indirect threading by
                   11245: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
                   11246: defining a few machine-specific macros for the direct-threading case.
                   11247: On the Forth level we also offer access words that hide the
                   11248: differences between the threading methods (@pxref{Threading Words}).
                   11249: 
                   11250: Indirect threading is implemented completely machine-independently.
                   11251: Direct threading needs routines for creating jumps to the executable
1.21      crook    11252: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
                   11253: machine-dependent, but they do not amount to many source lines. Therefore,
                   11254: even porting direct threading to a new machine requires little effort.
1.1       anton    11255: 
                   11256: @cindex --enable-indirect-threaded, configuration flag
                   11257: @cindex --enable-direct-threaded, configuration flag
                   11258: The default threading method is machine-dependent. You can enforce a
                   11259: specific threading method when building Gforth with the configuration
                   11260: flag @code{--enable-direct-threaded} or
                   11261: @code{--enable-indirect-threaded}. Note that direct threading is not
                   11262: supported on all machines.
                   11263: 
                   11264: @node DOES>,  , Direct or Indirect Threaded?, Threading
                   11265: @subsection DOES>
                   11266: @cindex @code{DOES>} implementation
                   11267: 
1.26      crook    11268: @cindex @code{dodoes} routine
                   11269: @cindex @code{DOES>}-code
1.1       anton    11270: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
                   11271: the chunk of code executed by every word defined by a
                   11272: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
                   11273: the Forth code to be executed, i.e. the code after the
1.26      crook    11274: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1       anton    11275: 
1.21      crook    11276: In fig-Forth the code field points directly to the @code{dodoes} and the
1.26      crook    11277: @code{DOES>}code address is stored in the cell after the code address (i.e. at
1.29      crook    11278: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1       anton    11279: the Forth-79 and all later standards, because in fig-Forth this address
                   11280: lies in the body (which is illegal in these standards). However, by
                   11281: making the code field larger for all words this solution becomes legal
                   11282: again. We use this approach for the indirect threaded version and for
                   11283: direct threading on some machines. Leaving a cell unused in most words
                   11284: is a bit wasteful, but on the machines we are targeting this is hardly a
                   11285: problem. The other reason for having a code field size of two cells is
                   11286: to avoid having different image files for direct and indirect threaded
                   11287: systems (direct threaded systems require two-cell code fields on many
                   11288: machines).
                   11289: 
1.26      crook    11290: @cindex @code{DOES>}-handler
1.1       anton    11291: The other approach is that the code field points or jumps to the cell
1.26      crook    11292: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
                   11293: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
                   11294: @code{DOES>}-code address by computing the code address, i.e., the address of
1.1       anton    11295: the jump to dodoes, and add the length of that jump field. A variant of
                   11296: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
                   11297: return address (which can be found in the return register on RISCs) is
1.26      crook    11298: the @code{DOES>}-code address. Since the two cells available in the code field
1.1       anton    11299: are used up by the jump to the code address in direct threading on many
                   11300: architectures, we use this approach for direct threading on these
                   11301: architectures. We did not want to add another cell to the code field.
                   11302: 
                   11303: @node Primitives, Performance, Threading, Engine
                   11304: @section Primitives
                   11305: @cindex primitives, implementation
                   11306: @cindex virtual machine instructions, implementation
                   11307: 
                   11308: @menu
                   11309: * Automatic Generation::        
                   11310: * TOS Optimization::            
                   11311: * Produced code::               
                   11312: @end menu
                   11313: 
                   11314: @node Automatic Generation, TOS Optimization, Primitives, Primitives
                   11315: @subsection Automatic Generation
                   11316: @cindex primitives, automatic generation
                   11317: 
                   11318: @cindex @file{prims2x.fs}
                   11319: Since the primitives are implemented in a portable language, there is no
                   11320: longer any need to minimize the number of primitives. On the contrary,
                   11321: having many primitives has an advantage: speed. In order to reduce the
                   11322: number of errors in primitives and to make programming them easier, we
                   11323: provide a tool, the primitive generator (@file{prims2x.fs}), that
                   11324: automatically generates most (and sometimes all) of the C code for a
                   11325: primitive from the stack effect notation.  The source for a primitive
                   11326: has the following form:
                   11327: 
                   11328: @cindex primitive source format
                   11329: @format
1.29      crook    11330: @i{Forth-name} @i{stack-effect}        @i{category}    [@i{pronounc.}]
                   11331: [@code{""}@i{glossary entry}@code{""}]
                   11332: @i{C code}
1.1       anton    11333: [@code{:}
1.29      crook    11334: @i{Forth code}]
1.1       anton    11335: @end format
                   11336: 
                   11337: The items in brackets are optional. The category and glossary fields
                   11338: are there for generating the documentation, the Forth code is there
                   11339: for manual implementations on machines without GNU C. E.g., the source
                   11340: for the primitive @code{+} is:
                   11341: @example
                   11342: +    n1 n2 -- n    core    plus
                   11343: n = n1+n2;
                   11344: @end example
                   11345: 
                   11346: This looks like a specification, but in fact @code{n = n1+n2} is C
                   11347: code. Our primitive generation tool extracts a lot of information from
                   11348: the stack effect notations@footnote{We use a one-stack notation, even
                   11349: though we have separate data and floating-point stacks; The separate
                   11350: notation can be generated easily from the unified notation.}: The number
                   11351: of items popped from and pushed on the stack, their type, and by what
                   11352: name they are referred to in the C code. It then generates a C code
                   11353: prelude and postlude for each primitive. The final C code for @code{+}
                   11354: looks like this:
                   11355: 
                   11356: @example
                   11357: I_plus:        /* + ( n1 n2 -- n ) */  /* label, stack effect */
                   11358: /*  */                          /* documentation */
                   11359: @{
                   11360: DEF_CA                          /* definition of variable ca (indirect threading) */
                   11361: Cell n1;                        /* definitions of variables */
                   11362: Cell n2;
                   11363: Cell n;
                   11364: n1 = (Cell) sp[1];              /* input */
                   11365: n2 = (Cell) TOS;
                   11366: sp += 1;                        /* stack adjustment */
                   11367: NAME("+")                       /* debugging output (with -DDEBUG) */
                   11368: @{
                   11369: n = n1+n2;                      /* C code taken from the source */
                   11370: @}
                   11371: NEXT_P1;                        /* NEXT part 1 */
                   11372: TOS = (Cell)n;                  /* output */
                   11373: NEXT_P2;                        /* NEXT part 2 */
                   11374: @}
                   11375: @end example
                   11376: 
                   11377: This looks long and inefficient, but the GNU C compiler optimizes quite
                   11378: well and produces optimal code for @code{+} on, e.g., the R3000 and the
                   11379: HP RISC machines: Defining the @code{n}s does not produce any code, and
                   11380: using them as intermediate storage also adds no cost.
                   11381: 
1.26      crook    11382: There are also other optimizations that are not illustrated by this
                   11383: example: assignments between simple variables are usually for free (copy
1.1       anton    11384: propagation). If one of the stack items is not used by the primitive
                   11385: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
                   11386: (dead code elimination). On the other hand, there are some things that
                   11387: the compiler does not do, therefore they are performed by
                   11388: @file{prims2x.fs}: The compiler does not optimize code away that stores
                   11389: a stack item to the place where it just came from (e.g., @code{over}).
                   11390: 
                   11391: While programming a primitive is usually easy, there are a few cases
                   11392: where the programmer has to take the actions of the generator into
                   11393: account, most notably @code{?dup}, but also words that do not (always)
1.26      crook    11394: fall through to @code{NEXT}.
1.1       anton    11395: 
                   11396: @node TOS Optimization, Produced code, Automatic Generation, Primitives
                   11397: @subsection TOS Optimization
                   11398: @cindex TOS optimization for primitives
                   11399: @cindex primitives, keeping the TOS in a register
                   11400: 
                   11401: An important optimization for stack machine emulators, e.g., Forth
                   11402: engines, is keeping  one or more of the top stack items in
1.29      crook    11403: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
                   11404: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1       anton    11405: @itemize @bullet
                   11406: @item
1.29      crook    11407: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1       anton    11408: due to fewer loads from and stores to the stack.
1.29      crook    11409: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
                   11410: @i{y<n}, due to additional moves between registers.
1.1       anton    11411: @end itemize
                   11412: 
                   11413: @cindex -DUSE_TOS
                   11414: @cindex -DUSE_NO_TOS
                   11415: In particular, keeping one item in a register is never a disadvantage,
                   11416: if there are enough registers. Keeping two items in registers is a
                   11417: disadvantage for frequent words like @code{?branch}, constants,
                   11418: variables, literals and @code{i}. Therefore our generator only produces
                   11419: code that keeps zero or one items in registers. The generated C code
                   11420: covers both cases; the selection between these alternatives is made at
                   11421: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
                   11422: code for @code{+} is just a simple variable name in the one-item case,
                   11423: otherwise it is a macro that expands into @code{sp[0]}. Note that the
                   11424: GNU C compiler tries to keep simple variables like @code{TOS} in
                   11425: registers, and it usually succeeds, if there are enough registers.
                   11426: 
                   11427: @cindex -DUSE_FTOS
                   11428: @cindex -DUSE_NO_FTOS
                   11429: The primitive generator performs the TOS optimization for the
                   11430: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
                   11431: operations the benefit of this optimization is even larger:
                   11432: floating-point operations take quite long on most processors, but can be
                   11433: performed in parallel with other operations as long as their results are
                   11434: not used. If the FP-TOS is kept in a register, this works. If
                   11435: it is kept on the stack, i.e., in memory, the store into memory has to
                   11436: wait for the result of the floating-point operation, lengthening the
                   11437: execution time of the primitive considerably.
                   11438: 
                   11439: The TOS optimization makes the automatic generation of primitives a
                   11440: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
                   11441: @code{TOS} is not sufficient. There are some special cases to
                   11442: consider:
                   11443: @itemize @bullet
                   11444: @item In the case of @code{dup ( w -- w w )} the generator must not
                   11445: eliminate the store to the original location of the item on the stack,
                   11446: if the TOS optimization is turned on.
                   11447: @item Primitives with stack effects of the form @code{--}
1.29      crook    11448: @i{out1}...@i{outy} must store the TOS to the stack at the start.
                   11449: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1       anton    11450: must load the TOS from the stack at the end. But for the null stack
                   11451: effect @code{--} no stores or loads should be generated.
                   11452: @end itemize
                   11453: 
                   11454: @node Produced code,  , TOS Optimization, Primitives
                   11455: @subsection Produced code
                   11456: @cindex primitives, assembly code listing
                   11457: 
                   11458: @cindex @file{engine.s}
                   11459: To see what assembly code is produced for the primitives on your machine
                   11460: with your compiler and your flag settings, type @code{make engine.s} and
                   11461: look at the resulting file @file{engine.s}.
                   11462: 
                   11463: @node  Performance,  , Primitives, Engine
                   11464: @section Performance
                   11465: @cindex performance of some Forth interpreters
                   11466: @cindex engine performance
                   11467: @cindex benchmarking Forth systems
                   11468: @cindex Gforth performance
                   11469: 
                   11470: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
                   11471: impossible to write a significantly faster engine.
                   11472: 
                   11473: On register-starved machines like the 386 architecture processors
                   11474: improvements are possible, because @code{gcc} does not utilize the
                   11475: registers as well as a human, even with explicit register declarations;
                   11476: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
                   11477: and hand-tuned it for the 486; this system is 1.19 times faster on the
                   11478: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40      anton    11479: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
                   11480: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
                   11481: registers fit in real registers (and we can even afford to use the TOS
                   11482: optimization), resulting in a speedup of 1.14 on the sieve over the
                   11483: earlier results.
1.1       anton    11484: 
                   11485: @cindex Win32Forth performance
                   11486: @cindex NT Forth performance
                   11487: @cindex eforth performance
                   11488: @cindex ThisForth performance
                   11489: @cindex PFE performance
                   11490: @cindex TILE performance
1.40      anton    11491: The potential advantage of assembly language implementations
1.1       anton    11492: is not necessarily realized in complete Forth systems: We compared
1.40      anton    11493: Gforth-0.4.9 (direct threaded, compiled with @code{gcc-2.95.1} and
1.1       anton    11494: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
                   11495: 1994) and Eforth (with and without peephole (aka pinhole) optimization
                   11496: of the threaded code); all these systems were written in assembly
                   11497: language. We also compared Gforth with three systems written in C:
                   11498: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
                   11499: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21      crook    11500: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
                   11501: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1       anton    11502: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
                   11503: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
                   11504: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
                   11505: 486DX2/66 with similar memory performance under Windows NT. Marcel
                   11506: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
                   11507: added the peephole optimizer, ran the benchmarks and reported the
                   11508: results.
1.40      anton    11509: 
1.1       anton    11510: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
                   11511: matrix multiplication come from the Stanford integer benchmarks and have
                   11512: been translated into Forth by Martin Fraeman; we used the versions
                   11513: included in the TILE Forth package, but with bigger data set sizes; and
                   11514: a recursive Fibonacci number computation for benchmarking calling
                   11515: performance. The following table shows the time taken for the benchmarks
                   11516: scaled by the time taken by Gforth (in other words, it shows the speedup
                   11517: factor that Gforth achieved over the other systems).
                   11518: 
                   11519: @example
1.40      anton    11520: relative      Win32-    NT       eforth       This-      
1.1       anton    11521:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
1.40      anton    11522: sieve     1.00  1.58  1.30   1.58  0.97  1.80  3.63  9.79
                   11523: bubble    1.00  1.55  1.67   1.75  1.04  1.78        4.59
                   11524: matmul    1.00  1.67  1.53   1.66  0.84  1.79        4.63
                   11525: fib       1.00  1.75  1.53   1.40  0.99  1.99  3.43  4.93
1.1       anton    11526: @end example
                   11527: 
1.26      crook    11528: You may be quite surprised by the good performance of Gforth when
                   11529: compared with systems written in assembly language. One important reason
                   11530: for the disappointing performance of these other systems is probably
                   11531: that they are not written optimally for the 486 (e.g., they use the
                   11532: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
                   11533: but costly method for relocating the Forth image: like @code{cforth}, it
                   11534: computes the actual addresses at run time, resulting in two address
                   11535: computations per @code{NEXT} (@pxref{Image File Background}).
                   11536: 
1.40      anton    11537: Only Eforth with the peephole optimizer performs comparable to
                   11538: Gforth. The speedups achieved with peephole optimization of threaded
                   11539: code are quite remarkable. Adding a peephole optimizer to Gforth should
                   11540: cause similar speedups.
1.1       anton    11541: 
                   11542: The speedup of Gforth over PFE, ThisForth and TILE can be easily
                   11543: explained with the self-imposed restriction of the latter systems to
                   11544: standard C, which makes efficient threading impossible (however, the
1.4       anton    11545: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1       anton    11546: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
                   11547: Moreover, current C compilers have a hard time optimizing other aspects
                   11548: of the ThisForth and the TILE source.
                   11549: 
1.26      crook    11550: The performance of Gforth on 386 architecture processors varies widely
                   11551: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
                   11552: allocate any of the virtual machine registers into real machine
                   11553: registers by itself and would not work correctly with explicit register
1.40      anton    11554: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
1.26      crook    11555: the Sieve) than the one measured above.
1.1       anton    11556: 
1.26      crook    11557: Note that there have been several releases of Win32Forth since the
                   11558: release presented here, so the results presented above may have little
1.40      anton    11559: predictive value for the performance of Win32Forth today (results for
                   11560: the current release on an i486DX2/66 are welcome).
1.1       anton    11561: 
                   11562: @cindex @file{Benchres}
                   11563: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
                   11564: Maierhofer (presented at EuroForth '95), an indirect threaded version of
                   11565: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
1.40      anton    11566: version of Gforth is slower on a 486 than the direct threaded version
                   11567: used here. The paper available at
1.1       anton    11568: @*@url{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
                   11569: it also contains numbers for some native code systems. You can find a
                   11570: newer version of these measurements at
                   11571: @url{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
                   11572: find numbers for Gforth on various machines in @file{Benchres}.
                   11573: 
1.26      crook    11574: @c ******************************************************************
1.13      pazsan   11575: @node Binding to System Library, Cross Compiler, Engine, Top
1.14      pazsan   11576: @chapter Binding to System Library
1.13      pazsan   11577: 
                   11578: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14      pazsan   11579: @chapter Cross Compiler
1.13      pazsan   11580: 
                   11581: Cross Compiler
                   11582: 
                   11583: @menu
                   11584: * Using the Cross Compiler::
                   11585: * How the Cross Compiler Works::
                   11586: @end menu
                   11587: 
1.21      crook    11588: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14      pazsan   11589: @section Using the Cross Compiler
1.13      pazsan   11590: 
1.21      crook    11591: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14      pazsan   11592: @section How the Cross Compiler Works
1.13      pazsan   11593: 
                   11594: @node Bugs, Origin, Cross Compiler, Top
1.21      crook    11595: @appendix Bugs
1.1       anton    11596: @cindex bug reporting
                   11597: 
1.21      crook    11598: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1       anton    11599: 
                   11600: If you find a bug, please send a bug report to
1.33      anton    11601: @email{bug-gforth@@gnu.org}. A bug report should include this
1.21      crook    11602: information:
                   11603: 
                   11604: @itemize @bullet
                   11605: @item
                   11606: The Gforth version used (it is announced at the start of an
                   11607: interactive Gforth session).
                   11608: @item
                   11609: The machine and operating system (on Unix
                   11610: systems @code{uname -a} will report this information).
                   11611: @item
                   11612: The installation options (send the file @file{config.status}).
                   11613: @item
                   11614: A complete list of changes (if any) you (or your installer) have made to the
                   11615: Gforth sources.
                   11616: @item
                   11617: A program (or a sequence of keyboard commands) that reproduces the bug.
                   11618: @item
                   11619: A description of what you think constitutes the buggy behaviour.
                   11620: @end itemize
1.1       anton    11621: 
                   11622: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
                   11623: to Report Bugs, gcc.info, GNU C Manual}.
                   11624: 
                   11625: 
1.21      crook    11626: @node Origin, Forth-related information, Bugs, Top
                   11627: @appendix Authors and Ancestors of Gforth
1.1       anton    11628: 
                   11629: @section Authors and Contributors
                   11630: @cindex authors of Gforth
                   11631: @cindex contributors to Gforth
                   11632: 
                   11633: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
                   11634: Ertl. The third major author was Jens Wilke.  Lennart Benschop (who was
                   11635: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
                   11636: with their continuous feedback. Lennart Benshop contributed
                   11637: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
                   11638: support for calling C libraries. Helpful comments also came from Paul
                   11639: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.12      anton    11640: Wavrik, Barrie Stott, Marc de Groot, and Jorge Acerada. Since the
                   11641: release of Gforth-0.2.1 there were also helpful comments from many
                   11642: others; thank you all, sorry for not listing you here (but digging
1.23      crook    11643: through my mailbox to extract your names is on my to-do list). Since the
                   11644: release of Gforth-0.4.0 Neal Crook worked on the manual.
1.1       anton    11645: 
                   11646: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
                   11647: and autoconf, among others), and to the creators of the Internet: Gforth
1.21      crook    11648: was developed across the Internet, and its authors did not meet
1.20      pazsan   11649: physically for the first 4 years of development.
1.1       anton    11650: 
                   11651: @section Pedigree
1.26      crook    11652: @cindex pedigree of Gforth
1.1       anton    11653: 
1.20      pazsan   11654: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1       anton    11655: Dirk Zoller) will cross-fertilize each other. Of course, a significant
                   11656: part of the design of Gforth was prescribed by ANS Forth.
                   11657: 
1.20      pazsan   11658: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1       anton    11659: 32 bit native code version of VolksForth for the Atari ST, written
                   11660: mostly by Dietrich Weineck.
                   11661: 
                   11662: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
                   11663: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
                   11664: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
                   11665: 
                   11666: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
                   11667: Forth-83 standard. !! Pedigree? When?
                   11668: 
                   11669: A team led by Bill Ragsdale implemented fig-Forth on many processors in
                   11670: 1979. Robert Selzer and Bill Ragsdale developed the original
                   11671: implementation of fig-Forth for the 6502 based on microForth.
                   11672: 
                   11673: The principal architect of microForth was Dean Sanderson. microForth was
                   11674: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
                   11675: the 1802, and subsequently implemented on the 8080, the 6800 and the
                   11676: Z80.
                   11677: 
                   11678: All earlier Forth systems were custom-made, usually by Charles Moore,
                   11679: who discovered (as he puts it) Forth during the late 60s. The first full
                   11680: Forth existed in 1971.
                   11681: 
                   11682: A part of the information in this section comes from @cite{The Evolution
                   11683: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
                   11684: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
                   11685: Notices 28(3), 1993.  You can find more historical and genealogical
                   11686: information about Forth there.
                   11687: 
1.21      crook    11688: @node Forth-related information, Word Index, Origin, Top
                   11689: @appendix Other Forth-related information
                   11690: @cindex Forth-related information
                   11691: 
                   11692: @menu
                   11693: * Internet resources::
                   11694: * Books::
                   11695: * The Forth Interest Group::
                   11696: * Conferences::
                   11697: @end menu
                   11698: 
                   11699: 
                   11700: @node Internet resources, Books, Forth-related information, Forth-related information
                   11701: @section Internet resources
1.26      crook    11702: @cindex internet resources
1.21      crook    11703: 
                   11704: @cindex comp.lang.forth
                   11705: @cindex frequently asked questions
                   11706: There is an active newsgroup (comp.lang.forth) discussing Forth and
                   11707: Forth-related issues. A frequently-asked-questions (FAQ) list
                   11708: is posted to the newsgroup regulary, and archived at these sites:
                   11709: 
                   11710: @itemize @bullet
                   11711: @item
                   11712: @url{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
                   11713: @item
                   11714: @url{ftp://ftp.forth.org/pub/Forth/FAQ/}
                   11715: @end itemize
                   11716: 
                   11717: The FAQ list should be considered mandatory reading before posting to
                   11718: the newsgroup.
                   11719: 
                   11720: Here are some other web sites holding Forth-related material:
                   11721: 
                   11722: @itemize @bullet
                   11723: @item
                   11724: @url{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
                   11725: @item
                   11726: @url{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
                   11727: @item
                   11728: @url{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
                   11729: @item
                   11730: @url{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
                   11731: Research page, including links to the Journal of Forth Application and
                   11732: Research (JFAR) and a searchable Forth bibliography.
                   11733: @end itemize
                   11734: 
                   11735: 
                   11736: @node Books, The Forth Interest Group, Internet resources, Forth-related information
                   11737: @section Books
1.26      crook    11738: @cindex books on Forth
1.21      crook    11739: 
                   11740: As the Standard is relatively new, there are not many books out yet. It
                   11741: is not recommended to learn Forth by using Gforth and a book that is not
                   11742: written for ANS Forth, as you will not know your mistakes from the
                   11743: deviations of the book. However, books based on the Forth-83 standard
                   11744: should be ok, because ANS Forth is primarily an extension of Forth-83.
1.44    ! crook    11745: Refer to the Forth FAQ for details of Forth-related books.
1.21      crook    11746: 
                   11747: @cindex standard document for ANS Forth
                   11748: @cindex ANS Forth document
                   11749: The definite reference if you want to write ANS Forth programs is, of
1.26      crook    11750: course, the ANS Forth document. It is available in printed form from the
1.21      crook    11751: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
                   11752: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
                   11753: $200. You can also get it from Global Engineering Documents (Tel.: USA
                   11754: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
                   11755: 
                   11756: @cite{dpANS6}, the last draft of the standard, which was then submitted
                   11757: to ANSI for publication is available electronically and for free in some
                   11758: MS Word format, and it has been converted to HTML
1.44    ! crook    11759: (@url{http://www.taygeta.com/forth/dpans.html}; this HTML version also
        !          11760: includes the answers to Requests for Interpretation (RFIs). Some
        !          11761: pointers to these versions can be found through
        !          11762: @*@url{http://www.complang.tuwien.ac.at/projects/forth.html}.
        !          11763: 
1.21      crook    11764: 
                   11765: @node The Forth Interest Group, Conferences, Books, Forth-related information
                   11766: @section The Forth Interest Group
                   11767: @cindex Forth interest group (FIG)
                   11768: 
                   11769: The Forth Interest Group (FIG) is a world-wide, non-profit,
1.26      crook    11770: member-supported organisation. It publishes a regular magazine,
                   11771: @var{FORTH Dimensions}, and offers other benefits of membership. You can
                   11772: contact the FIG through their office email address:
                   11773: @email{office@@forth.org} or by visiting their web site at
                   11774: @url{http://www.forth.org/}. This web site also includes links to FIG
                   11775: chapters in other countries and American cities
1.21      crook    11776: (@url{http://www.forth.org/chapters.html}).
                   11777: 
                   11778: @node Conferences, , The Forth Interest Group, Forth-related information
                   11779: @section Conferences
                   11780: @cindex Conferences
                   11781: 
                   11782: There are several regular conferences related to Forth. They are all
1.26      crook    11783: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
1.44    ! crook    11784: newsgroup:
1.21      crook    11785: 
                   11786: @itemize @bullet
                   11787: @item
                   11788: FORML -- the Forth modification laboratory convenes every year near
                   11789: Monterey, California.
                   11790: @item
                   11791: The Rochester Forth Conference -- an annual conference traditionally
                   11792: held in Rochester, New York.
                   11793: @item
                   11794: EuroForth -- this European conference takes place annually.
                   11795: @end itemize
                   11796: 
                   11797: 
1.41      anton    11798: @node Word Index, Name Index, Forth-related information, Top
1.1       anton    11799: @unnumbered Word Index
                   11800: 
1.26      crook    11801: This index is a list of Forth words that have ``glossary'' entries
                   11802: within this manual. Each word is listed with its stack effect and
                   11803: wordset.
1.1       anton    11804: 
                   11805: @printindex fn
                   11806: 
1.41      anton    11807: @node Name Index, Concept Index, Word Index, Top
                   11808: @unnumbered Name Index
                   11809: 
                   11810: This index is a list of Forth words that have ``glossary'' entries
                   11811: within this manual.
                   11812: 
                   11813: @printindex ky
                   11814: 
                   11815: @node Concept Index,  , Name Index, Top
1.1       anton    11816: @unnumbered Concept and Word Index
                   11817: 
1.26      crook    11818: Not all entries listed in this index are present verbatim in the
                   11819: text. This index also duplicates, in abbreviated form, all of the words
                   11820: listed in the Word Index (only the names are listed for the words here).
1.1       anton    11821: 
                   11822: @printindex cp
                   11823: 
                   11824: @contents
                   11825: @bye
                   11826: 

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