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

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.29      crook      98: @center This manual is permanently under construction and was last updated on 04-May-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
                    152: * Concept Index::               A menu covering many topics
1.12      anton     153: 
1.24      anton     154: @detailmenu --- The Detailed Node Listing ---
1.12      anton     155: 
1.26      crook     156: Goals of Gforth
                    157: 
                    158: * Gforth Extensions Sinful?::
                    159: 
1.29      crook     160: Gforth Environment
                    161: 
1.32      anton     162: * Invoking Gforth::             Getting in
                    163: * Leaving Gforth::              Getting out
                    164: * Command-line editing::        
1.29      crook     165: * Upper and lower case::
1.32      anton     166: * Environment variables::       ..that affect how Gforth starts up
                    167: * Gforth Files::                What gets installed and where
1.29      crook     168: 
1.24      anton     169: An Introduction to ANS Forth
                    170: 
                    171: * Introducing the Text Interpreter::
                    172: * Stacks and Postfix notation::
                    173: * Your first definition::
                    174: * How does that work?::
                    175: * Forth is written in Forth::
                    176: * Review - elements of a Forth system::
1.29      crook     177: * Where to go next::
1.24      anton     178: * Exercises::
                    179: 
1.12      anton     180: Forth Words
                    181: 
                    182: * Notation::                    
1.21      crook     183: * Comments::
                    184: * Boolean Flags::
1.12      anton     185: * Arithmetic::                  
                    186: * Stack Manipulation::          
                    187: * Memory::                      
                    188: * Control Structures::          
                    189: * Defining Words::              
1.21      crook     190: * The Text Interpreter::
1.12      anton     191: * Tokens for Words::            
1.21      crook     192: * Word Lists::                   
                    193: * Environmental Queries::
1.12      anton     194: * Files::                       
                    195: * Blocks::                      
                    196: * Other I/O::                   
                    197: * Programming Tools::           
                    198: * Assembler and Code Words::    
                    199: * Threading Words::             
1.26      crook     200: * Locals::                      
                    201: * Structures::                  
                    202: * Object-oriented Forth::       
1.21      crook     203: * Passing Commands to the OS::
                    204: * Miscellaneous Words::
1.12      anton     205: 
                    206: Arithmetic
                    207: 
                    208: * Single precision::            
                    209: * Bitwise operations::          
1.21      crook     210: * Double precision::            Double-cell integer arithmetic
                    211: * Numeric comparison::
1.32      anton     212: * Mixed precision::             Operations with single and double-cell integers
1.12      anton     213: * Floating Point::              
                    214: 
                    215: Stack Manipulation
                    216: 
                    217: * Data stack::                  
                    218: * Floating point stack::        
                    219: * Return stack::                
                    220: * Locals stack::                
                    221: * Stack pointer manipulation::  
                    222: 
                    223: Memory
                    224: 
1.32      anton     225: * Memory model::                
                    226: * Dictionary allocation::       
                    227: * Heap Allocation::             
                    228: * Memory Access::               
                    229: * Address arithmetic::          
                    230: * Memory Blocks::               
1.12      anton     231: 
                    232: Control Structures
                    233: 
1.32      anton     234: * Selection::                   IF.. ELSE.. ENDIF
                    235: * Simple Loops::                BEGIN..
                    236: * Counted Loops::               DO
                    237: * Arbitrary control structures::
                    238: * Calls and returns::
1.12      anton     239: * Exception Handling::          
                    240: 
                    241: Defining Words
                    242: 
1.32      anton     243: * Simple Defining Words::       Variables, values and constants
                    244: * Colon Definitions::
                    245: * User-defined Defining Words::
                    246: * Supplying names::
                    247: * Interpretation and Compilation Semantics::
1.12      anton     248: 
1.21      crook     249: The Text Interpreter
                    250: 
1.29      crook     251: * Input Sources::
1.21      crook     252: * Number Conversion::
                    253: * Interpret/Compile states::
                    254: * Literals::
                    255: * Interpreter Directives::
                    256: 
1.26      crook     257: Word Lists
                    258: 
                    259: * Why use word lists?::
                    260: * Word list examples::
                    261: 
                    262: Files
                    263: 
                    264: * Forth source files::
                    265: * General files::         
                    266: * Search Paths::                 
                    267: * Forth Search Paths::    
                    268: * General Search Paths::        
                    269: 
                    270: Other I/O
                    271: 
1.32      anton     272: * Simple numeric output::       Predefined formats
                    273: * Formatted numeric output::    Formatted (pictured) output
                    274: * String Formats::              How Forth stores strings in memory
                    275: * Displaying characters and strings:: Other stuff
                    276: * Input::                       Input
1.26      crook     277: 
                    278: Programming Tools
                    279: 
                    280: * Debugging::                   Simple and quick.
                    281: * Assertions::                  Making your programs self-checking.
                    282: * Singlestep Debugger::                Executing your program word by word.
                    283: 
                    284: Locals
                    285: 
                    286: * Gforth locals::               
                    287: * ANS Forth locals::            
                    288: 
                    289: Gforth locals
                    290: 
                    291: * Where are locals visible by name?::  
                    292: * How long do locals live?::    
                    293: * Programming Style::           
                    294: * Implementation::              
                    295: 
1.12      anton     296: Structures
                    297: 
                    298: * Why explicit structure support?::  
                    299: * Structure Usage::             
                    300: * Structure Naming Convention::  
                    301: * Structure Implementation::    
                    302: * Structure Glossary::          
                    303: 
                    304: Object-oriented Forth
                    305: 
1.24      anton     306: * Why object-oriented programming?::
                    307: * Object-Oriented Terminology::
                    308: * Objects::
                    309: * OOF::
                    310: * Mini-OOF::
1.23      crook     311: * Comparison with other object models::  
1.12      anton     312: 
1.24      anton     313: The @file{objects.fs} model
1.12      anton     314: 
                    315: * Properties of the Objects model::  
                    316: * Basic Objects Usage::         
1.23      crook     317: * The Objects base class::            
1.12      anton     318: * Creating objects::            
                    319: * Object-Oriented Programming Style::  
                    320: * Class Binding::               
                    321: * Method conveniences::         
                    322: * Classes and Scoping::         
                    323: * Object Interfaces::           
                    324: * Objects Implementation::      
                    325: * Objects Glossary::            
                    326: 
1.24      anton     327: The @file{oof.fs} model
1.12      anton     328: 
                    329: * Properties of the OOF model::
                    330: * Basic OOF Usage::
1.23      crook     331: * The OOF base class::
1.12      anton     332: * Class Declaration::
                    333: * Class Implementation::
                    334: 
1.24      anton     335: The @file{mini-oof.fs} model
1.23      crook     336: 
                    337: * Basic Mini-OOF Usage::
                    338: * Mini-OOF Example::
                    339: * Mini-OOF Implementation::
                    340: 
1.12      anton     341: Tools
                    342: 
                    343: * ANS Report::                  Report the words used, sorted by wordset.
                    344: 
                    345: ANS conformance
                    346: 
                    347: * The Core Words::              
                    348: * The optional Block word set::  
                    349: * The optional Double Number word set::  
                    350: * The optional Exception word set::  
                    351: * The optional Facility word set::  
                    352: * The optional File-Access word set::  
                    353: * The optional Floating-Point word set::  
                    354: * The optional Locals word set::  
                    355: * The optional Memory-Allocation word set::  
                    356: * The optional Programming-Tools word set::  
                    357: * The optional Search-Order word set::  
                    358: 
                    359: The Core Words
                    360: 
                    361: * core-idef::                   Implementation Defined Options                   
                    362: * core-ambcond::                Ambiguous Conditions                
                    363: * core-other::                  Other System Documentation                  
                    364: 
                    365: The optional Block word set
                    366: 
                    367: * block-idef::                  Implementation Defined Options
                    368: * block-ambcond::               Ambiguous Conditions               
                    369: * block-other::                 Other System Documentation                 
                    370: 
                    371: The optional Double Number word set
                    372: 
                    373: * double-ambcond::              Ambiguous Conditions              
                    374: 
                    375: The optional Exception word set
                    376: 
                    377: * exception-idef::              Implementation Defined Options              
                    378: 
                    379: The optional Facility word set
                    380: 
                    381: * facility-idef::               Implementation Defined Options               
                    382: * facility-ambcond::            Ambiguous Conditions            
                    383: 
                    384: The optional File-Access word set
                    385: 
                    386: * file-idef::                   Implementation Defined Options
                    387: * file-ambcond::                Ambiguous Conditions                
                    388: 
                    389: The optional Floating-Point word set
                    390: 
                    391: * floating-idef::               Implementation Defined Options
                    392: * floating-ambcond::            Ambiguous Conditions            
                    393: 
                    394: The optional Locals word set
                    395: 
                    396: * locals-idef::                 Implementation Defined Options                 
                    397: * locals-ambcond::              Ambiguous Conditions              
                    398: 
                    399: The optional Memory-Allocation word set
                    400: 
                    401: * memory-idef::                 Implementation Defined Options                 
                    402: 
                    403: The optional Programming-Tools word set
                    404: 
                    405: * programming-idef::            Implementation Defined Options            
                    406: * programming-ambcond::         Ambiguous Conditions         
                    407: 
                    408: The optional Search-Order word set
                    409: 
                    410: * search-idef::                 Implementation Defined Options                 
                    411: * search-ambcond::              Ambiguous Conditions              
                    412: 
                    413: Image Files
                    414: 
1.24      anton     415: * Image Licensing Issues::      Distribution terms for images.
                    416: * Image File Background::       Why have image files?
1.32      anton     417: * Non-Relocatable Image Files::   don't always work.
1.24      anton     418: * Data-Relocatable Image Files::  are better.
1.32      anton     419: * Fully Relocatable Image Files:: better yet.
1.24      anton     420: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.32      anton     421: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.24      anton     422: * Modifying the Startup Sequence::  and turnkey applications.
1.12      anton     423: 
                    424: Fully Relocatable Image Files
                    425: 
1.27      crook     426: * gforthmi::                    The normal way
1.12      anton     427: * cross.fs::                    The hard way
                    428: 
                    429: Engine
                    430: 
                    431: * Portability::                 
                    432: * Threading::                   
                    433: * Primitives::                  
                    434: * Performance::                 
                    435: 
                    436: Threading
                    437: 
                    438: * Scheduling::                  
                    439: * Direct or Indirect Threaded?::  
                    440: * DOES>::                       
                    441: 
                    442: Primitives
                    443: 
                    444: * Automatic Generation::        
                    445: * TOS Optimization::            
                    446: * Produced code::               
1.13      pazsan    447: 
                    448: Cross Compiler
                    449: 
                    450: * Using the Cross Compiler::
                    451: * How the Cross Compiler Works::
                    452: 
1.24      anton     453: Other Forth-related information
1.21      crook     454: 
                    455: * Internet resources::
                    456: * Books::
                    457: * The Forth Interest Group::
                    458: * Conferences::
                    459: 
1.24      anton     460: @end detailmenu
1.1       anton     461: @end menu
                    462: 
1.26      crook     463: @node License, Goals, Top, Top
1.1       anton     464: @unnumbered GNU GENERAL PUBLIC LICENSE
                    465: @center Version 2, June 1991
                    466: 
                    467: @display
                    468: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
                    469: 675 Mass Ave, Cambridge, MA 02139, USA
                    470: 
                    471: Everyone is permitted to copy and distribute verbatim copies
                    472: of this license document, but changing it is not allowed.
                    473: @end display
                    474: 
                    475: @unnumberedsec Preamble
                    476: 
                    477:   The licenses for most software are designed to take away your
                    478: freedom to share and change it.  By contrast, the GNU General Public
                    479: License is intended to guarantee your freedom to share and change free
                    480: software---to make sure the software is free for all its users.  This
                    481: General Public License applies to most of the Free Software
                    482: Foundation's software and to any other program whose authors commit to
                    483: using it.  (Some other Free Software Foundation software is covered by
                    484: the GNU Library General Public License instead.)  You can apply it to
                    485: your programs, too.
                    486: 
                    487:   When we speak of free software, we are referring to freedom, not
                    488: price.  Our General Public Licenses are designed to make sure that you
                    489: have the freedom to distribute copies of free software (and charge for
                    490: this service if you wish), that you receive source code or can get it
                    491: if you want it, that you can change the software or use pieces of it
                    492: in new free programs; and that you know you can do these things.
                    493: 
                    494:   To protect your rights, we need to make restrictions that forbid
                    495: anyone to deny you these rights or to ask you to surrender the rights.
                    496: These restrictions translate to certain responsibilities for you if you
                    497: distribute copies of the software, or if you modify it.
                    498: 
                    499:   For example, if you distribute copies of such a program, whether
                    500: gratis or for a fee, you must give the recipients all the rights that
                    501: you have.  You must make sure that they, too, receive or can get the
                    502: source code.  And you must show them these terms so they know their
                    503: rights.
                    504: 
                    505:   We protect your rights with two steps: (1) copyright the software, and
                    506: (2) offer you this license which gives you legal permission to copy,
                    507: distribute and/or modify the software.
                    508: 
                    509:   Also, for each author's protection and ours, we want to make certain
                    510: that everyone understands that there is no warranty for this free
                    511: software.  If the software is modified by someone else and passed on, we
                    512: want its recipients to know that what they have is not the original, so
                    513: that any problems introduced by others will not reflect on the original
                    514: authors' reputations.
                    515: 
                    516:   Finally, any free program is threatened constantly by software
                    517: patents.  We wish to avoid the danger that redistributors of a free
                    518: program will individually obtain patent licenses, in effect making the
                    519: program proprietary.  To prevent this, we have made it clear that any
                    520: patent must be licensed for everyone's free use or not licensed at all.
                    521: 
                    522:   The precise terms and conditions for copying, distribution and
                    523: modification follow.
                    524: 
                    525: @iftex
                    526: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
                    527: @end iftex
                    528: @ifinfo
                    529: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
                    530: @end ifinfo
                    531: 
                    532: @enumerate 0
                    533: @item
                    534: This License applies to any program or other work which contains
                    535: a notice placed by the copyright holder saying it may be distributed
                    536: under the terms of this General Public License.  The ``Program'', below,
                    537: refers to any such program or work, and a ``work based on the Program''
                    538: means either the Program or any derivative work under copyright law:
                    539: that is to say, a work containing the Program or a portion of it,
                    540: either verbatim or with modifications and/or translated into another
                    541: language.  (Hereinafter, translation is included without limitation in
                    542: the term ``modification''.)  Each licensee is addressed as ``you''.
                    543: 
                    544: Activities other than copying, distribution and modification are not
                    545: covered by this License; they are outside its scope.  The act of
                    546: running the Program is not restricted, and the output from the Program
                    547: is covered only if its contents constitute a work based on the
                    548: Program (independent of having been made by running the Program).
                    549: Whether that is true depends on what the Program does.
                    550: 
                    551: @item
                    552: You may copy and distribute verbatim copies of the Program's
                    553: source code as you receive it, in any medium, provided that you
                    554: conspicuously and appropriately publish on each copy an appropriate
                    555: copyright notice and disclaimer of warranty; keep intact all the
                    556: notices that refer to this License and to the absence of any warranty;
                    557: and give any other recipients of the Program a copy of this License
                    558: along with the Program.
                    559: 
                    560: You may charge a fee for the physical act of transferring a copy, and
                    561: you may at your option offer warranty protection in exchange for a fee.
                    562: 
                    563: @item
                    564: You may modify your copy or copies of the Program or any portion
                    565: of it, thus forming a work based on the Program, and copy and
                    566: distribute such modifications or work under the terms of Section 1
                    567: above, provided that you also meet all of these conditions:
                    568: 
                    569: @enumerate a
                    570: @item
                    571: You must cause the modified files to carry prominent notices
                    572: stating that you changed the files and the date of any change.
                    573: 
                    574: @item
                    575: You must cause any work that you distribute or publish, that in
                    576: whole or in part contains or is derived from the Program or any
                    577: part thereof, to be licensed as a whole at no charge to all third
                    578: parties under the terms of this License.
                    579: 
                    580: @item
                    581: If the modified program normally reads commands interactively
                    582: when run, you must cause it, when started running for such
                    583: interactive use in the most ordinary way, to print or display an
                    584: announcement including an appropriate copyright notice and a
                    585: notice that there is no warranty (or else, saying that you provide
                    586: a warranty) and that users may redistribute the program under
                    587: these conditions, and telling the user how to view a copy of this
                    588: License.  (Exception: if the Program itself is interactive but
                    589: does not normally print such an announcement, your work based on
                    590: the Program is not required to print an announcement.)
                    591: @end enumerate
                    592: 
                    593: These requirements apply to the modified work as a whole.  If
                    594: identifiable sections of that work are not derived from the Program,
                    595: and can be reasonably considered independent and separate works in
                    596: themselves, then this License, and its terms, do not apply to those
                    597: sections when you distribute them as separate works.  But when you
                    598: distribute the same sections as part of a whole which is a work based
                    599: on the Program, the distribution of the whole must be on the terms of
                    600: this License, whose permissions for other licensees extend to the
                    601: entire whole, and thus to each and every part regardless of who wrote it.
                    602: 
                    603: Thus, it is not the intent of this section to claim rights or contest
                    604: your rights to work written entirely by you; rather, the intent is to
                    605: exercise the right to control the distribution of derivative or
                    606: collective works based on the Program.
                    607: 
                    608: In addition, mere aggregation of another work not based on the Program
                    609: with the Program (or with a work based on the Program) on a volume of
                    610: a storage or distribution medium does not bring the other work under
                    611: the scope of this License.
                    612: 
                    613: @item
                    614: You may copy and distribute the Program (or a work based on it,
                    615: under Section 2) in object code or executable form under the terms of
                    616: Sections 1 and 2 above provided that you also do one of the following:
                    617: 
                    618: @enumerate a
                    619: @item
                    620: Accompany it with the complete corresponding machine-readable
                    621: source code, which must be distributed under the terms of Sections
                    622: 1 and 2 above on a medium customarily used for software interchange; or,
                    623: 
                    624: @item
                    625: Accompany it with a written offer, valid for at least three
                    626: years, to give any third party, for a charge no more than your
                    627: cost of physically performing source distribution, a complete
                    628: machine-readable copy of the corresponding source code, to be
                    629: distributed under the terms of Sections 1 and 2 above on a medium
                    630: customarily used for software interchange; or,
                    631: 
                    632: @item
                    633: Accompany it with the information you received as to the offer
                    634: to distribute corresponding source code.  (This alternative is
                    635: allowed only for noncommercial distribution and only if you
                    636: received the program in object code or executable form with such
                    637: an offer, in accord with Subsection b above.)
                    638: @end enumerate
                    639: 
                    640: The source code for a work means the preferred form of the work for
                    641: making modifications to it.  For an executable work, complete source
                    642: code means all the source code for all modules it contains, plus any
                    643: associated interface definition files, plus the scripts used to
                    644: control compilation and installation of the executable.  However, as a
                    645: special exception, the source code distributed need not include
                    646: anything that is normally distributed (in either source or binary
                    647: form) with the major components (compiler, kernel, and so on) of the
                    648: operating system on which the executable runs, unless that component
                    649: itself accompanies the executable.
                    650: 
                    651: If distribution of executable or object code is made by offering
                    652: access to copy from a designated place, then offering equivalent
                    653: access to copy the source code from the same place counts as
                    654: distribution of the source code, even though third parties are not
                    655: compelled to copy the source along with the object code.
                    656: 
                    657: @item
                    658: You may not copy, modify, sublicense, or distribute the Program
                    659: except as expressly provided under this License.  Any attempt
                    660: otherwise to copy, modify, sublicense or distribute the Program is
                    661: void, and will automatically terminate your rights under this License.
                    662: However, parties who have received copies, or rights, from you under
                    663: this License will not have their licenses terminated so long as such
                    664: parties remain in full compliance.
                    665: 
                    666: @item
                    667: You are not required to accept this License, since you have not
                    668: signed it.  However, nothing else grants you permission to modify or
                    669: distribute the Program or its derivative works.  These actions are
                    670: prohibited by law if you do not accept this License.  Therefore, by
                    671: modifying or distributing the Program (or any work based on the
                    672: Program), you indicate your acceptance of this License to do so, and
                    673: all its terms and conditions for copying, distributing or modifying
                    674: the Program or works based on it.
                    675: 
                    676: @item
                    677: Each time you redistribute the Program (or any work based on the
                    678: Program), the recipient automatically receives a license from the
                    679: original licensor to copy, distribute or modify the Program subject to
                    680: these terms and conditions.  You may not impose any further
                    681: restrictions on the recipients' exercise of the rights granted herein.
                    682: You are not responsible for enforcing compliance by third parties to
                    683: this License.
                    684: 
                    685: @item
                    686: If, as a consequence of a court judgment or allegation of patent
                    687: infringement or for any other reason (not limited to patent issues),
                    688: conditions are imposed on you (whether by court order, agreement or
                    689: otherwise) that contradict the conditions of this License, they do not
                    690: excuse you from the conditions of this License.  If you cannot
                    691: distribute so as to satisfy simultaneously your obligations under this
                    692: License and any other pertinent obligations, then as a consequence you
                    693: may not distribute the Program at all.  For example, if a patent
                    694: license would not permit royalty-free redistribution of the Program by
                    695: all those who receive copies directly or indirectly through you, then
                    696: the only way you could satisfy both it and this License would be to
                    697: refrain entirely from distribution of the Program.
                    698: 
                    699: If any portion of this section is held invalid or unenforceable under
                    700: any particular circumstance, the balance of the section is intended to
                    701: apply and the section as a whole is intended to apply in other
                    702: circumstances.
                    703: 
                    704: It is not the purpose of this section to induce you to infringe any
                    705: patents or other property right claims or to contest validity of any
                    706: such claims; this section has the sole purpose of protecting the
                    707: integrity of the free software distribution system, which is
                    708: implemented by public license practices.  Many people have made
                    709: generous contributions to the wide range of software distributed
                    710: through that system in reliance on consistent application of that
                    711: system; it is up to the author/donor to decide if he or she is willing
                    712: to distribute software through any other system and a licensee cannot
                    713: impose that choice.
                    714: 
                    715: This section is intended to make thoroughly clear what is believed to
                    716: be a consequence of the rest of this License.
                    717: 
                    718: @item
                    719: If the distribution and/or use of the Program is restricted in
                    720: certain countries either by patents or by copyrighted interfaces, the
                    721: original copyright holder who places the Program under this License
                    722: may add an explicit geographical distribution limitation excluding
                    723: those countries, so that distribution is permitted only in or among
                    724: countries not thus excluded.  In such case, this License incorporates
                    725: the limitation as if written in the body of this License.
                    726: 
                    727: @item
                    728: The Free Software Foundation may publish revised and/or new versions
                    729: of the General Public License from time to time.  Such new versions will
                    730: be similar in spirit to the present version, but may differ in detail to
                    731: address new problems or concerns.
                    732: 
                    733: Each version is given a distinguishing version number.  If the Program
                    734: specifies a version number of this License which applies to it and ``any
                    735: later version'', you have the option of following the terms and conditions
                    736: either of that version or of any later version published by the Free
                    737: Software Foundation.  If the Program does not specify a version number of
                    738: this License, you may choose any version ever published by the Free Software
                    739: Foundation.
                    740: 
                    741: @item
                    742: If you wish to incorporate parts of the Program into other free
                    743: programs whose distribution conditions are different, write to the author
                    744: to ask for permission.  For software which is copyrighted by the Free
                    745: Software Foundation, write to the Free Software Foundation; we sometimes
                    746: make exceptions for this.  Our decision will be guided by the two goals
                    747: of preserving the free status of all derivatives of our free software and
                    748: of promoting the sharing and reuse of software generally.
                    749: 
                    750: @iftex
                    751: @heading NO WARRANTY
                    752: @end iftex
                    753: @ifinfo
                    754: @center NO WARRANTY
                    755: @end ifinfo
                    756: 
                    757: @item
                    758: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
                    759: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
                    760: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
                    761: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
                    762: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
                    763: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
                    764: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
                    765: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
                    766: REPAIR OR CORRECTION.
                    767: 
                    768: @item
                    769: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
                    770: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
                    771: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
                    772: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
                    773: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
                    774: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
                    775: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
                    776: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
                    777: POSSIBILITY OF SUCH DAMAGES.
                    778: @end enumerate
                    779: 
                    780: @iftex
                    781: @heading END OF TERMS AND CONDITIONS
                    782: @end iftex
                    783: @ifinfo
                    784: @center END OF TERMS AND CONDITIONS
                    785: @end ifinfo
                    786: 
                    787: @page
                    788: @unnumberedsec How to Apply These Terms to Your New Programs
                    789: 
                    790:   If you develop a new program, and you want it to be of the greatest
                    791: possible use to the public, the best way to achieve this is to make it
                    792: free software which everyone can redistribute and change under these terms.
                    793: 
                    794:   To do so, attach the following notices to the program.  It is safest
                    795: to attach them to the start of each source file to most effectively
                    796: convey the exclusion of warranty; and each file should have at least
                    797: the ``copyright'' line and a pointer to where the full notice is found.
                    798: 
                    799: @smallexample
                    800: @var{one line to give the program's name and a brief idea of what it does.}
                    801: Copyright (C) 19@var{yy}  @var{name of author}
                    802: 
                    803: This program is free software; you can redistribute it and/or modify 
                    804: it under the terms of the GNU General Public License as published by 
                    805: the Free Software Foundation; either version 2 of the License, or 
                    806: (at your option) any later version.
                    807: 
                    808: This program is distributed in the hope that it will be useful,
                    809: but WITHOUT ANY WARRANTY; without even the implied warranty of
                    810: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                    811: GNU General Public License for more details.
                    812: 
                    813: You should have received a copy of the GNU General Public License
                    814: along with this program; if not, write to the Free Software
                    815: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
                    816: @end smallexample
                    817: 
                    818: Also add information on how to contact you by electronic and paper mail.
                    819: 
                    820: If the program is interactive, make it output a short notice like this
                    821: when it starts in an interactive mode:
                    822: 
                    823: @smallexample
                    824: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
                    825: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
                    826: type `show w'.  
                    827: This is free software, and you are welcome to redistribute it 
                    828: under certain conditions; type `show c' for details.
                    829: @end smallexample
                    830: 
                    831: The hypothetical commands @samp{show w} and @samp{show c} should show
                    832: the appropriate parts of the General Public License.  Of course, the
                    833: commands you use may be called something other than @samp{show w} and
                    834: @samp{show c}; they could even be mouse-clicks or menu items---whatever
                    835: suits your program.
                    836: 
                    837: You should also get your employer (if you work as a programmer) or your
                    838: school, if any, to sign a ``copyright disclaimer'' for the program, if
                    839: necessary.  Here is a sample; alter the names:
                    840: 
                    841: @smallexample
                    842: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
                    843: `Gnomovision' (which makes passes at compilers) written by James Hacker.
                    844: 
                    845: @var{signature of Ty Coon}, 1 April 1989
                    846: Ty Coon, President of Vice
                    847: @end smallexample
                    848: 
                    849: This General Public License does not permit incorporating your program into
                    850: proprietary programs.  If your program is a subroutine library, you may
                    851: consider it more useful to permit linking proprietary applications with the
                    852: library.  If this is what you want to do, use the GNU Library General
                    853: Public License instead of this License.
                    854: 
                    855: @iftex
                    856: @unnumbered Preface
                    857: @cindex Preface
1.21      crook     858: This manual documents Gforth. Some introductory material is provided for
                    859: readers who are unfamiliar with Forth or who are migrating to Gforth
                    860: from other Forth compilers. However, this manual is primarily a
                    861: reference manual.
1.1       anton     862: @end iftex
                    863: 
1.28      crook     864: @comment TODO much more blurb here.
1.26      crook     865: 
                    866: @c ******************************************************************
1.29      crook     867: @node Goals, Gforth Environment, License, Top
1.26      crook     868: @comment node-name,     next,           previous, up
                    869: @chapter Goals of Gforth
                    870: @cindex goals of the Gforth project
                    871: The goal of the Gforth Project is to develop a standard model for
                    872: ANS Forth. This can be split into several subgoals:
                    873: 
                    874: @itemize @bullet
                    875: @item
                    876: Gforth should conform to the ANS Forth Standard.
                    877: @item
                    878: It should be a model, i.e. it should define all the
                    879: implementation-dependent things.
                    880: @item
                    881: It should become standard, i.e. widely accepted and used. This goal
                    882: is the most difficult one.
                    883: @end itemize
                    884: 
                    885: To achieve these goals Gforth should be
                    886: @itemize @bullet
                    887: @item
                    888: Similar to previous models (fig-Forth, F83)
                    889: @item
                    890: Powerful. It should provide for all the things that are considered
                    891: necessary today and even some that are not yet considered necessary.
                    892: @item
                    893: Efficient. It should not get the reputation of being exceptionally
                    894: slow.
                    895: @item
                    896: Free.
                    897: @item
                    898: Available on many machines/easy to port.
                    899: @end itemize
                    900: 
                    901: Have we achieved these goals? Gforth conforms to the ANS Forth
                    902: standard. It may be considered a model, but we have not yet documented
                    903: which parts of the model are stable and which parts we are likely to
                    904: change. It certainly has not yet become a de facto standard, but it
                    905: appears to be quite popular. It has some similarities to and some
                    906: differences from previous models. It has some powerful features, but not
                    907: yet everything that we envisioned. We certainly have achieved our
                    908: execution speed goals (@pxref{Performance}).  It is free and available
                    909: on many machines.
                    910: 
                    911: @menu
                    912: * Gforth Extensions Sinful?::
                    913: @end menu
                    914: 
                    915: @node Gforth Extensions Sinful?, , Goals, Goals
                    916: @comment node-name,     next,           previous, up
                    917: @section Is it a Sin to use Gforth Extensions?
                    918: @cindex Gforth extensions
                    919: 
                    920: If you've been paying attention, you will have realised that there is an
                    921: ANS (American National Standard) for Forth. As you read through the rest
1.29      crook     922: of this manual, you will see documentation for @i{Standard} words, and
                    923: documentation for some appealing Gforth @i{extensions}. You might ask
                    924: yourself the question: @i{``Given that there is a standard, would I be
1.26      crook     925: committing a sin to use (non-Standard) Gforth extensions?''}
                    926: 
                    927: The answer to that question is somewhat pragmatic and somewhat
                    928: philosophical. Consider these points:
                    929: 
                    930: @itemize @bullet
                    931: @item
                    932: A number of the Gforth extensions can be implemented in ANS Forth using
                    933: files provided in the @file{compat/} directory. These are mentioned in
                    934: the text in passing.
                    935: @item
                    936: Forth has a rich historical precedent for programmers taking advantage
                    937: of implementation-dependent features of their tools (for example,
                    938: relying on a knowledge of the dictionary structure). Sometimes these
                    939: techniques are necessary to extract every last bit of performance from
                    940: the hardware, sometimes they are just a programming shorthand.
                    941: @item
                    942: The best way to break the rules is to know what the rules are. To learn
                    943: the rules, there is no substitute for studying the text of the Standard
                    944: itself. In particular, Appendix A of the Standard (@var{Rationale})
                    945: provides a valuable insight into the thought processes of the technical
                    946: committee.
                    947: @item
                    948: The best reason to break a rule is because you have to; because it's
                    949: more productive to do that, because it makes your code run fast enough
                    950: or because you can see no Standard way to achieve what you want to
                    951: achieve.
                    952: @end itemize
                    953: 
                    954: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
                    955: analyse your program and determine what non-Standard definitions it
                    956: relies upon.
                    957: 
1.29      crook     958: 
1.26      crook     959: @c ******************************************************************
1.29      crook     960: @node Gforth Environment, Introduction, Goals, Top
                    961: @chapter Gforth Environment
                    962: @cindex Gforth environment
1.21      crook     963: 
1.29      crook     964: Note: ultimately, the gforth man page will be auto-generated from the
                    965: material in this chapter.
1.21      crook     966: 
                    967: @menu
1.29      crook     968: * Invoking Gforth::             Getting in
                    969: * Leaving Gforth::              Getting out
                    970: * Command-line editing::        
                    971: * Upper and lower case::
                    972: * Environment variables::       ..that affect how Gforth starts up
                    973: * Gforth Files::                What gets installed and where
1.21      crook     974: @end menu
                    975: 
1.30      anton     976: @xref{Image Files} for related information about the creation of images.
1.29      crook     977: 
1.21      crook     978: @comment ----------------------------------------------
1.29      crook     979: @node Invoking Gforth, Leaving Gforth, ,Gforth Environment
                    980: @section Invoking Gforth
                    981: @cindex invoking Gforth
                    982: @cindex running Gforth
                    983: @cindex command-line options
                    984: @cindex options on the command line
                    985: @cindex flags on the command line
1.21      crook     986: 
1.30      anton     987: Gforth is made up of two parts; an executable ``engine'' (named
                    988: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
                    989: will usually just say @code{gforth} -- this automatically loads the
                    990: default image file @file{gforth.fi}. In many other cases the default
                    991: Gforth image will be invoked like this:
1.21      crook     992: @example
1.30      anton     993: gforth [file | -e forth-code] ...
1.21      crook     994: @end example
1.29      crook     995: @noindent
                    996: This interprets the contents of the files and the Forth code in the order they
                    997: are given.
1.21      crook     998: 
1.30      anton     999: In addition to the @file{gforth} engine, there is also an engine called
                   1000: @file{gforth-fast}, which is faster, but gives less informative error
                   1001: messages (@pxref{Error messages}).
                   1002: 
1.29      crook    1003: In general, the command line looks like this:
1.21      crook    1004: 
                   1005: @example
1.30      anton    1006: gforth[-fast] [engine options] [image options]
1.21      crook    1007: @end example
                   1008: 
1.30      anton    1009: The engine options must come before the rest of the command
1.29      crook    1010: line. They are:
1.26      crook    1011: 
1.29      crook    1012: @table @code
                   1013: @cindex -i, command-line option
                   1014: @cindex --image-file, command-line option
                   1015: @item --image-file @i{file}
                   1016: @itemx -i @i{file}
                   1017: Loads the Forth image @i{file} instead of the default
                   1018: @file{gforth.fi} (@pxref{Image Files}).
1.21      crook    1019: 
1.29      crook    1020: @cindex --path, command-line option
                   1021: @cindex -p, command-line option
                   1022: @item --path @i{path}
                   1023: @itemx -p @i{path}
                   1024: Uses @i{path} for searching the image file and Forth source code files
                   1025: instead of the default in the environment variable @code{GFORTHPATH} or
                   1026: the path specified at installation time (e.g.,
                   1027: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                   1028: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21      crook    1029: 
1.29      crook    1030: @cindex --dictionary-size, command-line option
                   1031: @cindex -m, command-line option
                   1032: @cindex @i{size} parameters for command-line options
                   1033: @cindex size of the dictionary and the stacks
                   1034: @item --dictionary-size @i{size}
                   1035: @itemx -m @i{size}
                   1036: Allocate @i{size} space for the Forth dictionary space instead of
                   1037: using the default specified in the image (typically 256K). The
                   1038: @i{size} specification for this and subsequent options consists of
                   1039: an integer and a unit (e.g.,
                   1040: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
                   1041: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                   1042: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                   1043: @code{e} is used.
1.21      crook    1044: 
1.29      crook    1045: @cindex --data-stack-size, command-line option
                   1046: @cindex -d, command-line option
                   1047: @item --data-stack-size @i{size}
                   1048: @itemx -d @i{size}
                   1049: Allocate @i{size} space for the data stack instead of using the
                   1050: default specified in the image (typically 16K).
1.21      crook    1051: 
1.29      crook    1052: @cindex --return-stack-size, command-line option
                   1053: @cindex -r, command-line option
                   1054: @item --return-stack-size @i{size}
                   1055: @itemx -r @i{size}
                   1056: Allocate @i{size} space for the return stack instead of using the
                   1057: default specified in the image (typically 15K).
1.21      crook    1058: 
1.29      crook    1059: @cindex --fp-stack-size, command-line option
                   1060: @cindex -f, command-line option
                   1061: @item --fp-stack-size @i{size}
                   1062: @itemx -f @i{size}
                   1063: Allocate @i{size} space for the floating point stack instead of
                   1064: using the default specified in the image (typically 15.5K). In this case
                   1065: the unit specifier @code{e} refers to floating point numbers.
1.21      crook    1066: 
1.29      crook    1067: @cindex --locals-stack-size, command-line option
                   1068: @cindex -l, command-line option
                   1069: @item --locals-stack-size @i{size}
                   1070: @itemx -l @i{size}
                   1071: Allocate @i{size} space for the locals stack instead of using the
                   1072: default specified in the image (typically 14.5K).
1.21      crook    1073: 
1.29      crook    1074: @cindex -h, command-line option
                   1075: @cindex --help, command-line option
                   1076: @item --help
                   1077: @itemx -h
                   1078: Print a message about the command-line options
1.21      crook    1079: 
1.29      crook    1080: @cindex -v, command-line option
                   1081: @cindex --version, command-line option
                   1082: @item --version
                   1083: @itemx -v
                   1084: Print version and exit
1.21      crook    1085: 
1.29      crook    1086: @cindex --debug, command-line option
                   1087: @item --debug
                   1088: Print some information useful for debugging on startup.
1.21      crook    1089: 
1.29      crook    1090: @cindex --offset-image, command-line option
                   1091: @item --offset-image
                   1092: Start the dictionary at a slightly different position than would be used
                   1093: otherwise (useful for creating data-relocatable images,
                   1094: @pxref{Data-Relocatable Image Files}).
1.21      crook    1095: 
1.29      crook    1096: @cindex --no-offset-im, command-line option
                   1097: @item --no-offset-im
                   1098: Start the dictionary at the normal position.
1.21      crook    1099: 
1.29      crook    1100: @cindex --clear-dictionary, command-line option
                   1101: @item --clear-dictionary
                   1102: Initialize all bytes in the dictionary to 0 before loading the image
                   1103: (@pxref{Data-Relocatable Image Files}).
                   1104: 
                   1105: @cindex --die-on-signal, command-line-option
                   1106: @item --die-on-signal
                   1107: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
                   1108: or the segmentation violation SIGSEGV) by translating it into a Forth
                   1109: @code{THROW}. With this option, Gforth exits if it receives such a
                   1110: signal. This option is useful when the engine and/or the image might be
                   1111: severely broken (such that it causes another signal before recovering
                   1112: from the first); this option avoids endless loops in such cases.
                   1113: @end table
                   1114: 
                   1115: @cindex loading files at startup
                   1116: @cindex executing code on startup
                   1117: @cindex batch processing with Gforth
                   1118: As explained above, the image-specific command-line arguments for the
                   1119: default image @file{gforth.fi} consist of a sequence of filenames and
                   1120: @code{-e @var{forth-code}} options that are interpreted in the sequence
                   1121: in which they are given. The @code{-e @var{forth-code}} or
                   1122: @code{--evaluate @var{forth-code}} option evaluates the Forth
                   1123: code. This option takes only one argument; if you want to evaluate more
                   1124: Forth words, you have to quote them or use @code{-e} several times. To exit
                   1125: after processing the command line (instead of entering interactive mode)
                   1126: append @code{-e bye} to the command line.
                   1127: 
                   1128: @cindex versions, invoking other versions of Gforth
                   1129: If you have several versions of Gforth installed, @code{gforth} will
                   1130: invoke the version that was installed last. @code{gforth-@i{version}}
                   1131: invokes a specific version. You may want to use the option
                   1132: @code{--path}, if your environment contains the variable
                   1133: @code{GFORTHPATH}.
                   1134: 
                   1135: Not yet implemented:
                   1136: On startup the system first executes the system initialization file
                   1137: (unless the option @code{--no-init-file} is given; note that the system
                   1138: resulting from using this option may not be ANS Forth conformant). Then
                   1139: the user initialization file @file{.gforth.fs} is executed, unless the
                   1140: option @code{--no-rc} is given; this file is first searched in @file{.},
                   1141: then in @file{~}, then in the normal path (see above).
1.21      crook    1142: 
                   1143: 
                   1144: 
1.29      crook    1145: @comment ----------------------------------------------
                   1146: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
                   1147: @section Leaving Gforth
                   1148: @cindex Gforth - leaving
                   1149: @cindex leaving Gforth
1.21      crook    1150: 
1.30      anton    1151: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
                   1152: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
                   1153: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
                   1154: data are discarded. @xref{Image Files} for ways of saving the state of
                   1155: the system before leaving Gforth.
1.21      crook    1156: 
1.29      crook    1157: doc-bye
1.21      crook    1158: 
1.29      crook    1159: @comment ----------------------------------------------
                   1160: @node Command-line editing, Upper and lower case,Leaving Gforth,Gforth Environment
                   1161: @section Command-line editing
                   1162: @cindex command-line editing
1.21      crook    1163: 
1.29      crook    1164: Gforth maintains a history file that records every line that you type to
                   1165: the text interpreter. This file is preserved between sessions, and is
                   1166: used to provide a command-line recall facility; if you type ctrl-P
                   1167: repeatedly you can recall successively older commands from this (or
                   1168: previous) session(s). The full list of command-line editing facilities is:
1.21      crook    1169: 
1.30      anton    1170: @comment use @table? - anton
1.21      crook    1171: @itemize @bullet
                   1172: @item
1.30      anton    1173: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
1.29      crook    1174: commands from the history buffer.
                   1175: @item
1.30      anton    1176: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
1.29      crook    1177: from the history buffer.
                   1178: @item
1.30      anton    1179: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
1.29      crook    1180: @item
1.30      anton    1181: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
1.29      crook    1182: @item
1.30      anton    1183: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
1.29      crook    1184: closing up the line.
                   1185: @item
1.30      anton    1186: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
1.29      crook    1187: @item
1.30      anton    1188: @kbd{Ctrl-a} to move the cursor to the start of the line.
1.21      crook    1189: @item
1.30      anton    1190: @kbd{Ctrl-e} to move the cursor to the end of the line.
1.21      crook    1191: @item
1.30      anton    1192: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
1.29      crook    1193: line.
1.21      crook    1194: @item
1.30      anton    1195: @key{TAB} to step through all possible full-word completions of the word
1.29      crook    1196: currently being typed.
1.21      crook    1197: @item
1.30      anton    1198: @kbd{Ctrl-d} at the start of the line to terminate Gforth (gracefully,
                   1199: using @code{bye}).
1.21      crook    1200: @end itemize
                   1201: 
1.29      crook    1202: When editing, displayable characters are inserted to the left of the
                   1203: cursor position; the line is always in ``insert'' (as opposed to
                   1204: ``overstrike'') mode.
                   1205: 
                   1206: @cindex history file
                   1207: @cindex @file{.gforth-history}
                   1208: On Unix systems, the history file is @file{~/.gforth-history} by
                   1209: default@footnote{i.e. it is stored in the user's home directory.}. You
                   1210: can find out the name and location of your history file using:
                   1211: 
                   1212: @example 
                   1213: history-file type \ Unix-class systems
1.21      crook    1214: 
1.29      crook    1215: history-file type \ Other systems
                   1216: history-dir  type
1.21      crook    1217: @end example
                   1218: 
1.29      crook    1219: If you enter long definitions by hand, you can use a text editor to
                   1220: paste them out of the history file into a Forth source file for reuse at
                   1221: a later time.
                   1222: 
                   1223: Gforth never trims the size of the history file, so you should do this
                   1224: periodically, if necessary.
                   1225: 
                   1226: @comment this is all defined in history.fs
                   1227: 
                   1228: 
                   1229: 
                   1230: @comment ----------------------------------------------
                   1231: @node Upper and lower case, Environment variables,Command-line editing,Gforth Environment
                   1232: @section Upper and lower case
                   1233: @cindex case-sensitivity
                   1234: @cindex upper and lower case
                   1235: 
                   1236: Gforth is case-insensitive, so you can enter definitions and invoke
                   1237: Standard words using upper, lower or mixed case (however,
                   1238: @pxref{core-idef, Implementation-defined options, Implementation-defined
                   1239: options}).
                   1240: 
1.30      anton    1241: ANS Forth only @i{requires} implementations to recognise Standard words
                   1242: when they are typed entirely in upper case. Therefore, a Standard
                   1243: program must use upper case for all Standard words. You can use whatever
                   1244: case you like for words that you define, but in a standard program you
                   1245: have to use the words in the same case that you defined them.
                   1246: 
                   1247: Gforth supports case sensitivity through @code{table}s (case-sensitive
                   1248: wordlists, @pxref{Word Lists}).
                   1249: 
                   1250: Two people have asked how to convert Gforth to case sensitivity; while
                   1251: we think this is a bad idea, you can change all wordlists into tables
                   1252: like this:
1.29      crook    1253: 
1.30      anton    1254: @example
                   1255: ' table-find forth-wordlist wordlist-map @ !
                   1256: @end example
                   1257: 
                   1258: Note that you now have to type the predefined words in the same case
                   1259: that we defined them, which are varying.  You may want to convert them
                   1260: to your favourite case before doing this operation (I won't explain how,
                   1261: because if you are even contemplating to do this, you'd better have
                   1262: enough knowledge of Forth systems to know this already).
1.29      crook    1263: 
                   1264: @comment ----------------------------------------------
                   1265: @node Environment variables, Gforth Files, Upper and lower case,Gforth Environment
                   1266: @section Environment variables
                   1267: @cindex environment variables
1.21      crook    1268: 
1.29      crook    1269: Gforth uses these environment variables:
1.21      crook    1270: 
1.29      crook    1271: @itemize @bullet
                   1272: @item
                   1273: @cindex GFORTHHIST - environment variable
                   1274: GFORTHHIST - (Unix systems only) specifies the directory in which to
                   1275: open/create the history file, @file{.gforth-history}. Default:
                   1276: @code{$HOME}.
1.21      crook    1277: 
1.29      crook    1278: @item
                   1279: @cindex GFORTHPATH - environment variable
                   1280: GFORTHPATH - specifies the path used when searching for the gforth image file and
                   1281: for Forth source-code files.
1.21      crook    1282: 
1.29      crook    1283: @item
                   1284: @cindex GFORTH - environment variable
                   1285: GFORTH - used by @file{gforthmi} @xref{gforthmi}.
1.26      crook    1286: 
1.29      crook    1287: @item
                   1288: @cindex GFORTHD - environment variable
                   1289: GFORTHD - used by @file{gforthmi} @xref{gforthmi}.
1.21      crook    1290: 
1.29      crook    1291: @item
                   1292: @cindex TMP, TEMP - environment variable
                   1293: TMP, TEMP - (non-Unix systems only) used as a potential location for the
                   1294: history file.
                   1295: @end itemize
1.21      crook    1296: 
1.29      crook    1297: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
                   1298: @comment mentioning these.
1.21      crook    1299: 
1.29      crook    1300: All the Gforth environment variables default to sensible values if they
                   1301: are not set.
1.21      crook    1302: 
                   1303: 
1.29      crook    1304: @comment ----------------------------------------------
                   1305: @node Gforth Files, ,Environment variables,Gforth Environment
                   1306: @section Gforth files
                   1307: @cindex Gforth files
1.21      crook    1308: 
1.30      anton    1309: When you Gforth on a Unix system in the default places, it installs
                   1310: files in these locations:
1.21      crook    1311: 
1.26      crook    1312: @itemize @bullet
                   1313: @item
1.29      crook    1314: @file{/usr/local/bin/gforth}
                   1315: @item
                   1316: @file{/usr/local/bin/gforthmi}
                   1317: @item
                   1318: @file{/usr/local/man/man1/gforth.1} - man page.
                   1319: @item
                   1320: @file{/usr/local/info} - the Info version of this manual.
                   1321: @item
1.30      anton    1322: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1.29      crook    1323: @item
                   1324: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1.26      crook    1325: @item
1.30      anton    1326: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1.26      crook    1327: @item
1.30      anton    1328: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1.26      crook    1329: @end itemize
1.21      crook    1330: 
1.30      anton    1331: You can select different places for installation by using
                   1332: @code{configure} options (listed with @code{configure --help}).
1.21      crook    1333: 
1.29      crook    1334: @c ******************************************************************
                   1335: @node Introduction, Words, Gforth Environment, Top
                   1336: @comment node-name,     next,           previous, up
                   1337: @chapter An Introduction to ANS Forth
                   1338: @cindex Forth - an introduction
1.21      crook    1339: 
1.29      crook    1340: The primary purpose of this manual is to document Gforth. However, since
                   1341: Forth is not a widely-known language and there is a lack of up-to-date
                   1342: teaching material, it seems worthwhile to provide some introductory
                   1343: material. @xref{Forth-related information} for other sources of Forth-related
                   1344: information.
1.21      crook    1345: 
1.29      crook    1346: The examples in this section should work on any ANS Forth; the
                   1347: output shown was produced using Gforth. Each example attempts to
                   1348: reproduce the exact output that Gforth produces. If you try out the
                   1349: examples (and you should), what you should type is shown @kbd{like this}
                   1350: and Gforth's response is shown @code{like this}. The single exception is
1.30      anton    1351: that, where the example shows @key{RET} it means that you should
1.29      crook    1352: press the ``carriage return'' key. Unfortunately, some output formats for
                   1353: this manual cannot show the difference between @kbd{this} and
                   1354: @code{this} which will make trying out the examples harder (but not
                   1355: impossible).
1.21      crook    1356: 
1.29      crook    1357: Forth is an unusual language. It provides an interactive development
                   1358: environment which includes both an interpreter and compiler. Forth
                   1359: programming style encourages you to break a problem down into many
                   1360: @cindex factoring
                   1361: small fragments (@dfn{factoring}), and then to develop and test each
                   1362: fragment interactively. Forth advocates assert that breaking the
                   1363: edit-compile-test cycle used by conventional programming languages can
                   1364: lead to great productivity improvements.
1.21      crook    1365: 
1.29      crook    1366: @menu
                   1367: * Introducing the Text Interpreter::
                   1368: * Stacks and Postfix notation::
                   1369: * Your first definition::
                   1370: * How does that work?::
                   1371: * Forth is written in Forth::
                   1372: * Review - elements of a Forth system::
                   1373: * Where to go next::
                   1374: * Exercises::
                   1375: @end menu
1.21      crook    1376: 
1.29      crook    1377: @comment ----------------------------------------------
                   1378: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                   1379: @section Introducing the Text Interpreter
                   1380: @cindex text interpreter
                   1381: @cindex outer interpreter
1.21      crook    1382: 
1.30      anton    1383: @c IMO this is too detailed and the pace is too slow for
                   1384: @c an introduction.  If you know German, take a look at
                   1385: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
                   1386: @c to see how I do it - anton 
                   1387: 
1.29      crook    1388: When you invoke the Forth image, you will see a startup banner printed
                   1389: and nothing else (if you have Gforth installed on your system, try
1.30      anton    1390: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29      crook    1391: its command line interpreter, which is called the @dfn{Text Interpreter}
                   1392: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
1.30      anton    1393: about the text interpreter as you read through this chapter, but
                   1394: @pxref{The Text Interpreter} for more detail).
1.21      crook    1395: 
1.29      crook    1396: Although it's not obvious, Forth is actually waiting for your
1.30      anton    1397: input. Type a number and press the @key{RET} key:
1.21      crook    1398: 
1.26      crook    1399: @example
1.30      anton    1400: @kbd{45@key{RET}}  ok
1.26      crook    1401: @end example
1.21      crook    1402: 
1.29      crook    1403: Rather than give you a prompt to invite you to input something, the text
                   1404: interpreter prints a status message @i{after} it has processed a line
                   1405: of input. The status message in this case (``@code{ ok}'' followed by
                   1406: carriage-return) indicates that the text interpreter was able to process
                   1407: all of your input successfully. Now type something illegal:
                   1408: 
                   1409: @example
1.30      anton    1410: @kbd{qwer341@key{RET}}
1.29      crook    1411: :1: Undefined word
                   1412: qwer341
                   1413: ^^^^^^^
                   1414: $400D2BA8 Bounce
                   1415: $400DBDA8 no.extensions
                   1416: @end example
1.23      crook    1417: 
1.29      crook    1418: The exact text, other than the ``Undefined word'' may differ slightly on
                   1419: your system, but the effect is the same; when the text interpreter
                   1420: detects an error, it discards any remaining text on a line, resets
1.30      anton    1421: certain internal state and prints an error message. @xref{Error
                   1422: messages} for a detailed description of error messages.
1.23      crook    1423: 
1.29      crook    1424: The text interpreter waits for you to press carriage-return, and then
                   1425: processes your input line. Starting at the beginning of the line, it
                   1426: breaks the line into groups of characters separated by spaces. For each
                   1427: group of characters in turn, it makes two attempts to do something:
1.23      crook    1428: 
1.29      crook    1429: @itemize @bullet
                   1430: @item
                   1431: It tries to treat it as a command. It does this by searching a @dfn{name
                   1432: dictionary}. If the group of characters matches an entry in the name
                   1433: dictionary, the name dictionary provides the text interpreter with
                   1434: information that allows the text interpreter perform some actions. In
                   1435: Forth jargon, we say that the group
                   1436: @cindex word
                   1437: @cindex definition
                   1438: @cindex execution token
                   1439: @cindex xt
                   1440: of characters names a @dfn{word}, that the dictionary search returns an
                   1441: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
                   1442: word, and that the text interpreter executes the xt. Often, the terms
                   1443: @dfn{word} and @dfn{definition} are used interchangeably.
                   1444: @item
                   1445: If the text interpreter fails to find a match in the name dictionary, it
                   1446: tries to treat the group of characters as a number in the current number
                   1447: base (when you start up Forth, the current number base is base 10). If
                   1448: the group of characters legitimately represents a number, the text
                   1449: interpreter pushes the number onto a stack (we'll learn more about that
                   1450: in the next section).
                   1451: @end itemize
1.23      crook    1452: 
1.29      crook    1453: If the text interpreter is unable to do either of these things with any
                   1454: group of characters, it discards the group of characters and the rest of
                   1455: the line, then prints an error message. If the text interpreter reaches
                   1456: the end of the line without error, it prints the status message ``@code{ ok}''
                   1457: followed by carriage-return.
1.21      crook    1458: 
1.29      crook    1459: This is the simplest command we can give to the text interpreter:
1.23      crook    1460: 
                   1461: @example
1.30      anton    1462: @key{RET}  ok
1.23      crook    1463: @end example
1.21      crook    1464: 
1.29      crook    1465: The text interpreter did everything we asked it to do (nothing) without
                   1466: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
                   1467: command:
1.21      crook    1468: 
1.23      crook    1469: @example
1.30      anton    1470: @kbd{12 dup fred dup@key{RET}}
1.29      crook    1471: :1: Undefined word
                   1472: 12 dup fred dup
                   1473:        ^^^^
                   1474: $400D2BA8 Bounce
                   1475: $400DBDA8 no.extensions
1.23      crook    1476: @end example
1.21      crook    1477: 
1.29      crook    1478: When you press the carriage-return key, the text interpreter starts to
                   1479: work its way along the line:
1.21      crook    1480: 
1.29      crook    1481: @itemize @bullet
                   1482: @item
                   1483: When it gets to the space after the @code{2}, it takes the group of
                   1484: characters @code{12} and looks them up in the name
                   1485: dictionary@footnote{We can't tell if it found them or not, but assume
                   1486: for now that it did not}. There is no match for this group of characters
                   1487: in the name dictionary, so it tries to treat them as a number. It is
                   1488: able to do this successfully, so it puts the number, 12, ``on the stack''
                   1489: (whatever that means).
                   1490: @item
                   1491: The text interpreter resumes scanning the line and gets the next group
                   1492: of characters, @code{dup}. It looks it up in the name dictionary and
                   1493: (you'll have to take my word for this) finds it, and executes the word
                   1494: @code{dup} (whatever that means).
                   1495: @item
                   1496: Once again, the text interpreter resumes scanning the line and gets the
                   1497: group of characters @code{fred}. It looks them up in the name
                   1498: dictionary, but can't find them. It tries to treat them as a number, but
                   1499: they don't represent any legal number.
                   1500: @end itemize
1.21      crook    1501: 
1.29      crook    1502: At this point, the text interpreter gives up and prints an error
                   1503: message. The error message shows exactly how far the text interpreter
                   1504: got in processing the line. In particular, it shows that the text
                   1505: interpreter made no attempt to do anything with the final character
                   1506: group, @code{dup}, even though we have good reason to believe that the
                   1507: text interpreter would have no problem looking that word up and
                   1508: executing it a second time.
1.21      crook    1509: 
                   1510: 
1.29      crook    1511: @comment ----------------------------------------------
                   1512: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                   1513: @section Stacks, postfix notation and parameter passing
                   1514: @cindex text interpreter
                   1515: @cindex outer interpreter
1.21      crook    1516: 
1.29      crook    1517: In procedural programming languages (like C and Pascal), the
                   1518: building-block of programs is the @dfn{function} or @dfn{procedure}. These
                   1519: functions or procedures are called with @dfn{explicit parameters}. For
                   1520: example, in C we might write:
1.21      crook    1521: 
1.23      crook    1522: @example
1.29      crook    1523: total = total + new_volume(length,height,depth);
1.23      crook    1524: @end example
1.21      crook    1525: 
1.23      crook    1526: @noindent
1.29      crook    1527: where new_volume is a function-call to another piece of code, and total,
                   1528: length, height and depth are all variables. length, height and depth are
                   1529: parameters to the function-call.
1.21      crook    1530: 
1.29      crook    1531: In Forth, the equivalent of the function or procedure is the
                   1532: @dfn{definition} and parameters are implicitly passed between
                   1533: definitions using a shared stack that is visible to the
                   1534: programmer. Although Forth does support variables, the existence of the
                   1535: stack means that they are used far less often than in most other
                   1536: programming languages. When the text interpreter encounters a number, it
                   1537: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30      anton    1538: actual number is implementation-dependent ...) and the particular stack
1.29      crook    1539: used for any operation is implied unambiguously by the operation being
                   1540: performed. The stack used for all integer operations is called the @dfn{data
                   1541: stack} and, since this is the stack used most commonly, references to
                   1542: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    1543: 
1.29      crook    1544: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    1545: 
1.23      crook    1546: @example
1.30      anton    1547: @kbd{1 2 3@key{RET}}  ok
1.23      crook    1548: @end example
1.21      crook    1549: 
1.29      crook    1550: Then this instructs the text interpreter to placed three numbers on the
                   1551: (data) stack. An analogy for the behaviour of the stack is to take a
                   1552: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
                   1553: the table. The 3 was the last card onto the pile (``last-in'') and if
                   1554: you take a card off the pile then, unless you're prepared to fiddle a
                   1555: bit, the card that you take off will be the 3 (``first-out''). The
                   1556: number that will be first-out of the stack is called the @dfn{top of
                   1557: stack}, which
                   1558: @cindex TOS definition
                   1559: is often abbreviated to @dfn{TOS}.
1.21      crook    1560: 
1.29      crook    1561: To understand how parameters are passed in Forth, consider the
                   1562: behaviour of the definition @code{+} (pronounced ``plus''). You will not
                   1563: be surprised to learn that this definition performs addition. More
                   1564: precisely, it adds two number together and produces a result. Where does
                   1565: it get the two numbers from? It takes the top two numbers off the
                   1566: stack. Where does it place the result? On the stack. You can act-out the
                   1567: behaviour of @code{+} with your playing cards like this:
1.21      crook    1568: 
                   1569: @itemize @bullet
                   1570: @item
1.29      crook    1571: Pick up two cards from the stack on the table
1.21      crook    1572: @item
1.29      crook    1573: Stare at them intently and ask yourself ``what @i{is} the sum of these two
                   1574: numbers''
1.21      crook    1575: @item
1.29      crook    1576: Decide that the answer is 5
1.21      crook    1577: @item
1.29      crook    1578: Shuffle the two cards back into the pack and find a 5
1.21      crook    1579: @item
1.29      crook    1580: Put a 5 on the remaining ace that's on the table.
1.21      crook    1581: @end itemize
                   1582: 
1.29      crook    1583: If you don't have a pack of cards handy but you do have Forth running,
                   1584: you can use the definition @code{.s} to show the current state of the stack,
                   1585: without affecting the stack. Type:
1.21      crook    1586: 
                   1587: @example
1.30      anton    1588: @kbd{clearstack 1 2 3@key{RET}} ok
                   1589: @kbd{.s@key{RET}} <3> 1 2 3  ok
1.23      crook    1590: @end example
                   1591: 
1.29      crook    1592: The text interpreter looks up the word @code{clearstack} and executes
                   1593: it; it tidies up the stack and removes any entries that may have been
                   1594: left on it by earlier examples. The text interpreter pushes each of the
                   1595: three numbers in turn onto the stack. Finally, the text interpreter
                   1596: looks up the word @code{.s} and executes it. The effect of executing
                   1597: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
                   1598: followed by a list of all the items on the stack; the item on the far
                   1599: right-hand side is the TOS.
1.21      crook    1600: 
1.29      crook    1601: You can now type:
1.21      crook    1602: 
1.29      crook    1603: @example
1.30      anton    1604: @kbd{+ .s@key{RET}} <2> 1 5  ok
1.29      crook    1605: @end example
1.21      crook    1606: 
1.29      crook    1607: @noindent
                   1608: which is correct; there are now 2 items on the stack and the result of
                   1609: the addition is 5.
1.23      crook    1610: 
1.29      crook    1611: If you're playing with cards, try doing a second addition: pick up the
                   1612: two cards, work out that their sum is 6, shuffle them into the pack,
                   1613: look for a 6 and place that on the table. You now have just one item on
                   1614: the stack. What happens if you try to do a third addition? Pick up the
                   1615: first card, pick up the second card -- ah! There is no second card. This
                   1616: is called a @dfn{stack underflow} and consitutes an error. If you try to
                   1617: do the same thing with Forth it will report an error (probably a Stack
                   1618: Underflow or an Invalid Memory Address error).
1.23      crook    1619: 
1.29      crook    1620: The opposite situation to a stack underflow is a @dfn{stack overflow},
                   1621: which simply accepts that there is a finite amount of storage space
                   1622: reserved for the stack. To stretch the playing card analogy, if you had
                   1623: enough packs of cards and you piled the cards up on the table, you would
                   1624: eventually be unable to add another card; you'd hit the ceiling. Gforth
                   1625: allows you to set the maximum size of the stacks. In general, the only
                   1626: time that you will get a stack overflow is because a definition has a
                   1627: bug in it and is generating data on the stack uncontrollably.
1.23      crook    1628: 
1.29      crook    1629: There's one final use for the playing card analogy. If you model your
                   1630: stack using a pack of playing cards, the maximum number of items on
                   1631: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   1632: @i{value} of any item on the stack is 13 (the King). In fact, the only
                   1633: possible numbers are positive integer numbers 1 through 13; you can't
                   1634: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   1635: think about some of the cards, you can accommodate different
                   1636: numbers. For example, you could think of the Jack as representing 0,
                   1637: the Queen as representing -1 and the King as representing -2. Your
                   1638: *range* remains unchanged (you can still only represent a total of 13
                   1639: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    1640: 
1.29      crook    1641: In that analogy, the limit was the amount of information that a single
                   1642: stack entry could hold, and Forth has a similar limit. In Forth, the
                   1643: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
                   1644: implementation dependent and affects the maximum value that a stack
                   1645: entry can hold. A Standard Forth provides a cell size of at least
                   1646: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    1647: 
1.29      crook    1648: Forth does not do any type checking for you, so you are free to
                   1649: manipulate and combine stack items in any way you wish. A convenient way
                   1650: of treating stack items is as 2's complement signed integers, and that
                   1651: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    1652: 
1.29      crook    1653: @example
1.30      anton    1654: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
1.29      crook    1655: @end example
1.21      crook    1656: 
1.29      crook    1657: If you use numbers and definitions like @code{+} in order to turn Forth
                   1658: into a great big pocket calculator, you will realise that it's rather
                   1659: different from a normal calculator. Rather than typing 2 + 3 = you had
                   1660: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
                   1661: result). The terminology used to describe this difference is to say that
                   1662: your calculator uses @dfn{Infix Notation} (parameters and operators are
                   1663: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
                   1664: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    1665: 
1.29      crook    1666: Whilst postfix notation might look confusing to begin with, it has
                   1667: several important advantages:
1.21      crook    1668: 
1.23      crook    1669: @itemize @bullet
                   1670: @item
1.29      crook    1671: it is unambiguous
1.23      crook    1672: @item
1.29      crook    1673: it is more concise
1.23      crook    1674: @item
1.29      crook    1675: it fits naturally with a stack-based system
1.23      crook    1676: @end itemize
1.21      crook    1677: 
1.29      crook    1678: To examine these claims in more detail, consider these sums:
1.21      crook    1679: 
1.29      crook    1680: @example
                   1681: 6 + 5 * 4 =
                   1682: 4 * 5 + 6 =
                   1683: @end example
1.21      crook    1684: 
1.29      crook    1685: If you're just learning maths or your maths is very rusty, you will
                   1686: probably come up with the answer 44 for the first and 26 for the
                   1687: second. If you are a bit of a whizz at maths you will remember the
                   1688: @i{convention} that multiplication takes precendence over addition, and
                   1689: you'd come up with the answer 26 both times. To explain the answer 26
                   1690: to someone who got the answer 44, you'd probably rewrite the first sum
                   1691: like this:
1.21      crook    1692: 
1.29      crook    1693: @example
                   1694: 6 + (5 * 4) =
                   1695: @end example
1.21      crook    1696: 
1.29      crook    1697: If what you really wanted was to perform the addition before the
                   1698: multiplication, you would have to use parentheses to force it.
1.21      crook    1699: 
1.29      crook    1700: If you did the first two sums on a pocket calculator you would probably
                   1701: get the right answers, unless you were very cautious and entered them using
                   1702: these keystroke sequences:
1.21      crook    1703: 
1.29      crook    1704: 6 + 5 = * 4 =
                   1705: 4 * 5 = + 6 =
1.21      crook    1706: 
1.29      crook    1707: Postfix notation is unambiguous because the order that the operators
                   1708: are applied is always explicit; that also means that parentheses are
                   1709: never required. The operators are @i{active} (the act of quoting the
                   1710: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    1711: 
1.29      crook    1712: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   1713: equivalent ways:
1.26      crook    1714: 
                   1715: @example
1.29      crook    1716: 6 5 4 * +      or:
                   1717: 5 4 * 6 +
1.26      crook    1718: @end example
1.23      crook    1719: 
1.29      crook    1720: An important thing that you should notice about this notation is that
                   1721: the @i{order} of the numbers does not change; if you want to subtract
                   1722: 2 from 10 you type @code{10 2 -}.
1.1       anton    1723: 
1.29      crook    1724: The reason that Forth uses postfix notation is very simple to explain: it
                   1725: makes the implementation extremely simple, and it follows naturally from
                   1726: using the stack as a mechanism for passing parameters. Another way of
                   1727: thinking about this is to realise that all Forth definitions are
                   1728: @i{active}; they execute as they are encountered by the text
                   1729: interpreter. The result of this is that the syntax of Forth is trivially
                   1730: simple.
1.1       anton    1731: 
                   1732: 
                   1733: 
1.29      crook    1734: @comment ----------------------------------------------
                   1735: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   1736: @section Your first Forth definition
                   1737: @cindex first definition
1.1       anton    1738: 
1.29      crook    1739: Until now, the examples we've seen have been trivial; we've just been
                   1740: using Forth as a bigger-than-pocket calculator. Also, each calculation
                   1741: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
                   1742: again@footnote{That's not quite true. If you press the up-arrow key on
                   1743: your keyboard you should be able to scroll back to any earlier command,
                   1744: edit it and re-enter it.} In this section we'll see how to add new
                   1745: words to Forth's vocabulary.
1.1       anton    1746: 
1.29      crook    1747: The easiest way to create a new word is to use a @dfn{colon
                   1748: definition}. We'll define a few and try them out before worrying too
                   1749: much about how they work. Try typing in these examples; be careful to
                   1750: copy the spaces accurately:
1.1       anton    1751: 
1.29      crook    1752: @example
                   1753: : add-two 2 + . ;
                   1754: : greet ." Hello and welcome" ;
                   1755: : demo 5 add-two ;
                   1756: @end example
1.1       anton    1757: 
1.29      crook    1758: @noindent
                   1759: Now try them out:
1.1       anton    1760: 
1.29      crook    1761: @example
1.30      anton    1762: @kbd{greet@key{RET}} Hello and welcome  ok
                   1763: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
                   1764: @kbd{4 add-two@key{RET}} 6  ok
                   1765: @kbd{demo@key{RET}} 7  ok
                   1766: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
1.29      crook    1767: @end example
1.1       anton    1768: 
1.29      crook    1769: The first new thing that we've introduced here is the pair of words
                   1770: @code{:} and @code{;}. These are used to start and terminate a new
                   1771: definition, respectively. The first word after the @code{:} is the name
                   1772: for the new definition.
1.1       anton    1773: 
1.29      crook    1774: As you can see from the examples, a definition is built up of words that
                   1775: have already been defined; Forth makes no distinction between
                   1776: definitions that existed when you started the system up, and those that
                   1777: you define yourself.
1.1       anton    1778: 
1.29      crook    1779: The examples also introduce the words @code{.} (dot), @code{."}
                   1780: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
                   1781: the stack and displays it. It's like @code{.s} except that it only
                   1782: displays the top item of the stack and it is destructive; after it has
                   1783: executed, the number is no longer on the stack. There is always one
                   1784: space printed after the number, and no spaces before it. Dot-quote
                   1785: defines a string (a sequence of characters) that will be printed when
                   1786: the word is executed. The string can contain any printable characters
                   1787: except @code{"}. A @code{"} has a special function; it is not a Forth
                   1788: word but it acts as a delimiter (the way that delimiters work is
                   1789: described in the next section). Finally, @code{dup} duplicates the value
                   1790: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    1791: 
1.29      crook    1792: We already know that the text interpreter searches through the
                   1793: dictionary to locate names. If you've followed the examples earlier, you
                   1794: will already have a definition called @code{add-two}. Lets try modifying
                   1795: it by typing in a new definition:
1.1       anton    1796: 
1.29      crook    1797: @example
1.30      anton    1798: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
1.29      crook    1799: @end example
1.5       anton    1800: 
1.29      crook    1801: Forth recognised that we were defining a word that already exists, and
                   1802: printed a message to warn us of that fact. Let's try out the new
                   1803: definition:
1.5       anton    1804: 
1.29      crook    1805: @example
1.30      anton    1806: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
1.29      crook    1807: @end example
1.1       anton    1808: 
1.29      crook    1809: @noindent
                   1810: All that we've actually done here, though, is to create a new
                   1811: definition, with a particular name. The fact that there was already a
                   1812: definition with the same name did not make any difference to the way
                   1813: that the new definition was created (except that Forth printed a warning
                   1814: message). The old definition of add-two still exists (try @code{demo}
                   1815: again to see that this is true). Any new definition will use the new
                   1816: definition of @code{add-two}, but old definitions continue to use the
                   1817: version that already existed at the time that they were @code{compiled}.
1.1       anton    1818: 
1.29      crook    1819: Before you go on to the next section, try defining and redefining some
                   1820: words of your own.
1.1       anton    1821: 
1.29      crook    1822: @comment ----------------------------------------------
                   1823: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   1824: @section How does that work?
                   1825: @cindex parsing words
1.1       anton    1826: 
1.30      anton    1827: @c That's pretty deep (IMO way too deep) for an introduction. - anton
                   1828: 
                   1829: @c Is it a good idea to talk about the interpretation semantics of a
                   1830: @c number? We don't have an xt to go along with it. - anton
                   1831: 
                   1832: @c Now that I have eliminated execution semantics, I wonder if it would not
                   1833: @c be better to keep them (or add run-time semantics), to make it easier to
                   1834: @c explain what compilation semantics usually does. - anton
                   1835: 
1.29      crook    1836: Now we're going to take another look at the definition of @code{add-two}
                   1837: from the previous section. From our knowledge of the way that the text
                   1838: interpreter works, we would have expected this result when we tried to
                   1839: define @code{add-two}:
1.21      crook    1840: 
1.29      crook    1841: @example
1.30      anton    1842: @kbd{: add-two 2 + . " ;@key{RET}}
1.29      crook    1843:   ^^^^^^^
                   1844: Error: Undefined word
                   1845: @end example
1.28      crook    1846: 
1.29      crook    1847: The reason that this didn't happen is bound up in the way that @code{:}
                   1848: works. The word @code{:} does two special things. The first special
                   1849: thing that it does prevents the text interpreter from ever seeing the
                   1850: characters @code{add-two}. The text interpreter uses a variable called
                   1851: @cindex modifying >IN
                   1852: @code{>IN} (pronounced ''to-in'') to keep track of where it is in the
                   1853: input line. When it encounters the word @code{:} it behaves in exactly
                   1854: the same way as it does for any other word; it looks it up in the name
                   1855: dictionary, finds its xt and executes it. When @code{:} executes, it
                   1856: looks at the input buffer, finds the word @code{add-two} and advances the
                   1857: value of @code{>IN} to point past it. It then does some other stuff
                   1858: associated with creating the new definition (including creating an entry
                   1859: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   1860: completes, control returns to the text interpreter, which is oblivious
                   1861: to the fact that it has been tricked into ignoring part of the input
                   1862: line.
1.21      crook    1863: 
1.29      crook    1864: @cindex parsing words
                   1865: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   1866: prevent the text interpreter from acting on the whole of the input line
                   1867: -- are called @dfn{parsing words}.
1.21      crook    1868: 
1.29      crook    1869: @cindex @code{state} - effect on the text interpreter
                   1870: @cindex text interpreter - effect of state
                   1871: The second special thing that @code{:} does is change the value of a
                   1872: variable called @code{state}, which affects the way that the text
                   1873: interpreter behaves. When Gforth starts up, @code{state} has the value
                   1874: 0, and the text interpreter is said to be @dfn{interpreting}. During a
                   1875: colon definition (started with @code{:}), @code{state} is set to -1 and
                   1876: the text interpreter is said to be @dfn{compiling}. The word @code{;}
                   1877: ends the definition -- one of the things that it does is to change the
                   1878: value of @code{state} back to 0.
1.21      crook    1879: 
1.29      crook    1880: We have already seen how the text interpreter behaves when it is
                   1881: interpreting; it looks for each character sequence in the dictionary,
                   1882: finds its xt and executes it, or it converts it to a number and pushes
                   1883: it onto the stack, or it fails to do either and generates an error.
1.21      crook    1884: 
1.29      crook    1885: When the text interpreter is compiling, its behaviour is slightly
                   1886: different; it still looks for each character sequence in the dictionary
1.30      anton    1887: and finds it, or converts it to a number, or fails to do either and
                   1888: generates an error.  But instead of the execution token of a word it
                   1889: finds and executes the compilation token.  For most words executing the
                   1890: compilation token results in laying down (@dfn{compiling}) the execution
                   1891: token, i.e., some magic to make that xt or number get executed or pushed
                   1892: at a later time; at the time that @code{add-two} is
                   1893: @dfn{executed}. Therefore, when you execute @code{add-two} its
                   1894: @dfn{run-time effect} is exactly the same as if you had typed @code{2 +
                   1895: .} outside of a definition, and pressed carriage-return.
1.28      crook    1896: 
1.30      anton    1897: In Forth, every word or number can be described in terms of two
1.29      crook    1898: properties:
1.28      crook    1899: 
                   1900: @itemize @bullet
                   1901: @item
1.30      anton    1902: Its @dfn{interpretation semantics}, represented by the execution token.
1.28      crook    1903: @item
1.30      anton    1904: Its @dfn{compilation semantics}, represented by the compilation token.
1.29      crook    1905: @end itemize
                   1906: 
1.30      anton    1907: The value of @code{state} determines whether the text interpreter will
                   1908: use the compilation or interpretation semantics of a word or number that
                   1909: it encounters.
1.29      crook    1910: 
                   1911: @itemize @bullet
1.28      crook    1912: @item
1.29      crook    1913: @cindex interpretation semantics
                   1914: When the text interpreter encounters a word or number in @dfn{interpret}
                   1915: state, it performs the @dfn{interpretation semantics} of the word or
                   1916: number.
1.28      crook    1917: @item
1.29      crook    1918: @cindex compilation semantics
                   1919: When the text interpreter encounters a word or number in @dfn{compile}
                   1920: state, it performs the @dfn{compilation semantics} of the word or
                   1921: number.
                   1922: @end itemize
                   1923: 
                   1924: @noindent
                   1925: Numbers are always treated in a fixed way:
                   1926: 
                   1927: @itemize @bullet
1.28      crook    1928: @item
1.30      anton    1929: When the number is @dfn{interpreted}, its behaviour is to push the number onto the stack.
1.28      crook    1930: @item
1.30      anton    1931: When the number is @dfn{compiled}, a piece of code is appended to the
                   1932: current definition that pushes the number when it runs. (In other words,
                   1933: the compilation semantics of a number are to postpone its interpretation
                   1934: semantics until the run-time of the definition that it is being compiled
                   1935: into.)
1.29      crook    1936: @end itemize
                   1937: 
                   1938: The behaviour of a word is not so regular, but most have @i{default
1.30      anton    1939: compilation semantics} which means that they behave like this:
1.29      crook    1940: 
                   1941: @itemize @bullet
1.28      crook    1942: @item
1.30      anton    1943: The @dfn{interpretation semantics} of the word are to do something useful.
                   1944: @item
1.29      crook    1945: The @dfn{compilation semantics} of the word are to append its
1.30      anton    1946: @dfn{interpretation semantics} to the current definition (so that its
                   1947: run-time behaviour is to do something useful).
1.28      crook    1948: @end itemize
                   1949: 
1.30      anton    1950: @cindex immediate words
1.29      crook    1951: The actual behaviour of any particular word depends upon the way in
                   1952: which it was defined. When the text interpreter finds the word in the
                   1953: name dictionary, it not only retrieves the xt for the word, it also
                   1954: retrieves some flags: the @dfn{compile-only} flag and the @dfn{immediate
                   1955: flag}. The compile-only flag indicates that the word has no
1.30      anton    1956: interpretation semantics (the run-time behaviour for the default
                   1957: compilation semantics is not affected by this flag, however); any
                   1958: attempt to interpret a word that has the compile-only flag set will
                   1959: generate an error (for example, @code{IF} has no interpretation
                   1960: semantics). The immediate flag changes the compilation semantics of the
                   1961: word; if it is set, the compilation semantics are equal to the
                   1962: interpretation semantics (again ignoring the compile-only flag).  it. In
                   1963: other words, these so-called @dfn{immediate} words behave like this:
1.29      crook    1964: 
                   1965: @itemize @bullet
                   1966: @item
1.30      anton    1967: The @dfn{interpretation semantics} of the word are to do something useful.
1.29      crook    1968: @item
1.30      anton    1969: The @dfn{compilation semantics} of the word are to do something useful
                   1970: (and actually the same thing); i.e., it is executed during compilation.
1.29      crook    1971: @end itemize
1.28      crook    1972: 
1.29      crook    1973: This example shows the difference between an immediate and a
                   1974: non-immediate word:
1.28      crook    1975: 
1.29      crook    1976: @example
                   1977: : show-state state @@ . ;
                   1978: : show-state-now show-state ; immediate
                   1979: : word1 show-state ;
                   1980: : word2 show-state-now ;
1.28      crook    1981: @end example
1.23      crook    1982: 
1.29      crook    1983: The word @code{immediate} after the definition of @code{show-state-now}
                   1984: makes that word an immediate word. These definitions introduce a new
                   1985: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
                   1986: variable, and leaves it on the stack. Therefore, the behaviour of
                   1987: @code{show-state} is to print a number that represents the current value
                   1988: of @code{state}.
1.28      crook    1989: 
1.29      crook    1990: When you execute @code{word1}, it prints the number 0, indicating that
                   1991: the system is interpreting. When the text interpreter compiled the
                   1992: definition of @code{word1}, it encountered @code{show-state} whose
1.30      anton    1993: compilation semantics are to append its interpretation semantics to the
1.29      crook    1994: current definition. When you execute @code{word1}, it performs the
1.30      anton    1995: interpretation semantics of @code{show-state}.  At the time that @code{word1}
1.29      crook    1996: (and therefore @code{show-state}) are executed, the system is
                   1997: interpreting.
1.28      crook    1998: 
1.30      anton    1999: When you pressed @key{RET} after entering the definition of @code{word2},
1.29      crook    2000: you should have seen the number -1 printed, followed by ``@code{
                   2001: ok}''. When the text interpreter compiled the definition of
                   2002: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30      anton    2003: whose compilation semantics are therefore to perform its interpretation
1.29      crook    2004: semantics. It is executed straight away (even before the text
                   2005: interpreter has moved on to process another group of characters; the
                   2006: @code{;} in this example). The effect of executing it are to display the
                   2007: value of @code{state} @i{at the time that the definition of}
                   2008: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
                   2009: system is compiling at this time. If you execute @code{word2} it does
                   2010: nothing at all.
1.28      crook    2011: 
1.29      crook    2012: @cindex @code{."}, how it works
                   2013: Before leaving the subject of immediate words, consider the behaviour of
                   2014: @code{."} in the definition of @code{greet}, in the previous
                   2015: section. This word is both a parsing word and an immediate word. Notice
                   2016: that there is a space between @code{."} and the start of the text
                   2017: @code{Hello and welcome}, but that there is no space between the last
                   2018: letter of @code{welcome} and the @code{"} character. The reason for this
                   2019: is that @code{."} is a Forth word; it must have a space after it so that
                   2020: the text interpreter can identify it. The @code{"} is not a Forth word;
                   2021: it is a @dfn{delimiter}. The examples earlier show that, when the string
                   2022: is displayed, there is neither a space before the @code{H} nor after the
                   2023: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   2024: that @code{greet} is defined. When it executes, its behaviour is to
                   2025: search forward in the input line looking for the delimiter. When it
                   2026: finds the delimiter, it updates @code{>IN} to point past the
                   2027: delimiter. It also compiles some magic code into the definition of
                   2028: @code{greet}; the xt of a run-time routine that prints a text string. It
                   2029: compiles the string @code{Hello and welcome} into memory so that it is
                   2030: available to be printed later. When the text interpreter gains control,
                   2031: the next word it finds in the input stream is @code{;} and so it
                   2032: terminates the definition of @code{greet}.
1.28      crook    2033: 
                   2034: 
                   2035: @comment ----------------------------------------------
1.29      crook    2036: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   2037: @section Forth is written in Forth
                   2038: @cindex structure of Forth programs
                   2039: 
                   2040: When you start up a Forth compiler, a large number of definitions
                   2041: already exist. In Forth, you develop a new application using bottom-up
                   2042: programming techniques to create new definitions that are defined in
                   2043: terms of existing definitions. As you create each definition you can
                   2044: test and debug it interactively.
                   2045: 
                   2046: If you have tried out the examples in this section, you will probably
                   2047: have typed them in by hand; when you leave Gforth, your definitions will
                   2048: be lost. You can avoid this by using a text editor to enter Forth source
                   2049: code into a file, and then loading code from the file using
                   2050: @code{include} (@xref{Forth source files}). A Forth source file is
                   2051: processed by the text interpreter, just as though you had typed it in by
                   2052: hand@footnote{Actually, there are some subtle differences -- see
                   2053: @ref{The Text Interpreter}.}.
                   2054: 
                   2055: Gforth also supports the traditional Forth alternative to using text
                   2056: files for program entry (@xref{Blocks}).
1.28      crook    2057: 
1.29      crook    2058: In common with many, if not most, Forth compilers, most of Gforth is
                   2059: actually written in Forth. All of the @file{.fs} files in the
                   2060: installation directory@footnote{For example,
1.30      anton    2061: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29      crook    2062: study to see examples of Forth programming.
1.28      crook    2063: 
1.29      crook    2064: Gforth maintains a history file that records every line that you type to
                   2065: the text interpreter. This file is preserved between sessions, and is
                   2066: used to provide a command-line recall facility. If you enter long
                   2067: definitions by hand, you can use a text editor to paste them out of the
                   2068: history file into a Forth source file for reuse at a later time
                   2069: (@pxref{Command-line editing} for more information).
1.28      crook    2070: 
                   2071: 
                   2072: @comment ----------------------------------------------
1.29      crook    2073: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
                   2074: @section Review - elements of a Forth system
                   2075: @cindex elements of a Forth system
1.28      crook    2076: 
1.29      crook    2077: To summarise this chapter:
1.28      crook    2078: 
                   2079: @itemize @bullet
                   2080: @item
1.29      crook    2081: Forth programs use @dfn{factoring} to break a problem down into small
                   2082: fragments called @dfn{words} or @dfn{definitions}.
                   2083: @item
                   2084: Forth program development is an interactive process.
                   2085: @item
                   2086: The main command loop that accepts input, and controls both
                   2087: interpretation and compilation, is called the @dfn{text interpreter}
                   2088: (also known as the @dfn{outer interpreter}).
                   2089: @item
                   2090: Forth has a very simple syntax, consisting of words and numbers
                   2091: separated by spaces or carriage-return characters. Any additional syntax
                   2092: is imposed by @dfn{parsing words}.
                   2093: @item
                   2094: Forth uses a stack to pass parameters between words. As a result, it
                   2095: uses postfix notation.
                   2096: @item
                   2097: To use a word that has previously been defined, the text interpreter
                   2098: searches for the word in the @dfn{name dictionary}.
                   2099: @item
1.30      anton    2100: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28      crook    2101: @item
1.29      crook    2102: The text interpreter uses the value of @code{state} to select between
                   2103: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
                   2104: semantics} of a word that it encounters.
1.28      crook    2105: @item
1.30      anton    2106: The relationship between the @dfn{interpretation semantics} and
                   2107: @dfn{compilation semantics} for a word
1.29      crook    2108: depend upon the way in which the word was defined (for example, whether
                   2109: it is an @dfn{immediate} word).
1.28      crook    2110: @item
1.29      crook    2111: Forth definitions can be implemented in Forth (called @dfn{high-level
                   2112: definitions}) or in some other way (usually a lower-level language and
                   2113: as a result often called @dfn{low-level definitions}, @dfn{code
                   2114: definitions} or @dfn{primitives}).
1.28      crook    2115: @item
1.29      crook    2116: Many Forth systems are implemented mainly in Forth.
1.28      crook    2117: @end itemize
                   2118: 
                   2119: 
1.29      crook    2120: @comment ----------------------------------------------
                   2121: @node Where to go next,Exercises,Review - elements of a Forth system, Introduction
                   2122: @section Where To Go Next
                   2123: @cindex where to go next
1.28      crook    2124: 
1.29      crook    2125: Amazing as it may seem, if you have read (and understood) this far, you
                   2126: know almost all the fundamentals about the inner workings of a Forth
                   2127: system. You certainly know enough to be able to read and understand the
                   2128: rest of this manual and the ANS Forth document, to learn more about the
                   2129: facilities that Forth in general and Gforth in particular provide. Even
                   2130: scarier, you know almost enough to implement your own Forth system.
1.30      anton    2131: However, that's not a good idea just yet... better to try writing some
1.29      crook    2132: programs in Gforth.
1.28      crook    2133: 
1.29      crook    2134: Forth has such a rich vocabulary that it can be hard to know where to
                   2135: start in learning it. This section suggests a few sets of words that are
                   2136: enough to write small but useful programs. Use the word index in this
                   2137: document to learn more about each word, then try it out and try to write
                   2138: small definitions using it. Start by experimenting with these words:
1.28      crook    2139: 
                   2140: @itemize @bullet
                   2141: @item
1.29      crook    2142: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
                   2143: @item
                   2144: Comparison: @code{MIN MAX =}
                   2145: @item
                   2146: Logic: @code{AND OR XOR NOT}
                   2147: @item
                   2148: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    2149: @item
1.29      crook    2150: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    2151: @item
1.29      crook    2152: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    2153: @item
1.29      crook    2154: Defining words: @code{: ; CREATE}
1.28      crook    2155: @item
1.29      crook    2156: Memory allocation words: @code{ALLOT ,}
1.28      crook    2157: @item
1.29      crook    2158: Tools: @code{SEE WORDS .S MARKER}
                   2159: @end itemize
                   2160: 
                   2161: When you have mastered those, go on to:
                   2162: 
                   2163: @itemize @bullet
1.28      crook    2164: @item
1.29      crook    2165: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    2166: @item
1.29      crook    2167: Memory access: @code{@@ !}
1.28      crook    2168: @end itemize
1.23      crook    2169: 
1.29      crook    2170: When you have mastered these, there's nothing for it but to read through
                   2171: the whole of this manual and find out what you've missed.
                   2172: 
                   2173: @comment ----------------------------------------------
                   2174: @node Exercises, ,Where to go next, Introduction
                   2175: @section Exercises
                   2176: @cindex exercises
                   2177: 
                   2178: TODO: provide a set of programming excercises linked into the stuff done
                   2179: already and into other sections of the manual. Provide solutions to all
                   2180: the exercises in a .fs file in the distribution.
                   2181: 
                   2182: @c Get some inspiration from Starting Forth and Kelly&Spies.
                   2183: 
                   2184: @c excercises:
                   2185: @c 1. take inches and convert to feet and inches.
                   2186: @c 2. take temperature and convert from fahrenheight to celcius;
                   2187: @c    may need to care about symmetric vs floored??
                   2188: @c 3. take input line and do character substitution
                   2189: @c    to encipher or decipher
                   2190: @c 4. as above but work on a file for in and out
                   2191: @c 5. take input line and convert to pig-latin 
                   2192: @c
                   2193: @c thing of sets of things to exercise then come up with
                   2194: @c problems that need those things.
                   2195: 
                   2196: 
1.26      crook    2197: @c ******************************************************************
1.29      crook    2198: @node Words, Error messages, Introduction, Top
1.1       anton    2199: @chapter Forth Words
1.26      crook    2200: @cindex words
1.1       anton    2201: 
                   2202: @menu
                   2203: * Notation::                    
1.21      crook    2204: * Comments::
                   2205: * Boolean Flags::
1.1       anton    2206: * Arithmetic::                  
                   2207: * Stack Manipulation::          
1.5       anton    2208: * Memory::                      
1.1       anton    2209: * Control Structures::          
                   2210: * Defining Words::              
1.21      crook    2211: * The Text Interpreter::
1.12      anton    2212: * Tokens for Words::            
1.21      crook    2213: * Word Lists::                   
                   2214: * Environmental Queries::
1.12      anton    2215: * Files::                       
                   2216: * Blocks::                      
                   2217: * Other I/O::                   
                   2218: * Programming Tools::           
                   2219: * Assembler and Code Words::    
                   2220: * Threading Words::             
1.26      crook    2221: * Locals::                      
                   2222: * Structures::                  
                   2223: * Object-oriented Forth::       
1.21      crook    2224: * Passing Commands to the OS::
                   2225: * Miscellaneous Words::
1.1       anton    2226: @end menu
                   2227: 
1.21      crook    2228: @node Notation, Comments, Words, Words
1.1       anton    2229: @section Notation
                   2230: @cindex notation of glossary entries
                   2231: @cindex format of glossary entries
                   2232: @cindex glossary notation format
                   2233: @cindex word glossary entry format
                   2234: 
                   2235: The Forth words are described in this section in the glossary notation
                   2236: that has become a de-facto standard for Forth texts, i.e.,
                   2237: 
                   2238: @format
1.29      crook    2239: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    2240: @end format
1.29      crook    2241: @i{Description}
1.1       anton    2242: 
                   2243: @table @var
                   2244: @item word
1.28      crook    2245: The name of the word.
1.1       anton    2246: 
                   2247: @item Stack effect
                   2248: @cindex stack effect
1.29      crook    2249: The stack effect is written in the notation @code{@i{before} --
                   2250: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    2251: stack entries before and after the execution of the word. The rest of
                   2252: the stack is not touched by the word. The top of stack is rightmost,
                   2253: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   2254: uses a separate floating point stack, but a unified stack
1.29      crook    2255: notation. Also, return stack effects are not shown in @i{stack
                   2256: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    2257: the type and/or the function of the item. See below for a discussion of
                   2258: the types.
                   2259: 
                   2260: All words have two stack effects: A compile-time stack effect and a
                   2261: run-time stack effect. The compile-time stack-effect of most words is
1.29      crook    2262: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    2263: this standard behaviour, or the word does other unusual things at
                   2264: compile time, both stack effects are shown; otherwise only the run-time
                   2265: stack effect is shown.
                   2266: 
                   2267: @cindex pronounciation of words
                   2268: @item pronunciation
                   2269: How the word is pronounced.
                   2270: 
                   2271: @cindex wordset
                   2272: @item wordset
1.21      crook    2273: The ANS Forth standard is divided into several word sets. A standard
                   2274: system need not support all of them. Therefore, in theory, the fewer
                   2275: word sets your program uses the more portable it will be. However, we
                   2276: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    2277: all word sets. Words that are not defined in ANS Forth have
1.21      crook    2278: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    2279: describes words that will work in future releases of Gforth;
                   2280: @code{gforth-internal} words are more volatile. Environmental query
                   2281: strings are also displayed like words; you can recognize them by the
1.21      crook    2282: @code{environment} in the word set field.
1.1       anton    2283: 
                   2284: @item Description
                   2285: A description of the behaviour of the word.
                   2286: @end table
                   2287: 
                   2288: @cindex types of stack items
                   2289: @cindex stack item types
                   2290: The type of a stack item is specified by the character(s) the name
                   2291: starts with:
                   2292: 
                   2293: @table @code
                   2294: @item f
                   2295: @cindex @code{f}, stack item type
                   2296: Boolean flags, i.e. @code{false} or @code{true}.
                   2297: @item c
                   2298: @cindex @code{c}, stack item type
                   2299: Char
                   2300: @item w
                   2301: @cindex @code{w}, stack item type
                   2302: Cell, can contain an integer or an address
                   2303: @item n
                   2304: @cindex @code{n}, stack item type
                   2305: signed integer
                   2306: @item u
                   2307: @cindex @code{u}, stack item type
                   2308: unsigned integer
                   2309: @item d
                   2310: @cindex @code{d}, stack item type
                   2311: double sized signed integer
                   2312: @item ud
                   2313: @cindex @code{ud}, stack item type
                   2314: double sized unsigned integer
                   2315: @item r
                   2316: @cindex @code{r}, stack item type
                   2317: Float (on the FP stack)
1.21      crook    2318: @item a-
1.1       anton    2319: @cindex @code{a_}, stack item type
                   2320: Cell-aligned address
1.21      crook    2321: @item c-
1.1       anton    2322: @cindex @code{c_}, stack item type
                   2323: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    2324: @item f-
1.1       anton    2325: @cindex @code{f_}, stack item type
                   2326: Float-aligned address
1.21      crook    2327: @item df-
1.1       anton    2328: @cindex @code{df_}, stack item type
                   2329: Address aligned for IEEE double precision float
1.21      crook    2330: @item sf-
1.1       anton    2331: @cindex @code{sf_}, stack item type
                   2332: Address aligned for IEEE single precision float
                   2333: @item xt
                   2334: @cindex @code{xt}, stack item type
                   2335: Execution token, same size as Cell
                   2336: @item wid
                   2337: @cindex @code{wid}, stack item type
1.21      crook    2338: Word list ID, same size as Cell
1.1       anton    2339: @item f83name
                   2340: @cindex @code{f83name}, stack item type
                   2341: Pointer to a name structure
                   2342: @item "
                   2343: @cindex @code{"}, stack item type
1.12      anton    2344: string in the input stream (not on the stack). The terminating character
                   2345: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    2346: quotes.
                   2347: @end table
                   2348: 
1.21      crook    2349: @node Comments, Boolean Flags, Notation, Words
                   2350: @section Comments
1.26      crook    2351: @cindex comments
1.21      crook    2352: 
1.29      crook    2353: Forth supports two styles of comment; the traditional @i{in-line} comment,
                   2354: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    2355: 
1.23      crook    2356: doc-(
1.21      crook    2357: doc-\
1.23      crook    2358: doc-\G
1.21      crook    2359: 
                   2360: @node Boolean Flags, Arithmetic, Comments, Words
                   2361: @section Boolean Flags
1.26      crook    2362: @cindex Boolean flags
1.21      crook    2363: 
                   2364: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   2365: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    2366: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29      crook    2367: a cell that has @i{any} bit set as @code{true}.
1.21      crook    2368: 
                   2369: doc-true
                   2370: doc-false
1.29      crook    2371: doc-on
                   2372: doc-off
1.21      crook    2373: 
                   2374: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    2375: @section Arithmetic
                   2376: @cindex arithmetic words
                   2377: 
                   2378: @cindex division with potentially negative operands
                   2379: Forth arithmetic is not checked, i.e., you will not hear about integer
                   2380: overflow on addition or multiplication, you may hear about division by
                   2381: zero if you are lucky. The operator is written after the operands, but
                   2382: the operands are still in the original order. I.e., the infix @code{2-1}
                   2383: corresponds to @code{2 1 -}. Forth offers a variety of division
                   2384: operators. If you perform division with potentially negative operands,
                   2385: you do not want to use @code{/} or @code{/mod} with its undefined
                   2386: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   2387: former, @pxref{Mixed precision}).
1.26      crook    2388: @comment TODO discuss the different division forms and the std approach
1.1       anton    2389: 
                   2390: @menu
                   2391: * Single precision::            
                   2392: * Bitwise operations::          
1.21      crook    2393: * Double precision::            Double-cell integer arithmetic
                   2394: * Numeric comparison::
1.29      crook    2395: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    2396: * Floating Point::              
                   2397: @end menu
                   2398: 
                   2399: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
                   2400: @subsection Single precision
                   2401: @cindex single precision arithmetic words
                   2402: 
1.21      crook    2403: By default, numbers in Forth are single-precision integers that are 1
1.26      crook    2404: cell in size. They can be signed or unsigned, depending upon how you
1.21      crook    2405: treat them. @xref{Number Conversion} for the rules used by the text
                   2406: interpreter for recognising single-precision integers.
                   2407: 
1.1       anton    2408: doc-+
1.21      crook    2409: doc-1+
1.1       anton    2410: doc--
1.21      crook    2411: doc-1-
1.1       anton    2412: doc-*
                   2413: doc-/
                   2414: doc-mod
                   2415: doc-/mod
                   2416: doc-negate
                   2417: doc-abs
                   2418: doc-min
                   2419: doc-max
1.21      crook    2420: doc-d>s
1.27      crook    2421: doc-floored
1.1       anton    2422: 
1.21      crook    2423: @node Bitwise operations, Double precision, Single precision, Arithmetic
1.1       anton    2424: @subsection Bitwise operations
                   2425: @cindex bitwise operation words
                   2426: 
                   2427: doc-and
                   2428: doc-or
                   2429: doc-xor
                   2430: doc-invert
1.21      crook    2431: doc-lshift
                   2432: doc-rshift
1.1       anton    2433: doc-2*
1.21      crook    2434: doc-d2*
1.1       anton    2435: doc-2/
1.21      crook    2436: doc-d2/
                   2437: 
                   2438: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
                   2439: @subsection Double precision
                   2440: @cindex double precision arithmetic words
                   2441: 
                   2442: @xref{Number Conversion} for the rules used by the text interpreter for
                   2443: recognising double-precision integers.
                   2444: 
                   2445: A double precision number is represented by a cell pair, with the most
1.31      anton    2446: significant cell at the TOS. It is trivial to convert an unsigned
1.26      crook    2447: single to an (unsigned) double; simply push a @code{0} onto the
                   2448: TOS. Since numbers are represented by Gforth using 2's complement
                   2449: arithmetic, converting a signed single to a (signed) double requires
1.31      anton    2450: sign-extension across the most significant cell. This can be achieved
1.26      crook    2451: using @code{s>d}. The moral of the story is that you cannot convert a
                   2452: number without knowing whether it represents an unsigned or a
                   2453: signed number.
1.21      crook    2454: 
                   2455: doc-s>d
                   2456: doc-d+
                   2457: doc-d-
                   2458: doc-dnegate
                   2459: doc-dabs
                   2460: doc-dmin
                   2461: doc-dmax
                   2462: 
                   2463: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
                   2464: @subsection Numeric comparison
                   2465: @cindex numeric comparison words
                   2466: 
1.28      crook    2467: doc-<
                   2468: doc-<=
                   2469: doc-<>
                   2470: doc-=
                   2471: doc->
                   2472: doc->=
                   2473: 
1.21      crook    2474: doc-0<
1.23      crook    2475: doc-0<=
1.21      crook    2476: doc-0<>
                   2477: doc-0=
1.23      crook    2478: doc-0>
                   2479: doc-0>=
1.28      crook    2480: 
                   2481: doc-u<
                   2482: doc-u<=
1.31      anton    2483: @c TODO why u<> and u= ... they are the same as <> and =
                   2484: @c commented them out because they are unnecessary
                   2485: @c doc-u<>
                   2486: @c doc-u=
1.28      crook    2487: doc-u>
                   2488: doc-u>=
                   2489: 
                   2490: doc-within
                   2491: 
                   2492: doc-d<
                   2493: doc-d<=
                   2494: doc-d<>
                   2495: doc-d=
                   2496: doc-d>
                   2497: doc-d>=
1.23      crook    2498: 
1.21      crook    2499: doc-d0<
1.23      crook    2500: doc-d0<=
                   2501: doc-d0<>
1.21      crook    2502: doc-d0=
1.23      crook    2503: doc-d0>
                   2504: doc-d0>=
                   2505: 
1.21      crook    2506: doc-du<
1.28      crook    2507: doc-du<=
1.31      anton    2508: @c doc-du<>
                   2509: @c doc-du=
1.28      crook    2510: doc-du>
                   2511: doc-du>=
1.1       anton    2512: 
1.21      crook    2513: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    2514: @subsection Mixed precision
                   2515: @cindex mixed precision arithmetic words
                   2516: 
                   2517: doc-m+
                   2518: doc-*/
                   2519: doc-*/mod
                   2520: doc-m*
                   2521: doc-um*
                   2522: doc-m*/
                   2523: doc-um/mod
                   2524: doc-fm/mod
                   2525: doc-sm/rem
                   2526: 
1.21      crook    2527: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    2528: @subsection Floating Point
                   2529: @cindex floating point arithmetic words
                   2530: 
1.21      crook    2531: @xref{Number Conversion} for the rules used by the text interpreter for
                   2532: recognising floating-point numbers.
1.1       anton    2533: 
1.32      anton    2534: Gforth has a separate floating point
1.26      crook    2535: stack, but the documentation uses the unified notation.
1.1       anton    2536: 
                   2537: @cindex floating-point arithmetic, pitfalls
                   2538: Floating point numbers have a number of unpleasant surprises for the
                   2539: unwary (e.g., floating point addition is not associative) and even a few
                   2540: for the wary. You should not use them unless you know what you are doing
                   2541: or you don't care that the results you get are totally bogus. If you
                   2542: want to learn about the problems of floating point numbers (and how to
                   2543: avoid them), you might start with @cite{David Goldberg, What Every
                   2544: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
1.17      anton    2545: Computing Surveys 23(1):5@minus{}48, March 1991}
                   2546: (@url{http://www.validgh.com/goldberg/paper.ps}).
1.1       anton    2547: 
1.21      crook    2548: doc-d>f
                   2549: doc-f>d
1.1       anton    2550: doc-f+
                   2551: doc-f-
                   2552: doc-f*
                   2553: doc-f/
                   2554: doc-fnegate
                   2555: doc-fabs
                   2556: doc-fmax
                   2557: doc-fmin
                   2558: doc-floor
                   2559: doc-fround
                   2560: doc-f**
                   2561: doc-fsqrt
                   2562: doc-fexp
                   2563: doc-fexpm1
                   2564: doc-fln
                   2565: doc-flnp1
                   2566: doc-flog
                   2567: doc-falog
1.32      anton    2568: doc-f2*
                   2569: doc-f2/
                   2570: doc-1/f
                   2571: doc-precision
                   2572: doc-set-precision
                   2573: 
                   2574: @cindex angles in trigonometric operations
                   2575: @cindex trigonometric operations
                   2576: Angles in floating point operations are given in radians (a full circle
                   2577: has 2 pi radians).
                   2578: 
1.1       anton    2579: doc-fsin
                   2580: doc-fcos
                   2581: doc-fsincos
                   2582: doc-ftan
                   2583: doc-fasin
                   2584: doc-facos
                   2585: doc-fatan
                   2586: doc-fatan2
                   2587: doc-fsinh
                   2588: doc-fcosh
                   2589: doc-ftanh
                   2590: doc-fasinh
                   2591: doc-facosh
                   2592: doc-fatanh
1.21      crook    2593: doc-pi
1.28      crook    2594: 
1.32      anton    2595: @cindex equality of floats
                   2596: @cindex floating-point comparisons
1.31      anton    2597: One particular problem with floating-point arithmetic is that comparison
                   2598: for equality often fails when you would expect it to succeed.  For this
                   2599: reason approximate equality is often preferred (but you still have to
                   2600: know what you are doing).  The comparison words are:
                   2601: 
                   2602: doc-f~rel
                   2603: doc-f~abs
                   2604: doc-f=
                   2605: doc-f~
                   2606: doc-f<>
                   2607: 
                   2608: doc-f<
                   2609: doc-f<=
                   2610: doc-f>
                   2611: doc-f>=
                   2612: 
1.21      crook    2613: doc-f0<
1.28      crook    2614: doc-f0<=
                   2615: doc-f0<>
1.21      crook    2616: doc-f0=
1.28      crook    2617: doc-f0>
                   2618: doc-f0>=
                   2619: 
1.1       anton    2620: 
                   2621: @node Stack Manipulation, Memory, Arithmetic, Words
                   2622: @section Stack Manipulation
                   2623: @cindex stack manipulation words
                   2624: 
                   2625: @cindex floating-point stack in the standard
1.21      crook    2626: Gforth maintains a number of separate stacks:
                   2627: 
1.29      crook    2628: @cindex data stack
                   2629: @cindex parameter stack
1.21      crook    2630: @itemize @bullet
                   2631: @item
1.29      crook    2632: A data stack (also known as the @dfn{parameter stack}) -- for
                   2633: characters, cells, addresses, and double cells.
1.21      crook    2634: 
1.29      crook    2635: @cindex floating-point stack
1.21      crook    2636: @item
                   2637: A floating point stack -- for floating point numbers.
                   2638: 
1.29      crook    2639: @cindex return stack
1.21      crook    2640: @item
                   2641: A return stack -- for storing the return addresses of colon
1.32      anton    2642: definitions and other (non-FP) data.
1.21      crook    2643: 
1.29      crook    2644: @cindex locals stack
1.21      crook    2645: @item
                   2646: A locals stack for storing local variables.
                   2647: @end itemize
                   2648: 
1.1       anton    2649: @menu
                   2650: * Data stack::                  
                   2651: * Floating point stack::        
                   2652: * Return stack::                
                   2653: * Locals stack::                
                   2654: * Stack pointer manipulation::  
                   2655: @end menu
                   2656: 
                   2657: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   2658: @subsection Data stack
                   2659: @cindex data stack manipulation words
                   2660: @cindex stack manipulations words, data stack
                   2661: 
                   2662: doc-drop
                   2663: doc-nip
                   2664: doc-dup
                   2665: doc-over
                   2666: doc-tuck
                   2667: doc-swap
1.21      crook    2668: doc-pick
1.1       anton    2669: doc-rot
                   2670: doc--rot
                   2671: doc-?dup
                   2672: doc-roll
                   2673: doc-2drop
                   2674: doc-2nip
                   2675: doc-2dup
                   2676: doc-2over
                   2677: doc-2tuck
                   2678: doc-2swap
                   2679: doc-2rot
                   2680: 
                   2681: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   2682: @subsection Floating point stack
                   2683: @cindex floating-point stack manipulation words
                   2684: @cindex stack manipulation words, floating-point stack
                   2685: 
1.32      anton    2686: Whilst every sane Forth has a separate floating-point stack, it is not
                   2687: strictly required; an ANS Forth system could theoretically keep
                   2688: floating-point numbers on the data stack. As an additional difficulty,
                   2689: you don't know how many cells a floating-point number takes. It is
                   2690: reportedly possible to write words in a way that they work also for a
                   2691: unified stack model, but we do not recommend trying it. Instead, just
                   2692: say that your program has an environmental dependency on a separate
                   2693: floating-point stack.
                   2694: 
                   2695: doc-floating-stack
                   2696: 
1.1       anton    2697: doc-fdrop
                   2698: doc-fnip
                   2699: doc-fdup
                   2700: doc-fover
                   2701: doc-ftuck
                   2702: doc-fswap
1.21      crook    2703: doc-fpick
1.1       anton    2704: doc-frot
                   2705: 
                   2706: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   2707: @subsection Return stack
                   2708: @cindex return stack manipulation words
                   2709: @cindex stack manipulation words, return stack
                   2710: 
1.32      anton    2711: @cindex return stack and locals
                   2712: @cindex locals and return stack
                   2713: A Forth system is allowed to keep local variables on the
                   2714: return stack. This is reasonable, as local variables usually eliminate
                   2715: the need to use the return stack explicitly. So, if you want to produce
                   2716: a standard compliant program and you are using local variables in a
                   2717: word, forget about return stack manipulations in that word (refer to the
                   2718: standard document for the exact rules).
                   2719: 
1.1       anton    2720: doc->r
                   2721: doc-r>
                   2722: doc-r@
                   2723: doc-rdrop
                   2724: doc-2>r
                   2725: doc-2r>
                   2726: doc-2r@
                   2727: doc-2rdrop
                   2728: 
                   2729: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   2730: @subsection Locals stack
                   2731: 
1.26      crook    2732: @comment TODO
1.21      crook    2733: 
1.1       anton    2734: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   2735: @subsection Stack pointer manipulation
                   2736: @cindex stack pointer manipulation words
                   2737: 
1.21      crook    2738: doc-sp0
1.1       anton    2739: doc-sp@
                   2740: doc-sp!
1.21      crook    2741: doc-fp0
1.1       anton    2742: doc-fp@
                   2743: doc-fp!
1.21      crook    2744: doc-rp0
1.1       anton    2745: doc-rp@
                   2746: doc-rp!
1.21      crook    2747: doc-lp0
1.1       anton    2748: doc-lp@
                   2749: doc-lp!
                   2750: 
                   2751: @node Memory, Control Structures, Stack Manipulation, Words
                   2752: @section Memory
1.26      crook    2753: @cindex memory words
1.1       anton    2754: 
1.32      anton    2755: @menu
                   2756: * Memory model::                
                   2757: * Dictionary allocation::       
                   2758: * Heap Allocation::             
                   2759: * Memory Access::               
                   2760: * Address arithmetic::          
                   2761: * Memory Blocks::               
                   2762: @end menu
                   2763: 
                   2764: @node Memory model, Dictionary allocation, Memory, Memory
                   2765: @subsection ANS Forth and Gforth memory models
                   2766: 
                   2767: @c The ANS Forth description is a mess (e.g., is the heap part of
                   2768: @c the dictionary?), so let's not stick to closely with it.
                   2769: 
                   2770: ANS Forth considers a Forth system as consisting of several memories, of
                   2771: which only @dfn{data space} is managed and accessible with the memory
                   2772: words.  Memory not necessarily in data space includes the stacks, the
                   2773: code (called code space) and the headers (called name space). In Gforth
                   2774: everything is in data space, but the code for the primitives is usually
                   2775: read-only.
                   2776: 
                   2777: Data space is divided into a number of areas: The (data space portion of
                   2778: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
                   2779: refer to the search data structure embodied in word lists and headers,
                   2780: because it is used for looking up names, just as you would in a
                   2781: conventional dictionary.}, the heap, and a number of system-allocated
                   2782: buffers.
                   2783: 
                   2784: In ANS Forth data space is also divided into contiguous regions.  You
                   2785: can only use address arithmetic within a contiguous region, not between
                   2786: them.  Usually each allocation gives you one contiguous region, but the
1.33      anton    2787: dictionary allocation words have additional rules (@pxref{Dictionary
1.32      anton    2788: allocation}).
                   2789: 
                   2790: Gforth provides one big address space, and address arithmetic can be
                   2791: performed between any addresses. However, in the dictionary headers or
                   2792: code are interleaved with data, so almost the only contiguous data space
                   2793: regions there are those described by ANS Forth as contiguous; but you
                   2794: can be sure that the dictionary is allocated towards increasing
                   2795: addresses even between contiguous regions.  The memory order of
                   2796: allocations in the heap is platform-dependent (and possibly different
                   2797: from one run to the next).
                   2798: 
                   2799: @subsubsection ANS Forth dictionary details
                   2800: 
                   2801: @c !! I have deleted some of the stuff this section refers to - anton
1.27      crook    2802: 
1.32      anton    2803: This section is just informative, you can skip it if you are in a hurry.
1.27      crook    2804: 
1.29      crook    2805: When you create a colon definition, the text interpreter compiles the
1.32      anton    2806: code for the definition into the code space and compiles the name
                   2807: of the definition into the header space, together with other
1.27      crook    2808: information about the definition (such as its execution token).
                   2809: 
                   2810: When you create a variable, the execution of @code{variable} will
1.32      anton    2811: compile some code, assign one cell in data space, and compile the name
                   2812: of the variable into the header space.
1.27      crook    2813: 
                   2814: @cindex memory regions - relationship between them
                   2815: ANS Forth does not specify the relationship between the three memory
                   2816: regions, and specifies that a Standard program must not access code or
                   2817: data space directly -- it may only access data space directly. In
                   2818: addition, the Standard defines what relationships you may and may not
                   2819: rely on when allocating regions in data space. These constraints are
                   2820: simply a reflection of the many diverse techniques that are used to
                   2821: implement Forth systems; understanding and following the requirements of
                   2822: the Standard allows you to write portable programs -- programs that run
                   2823: in the same way on any of these diverse systems. Another way of looking
                   2824: at this is to say that ANS Forth was designed to permit compliant Forth
                   2825: systems to be implemented in many diverse ways.
                   2826: 
                   2827: @cindex memory regions - how they are assigned
1.29      crook    2828: Here are some examples of ways in which name, code and data spaces
                   2829: might be assigned in different Forth implementations:
1.27      crook    2830: 
                   2831: @itemize @bullet
                   2832: @item
                   2833: For a Forth system that runs from RAM under a general-purpose operating
                   2834: system, it can be convenient to interleave name, code and data spaces in
                   2835: a single contiguous memory region. This organisation can be
                   2836: memory-efficient (for example, because the relationship between the name
1.32      anton    2837: dictionary entry and the associated code space entry can be
1.27      crook    2838: implicit, rather than requiring an explicit memory pointer to reference
1.32      anton    2839: from the header space and the code space). This is the
1.27      crook    2840: organisation used by Gforth, as this example@footnote{The addresses
                   2841: in the example have been truncated to fit it onto the page, and the
                   2842: addresses and data shown will not match the output from your system} shows:
                   2843: @example
                   2844: hex
                   2845: variable fred 123456 fred !
                   2846: variable jim abcd jim !
                   2847: : foo + / - ;
                   2848: ' fred 10 - 50 dump 
                   2849: ..80: 5C 46 0E 40  84 66 72 65 - 64 20 20 20  20 20 20 20  \F.@.fred       
                   2850: ..90: D0 9B 04 08  00 00 00 00 - 56 34 12 00  80 46 0E 40  ........V4...F.@
                   2851: ..A0: 83 6A 69 6D  20 20 20 20 - D0 9B 04 08  00 00 00 00  .jim    ........
                   2852: ..B0: CD AB 00 00  9C 46 0E 40 - 83 66 6F 6F  20 20 20 20  .....F.@.foo    
                   2853: ..C0: 80 9B 04 08  00 00 00 00 - E4 2E 05 08  0C 2F 05 08  ............./..
                   2854: @end example
                   2855: 
                   2856: @item
                   2857: For a high-performance system running on a modern RISC processor with a
                   2858: modified Harvard architecture (one that has a unified main memory but
                   2859: separate instruction and data caches), it is desirable to separate
                   2860: processor instructions from processor data. This encourages a high cache
1.32      anton    2861: density and therefore a high cache hit rate. The Forth code space
1.27      crook    2862: is not necessarily made up entirely of processor instructions; its
                   2863: nature is dependent upon the Forth implementation. 
                   2864: 
                   2865: @item
                   2866: A Forth compiler that runs on a segmented 8086 processor could be
                   2867: designed to interleave the name, code and data spaces within a single
                   2868: 64Kbyte segment. A more common implementation choice is to use a
                   2869: separate 64Kbyte segment for each region, which provides more memory
                   2870: overall but provides an address map in which only the data space is
                   2871: accessible.
                   2872: 
                   2873: @item
                   2874: Microprocessors exist that run Forth (or many of the primitives required
                   2875: to implement the Forth virtual machine efficiently) directly. On these
                   2876: processors, the relationship between name, code and data spaces may be
1.32      anton    2877: imposed as a side-effect of the architecture of the processor.
1.27      crook    2878: 
                   2879: @item
                   2880: A Forth compiler that executes from ROM on an embedded system needs its
                   2881: data space separated from the name and code spaces so that the data
                   2882: space can be mapped to a RAM area.
                   2883: 
                   2884: @item 
                   2885: A Forth compiler that runs on an embedded system may have a requirement
                   2886: for a small memory footprint. On such a system it can be useful to
1.32      anton    2887: separate the header space from the data and code spaces; once the
                   2888: application has been compiled, the header space is no longer
1.27      crook    2889: required@footnote{more strictly speaking, most applications can be
1.32      anton    2890: designed so that this is the case}. The header space can be deleted
1.29      crook    2891: entirely, or could be stored in memory on a remote @i{host} system for
1.27      crook    2892: debug and development purposes. In the latter case, the compiler running
1.29      crook    2893: on the @i{target} system could implement a protocol across a
1.32      anton    2894: communication link that would allow it to interrogate the header space.
1.27      crook    2895: @end itemize
                   2896: 
1.1       anton    2897: 
1.32      anton    2898: @node Dictionary allocation, Heap Allocation, Memory model, Memory
                   2899: @subsection Dictionary allocation
1.27      crook    2900: @cindex reserving data space
                   2901: @cindex data space - reserving some
                   2902: 
1.32      anton    2903: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
                   2904: you want to deallocate X, you also deallocate everything
                   2905: allocated after X.
                   2906: 
                   2907: The allocations using the words below are contiguous and grow the region
                   2908: towards increasing addresses.  Other words that allocate dictionary
                   2909: memory of any kind (i.e., defining words including @code{:noname}) end
                   2910: the contiguous region and start a new one.
                   2911: 
                   2912: In ANS Forth only @code{create}d words are guaranteed to produce an
                   2913: address that is the start of the following contiguous region.  In
                   2914: particular, the cell allocated by @code{variable} is not guaranteed to
                   2915: be contiguous with following @code{allot}ed memory.
                   2916: 
                   2917: You can deallocate memory by using @code{allot} with a negative argument
                   2918: (with some restrictions, see @code{allot}). For larger deallocations use
                   2919: @code{marker}.
1.27      crook    2920: 
1.29      crook    2921: 
1.27      crook    2922: doc-here
                   2923: doc-unused
                   2924: doc-allot
                   2925: doc-c,
1.29      crook    2926: doc-f,
1.27      crook    2927: doc-,
                   2928: doc-2,
1.29      crook    2929: @cindex user space
                   2930: doc-udp
                   2931: doc-uallot
1.27      crook    2932: 
1.32      anton    2933: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
                   2934: course you should allocate memory in an aligned way, too. I.e., before
                   2935: allocating allocating a cell, @code{here} must be cell-aligned, etc.
                   2936: The words below align @code{here} if it is not already.  Basically it is
                   2937: only already aligned for a type, if the last allocation was a multiple
                   2938: of the size of this type and if @code{here} was aligned for this type
                   2939: before.
                   2940: 
                   2941: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
                   2942: ANS Forth (@code{maxalign}ed in Gforth).
                   2943: 
                   2944: doc-align
                   2945: doc-falign
                   2946: doc-sfalign
                   2947: doc-dfalign
                   2948: doc-maxalign
                   2949: doc-cfalign
                   2950: 
                   2951: 
                   2952: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
                   2953: @subsection Heap allocation
                   2954: @cindex heap allocation
                   2955: @cindex dynamic allocation of memory
                   2956: @cindex memory-allocation word set
                   2957: 
                   2958: Heap allocation supports deallocation of allocated memory in any
                   2959: order. Dictionary allocation is not affected by it (i.e., it does not
                   2960: end a contiguous region). In Gforth, these words are implemented using
                   2961: the standard C library calls malloc(), free() and resize().
                   2962: 
                   2963: doc-allocate
                   2964: doc-free
                   2965: doc-resize
                   2966: 
1.27      crook    2967: 
1.32      anton    2968: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1       anton    2969: @subsection Memory Access
                   2970: @cindex memory access words
                   2971: 
                   2972: doc-@
                   2973: doc-!
                   2974: doc-+!
                   2975: doc-c@
                   2976: doc-c!
                   2977: doc-2@
                   2978: doc-2!
                   2979: doc-f@
                   2980: doc-f!
                   2981: doc-sf@
                   2982: doc-sf!
                   2983: doc-df@
                   2984: doc-df!
                   2985: 
1.32      anton    2986: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   2987: @subsection Address arithmetic
1.1       anton    2988: @cindex address arithmetic words
                   2989: 
1.32      anton    2990: Address arithmetic is the foundation on which data structures like
                   2991: arrays, records (@pxref{Structures}) and objects (@pxref{Object-oriented
                   2992: Forth}) are built.
                   2993: 
1.1       anton    2994: ANS Forth does not specify the sizes of the data types. Instead, it
                   2995: offers a number of words for computing sizes and doing address
1.29      crook    2996: arithmetic. Address arithmetic is performed in terms of address units
                   2997: (aus); on most systems the address unit is one byte. Note that a
                   2998: character may have more than one au, so @code{chars} is no noop (on
                   2999: systems where it is a noop, it compiles to nothing).
1.1       anton    3000: 
                   3001: @cindex alignment of addresses for types
                   3002: ANS Forth also defines words for aligning addresses for specific
                   3003: types. Many computers require that accesses to specific data types
                   3004: must only occur at specific addresses; e.g., that cells may only be
                   3005: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   3006: accesses, it can usually perform aligned accesses faster. 
                   3007: 
                   3008: For the performance-conscious: alignment operations are usually only
                   3009: necessary during the definition of a data structure, not during the
                   3010: (more frequent) accesses to it.
                   3011: 
                   3012: ANS Forth defines no words for character-aligning addresses. This is not
                   3013: an oversight, but reflects the fact that addresses that are not
                   3014: char-aligned have no use in the standard and therefore will not be
                   3015: created.
                   3016: 
                   3017: @cindex @code{CREATE} and alignment
1.29      crook    3018: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    3019: are cell-aligned; in addition, Gforth guarantees that these addresses
                   3020: are aligned for all purposes.
                   3021: 
1.26      crook    3022: Note that the ANS Forth word @code{char} has nothing to do with address
                   3023: arithmetic.
1.1       anton    3024: 
                   3025: doc-chars
                   3026: doc-char+
                   3027: doc-cells
                   3028: doc-cell+
                   3029: doc-cell
                   3030: doc-aligned
                   3031: doc-floats
                   3032: doc-float+
                   3033: doc-float
                   3034: doc-faligned
                   3035: doc-sfloats
                   3036: doc-sfloat+
                   3037: doc-sfaligned
                   3038: doc-dfloats
                   3039: doc-dfloat+
                   3040: doc-dfaligned
                   3041: doc-maxaligned
                   3042: doc-cfaligned
                   3043: doc-address-unit-bits
                   3044: 
1.32      anton    3045: @node Memory Blocks,  , Address arithmetic, Memory
1.1       anton    3046: @subsection Memory Blocks
                   3047: @cindex memory block words
1.27      crook    3048: @cindex character strings - moving and copying
                   3049: 
                   3050: Memory blocks often represent character strings; @xref{String Formats}
                   3051: for ways of storing character strings in memory. @xref{Displaying
                   3052: characters and strings} for other string-processing words.
1.1       anton    3053: 
1.32      anton    3054: Some of these words work on address units. Others work on character
                   3055: units (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
                   3056: address. Choose the correct operation depending upon your data type.
1.21      crook    3057: 
                   3058: When copying characters between overlapping memory regions, choose
                   3059: carefully between @code{cmove} and @code{cmove>}.
                   3060: 
1.29      crook    3061: You can only use any of these words @i{portably} to access data space.
1.21      crook    3062: 
1.27      crook    3063: @comment TODO - think the naming of the arguments is wrong for move
1.29      crook    3064: @comment well, really it seems to be the Standard that's wrong; it
                   3065: @comment describes MOVE as a word that requires a CELL-aligned source
                   3066: @comment and destination address but a xtranfer count that need not
                   3067: @comment be a multiple of CELL.
1.1       anton    3068: doc-move
                   3069: doc-erase
                   3070: doc-cmove
                   3071: doc-cmove>
                   3072: doc-fill
                   3073: doc-blank
1.21      crook    3074: doc-compare
                   3075: doc-search
1.27      crook    3076: doc--trailing
                   3077: doc-/string
                   3078: 
                   3079: @comment TODO examples
                   3080: 
1.1       anton    3081: 
1.26      crook    3082: @node Control Structures, Defining Words, Memory, Words
1.1       anton    3083: @section Control Structures
                   3084: @cindex control structures
                   3085: 
1.33      anton    3086: Control structures in Forth cannot be used interpretively, only in a
                   3087: colon definition@footnote{To be precise, they have no interpretation
                   3088: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
                   3089: not like this limitation, but have not seen a satisfying way around it
                   3090: yet, although many schemes have been proposed.
1.1       anton    3091: 
                   3092: @menu
1.33      anton    3093: * Selection::                   IF ... ELSE ... ENDIF
                   3094: * Simple Loops::                BEGIN ...
1.29      crook    3095: * Counted Loops::               DO
                   3096: * Arbitrary control structures::
                   3097: * Calls and returns::
1.1       anton    3098: * Exception Handling::          
                   3099: @end menu
                   3100: 
                   3101: @node Selection, Simple Loops, Control Structures, Control Structures
                   3102: @subsection Selection
                   3103: @cindex selection control structures
                   3104: @cindex control structures for selection
                   3105: 
1.33      anton    3106: @c what's the purpose of all these @i? Maybe we should define a macro
                   3107: @c so we can produce logical markup.  - anton
                   3108: 
1.1       anton    3109: @cindex @code{IF} control structure
                   3110: @example
1.29      crook    3111: @i{flag}
1.1       anton    3112: IF
1.29      crook    3113:   @i{code}
1.1       anton    3114: ENDIF
                   3115: @end example
1.21      crook    3116: @noindent
1.33      anton    3117: 
                   3118: @var{code} is executed if @var{flag} is non-zero (that's truth as far as
                   3119: @code{IF} etc. are concerned).
                   3120: 
1.1       anton    3121: @example
1.29      crook    3122: @i{flag}
1.1       anton    3123: IF
1.29      crook    3124:   @i{code1}
1.1       anton    3125: ELSE
1.29      crook    3126:   @i{code2}
1.1       anton    3127: ENDIF
                   3128: @end example
                   3129: 
1.33      anton    3130: If @var{flag} is true, perform @var{code1}, otherwise @var{code2}.
                   3131: 
1.1       anton    3132: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   3133: standard, and @code{ENDIF} is not, although it is quite popular. We
                   3134: recommend using @code{ENDIF}, because it is less confusing for people
                   3135: who also know other languages (and is not prone to reinforcing negative
                   3136: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   3137: system that only supplies @code{THEN} is simple:
                   3138: @example
1.21      crook    3139: : ENDIF   POSTPONE THEN ; immediate
1.1       anton    3140: @end example
                   3141: 
                   3142: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   3143: (adv.)}  has the following meanings:
                   3144: @quotation
                   3145: ... 2b: following next after in order ... 3d: as a necessary consequence
                   3146: (if you were there, then you saw them).
                   3147: @end quotation
                   3148: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   3149: and many other programming languages has the meaning 3d.]
                   3150: 
1.21      crook    3151: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    3152: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    3153: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    3154: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   3155: @file{compat/control.fs}.
                   3156: 
                   3157: @cindex @code{CASE} control structure
                   3158: @example
1.29      crook    3159: @i{n}
1.1       anton    3160: CASE
1.29      crook    3161:   @i{n1} OF @i{code1} ENDOF
                   3162:   @i{n2} OF @i{code2} ENDOF
1.1       anton    3163:   @dots{}
                   3164: ENDCASE
                   3165: @end example
                   3166: 
1.29      crook    3167: Executes the first @i{codei}, where the @i{ni} is equal to
                   3168: @i{n}. A default case can be added by simply writing the code after
                   3169: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
1.1       anton    3170: but must not consume it.
                   3171: 
                   3172: @node Simple Loops, Counted Loops, Selection, Control Structures
                   3173: @subsection Simple Loops
                   3174: @cindex simple loops
                   3175: @cindex loops without count 
                   3176: 
                   3177: @cindex @code{WHILE} loop
                   3178: @example
                   3179: BEGIN
1.29      crook    3180:   @i{code1}
                   3181:   @i{flag}
1.1       anton    3182: WHILE
1.29      crook    3183:   @i{code2}
1.1       anton    3184: REPEAT
                   3185: @end example
                   3186: 
1.29      crook    3187: @i{code1} is executed and @i{flag} is computed. If it is true,
                   3188: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    3189: false, execution continues after the @code{REPEAT}.
                   3190: 
                   3191: @cindex @code{UNTIL} loop
                   3192: @example
                   3193: BEGIN
1.29      crook    3194:   @i{code}
                   3195:   @i{flag}
1.1       anton    3196: UNTIL
                   3197: @end example
                   3198: 
1.29      crook    3199: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    3200: 
                   3201: @cindex endless loop
                   3202: @cindex loops, endless
                   3203: @example
                   3204: BEGIN
1.29      crook    3205:   @i{code}
1.1       anton    3206: AGAIN
                   3207: @end example
                   3208: 
                   3209: This is an endless loop.
                   3210: 
                   3211: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   3212: @subsection Counted Loops
                   3213: @cindex counted loops
                   3214: @cindex loops, counted
                   3215: @cindex @code{DO} loops
                   3216: 
                   3217: The basic counted loop is:
                   3218: @example
1.29      crook    3219: @i{limit} @i{start}
1.1       anton    3220: ?DO
1.29      crook    3221:   @i{body}
1.1       anton    3222: LOOP
                   3223: @end example
                   3224: 
1.29      crook    3225: This performs one iteration for every integer, starting from @i{start}
                   3226: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    3227: accessed with @code{i}. For example, the loop:
1.1       anton    3228: @example
                   3229: 10 0 ?DO
                   3230:   i .
                   3231: LOOP
                   3232: @end example
1.21      crook    3233: @noindent
                   3234: prints @code{0 1 2 3 4 5 6 7 8 9}
                   3235: 
1.1       anton    3236: The index of the innermost loop can be accessed with @code{i}, the index
                   3237: of the next loop with @code{j}, and the index of the third loop with
                   3238: @code{k}.
                   3239: 
                   3240: doc-i
                   3241: doc-j
                   3242: doc-k
                   3243: 
                   3244: The loop control data are kept on the return stack, so there are some
1.21      crook    3245: restrictions on mixing return stack accesses and counted loop words. In
                   3246: particuler, if you put values on the return stack outside the loop, you
                   3247: cannot read them inside the loop@footnote{well, not in a way that is
                   3248: portable.}. If you put values on the return stack within a loop, you
                   3249: have to remove them before the end of the loop and before accessing the
                   3250: index of the loop.
1.1       anton    3251: 
                   3252: There are several variations on the counted loop:
                   3253: 
1.21      crook    3254: @itemize @bullet
                   3255: @item
                   3256: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   3257: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   3258: 
                   3259: @example
                   3260: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   3261: @end example
                   3262: prints @code{0 1 2 3}
                   3263: 
1.1       anton    3264: 
1.21      crook    3265: @item
                   3266: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   3267: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   3268: return stack so @code{EXIT} can get to its return address. For example:
                   3269: 
                   3270: @example
                   3271: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   3272: @end example
                   3273: prints @code{0 1 2 3}
                   3274: 
                   3275: 
                   3276: @item
1.29      crook    3277: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    3278: (and @code{LOOP} iterates until they become equal by wrap-around
                   3279: arithmetic). This behaviour is usually not what you want. Therefore,
                   3280: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29      crook    3281: @code{?DO}), which do not enter the loop if @i{start} is greater than
                   3282: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    3283: unsigned loop parameters.
                   3284: 
1.21      crook    3285: @item
                   3286: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   3287: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   3288: if you know that the loop is entered in any case. Such knowledge tends
                   3289: to become invalid during maintenance of a program, and then the
                   3290: @code{DO} will make trouble.
                   3291: 
                   3292: @item
1.29      crook    3293: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
                   3294: index by @i{n} instead of by 1. The loop is terminated when the border
                   3295: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    3296: 
1.21      crook    3297: @example
                   3298: 4 0 +DO  i .  2 +LOOP
                   3299: @end example
                   3300: @noindent
                   3301: prints @code{0 2}
                   3302: 
                   3303: @example
                   3304: 4 1 +DO  i .  2 +LOOP
                   3305: @end example
                   3306: @noindent
                   3307: prints @code{1 3}
1.1       anton    3308: 
                   3309: 
                   3310: @cindex negative increment for counted loops
                   3311: @cindex counted loops with negative increment
1.29      crook    3312: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    3313: 
1.21      crook    3314: @example
                   3315: -1 0 ?DO  i .  -1 +LOOP
                   3316: @end example
                   3317: @noindent
                   3318: prints @code{0 -1}
1.1       anton    3319: 
1.21      crook    3320: @example
                   3321: 0 0 ?DO  i .  -1 +LOOP
                   3322: @end example
                   3323: prints nothing.
1.1       anton    3324: 
1.29      crook    3325: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
                   3326: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
                   3327: index by @i{u} each iteration. The loop is terminated when the border
                   3328: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    3329: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   3330: 
1.21      crook    3331: @example
                   3332: -2 0 -DO  i .  1 -LOOP
                   3333: @end example
                   3334: @noindent
                   3335: prints @code{0 -1}
1.1       anton    3336: 
1.21      crook    3337: @example
                   3338: -1 0 -DO  i .  1 -LOOP
                   3339: @end example
                   3340: @noindent
                   3341: prints @code{0}
                   3342: 
                   3343: @example
                   3344: 0 0 -DO  i .  1 -LOOP
                   3345: @end example
                   3346: @noindent
                   3347: prints nothing.
1.1       anton    3348: 
1.21      crook    3349: @end itemize
1.1       anton    3350: 
                   3351: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    3352: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   3353: for these words that uses only standard words is provided in
                   3354: @file{compat/loops.fs}.
1.1       anton    3355: 
                   3356: 
                   3357: @cindex @code{FOR} loops
1.26      crook    3358: Another counted loop is:
1.1       anton    3359: @example
1.29      crook    3360: @i{n}
1.1       anton    3361: FOR
1.29      crook    3362:   @i{body}
1.1       anton    3363: NEXT
                   3364: @end example
                   3365: This is the preferred loop of native code compiler writers who are too
1.26      crook    3366: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29      crook    3367: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
                   3368: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    3369: Forth systems may behave differently, even if they support @code{FOR}
                   3370: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    3371: 
                   3372: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   3373: @subsection Arbitrary control structures
                   3374: @cindex control structures, user-defined
                   3375: 
                   3376: @cindex control-flow stack
                   3377: ANS Forth permits and supports using control structures in a non-nested
                   3378: way. Information about incomplete control structures is stored on the
                   3379: control-flow stack. This stack may be implemented on the Forth data
                   3380: stack, and this is what we have done in Gforth.
                   3381: 
                   3382: @cindex @code{orig}, control-flow stack item
                   3383: @cindex @code{dest}, control-flow stack item
                   3384: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   3385: entry represents a backward branch target. A few words are the basis for
                   3386: building any control structure possible (except control structures that
                   3387: need storage, like calls, coroutines, and backtracking).
                   3388: 
                   3389: doc-if
                   3390: doc-ahead
                   3391: doc-then
                   3392: doc-begin
                   3393: doc-until
                   3394: doc-again
                   3395: doc-cs-pick
                   3396: doc-cs-roll
                   3397: 
1.21      crook    3398: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   3399: manipulate the control-flow stack in a portable way. Without them, you
                   3400: would need to know how many stack items are occupied by a control-flow
                   3401: entry (many systems use one cell. In Gforth they currently take three,
                   3402: but this may change in the future).
                   3403: 
1.1       anton    3404: Some standard control structure words are built from these words:
                   3405: 
                   3406: doc-else
                   3407: doc-while
                   3408: doc-repeat
                   3409: 
                   3410: Gforth adds some more control-structure words:
                   3411: 
                   3412: doc-endif
                   3413: doc-?dup-if
                   3414: doc-?dup-0=-if
                   3415: 
                   3416: Counted loop words constitute a separate group of words:
                   3417: 
                   3418: doc-?do
                   3419: doc-+do
                   3420: doc-u+do
                   3421: doc--do
                   3422: doc-u-do
                   3423: doc-do
                   3424: doc-for
                   3425: doc-loop
                   3426: doc-+loop
                   3427: doc--loop
                   3428: doc-next
                   3429: doc-leave
                   3430: doc-?leave
                   3431: doc-unloop
                   3432: doc-done
                   3433: 
1.21      crook    3434: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   3435: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    3436: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   3437: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   3438: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   3439: resolved (by using one of the loop-ending words or @code{DONE}).
                   3440: 
1.26      crook    3441: Another group of control structure words are:
1.1       anton    3442: 
                   3443: doc-case
                   3444: doc-endcase
                   3445: doc-of
                   3446: doc-endof
                   3447: 
1.21      crook    3448: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   3449: @code{CS-ROLL}.
1.1       anton    3450: 
                   3451: @subsubsection Programming Style
                   3452: 
                   3453: In order to ensure readability we recommend that you do not create
                   3454: arbitrary control structures directly, but define new control structure
                   3455: words for the control structure you want and use these words in your
1.26      crook    3456: program. For example, instead of writing:
1.1       anton    3457: 
                   3458: @example
1.26      crook    3459: BEGIN
1.1       anton    3460:   ...
1.26      crook    3461: IF [ 1 CS-ROLL ]
1.1       anton    3462:   ...
1.26      crook    3463: AGAIN THEN
1.1       anton    3464: @end example
                   3465: 
1.21      crook    3466: @noindent
1.1       anton    3467: we recommend defining control structure words, e.g.,
                   3468: 
                   3469: @example
1.26      crook    3470: : WHILE ( DEST -- ORIG DEST )
                   3471:  POSTPONE IF
                   3472:  1 CS-ROLL ; immediate
                   3473: 
                   3474: : REPEAT ( orig dest -- )
                   3475:  POSTPONE AGAIN
                   3476:  POSTPONE THEN ; immediate
1.1       anton    3477: @end example
                   3478: 
1.21      crook    3479: @noindent
1.1       anton    3480: and then using these to create the control structure:
                   3481: 
                   3482: @example
1.26      crook    3483: BEGIN
1.1       anton    3484:   ...
1.26      crook    3485: WHILE
1.1       anton    3486:   ...
1.26      crook    3487: REPEAT
1.1       anton    3488: @end example
                   3489: 
                   3490: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   3491: @code{WHILE} are predefined, so in this example it would not be
                   3492: necessary to define them.
                   3493: 
                   3494: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   3495: @subsection Calls and returns
                   3496: @cindex calling a definition
                   3497: @cindex returning from a definition
                   3498: 
1.3       anton    3499: @cindex recursive definitions
                   3500: A definition can be called simply be writing the name of the definition
1.26      crook    3501: to be called. Normally a definition is invisible during its own
1.3       anton    3502: definition. If you want to write a directly recursive definition, you
1.26      crook    3503: can use @code{recursive} to make the current definition visible, or
                   3504: @code{recurse} to call the current definition directly.
1.3       anton    3505: 
                   3506: doc-recursive
                   3507: doc-recurse
                   3508: 
1.21      crook    3509: @comment TODO add example of the two recursion methods
1.12      anton    3510: @quotation
                   3511: @progstyle
                   3512: I prefer using @code{recursive} to @code{recurse}, because calling the
                   3513: definition by name is more descriptive (if the name is well-chosen) than
                   3514: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   3515: implementation, it is much better to read (and think) ``now sort the
                   3516: partitions'' than to read ``now do a recursive call''.
                   3517: @end quotation
1.3       anton    3518: 
1.29      crook    3519: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    3520: 
                   3521: @example
1.28      crook    3522: Defer foo
1.3       anton    3523: 
                   3524: : bar ( ... -- ... )
                   3525:  ... foo ... ;
                   3526: 
                   3527: :noname ( ... -- ... )
                   3528:  ... bar ... ;
                   3529: IS foo
                   3530: @end example
                   3531: 
1.33      anton    3532: Deferred words are discussed in more detail in @ref{Simple
                   3533: Defining Words}.
                   3534: 
1.26      crook    3535: The current definition returns control to the calling definition when
1.33      anton    3536: the end of the definition is reached or @code{EXIT} is encountered.
1.1       anton    3537: 
                   3538: doc-exit
                   3539: doc-;s
                   3540: 
                   3541: @node Exception Handling,  , Calls and returns, Control Structures
                   3542: @subsection Exception Handling
1.26      crook    3543: @cindex exceptions
1.1       anton    3544: 
1.26      crook    3545: If your program detects a fatal error condition, the simplest action
                   3546: that it can take is to @code{quit}. This resets the return stack and
                   3547: restarts the text interpreter, but does not print any error message.
1.21      crook    3548: 
1.26      crook    3549: The next stage in severity is to execute @code{abort}, which has the
                   3550: same effect as @code{quit}, with the addition that it resets the data
                   3551: stack.
1.1       anton    3552: 
1.26      crook    3553: A slightly more sophisticated approach is use use @code{abort"}, which
                   3554: compiles a string to be used as an error message and does a conditional
                   3555: @code{abort} at run-time. For example:
1.1       anton    3556: 
1.26      crook    3557: @example
1.30      anton    3558: @kbd{: checker abort" That flag was true" ." A false flag" ;@key{RET}}  ok
                   3559: @kbd{0 checker@key{RET}} A false flag ok
                   3560: @kbd{1 checker@key{RET}}
1.26      crook    3561: :1: That flag was true
                   3562: 1 checker
                   3563:   ^^^^^^^
                   3564: $400D1648 throw 
                   3565: $400E4660
                   3566: @end example
1.1       anton    3567: 
1.26      crook    3568: These simple techniques allow a program to react to a fatal error
                   3569: condition, but they are not exactly user-friendly. The ANS Forth
                   3570: Exception word set provides the pair of words @code{throw} and
                   3571: @code{catch}, which can be used to provide sophisticated error-handling.
1.1       anton    3572: 
1.26      crook    3573: @code{catch} has a similar behaviour to @code{execute}, in that it takes
1.29      crook    3574: an @i{xt} as a parameter and starts execution of the xt. However,
1.26      crook    3575: before passing control to the xt, @code{catch} pushes an
1.29      crook    3576: @dfn{exception frame} onto the @dfn{exception stack}. This exception
1.26      crook    3577: frame is used to restore the system to a known state if a detected error
                   3578: occurs during the execution of the xt. A typical way to use @code{catch}
                   3579: would be:
1.1       anton    3580: 
1.26      crook    3581: @example
                   3582: ... ['] foo catch IF ...
                   3583: @end example
1.1       anton    3584: 
1.33      anton    3585: @c TOS is undefined. - anton
1.26      crook    3586: Whilst @code{foo} executes, it can call other words to any level of
                   3587: nesting, as usual.  If @code{foo} (and all the words that it calls)
1.33      anton    3588: execute successfully, control will ultimately pass to the word following
                   3589: the @code{catch}, and there will be a 0 at TOS.  However, if any word
                   3590: detects an error, it can terminate the execution of @code{foo} by
                   3591: pushing a non-zero error code onto the stack and then performing a
                   3592: @code{throw}. The execution of @code{throw} will pass control to the
                   3593: word following the @code{catch}, but this time the TOS will hold the
                   3594: error code. Therefore, the @code{IF} in the example can be used to
                   3595: determine whether @code{foo} executed successfully.
1.1       anton    3596: 
1.26      crook    3597: This simple example shows how you can use @code{throw} and @code{catch}
                   3598: to ``take over'' exception handling from the system:
1.1       anton    3599: @example
1.26      crook    3600: : my-div ['] / catch if ." DIVIDE ERROR" else ." OK.. " . then ;
1.1       anton    3601: @end example
                   3602: 
1.26      crook    3603: The next example is more sophisticated and shows a multi-level
                   3604: @code{throw} and @code{catch}. To understand this example, start at the
                   3605: definition of @code{top-level} and work backwards:
                   3606: 
1.1       anton    3607: @example
1.26      crook    3608: : lowest-level ( -- c )
                   3609:     key dup 27 = if
                   3610:        1 throw \ ESCAPE key pressed
                   3611:     else
                   3612:        ." lowest-level successfull" CR
                   3613:     then
                   3614: ;
                   3615: 
                   3616: : lower-level ( -- c )
                   3617:     lowest-level
                   3618:     \ at this level consider a CTRL-U to be a fatal error
                   3619:     dup 21 = if \ CTRL-U
                   3620:        2 throw
                   3621:     else
                   3622:        ." lower-level successfull" CR
                   3623:     then
                   3624: ;
                   3625: 
                   3626: : low-level ( -- c )
                   3627:     ['] lower-level catch
                   3628:     ?dup if
                   3629:        \ error occurred - do we recognise it?
                   3630:        dup 1 = if
                   3631:            \ ESCAPE key pressed.. pretend it was an E
                   3632:            [char] E
                   3633:        else throw \ propogate the error upwards
                   3634:        then
                   3635:     then
                   3636:     ." low-level successfull" CR
                   3637: ;
                   3638: 
                   3639: : top-level ( -- )
                   3640:     CR ['] low-level catch \ CATCH is used like EXECUTE
                   3641:     ?dup if \ error occurred..
                   3642:        ." Error " . ." occurred - contact your supplier"
                   3643:     else
                   3644:        ." The '" emit ." ' key was pressed" CR
                   3645:     then
                   3646: ;
1.1       anton    3647: @end example
                   3648: 
1.26      crook    3649: The ANS Forth document assigns @code{throw} codes thus:
1.1       anton    3650: 
1.26      crook    3651: @itemize @bullet
                   3652: @item
                   3653: codes in the range -1 -- -255 are reserved to be assigned by the
                   3654: Standard. Assignments for codes in the range -1 -- -58 are currently
                   3655: documented in the Standard. In particular, @code{-1 throw} is equivalent
                   3656: to @code{abort} and @code{-2 throw} is equivalent to @code{abort"}.
                   3657: @item
                   3658: codes in the range -256 -- -4095 are reserved to be assigned by the system.
                   3659: @item
                   3660: all other codes may be assigned by programs.
                   3661: @end itemize
1.1       anton    3662: 
1.26      crook    3663: Gforth provides the word @code{exception} as a mechanism for assigning
                   3664: system throw codes to applications. This allows multiple applications to
                   3665: co-exist in memory without any clash of @code{throw} codes. A definition
                   3666: of @code{exception} in ANS Forth is provided in
                   3667: @file{compat/exception.fs}.
1.1       anton    3668: 
1.26      crook    3669: doc-quit
                   3670: doc-abort
                   3671: doc-abort"
1.1       anton    3672: 
1.26      crook    3673: doc-catch
1.29      crook    3674: doc-throw
                   3675: doc---exception-exception
                   3676: 
                   3677: 
                   3678: @c -------------------------------------------------------------
                   3679: @node Defining Words, The Text Interpreter, Control Structures, Words
                   3680: @section Defining Words
                   3681: @cindex defining words
                   3682: 
                   3683: @menu
                   3684: * Simple Defining Words::       Variables, values and constants
                   3685: * Colon Definitions::
                   3686: * User-defined Defining Words::
                   3687: * Supplying names::
                   3688: * Interpretation and Compilation Semantics::
                   3689: @end menu
                   3690: 
                   3691: @node Simple Defining Words, Colon Definitions, Defining Words, Defining Words
                   3692: @subsection Simple Defining Words
                   3693: @cindex simple defining words
                   3694: @cindex defining words, simple
                   3695: 
1.33      anton    3696: @c split this section?
                   3697: 
1.29      crook    3698: Defining words are used to create new entries in the dictionary. The
                   3699: simplest defining word is @code{CREATE}. @code{CREATE} is used like
                   3700: this:
                   3701: 
                   3702: @example
                   3703: CREATE new-word1
                   3704: @end example
                   3705: 
                   3706: @code{CREATE} is a parsing word that generates a dictionary entry for
                   3707: @code{new-word1}. When @code{new-word1} is executed, all that it does is
                   3708: leave an address on the stack. The address represents the value of
                   3709: the data space pointer (@code{HERE}) at the time that @code{new-word1}
                   3710: was defined. Therefore, @code{CREATE} is a way of associating a name
                   3711: with the address of a region of memory.
                   3712: 
1.34      anton    3713: doc-create
                   3714: 
1.29      crook    3715: By extending this example to reserve some memory in data space, we end
                   3716: up with a @i{variable}. Here are two different ways to do it:
                   3717: 
                   3718: @example
                   3719: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
                   3720: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
                   3721: @end example
                   3722: 
                   3723: The variable can be examined and modified using @code{@@} (``fetch'') and
                   3724: @code{!} (``store'') like this:
                   3725: 
                   3726: @example
                   3727: new-word2 @@ .      \ get address, fetch from it and display
                   3728: 1234 new-word2 !   \ new value, get address, store to it
                   3729: @end example
                   3730: 
                   3731: As a final refinement, the whole code sequence can be wrapped up in a
                   3732: defining word (pre-empting the subject of the next section), making it
                   3733: easier to create new variables:
                   3734: 
                   3735: @example
1.33      anton    3736: : myvariable ( "name" -- a-addr ) CREATE 0 , ;
1.29      crook    3737: 
                   3738: myvariable foo
                   3739: myvariable joe
                   3740: 
                   3741: 45 3 * foo !   \ set foo to 135
                   3742: 1234 joe !     \ set joe to 1234
                   3743: 3 joe +!       \ increment joe by 3.. to 1237
                   3744: @end example
                   3745: 
                   3746: Not surprisingly, there is no need to define @code{myvariable}, since
                   3747: Forth already has a definition @code{Variable}. It behaves in exactly
1.33      anton    3748: the same way as @code{myvariable}. Forth also provides @code{2Variable}
                   3749: and @code{fvariable} for double and floating-point variables,
                   3750: respectively.
1.29      crook    3751: 
1.34      anton    3752: doc-variable
                   3753: doc-2variable
                   3754: doc-fvariable
                   3755: 
1.29      crook    3756: @cindex arrays
                   3757: A similar mechanism can be used to create arrays. For example, an
                   3758: 80-character text input buffer:
                   3759: 
                   3760: @example
                   3761: CREATE text-buf 80 chars allot
                   3762: 
                   3763: text-buf 0 chars c@@ \ the 1st character (offset 0)
                   3764: text-buf 3 chars c@@ \ the 4th character (offset 3)
                   3765: @end example
                   3766: 
                   3767: You can build arbitrarily complex data structures by allocating
                   3768: appropriate areas of memory. @xref{Structures} for further discussions
                   3769: of this, and to learn about some Gforth tools that make it easier.
                   3770: 
                   3771: @cindex user variables
                   3772: @cindex user space
                   3773: The defining word @code{User} behaves in the same way as @code{Variable}.
                   3774: The difference is that it reserves space in @i{user (data) space} rather
                   3775: than normal data space. In a Forth system that has a multi-tasker, each
                   3776: task has its own set of user variables.
                   3777: 
1.34      anton    3778: doc-user
                   3779: 
1.29      crook    3780: @comment TODO is that stuff about user variables strictly correct? Is it
                   3781: @comment just terminal tasks that have user variables?
                   3782: @comment should document tasker.fs (with some examples) elsewhere
                   3783: @comment in this manual, then expand on user space and user variables.
                   3784: 
                   3785: After @code{CREATE} and @code{Variable}s, the next defining word to
                   3786: consider is @code{Constant}. @code{Constant} allows you to declare a
                   3787: fixed value and refer to it by name. For example:
                   3788: 
                   3789: @example
                   3790: 12 Constant INCHES-PER-FOOT
                   3791: 3E+08 fconstant SPEED-O-LIGHT
                   3792: @end example
                   3793: 
                   3794: A @code{Variable} can be both read and written, so its run-time
                   3795: behaviour is to supply an address through which its current value can be
                   3796: manipulated. In contrast, the value of a @code{Constant} cannot be
                   3797: changed once it has been declared@footnote{Well, often it can be -- but
                   3798: not in a Standard, portable way. It's safer to use a @code{Value} (read
                   3799: on).} so it's not necessary to supply the address -- it is more
                   3800: efficient to return the value of the constant directly. That's exactly
                   3801: what happens; the run-time effect of a constant is to put its value on
                   3802: the top of the stack (@ref{User-defined Defining Words} describes one
                   3803: way of implementing @code{Constant}).
                   3804: 
                   3805: Gforth also provides @code{2Constant} and @code{fconstant} for defining
                   3806: double and floating-point constants, respectively.
                   3807: 
1.34      anton    3808: doc-constant
                   3809: doc-2constant
                   3810: doc-fconstant
                   3811: 
                   3812: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.29      crook    3813: Constants in Forth behave differently from their equivalents in other
                   3814: programming languages. In other languages, a constant (such as an EQU in
                   3815: assembler or a #define in C) only exists at compile-time; in the
                   3816: executable program the constant has been translated into an absolute
                   3817: number and, unless you are using a symbolic debugger, it's impossible to
                   3818: know what abstract thing that number represents. In Forth a constant has
1.32      anton    3819: an entry in the header space and remains there after the code that
1.29      crook    3820: uses it has been defined. In fact, it must remain in the dictionary
                   3821: since it has run-time duties to perform. For example:
                   3822: 
                   3823: @example
                   3824: 12 Constant INCHES-PER-FOOT
                   3825: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
                   3826: @end example
                   3827: 
                   3828: @cindex in-lining of constants
                   3829: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
                   3830: associated with the constant @code{INCHES-PER-FOOT}. If you use
                   3831: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
                   3832: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
                   3833: attempt to optimise constants by in-lining them where they are used. You
                   3834: can force Gforth to in-line a constant like this:
                   3835: 
                   3836: @example
                   3837: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
                   3838: @end example
                   3839: 
                   3840: If you use @code{see} to decompile @i{this} version of
                   3841: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.33      anton    3842: longer present. @xref{Interpret/Compile states} and @ref{Literals} on
                   3843: how this works.
1.29      crook    3844: 
                   3845: In-lining constants in this way might improve execution time
                   3846: fractionally, and can ensure that a constant is now only referenced at
                   3847: compile-time. However, the definition of the constant still remains in
                   3848: the dictionary. Some Forth compilers provide a mechanism for controlling
                   3849: a second dictionary for holding transient words such that this second
                   3850: dictionary can be deleted later in order to recover memory
                   3851: space. However, there is no standard way of doing this.
                   3852: 
                   3853: One aspect of constants and variables that can sometimes be confusing is
                   3854: that they have different stack effects; one returns its value whilst the
                   3855: other returns the address of its value. The defining word @code{Value}
                   3856: provides an alternative to @code{Variable}, and has the same stack
                   3857: effect as a constant. A @code{Value} needs an additional word, @code{TO}
                   3858: to allow its value to be changed. Here are some examples:
                   3859: 
                   3860: @example
                   3861: 12 Value APPLES \ a Value is initialised when it is declared.. like a
                   3862:                 \ constant but unlike a variable
                   3863: 34 TO APPLES    \ Change the value of APPLES. TO is a parsing word
                   3864: APPLES          \ puts 34 on the top of the stack.
                   3865: @end example
                   3866: 
1.34      anton    3867: doc-value
                   3868: doc-to
                   3869: 
1.29      crook    3870: The defining word @code{Defer} allows you to define a word by name
                   3871: without defining its behaviour; the definition of its behaviour is
                   3872: deferred. Here are two situation where this can be useful:
                   3873: 
                   3874: @itemize @bullet
                   3875: @item
                   3876: Where you want to allow the behaviour of a word to be altered later, and
                   3877: for all precompiled references to the word to change when its behaviour
                   3878: is changed.
                   3879: @item
                   3880: For mutual recursion; @xref{Calls and returns}.
                   3881: @end itemize
                   3882: 
                   3883: In the following example, @code{foo} always invokes the version of
                   3884: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
                   3885: always invokes the version that prints ``@code{Hello}''. There is no way
                   3886: of getting @code{foo} to use the later version without re-ordering the
                   3887: source code and recompilng it.
                   3888: 
                   3889: @example
                   3890: : greet ." Good morning" ;
                   3891: : foo ... greet ... ;
                   3892: : greet ." Hello" ;
                   3893: : bar ... greet ... ;
                   3894: @end example
                   3895: 
                   3896: This problem can be solved by defining @code{greet} as a @code{Defer}red
                   3897: word. The behaviour of a @code{Defer}red word can be defined and
                   3898: redefined at any time by using @code{IS} to associate the xt of a
                   3899: previously-defined word with it. The previous example becomes:
                   3900: 
                   3901: @example
                   3902: Defer greet
                   3903: : foo ... greet ... ;
                   3904: : bar ... greet ... ;
                   3905: : greet1 ." Good morning" ;
                   3906: : greet2 ." Hello" ;
1.35      anton    3907: ' greet2 <IS> greet  \ make greet behave like greet2
                   3908: @end example
                   3909: 
                   3910: One thing to note is that @code{<IS>} consumes it's name when it is
                   3911: executed.  If you want to specify the name at compile time, use
                   3912: @code{[IS]}:
                   3913: 
                   3914: @example
                   3915: : set-greet ( xt -- )
                   3916:   [IS] greet ;
                   3917: 
                   3918: ' greet1 set-greet
1.29      crook    3919: @end example
                   3920: 
                   3921: A deferred word can only inherit default semantics from the xt (because
                   3922: that is all that an xt can represent -- @pxref{Tokens for Words} for
                   3923: more discussion of this). However, the semantics of the deferred word
                   3924: itself can be modified at the time that it is defined. For example:
                   3925: 
                   3926: @example
                   3927: : bar .... ; compile-only
                   3928: Defer fred immediate
                   3929: Defer jim
                   3930: 
1.35      anton    3931: ' bar <IS> jim  \ jim has default semantics
                   3932: ' bar <IS> fred \ fred is immediate
1.29      crook    3933: @end example
1.1       anton    3934: 
1.34      anton    3935: doc-defer
1.35      anton    3936: doc-<is>
                   3937: doc-[is]
                   3938: @comment TODO document these: what's defers [is]
1.34      anton    3939: doc-what's
                   3940: doc-defers
                   3941: 
                   3942: Definitions in ANS Forth for @code{defer}, @code{<is>} and
                   3943: @code{[is]} are provided in @file{compat/defer.fs}.
                   3944: 
1.29      crook    3945: The defining word @code{Alias} allows you to define a word by name that
                   3946: has the same behaviour as some other word. Here are two situation where
                   3947: this can be useful:
1.1       anton    3948: 
1.29      crook    3949: @itemize @bullet
                   3950: @item
                   3951: When you want access to a word's definition from a different word list
                   3952: (for an example of this, see the definition of the @code{Root} word list
                   3953: in the Gforth source).
                   3954: @item
                   3955: When you want to create a synonym; a definition that can be known by
                   3956: either of two names (for example, @code{THEN} and @code{ENDIF} are
                   3957: aliases).
                   3958: @end itemize
1.1       anton    3959: 
1.29      crook    3960: The word whose behaviour the alias is to inherit is represented by an
1.34      anton    3961: xt. Therefore, the alias only inherits default semantics from its
1.29      crook    3962: ancestor. The semantics of the alias itself can be modified at the time
                   3963: that it is defined. For example:
1.1       anton    3964: 
1.29      crook    3965: @example
                   3966: : foo ... ; immediate
1.1       anton    3967: 
1.29      crook    3968: ' foo Alias bar \ bar is not an immediate word
                   3969: ' foo Alias fooby immediate \ fooby is an immediate word
                   3970: @end example
1.26      crook    3971: 
1.34      anton    3972: @c "combined words" is an undefined term
                   3973: Words that are aliases have the same xt, different headers in the
                   3974: dictionary, and consequently different name tokens (@pxref{Tokens for
                   3975: Words}) and possibly different immediate flags.  An alias can only have
                   3976: default or immediate compilation semantics; you can define aliases for
                   3977: combined words with @code{interpret/compile:}.
1.27      crook    3978: 
1.33      anton    3979: @c distribute this to the appropriate paragraphs? - anton
1.29      crook    3980: doc-alias
1.1       anton    3981: 
1.26      crook    3982: @node Colon Definitions, User-defined Defining Words, Simple Defining Words, Defining Words
                   3983: @subsection Colon Definitions
                   3984: @cindex colon definitions
1.1       anton    3985: 
1.26      crook    3986: @example
                   3987: : name ( ... -- ... )
                   3988:     word1 word2 word3 ;
                   3989: @end example
1.1       anton    3990: 
1.29      crook    3991: @noindent
                   3992: Creates a word called @code{name} that, upon execution, executes
1.26      crook    3993: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.1       anton    3994: 
1.29      crook    3995: The explanation above is somewhat superficial. @xref{Your first
                   3996: definition} for simple examples of colon definitions, then
                   3997: @xref{Interpretation and Compilation Semantics} for an in-depth
                   3998: discussion of some of the issues involved.
1.26      crook    3999: 
                   4000: doc-:
                   4001: doc-;
1.1       anton    4002: 
1.26      crook    4003: @node User-defined Defining Words, Supplying names, Colon Definitions, Defining Words
                   4004: @subsection User-defined Defining Words
                   4005: @cindex user-defined defining words
                   4006: @cindex defining words, user-defined
1.1       anton    4007: 
1.29      crook    4008: You can create a new defining word by wrapping defining-time code around
                   4009: an existing defining word and putting the sequence in a colon
                   4010: definition. For example, suppose that you have a word @code{stats} that
                   4011: gathers statistics about colon definitions given the @i{xt} of the
                   4012: definition, and you want every colon definition in your application to
                   4013: make a call to @code{stats}. You can define and use a new version of
                   4014: @code{:} like this:
                   4015: 
                   4016: @example
                   4017: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
                   4018:   ... ;  \ other code
                   4019: 
                   4020: : my: : lastxt postpone literal ['] stats compile, ;
                   4021: 
                   4022: my: foo + - ;
                   4023: @end example
                   4024: 
                   4025: When @code{foo} is defined using @code{my:} these steps occur:
                   4026: 
                   4027: @itemize @bullet
                   4028: @item
                   4029: @code{my:} is executed.
                   4030: @item
                   4031: The @code{:} within the definition (the one between @code{my:} and
                   4032: @code{lastxt}) is executed, and does just what it always does; it parses
                   4033: the input stream for a name, builds a dictionary header for the name
                   4034: @code{foo} and switches @code{state} from interpret to compile.
                   4035: @item
                   4036: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
                   4037: being defined -- @code{foo} -- onto the stack.
                   4038: @item
                   4039: The code that was produced by @code{postpone literal} is executed; this
                   4040: causes the value on the stack to be compiled as a literal in the code
                   4041: area of @code{foo}.
                   4042: @item
                   4043: The code @code{['] stats} compiles a literal into the definition of
                   4044: @code{my:}. When @code{compile,} is executed, that literal -- the
                   4045: execution token for @code{stats} -- is layed down in the code area of
                   4046: @code{foo} , following the literal@footnote{Strictly speaking, the
                   4047: mechanism that @code{compile,} uses to convert an @i{xt} into something
                   4048: in the code area is implementation-dependent. A threaded implementation
                   4049: might spit out the execution token directly whilst another
                   4050: implementation might spit out a native code sequence.}.
                   4051: @item
                   4052: At this point, the execution of @code{my:} is complete, and control
                   4053: returns to the text interpreter. The text interpreter is in compile
                   4054: state, so subsequent text @code{+ -} is compiled into the definition of
                   4055: @code{foo} and the @code{;} terminates the definition as always.
                   4056: @end itemize
                   4057: 
                   4058: You can use @code{see} to decompile a word that was defined using
                   4059: @code{my:} and see how it is different from a normal @code{:}
                   4060: definition. For example:
                   4061: 
                   4062: @example
                   4063: : bar + - ;  \ like foo but using : rather than my:
                   4064: see bar
                   4065: : bar
                   4066:   + - ;
                   4067: see foo
                   4068: : foo
                   4069:   107645672 stats + - ;
                   4070: 
                   4071: \ use ' stats . to show that 107645672 is the xt for stats
                   4072: @end example
                   4073: 
                   4074: 
1.33      anton    4075: @c a deferred word is not neccessary for these examples. - anton
1.29      crook    4076: Rather than edit your application's source code to change every @code{:}
                   4077: to a @code{my:}, use a deferred word:
                   4078: 
                   4079: @example
                   4080: : real: : ;     \ retain access to the original
                   4081: defer :         \ redefine as a deferred word
                   4082: ' my: IS :      \ use special version of :
                   4083: \
                   4084: \ load application here
                   4085: \
                   4086: ' real: IS :    \ go back to the original
                   4087: @end example
                   4088: 
                   4089: You can use techniques like this to make new defining words in terms of
                   4090: @i{any} existing defining word.
1.1       anton    4091: 
                   4092: 
1.29      crook    4093: @cindex defining defining words
1.26      crook    4094: @cindex @code{CREATE} ... @code{DOES>}
                   4095: If you want the words defined with your defining words to behave
                   4096: differently from words defined with standard defining words, you can
                   4097: write your defining word like this:
1.1       anton    4098: 
                   4099: @example
1.26      crook    4100: : def-word ( "name" -- )
1.29      crook    4101:     CREATE @i{code1}
1.26      crook    4102: DOES> ( ... -- ... )
1.29      crook    4103:     @i{code2} ;
1.26      crook    4104: 
                   4105: def-word name
1.1       anton    4106: @end example
                   4107: 
1.29      crook    4108: @cindex child words
                   4109: This fragment defines a @dfn{defining word} @code{def-word} and then
                   4110: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
                   4111: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
                   4112: is not executed at this time. The word @code{name} is sometimes called a
                   4113: @dfn{child} of @code{def-word}.
                   4114: 
                   4115: When you execute @code{name}, the address of the body of @code{name} is
                   4116: put on the data stack and @i{code2} is executed (the address of the body
                   4117: of @code{name} is the address @code{HERE} returns immediately after the
                   4118: @code{CREATE}).
                   4119: 
                   4120: @cindex atavism in child words
1.33      anton    4121: You can use @code{def-word} to define a set of child words that behave
1.29      crook    4122: differently, though atavistically; they all have a common run-time
                   4123: behaviour determined by @i{code2}. Typically, the @i{code1} sequence
                   4124: builds a data area in the body of the child word. The structure of the
                   4125: data is common to all children of @code{def-word}, but the data values
                   4126: are specific -- and private -- to each child word. When a child word is
                   4127: executed, the address of its private data area is passed as a parameter
                   4128: on TOS to be used and manipulated@footnote{It is legitimate both to read
                   4129: and write to this data area.} by @i{code2}.
                   4130: 
                   4131: The two fragments of code that make up the defining words act (are
                   4132: executed) at two completely separate times:
1.1       anton    4133: 
1.29      crook    4134: @itemize @bullet
                   4135: @item
                   4136: At @i{define time}, the defining word executes @i{code1} to generate a
                   4137: child word
                   4138: @item
                   4139: At @i{child execution time}, when a child word is invoked, @i{code2}
                   4140: is executed, using parameters (data) that are private and specific to
                   4141: the child word.
                   4142: @end itemize
                   4143: 
                   4144: @c NAC I think this is a really bad example, because it diminishes
                   4145: @c rather than emphasising the fact that some important stuff happens
                   4146: @c at define time, and other important stuff happens at child-invocation
                   4147: @c time, and that those two times are potentially very different.
1.33      anton    4148: 
                   4149: @c Well, IMO CREATE-DOES> is usually presented with much ado, making
                   4150: @c people think that it's hard to understand, and making those people who
                   4151: @c understand it easily think that it's hyped.  I prefer presenting it in a
                   4152: @c diminished way and only emphasize the special issues later. - anton
                   4153: 
                   4154: In other words, if you make the following definitions:
                   4155: @example
                   4156: : def-word1 ( "name" -- )
                   4157:     CREATE @i{code1} ;
                   4158: 
                   4159: : action1 ( ... -- ... )
                   4160:     @i{code2} ;
                   4161: 
                   4162: def-word1 name1
                   4163: @end example
                   4164: 
                   4165: Using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    4166: 
1.29      crook    4167: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    4168: 
1.1       anton    4169: @example
1.29      crook    4170: : CONSTANT ( w "name" -- )
                   4171:     CREATE ,
1.26      crook    4172: DOES> ( -- w )
                   4173:     @@ ;
1.1       anton    4174: @end example
                   4175: 
1.29      crook    4176: @comment There is a beautiful description of how this works and what
                   4177: @comment it does in the Forthwrite 100th edition.. as well as an elegant
                   4178: @comment commentary on the Counting Fruits problem.
                   4179: 
                   4180: When you create a constant with @code{5 CONSTANT five}, a set of
                   4181: define-time actions take place; first a new word @code{five} is created,
                   4182: then the value 5 is laid down in the body of @code{five} with
                   4183: @code{,}. When @code{five} is invoked, the address of the body is put on
                   4184: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
                   4185: no code of its own; it simply contains a data field and a pointer to the
                   4186: code that follows @code{DOES>} in its defining word. That makes words
                   4187: created in this way very compact.
                   4188: 
                   4189: The final example in this section is intended to remind you that space
                   4190: reserved in @code{CREATE}d words is @i{data} space and therefore can be
                   4191: both read and written by a Standard program@footnote{Exercise: use this
                   4192: example as a starting point for your own implementation of @code{Value}
                   4193: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
                   4194: @code{[']}.}:
                   4195: 
                   4196: @example
                   4197: : foo ( "name" -- )
                   4198:     CREATE -1 ,
                   4199: DOES> ( -- )
1.33      anton    4200:     @@ . ;
1.29      crook    4201: 
                   4202: foo first-word
                   4203: foo second-word
                   4204: 
                   4205: 123 ' first-word >BODY !
                   4206: @end example
                   4207: 
                   4208: If @code{first-word} had been a @code{CREATE}d word, we could simply
                   4209: have executed it to get the address of its data field. However, since it
                   4210: was defined to have @code{DOES>} actions, its execution semantics are to
                   4211: perform those @code{DOES>} actions. To get the address of its data field
                   4212: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
                   4213: translate the xt into the address of the data field.  When you execute
                   4214: @code{first-word}, it will display @code{123}. When you execute
                   4215: @code{second-word} it will display @code{-1}.
1.26      crook    4216: 
                   4217: @cindex stack effect of @code{DOES>}-parts
                   4218: @cindex @code{DOES>}-parts, stack effect
1.29      crook    4219: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    4220: the stack effect of the defined words, not the stack effect of the
                   4221: following code (the following code expects the address of the body on
                   4222: the top of stack, which is not reflected in the stack comment). This is
                   4223: the convention that I use and recommend (it clashes a bit with using
                   4224: locals declarations for stack effect specification, though).
1.1       anton    4225: 
1.26      crook    4226: @subsubsection Applications of @code{CREATE..DOES>}
                   4227: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1       anton    4228: 
1.26      crook    4229: You may wonder how to use this feature. Here are some usage patterns:
1.1       anton    4230: 
1.26      crook    4231: @cindex factoring similar colon definitions
                   4232: When you see a sequence of code occurring several times, and you can
                   4233: identify a meaning, you will factor it out as a colon definition. When
                   4234: you see similar colon definitions, you can factor them using
                   4235: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   4236: that look very similar:
1.1       anton    4237: @example
1.26      crook    4238: : ori, ( reg-target reg-source n -- )
                   4239:     0 asm-reg-reg-imm ;
                   4240: : andi, ( reg-target reg-source n -- )
                   4241:     1 asm-reg-reg-imm ;
1.1       anton    4242: @end example
                   4243: 
1.26      crook    4244: @noindent
                   4245: This could be factored with:
                   4246: @example
                   4247: : reg-reg-imm ( op-code -- )
                   4248:     CREATE ,
                   4249: DOES> ( reg-target reg-source n -- )
                   4250:     @@ asm-reg-reg-imm ;
                   4251: 
                   4252: 0 reg-reg-imm ori,
                   4253: 1 reg-reg-imm andi,
                   4254: @end example
1.1       anton    4255: 
1.26      crook    4256: @cindex currying
                   4257: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   4258: supply a part of the parameters for a word (known as @dfn{currying} in
                   4259: the functional language community). E.g., @code{+} needs two
                   4260: parameters. Creating versions of @code{+} with one parameter fixed can
                   4261: be done like this:
1.1       anton    4262: @example
1.26      crook    4263: : curry+ ( n1 -- )
                   4264:     CREATE ,
                   4265: DOES> ( n2 -- n1+n2 )
                   4266:     @@ + ;
                   4267: 
                   4268:  3 curry+ 3+
                   4269: -2 curry+ 2-
1.1       anton    4270: @end example
                   4271: 
1.26      crook    4272: @subsubsection The gory details of @code{CREATE..DOES>}
                   4273: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    4274: 
1.26      crook    4275: doc-does>
1.1       anton    4276: 
1.26      crook    4277: @cindex @code{DOES>} in a separate definition
                   4278: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   4279: same definition; you can put the @code{DOES>}-part in a separate
1.29      crook    4280: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    4281: @example
                   4282: : does1 
                   4283: DOES> ( ... -- ... )
                   4284:     ... ;
1.1       anton    4285: 
1.26      crook    4286: : does2
                   4287: DOES> ( ... -- ... )
                   4288:     ... ;
1.1       anton    4289: 
1.26      crook    4290: : def-word ( ... -- ... )
                   4291:     create ...
                   4292:     IF
                   4293:        does1
                   4294:     ELSE
                   4295:        does2
                   4296:     ENDIF ;
                   4297: @end example
1.1       anton    4298: 
1.26      crook    4299: In this example, the selection of whether to use @code{does1} or
                   4300: @code{does2} is made at compile-time; at the time that the child word is
1.29      crook    4301: @code{CREATE}d.
1.1       anton    4302: 
1.26      crook    4303: @cindex @code{DOES>} in interpretation state
                   4304: In a standard program you can apply a @code{DOES>}-part only if the last
                   4305: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   4306: will override the behaviour of the last word defined in any case. In a
                   4307: standard program, you can use @code{DOES>} only in a colon
                   4308: definition. In Gforth, you can also use it in interpretation state, in a
                   4309: kind of one-shot mode; for example:
1.1       anton    4310: @example
1.26      crook    4311: CREATE name ( ... -- ... )
1.29      crook    4312:   @i{initialization}
1.26      crook    4313: DOES>
1.29      crook    4314:   @i{code} ;
1.1       anton    4315: @end example
                   4316: 
1.26      crook    4317: @noindent
                   4318: is equivalent to the standard:
1.1       anton    4319: @example
1.26      crook    4320: :noname
                   4321: DOES>
1.29      crook    4322:     @i{code} ;
1.26      crook    4323: CREATE name EXECUTE ( ... -- ... )
1.29      crook    4324:     @i{initialization}
1.1       anton    4325: @end example
                   4326: 
1.26      crook    4327: You can get the address of the body of a word with:
                   4328: 
                   4329: doc->body
1.1       anton    4330: 
1.26      crook    4331: @node Supplying names, Interpretation and Compilation Semantics, User-defined Defining Words, Defining Words
1.29      crook    4332: @subsection Supplying the name of a defined word
1.26      crook    4333: @cindex names for defined words
                   4334: @cindex defining words, name parameter
1.1       anton    4335: 
1.26      crook    4336: @cindex defining words, name given in a string
1.29      crook    4337: By default, a defining word takes the name for the defined word from the
1.26      crook    4338: input stream. Sometimes you want to supply the name from a string. You
                   4339: can do this with:
1.1       anton    4340: 
1.26      crook    4341: doc-nextname
1.1       anton    4342: 
1.26      crook    4343: For example:
1.1       anton    4344: 
1.26      crook    4345: @example
                   4346: s" foo" nextname create
                   4347: @end example
                   4348: @noindent
                   4349: is equivalent to:
                   4350: @example
                   4351: create foo
                   4352: @end example
1.1       anton    4353: 
1.26      crook    4354: @cindex defining words without name
1.29      crook    4355: Sometimes you want to define an @dfn{anonymous word}; a word without a
1.26      crook    4356: name. You can do this with:
1.1       anton    4357: 
1.26      crook    4358: doc-:noname
1.1       anton    4359: 
1.26      crook    4360: This leaves the execution token for the word on the stack after the
                   4361: closing @code{;}. Here's an example in which a deferred word is
                   4362: initialised with an @code{xt} from an anonymous colon definition:
                   4363: @example
                   4364: Defer deferred
                   4365: :noname ( ... -- ... )
                   4366:   ... ;
                   4367: IS deferred
                   4368: @end example
1.1       anton    4369: 
1.29      crook    4370: @noindent
1.26      crook    4371: Gforth provides an alternative way of doing this, using two separate
                   4372: words:
1.1       anton    4373: 
1.26      crook    4374: doc-noname
                   4375: @cindex execution token of last defined word
                   4376: doc-lastxt
1.1       anton    4377: 
1.29      crook    4378: @noindent
1.26      crook    4379: The previous example can be rewritten using @code{noname} and
                   4380: @code{lastxt}:
1.1       anton    4381: 
1.26      crook    4382: @example
                   4383: Defer deferred
                   4384: noname : ( ... -- ... )
                   4385:   ... ;
                   4386: lastxt IS deferred
                   4387: @end example
1.1       anton    4388: 
1.29      crook    4389: @noindent
1.33      anton    4390: @code{noname} and @code{nextname} work with any defining word, not just
                   4391: @code{:}.
                   4392: 
1.26      crook    4393: @code{lastxt} also works when the last word was not defined as
1.29      crook    4394: @code{noname}. It also has the useful property that is is valid as soon
                   4395: as the header for a definition has been build. Thus:
                   4396: 
                   4397: @example
                   4398: lastxt . : foo [ lastxt . ] ; ' foo .
                   4399: @end example
                   4400: 
                   4401: @noindent
                   4402: prints 3 numbers; the last two are the same.
1.1       anton    4403: 
                   4404: 
1.26      crook    4405: @node Interpretation and Compilation Semantics,  , Supplying names, Defining Words
                   4406: @subsection Interpretation and Compilation Semantics
                   4407: @cindex semantics, interpretation and compilation
1.1       anton    4408: 
1.26      crook    4409: @cindex interpretation semantics
                   4410: The @dfn{interpretation semantics} of a word are what the text
                   4411: interpreter does when it encounters the word in interpret state. It also
                   4412: appears in some other contexts, e.g., the execution token returned by
1.29      crook    4413: @code{' @i{word}} identifies the interpretation semantics of
                   4414: @i{word} (in other words, @code{' @i{word} execute} is equivalent to
                   4415: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    4416: 
1.26      crook    4417: @cindex compilation semantics
                   4418: The @dfn{compilation semantics} of a word are what the text interpreter
                   4419: does when it encounters the word in compile state. It also appears in
1.29      crook    4420: other contexts, e.g, @code{POSTPONE @i{word}} compiles@footnote{In
1.26      crook    4421: standard terminology, ``appends to the current definition''.} the
1.29      crook    4422: compilation semantics of @i{word}.
1.1       anton    4423: 
1.26      crook    4424: @cindex execution semantics
                   4425: The standard also talks about @dfn{execution semantics}. They are used
                   4426: only for defining the interpretation and compilation semantics of many
                   4427: words. By default, the interpretation semantics of a word are to
                   4428: @code{execute} its execution semantics, and the compilation semantics of
                   4429: a word are to @code{compile,} its execution semantics.@footnote{In
                   4430: standard terminology: The default interpretation semantics are its
                   4431: execution semantics; the default compilation semantics are to append its
                   4432: execution semantics to the execution semantics of the current
                   4433: definition.}
                   4434: 
                   4435: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   4436: 
                   4437: @cindex immediate words
                   4438: @cindex compile-only words
                   4439: You can change the semantics of the most-recently defined word:
                   4440: 
                   4441: doc-immediate
                   4442: doc-compile-only
                   4443: doc-restrict
                   4444: 
                   4445: Note that ticking (@code{'}) a compile-only word gives an error
                   4446: (``Interpreting a compile-only word'').
1.1       anton    4447: 
1.26      crook    4448: Gforth also allows you to define words with arbitrary combinations of
                   4449: interpretation and compilation semantics.
1.1       anton    4450: 
1.26      crook    4451: doc-interpret/compile:
1.1       anton    4452: 
1.26      crook    4453: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   4454: recommend that you do not define such words, as cute as they may be:
                   4455: they make it hard to get at both parts of the word in some contexts.
                   4456: E.g., assume you want to get an execution token for the compilation
                   4457: part. Instead, define two words, one that embodies the interpretation
                   4458: part, and one that embodies the compilation part.  Once you have done
                   4459: that, you can define a combined word with @code{interpret/compile:} for
                   4460: the convenience of your users.
1.1       anton    4461: 
1.26      crook    4462: You might try to use this feature to provide an optimizing
                   4463: implementation of the default compilation semantics of a word. For
                   4464: example, by defining:
1.1       anton    4465: @example
1.26      crook    4466: :noname
                   4467:    foo bar ;
                   4468: :noname
                   4469:    POSTPONE foo POSTPONE bar ;
1.29      crook    4470: interpret/compile: opti-foobar
1.1       anton    4471: @end example
1.26      crook    4472: 
1.23      crook    4473: @noindent
1.26      crook    4474: as an optimizing version of:
                   4475: 
1.1       anton    4476: @example
1.26      crook    4477: : foobar
                   4478:     foo bar ;
1.1       anton    4479: @end example
                   4480: 
1.26      crook    4481: Unfortunately, this does not work correctly with @code{[compile]},
                   4482: because @code{[compile]} assumes that the compilation semantics of all
                   4483: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29      crook    4484: opti-foobar} would compile compilation semantics, whereas
                   4485: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    4486: 
1.26      crook    4487: @cindex state-smart words (are a bad idea)
1.29      crook    4488: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    4489: by @code{interpret/compile:} (words are state-smart if they check
                   4490: @code{STATE} during execution). E.g., they would try to code
                   4491: @code{foobar} like this:
1.1       anton    4492: 
1.26      crook    4493: @example
                   4494: : foobar
                   4495:   STATE @@
                   4496:   IF ( compilation state )
                   4497:     POSTPONE foo POSTPONE bar
                   4498:   ELSE
                   4499:     foo bar
                   4500:   ENDIF ; immediate
                   4501: @end example
1.1       anton    4502: 
1.26      crook    4503: Although this works if @code{foobar} is only processed by the text
                   4504: interpreter, it does not work in other contexts (like @code{'} or
                   4505: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   4506: for a state-smart word, not for the interpretation semantics of the
                   4507: original @code{foobar}; when you execute this execution token (directly
                   4508: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   4509: state, the result will not be what you expected (i.e., it will not
                   4510: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   4511: write them@footnote{For a more detailed discussion of this topic, see
                   4512: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
                   4513: Ertl; presented at EuroForth '98 and available from
1.33      anton    4514: @url{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz}}!
1.1       anton    4515: 
1.26      crook    4516: @cindex defining words with arbitrary semantics combinations
                   4517: It is also possible to write defining words that define words with
                   4518: arbitrary combinations of interpretation and compilation semantics. In
                   4519: general, they look like this:
1.1       anton    4520: 
1.26      crook    4521: @example
                   4522: : def-word
                   4523:     create-interpret/compile
1.29      crook    4524:     @i{code1}
1.26      crook    4525: interpretation>
1.29      crook    4526:     @i{code2}
1.26      crook    4527: <interpretation
                   4528: compilation>
1.29      crook    4529:     @i{code3}
1.26      crook    4530: <compilation ;
                   4531: @end example
1.1       anton    4532: 
1.29      crook    4533: For a @i{word} defined with @code{def-word}, the interpretation
                   4534: semantics are to push the address of the body of @i{word} and perform
                   4535: @i{code2}, and the compilation semantics are to push the address of
                   4536: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    4537: can also be defined like this (except that the defined constants don't
                   4538: behave correctly when @code{[compile]}d):
1.1       anton    4539: 
1.26      crook    4540: @example
                   4541: : constant ( n "name" -- )
                   4542:     create-interpret/compile
                   4543:     ,
                   4544: interpretation> ( -- n )
                   4545:     @@
                   4546: <interpretation
                   4547: compilation> ( compilation. -- ; run-time. -- n )
                   4548:     @@ postpone literal
                   4549: <compilation ;
                   4550: @end example
1.1       anton    4551: 
1.26      crook    4552: doc-create-interpret/compile
                   4553: doc-interpretation>
                   4554: doc-<interpretation
                   4555: doc-compilation>
                   4556: doc-<compilation
1.1       anton    4557: 
1.29      crook    4558: Words defined with @code{interpret/compile:} and
1.26      crook    4559: @code{create-interpret/compile} have an extended header structure that
                   4560: differs from other words; however, unless you try to access them with
                   4561: plain address arithmetic, you should not notice this. Words for
                   4562: accessing the header structure usually know how to deal with this; e.g.,
1.29      crook    4563: @code{'} @i{word} @code{>body} also gives you the body of a word created
                   4564: with @code{create-interpret/compile}.
1.1       anton    4565: 
1.27      crook    4566: doc-postpone
1.29      crook    4567: @comment TODO -- expand glossary text for POSTPONE
1.27      crook    4568: 
1.26      crook    4569: @c ----------------------------------------------------------
                   4570: @node The Text Interpreter, Tokens for Words, Defining Words, Words
                   4571: @section  The Text Interpreter
                   4572: @cindex interpreter - outer
                   4573: @cindex text interpreter
                   4574: @cindex outer interpreter
1.1       anton    4575: 
1.34      anton    4576: @c Should we really describe all these ugly details?  IMO the text
                   4577: @c interpreter should be much cleaner, but that may not be possible within
                   4578: @c ANS Forth. - anton
                   4579: 
1.29      crook    4580: The text interpreter@footnote{This is an expanded version of the
                   4581: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34      anton    4582: that processes input from the current input device. It is also called
                   4583: the outer interpreter, in contrast to the inner interpreter
                   4584: (@pxref{Engine}) which executes the compiled Forth code on interpretive
                   4585: implementations.
1.27      crook    4586: 
1.29      crook    4587: @cindex interpret state
                   4588: @cindex compile state
                   4589: The text interpreter operates in one of two states: @dfn{interpret
                   4590: state} and @dfn{compile state}. The current state is defined by the
                   4591: aptly-named variable, @code{state}.
                   4592: 
                   4593: This section starts by describing how the text interpreter behaves when
                   4594: it is in interpret state, processing input from the user input device --
                   4595: the keyboard. This is the mode that a Forth system is in after it starts
                   4596: up.
                   4597: 
                   4598: @cindex input buffer
                   4599: @cindex terminal input buffer
                   4600: The text interpreter works from an area of memory called the @dfn{input
                   4601: buffer}@footnote{When the text interpreter is processing input from the
                   4602: keyboard, this area of memory is called the @dfn{terminal input buffer}
                   4603: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
                   4604: @code{#TIB}.}, which stores your keyboard input when you press the
1.30      anton    4605: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29      crook    4606: leading spaces (called @dfn{delimiters}) then parses a string (a
                   4607: sequence of non-space characters) until it reaches either a space
                   4608: character or the end of the buffer. Having parsed a string, it makes two
                   4609: attempts to process it:
1.27      crook    4610: 
1.29      crook    4611: @cindex dictionary
1.27      crook    4612: @itemize @bullet
                   4613: @item
1.29      crook    4614: It looks for the string in a @dfn{dictionary} of definitions. If the
                   4615: string is found, the string names a @dfn{definition} (also known as a
                   4616: @dfn{word}) and the dictionary search returns information that allows
                   4617: the text interpreter to perform the word's @dfn{interpretation
                   4618: semantics}. In most cases, this simply means that the word will be
                   4619: executed.
1.27      crook    4620: @item
                   4621: If the string is not found in the dictionary, the text interpreter
1.29      crook    4622: attempts to treat it as a number, using the rules described in
                   4623: @ref{Number Conversion}. If the string represents a legal number in the
                   4624: current radix, the number is pushed onto a parameter stack (the data
                   4625: stack for integers, the floating-point stack for floating-point
                   4626: numbers).
                   4627: @end itemize
                   4628: 
                   4629: If both attempts fail, or if the word is found in the dictionary but has
                   4630: no interpretation semantics@footnote{This happens if the word was
                   4631: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
                   4632: remainder of the input buffer, issues an error message and waits for
                   4633: more input. If one of the attempts succeeds, the text interpreter
                   4634: repeats the parsing process until the whole of the input buffer has been
                   4635: processed, at which point it prints the status message ``@code{ ok}''
                   4636: and waits for more input.
                   4637: 
                   4638: @cindex parse area
                   4639: The text interpreter keeps track of its position in the input buffer by
                   4640: updating a variable called @code{>IN} (pronounced ``to-in''). The value
                   4641: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
                   4642: of the input buffer. The region from offset @code{>IN @@} to the end of
                   4643: the input buffer is called the @dfn{parse area}@footnote{In other words,
                   4644: the text interpreter processes the contents of the input buffer by
                   4645: parsing strings from the parse area until the parse area is empty.}.
                   4646: This example shows how @code{>IN} changes as the text interpreter parses
                   4647: the input buffer:
                   4648: 
                   4649: @example
                   4650: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
                   4651:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
                   4652: 
                   4653: 1 2 3 remaining + remaining . 
                   4654: 
                   4655: : foo 1 2 3 remaining SWAP remaining ;
                   4656: @end example
                   4657: 
                   4658: @noindent
                   4659: The result is:
                   4660: 
                   4661: @example
                   4662: ->+ remaining .<-
                   4663: ->.<-5  ok
                   4664: 
                   4665: ->SWAP remaining ;-<
                   4666: ->;<-  ok
                   4667: @end example
                   4668: 
                   4669: @cindex parsing words
                   4670: The value of @code{>IN} can also be modified by a word in the input
                   4671: buffer that is executed by the text interpreter.  This means that a word
                   4672: can ``trick'' the text interpreter into either skipping a section of the
                   4673: input buffer@footnote{This is how parsing words work.} or into parsing a
                   4674: section twice. For example:
1.27      crook    4675: 
1.29      crook    4676: @example
                   4677: : lat ." <<lat>>" ;
                   4678: : flat ." <<flat>>" >IN DUP @@ 3 - SWAP ! ;
                   4679: @end example
                   4680: 
                   4681: @noindent
                   4682: When @code{flat} is executed, this output is produced@footnote{Exercise
                   4683: for the reader: what would happen if the @code{3} were replaced with
                   4684: @code{4}?}:
                   4685: 
                   4686: @example
                   4687: <<flat>><<lat>>
                   4688: @end example
                   4689: 
                   4690: @noindent
                   4691: Two important notes about the behaviour of the text interpreter:
1.27      crook    4692: 
                   4693: @itemize @bullet
                   4694: @item
                   4695: It processes each input string to completion before parsing additional
1.29      crook    4696: characters from the input buffer.
                   4697: @item
                   4698: It treats the input buffer as a read-only region (and so must your code).
                   4699: @end itemize
                   4700: 
                   4701: @noindent
                   4702: When the text interpreter is in compile state, its behaviour changes in
                   4703: these ways:
                   4704: 
                   4705: @itemize @bullet
                   4706: @item
                   4707: If a parsed string is found in the dictionary, the text interpreter will
                   4708: perform the word's @dfn{compilation semantics}. In most cases, this
                   4709: simply means that the execution semantics of the word will be appended
                   4710: to the current definition.
1.27      crook    4711: @item
1.29      crook    4712: When a number is encountered, it is compiled into the current definition
                   4713: (as a literal) rather than being pushed onto a parameter stack.
                   4714: @item
                   4715: If an error occurs, @code{state} is modified to put the text interpreter
                   4716: back into interpret state.
                   4717: @item
                   4718: Each time a line is entered from the keyboard, Gforth prints
                   4719: ``@code{ compiled}'' rather than `` @code{ok}''.
                   4720: @end itemize
                   4721: 
                   4722: @cindex text interpreter - input sources
                   4723: When the text interpreter is using an input device other than the
                   4724: keyboard, its behaviour changes in these ways:
                   4725: 
                   4726: @itemize @bullet
                   4727: @item
                   4728: When the parse area is empty, the text interpreter attempts to refill
                   4729: the input buffer from the input source. When the input source is
                   4730: exhausted, the input source is set back to the user input device.
                   4731: @item
                   4732: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
                   4733: time the parse area is emptied.
                   4734: @item
                   4735: If an error occurs, the input source is set back to the user input
                   4736: device.
1.27      crook    4737: @end itemize
1.21      crook    4738: 
1.29      crook    4739: @ref{Input Sources} describes this in more detail.
                   4740: 
1.26      crook    4741: doc->in
1.27      crook    4742: doc-source
                   4743: 
1.26      crook    4744: doc-tib
                   4745: doc-#tib
1.1       anton    4746: 
1.26      crook    4747: @menu
1.29      crook    4748: * Input Sources::
1.26      crook    4749: * Number Conversion::
                   4750: * Interpret/Compile states::
                   4751: * Literals::
                   4752: * Interpreter Directives::
                   4753: @end menu
1.1       anton    4754: 
1.29      crook    4755: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
                   4756: @subsection Input Sources
                   4757: @cindex input sources
                   4758: @cindex text interpreter - input sources
                   4759: 
                   4760: By default, the text interpreter accepts input from the user input
                   4761: device (the keyboard) when Forth starts up. The text interpreter can
                   4762: process input from any of these sources:
                   4763: 
                   4764: @itemize @bullet
                   4765: @item
                   4766: The user input device -- the keyboard.
                   4767: @item
                   4768: A file, using the words described in @ref{Forth source files}.
                   4769: @item
                   4770: A block, using the words described in @ref{Blocks}.
                   4771: @item
                   4772: A text string, using @code{evaluate}.
                   4773: @end itemize
                   4774: 
                   4775: A program can identify the current input device from the values of
                   4776: @code{source-id} and @code{blk}.
                   4777: 
                   4778: doc-source-id
                   4779: doc-blk
                   4780: 
                   4781: doc-save-input
                   4782: doc-restore-input
                   4783: 
                   4784: doc-evaluate
1.1       anton    4785: 
1.29      crook    4786: 
                   4787: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    4788: @subsection Number Conversion
                   4789: @cindex number conversion
                   4790: @cindex double-cell numbers, input format
                   4791: @cindex input format for double-cell numbers
                   4792: @cindex single-cell numbers, input format
                   4793: @cindex input format for single-cell numbers
                   4794: @cindex floating-point numbers, input format
                   4795: @cindex input format for floating-point numbers
1.1       anton    4796: 
1.29      crook    4797: This section describes the rules that the text interpreter uses when it
                   4798: tries to convert a string into a number.
1.1       anton    4799: 
1.26      crook    4800: Let <digit> represent any character that is a legal digit in the current
1.29      crook    4801: number base@footnote{For example, 0-9 when the number base is decimal or
                   4802: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    4803: 
1.26      crook    4804: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    4805: 
1.29      crook    4806: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
                   4807: in the braces (@i{a} or @i{b} or neither).
1.1       anton    4808: 
1.26      crook    4809: Let * represent any number of instances of the previous character
                   4810: (including none).
1.1       anton    4811: 
1.26      crook    4812: Let any other character represent itself.
1.1       anton    4813: 
1.29      crook    4814: @noindent
1.26      crook    4815: Now, the conversion rules are:
1.21      crook    4816: 
1.26      crook    4817: @itemize @bullet
                   4818: @item
                   4819: A string of the form <digit><digit>* is treated as a single-precision
1.29      crook    4820: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    4821: @item
                   4822: A string of the form -<digit><digit>* is treated as a single-precision
1.29      crook    4823: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    4824: arithmetic. Examples are -45 -5681 -0
                   4825: @item
                   4826: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29      crook    4827: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
                   4828: (all three of these represent the same number).
1.26      crook    4829: @item
                   4830: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29      crook    4831: double-precision (double-cell-sized) negative integer, and is
1.26      crook    4832: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29      crook    4833: -34.65 (all three of these represent the same number).
1.26      crook    4834: @item
1.29      crook    4835: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
                   4836: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35      anton    4837: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29      crook    4838: number) +12.E-4
1.26      crook    4839: @end itemize
1.1       anton    4840: 
1.26      crook    4841: By default, the number base used for integer number conversion is given
1.35      anton    4842: by the contents of the variable @code{base}.  Note that a lot of
                   4843: confusion can result from unexpected values of @code{base}.  If you
                   4844: change @code{base} anywhere, make sure to save the old value and restore
                   4845: it afterwards.  In general I recommend keeping @code{base} decimal, and
                   4846: using the prefixes described below for the popular non-decimal bases.
1.1       anton    4847: 
1.29      crook    4848: doc-dpl
1.26      crook    4849: doc-base
                   4850: doc-hex
                   4851: doc-decimal
1.1       anton    4852: 
1.26      crook    4853: @cindex '-prefix for character strings
                   4854: @cindex &-prefix for decimal numbers
                   4855: @cindex %-prefix for binary numbers
                   4856: @cindex $-prefix for hexadecimal numbers
1.35      anton    4857: Gforth allows you to override the value of @code{base} by using a
1.29      crook    4858: prefix@footnote{Some Forth implementations provide a similar scheme by
                   4859: implementing @code{$} etc. as parsing words that process the subsequent
                   4860: number in the input stream and push it onto the stack. For example, see
                   4861: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
                   4862: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
                   4863: is required between the prefix and the number.} before the first digit
                   4864: of an (integer) number. Four prefixes are supported:
1.1       anton    4865: 
1.26      crook    4866: @itemize @bullet
                   4867: @item
1.35      anton    4868: @code{&} -- decimal
1.26      crook    4869: @item
1.35      anton    4870: @code{%} -- binary
1.26      crook    4871: @item
1.35      anton    4872: @code{$} -- hexadecimal
1.26      crook    4873: @item
1.35      anton    4874: @code{'} -- base @code{max-char+1}
1.26      crook    4875: @end itemize
1.1       anton    4876: 
1.26      crook    4877: Here are some examples, with the equivalent decimal number shown after
                   4878: in braces:
1.1       anton    4879: 
1.26      crook    4880: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
                   4881: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
                   4882: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
                   4883: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    4884: 
1.26      crook    4885: @cindex number conversion - traps for the unwary
1.29      crook    4886: @noindent
1.26      crook    4887: Number conversion has a number of traps for the unwary:
1.1       anton    4888: 
1.26      crook    4889: @itemize @bullet
                   4890: @item
                   4891: You cannot determine the current number base using the code sequence
1.35      anton    4892: @code{base @@ .} -- the number base is always 10 in the current number
                   4893: base. Instead, use something like @code{base @@ dec.}
1.26      crook    4894: @item
                   4895: If the number base is set to a value greater than 14 (for example,
                   4896: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   4897: it to be intepreted as either a single-precision integer or a
                   4898: floating-point number (Gforth treats it as an integer). The ambiguity
                   4899: can be resolved by explicitly stating the sign of the mantissa and/or
                   4900: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   4901: ambiguity arises; either representation will be treated as a
                   4902: floating-point number.
                   4903: @item
1.29      crook    4904: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    4905: It is used to specify file types.
                   4906: @item
                   4907: ANS Forth requires the @code{.} of a double-precision number to
                   4908: be the final character in the string. Allowing the @code{.} to be
                   4909: anywhere after the first digit is a Gforth extension.
                   4910: @item
                   4911: The number conversion process does not check for overflow.
                   4912: @item
                   4913: In Gforth, number conversion to floating-point numbers always use base
1.35      anton    4914: 10, irrespective of the value of @code{base}. In ANS Forth,
1.26      crook    4915: conversion to floating-point numbers whilst the value of
1.35      anton    4916: @code{base} is not 10 is an ambiguous condition.
1.26      crook    4917: @end itemize
1.1       anton    4918: 
1.29      crook    4919: @ref{Input} describes words that you can use to read numbers into your
                   4920: programs.
1.1       anton    4921: 
1.26      crook    4922: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
                   4923: @subsection Interpret/Compile states
                   4924: @cindex Interpret/Compile states
1.1       anton    4925: 
1.29      crook    4926: A standard program is not permitted to change @code{state}
                   4927: explicitly. However, it can change @code{state} implicitly, using the
                   4928: words @code{[} and @code{]}. When @code{[} is executed it switches
                   4929: @code{state} to interpret state, and therefore the text interpreter
                   4930: starts interpreting. When @code{]} is executed it switches @code{state}
                   4931: to compile state and therefore the text interpreter starts
                   4932: compiling. The most common usage for these words is to compile literals,
                   4933: as shown in @ref{Literals}. However, they give you the freedom to switch
1.35      anton    4934: modes at will.
                   4935: 
                   4936: @c This is a bad example: It's non-standard, and it's not necessary.
                   4937: @c However, I can't think of a good example for switching into compile
                   4938: @c state when there is no current word (@code{state}-smart words are not a
                   4939: @c good reason).  So maybe we should use an example for switching into
                   4940: @c interpret @code{state} in a colon def. - anton
                   4941: 
                   4942: Here is an example of building a jump-table of execution
1.29      crook    4943: tokens:
                   4944: 
                   4945: @example
                   4946: : AA ." this is A" ;
                   4947: : BB ." this is B" ;
                   4948: : CC ." this is C" ;
                   4949: 
                   4950: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
                   4951: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
                   4952:   cells table + @ execute ;
                   4953: @end example
                   4954: 
                   4955: @noindent
                   4956: Now @code{0 go} will display ``@code{this is A}''. The table can be
                   4957: built far more neatly@footnote{The source code is neater.. what is
                   4958: compiled in memory in each case is identical.} like this:
                   4959: 
                   4960: @example
                   4961: create table ] aa bb cc [
                   4962: @end example
                   4963: 
                   4964: The problem with this code is that it is not portable; it will only work
                   4965: on systems where code space and data space co-incide. The reason is that
                   4966: both tables @i{compile} execution tokens -- into code space. The
                   4967: Standard only allows data space to be assigned for a @code{CREATE}d
                   4968: word. In addition, the Standard only allows @code{@@} to access data
                   4969: space, whilst this example is using it to access code space. The only
                   4970: portable, Standard way to build this table is to build it in data space,
                   4971: like this:
                   4972: 
                   4973: @example
                   4974: create table ' aa , ' bb , ' cc ,
                   4975: @end example
                   4976: 
                   4977: @noindent
                   4978: A similar technique can be used to build a table of constants:
                   4979: 
                   4980: @example
                   4981: create primes 1 , 3 , 5 , 7 , 11 ,
                   4982: @end example
1.1       anton    4983: 
1.26      crook    4984: doc-state
                   4985: doc-[
                   4986: doc-]
1.1       anton    4987: 
1.26      crook    4988: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
                   4989: @subsection Literals
                   4990: @cindex Literals
1.21      crook    4991: 
1.29      crook    4992: Often, you want to use a number within a colon definition. When you do
                   4993: this, the text interpreter automatically compiles the number as a
                   4994: @i{literal}. A literal is a number whose run-time effect is to be pushed
                   4995: onto the stack.  If you had to do some maths to generate the number, you
                   4996: might write it like this:
                   4997: 
                   4998: @example
                   4999: : HOUR-TO-SEC ( n1 -- n2 )
                   5000:   60 *      \ to minutes
                   5001:   60 * ;    \ to seconds
                   5002: @end example
                   5003: 
                   5004: It is very clear what this definition is doing, but it's inefficient
                   5005: since it is performing 2 multiples at run-time. An alternative would be
                   5006: to write:
                   5007: 
                   5008: @example
                   5009: : HOUR-TO-SEC ( n1 -- n2 )
                   5010:   3600 * ;  \ to seconds
                   5011: @end example
                   5012: 
                   5013: Which does the same thing, and has the advantage of using a single
                   5014: multiply. Ideally, we'd like the efficiency of the second with the
                   5015: readability of the first.
                   5016: 
                   5017: @code{Literal} allows us to achieve that. It takes a number from the
                   5018: stack and lays it down in the current definition just as though the
                   5019: number had been typed directly into the definition. Our first attempt
                   5020: might look like this:
                   5021: 
                   5022: @example
                   5023: 60          \ mins per hour
                   5024: 60 *        \ seconds per minute
                   5025: : HOUR-TO-SEC ( n1 -- n2 )
                   5026:   Literal * ;  \ to seconds
                   5027: @end example
                   5028: 
                   5029: But this produces the error message @code{unstructured}. What happened?
                   5030: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
                   5031: @i{colon-sys} is implementation-defined. In other words, once we start a
                   5032: colon definition we can't portably access anything that was on the stack
                   5033: before the definition began@footnote{@cite{Two Problems in ANS Forth},
                   5034: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
                   5035: some situations where you might want to access stack items above
                   5036: colon-sys, and provides a solution to the problem.}. The correct way of
                   5037: solving this problem in this instance is to use @code{[ ]} like this:
                   5038: 
                   5039: @example
                   5040: : HOUR-TO-SEC ( n1 -- n2 )
                   5041:   [ 60          \ minutes per hour
                   5042:     60 * ]      \ seconds per minute
                   5043:   LITERAL * ;   \ to seconds
                   5044: @end example
1.23      crook    5045: 
1.26      crook    5046: doc-literal
                   5047: doc-]L
                   5048: doc-2literal
                   5049: doc-fliteral
1.1       anton    5050: 
1.29      crook    5051: @node Interpreter Directives, , Literals, The Text Interpreter
1.26      crook    5052: @subsection Interpreter Directives
                   5053: @cindex interpreter directives
1.1       anton    5054: 
1.29      crook    5055: These words are usually used in interpret state; typically to control
                   5056: which parts of a source file are processed by the text
1.26      crook    5057: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   5058: supplements these with a rich set of immediate control structure words
                   5059: to compensate for the fact that the non-immediate versions can only be
1.29      crook    5060: used in compile state (@pxref{Control Structures}). Typical usages:
                   5061: 
                   5062: @example
                   5063: FALSE Constant ASSEMBLER
                   5064: .
                   5065: .
                   5066: ASSEMBLER [IF]
                   5067: : ASSEMBLER-FEATURE
                   5068:   ...
                   5069: ;
                   5070: [ENDIF]
                   5071: .
                   5072: .
                   5073: : SEE
                   5074:   ... \ general-purpose SEE code
                   5075:   [ ASSEMBLER [IF] ]
                   5076:   ... \ assembler-specific SEE code
                   5077:   [ [ENDIF] ]
                   5078: ;
                   5079: @end example
1.1       anton    5080: 
1.26      crook    5081: doc-[IF]
                   5082: doc-[ELSE]
                   5083: doc-[THEN]
                   5084: doc-[ENDIF]
1.1       anton    5085: 
1.26      crook    5086: doc-[IFDEF]
                   5087: doc-[IFUNDEF]
1.1       anton    5088: 
1.26      crook    5089: doc-[?DO]
                   5090: doc-[DO]
                   5091: doc-[FOR]
                   5092: doc-[LOOP]
                   5093: doc-[+LOOP]
                   5094: doc-[NEXT]
1.1       anton    5095: 
1.26      crook    5096: doc-[BEGIN]
                   5097: doc-[UNTIL]
                   5098: doc-[AGAIN]
                   5099: doc-[WHILE]
                   5100: doc-[REPEAT]
1.1       anton    5101: 
1.27      crook    5102: 
                   5103: 
1.26      crook    5104: @c -------------------------------------------------------------
                   5105: @node Tokens for Words, Word Lists, The Text Interpreter, Words
                   5106: @section Tokens for Words
                   5107: @cindex tokens for words
1.1       anton    5108: 
1.28      crook    5109: This section describes the creation and use of tokens that represent
1.29      crook    5110: words.
                   5111: 
1.32      anton    5112: Named words have information stored in their header space entries to
1.29      crook    5113: indicate any non-default semantics (@pxref{Interpretation and
                   5114: Compilation Semantics}). The semantics can be modified, using
                   5115: @code{immediate} and/or @code{compile-only}, at the time that the words
1.32      anton    5116: are defined. Unnamed words have (by definition) no header space
1.29      crook    5117: entry, and therefore must have default semantics.
1.21      crook    5118: 
1.26      crook    5119: Named words have interpretation and compilation semantics. Unnamed words
                   5120: just have execution semantics.
1.21      crook    5121: 
1.29      crook    5122: @cindex xt
                   5123: @cindex execution token
                   5124: The execution semantics of an unnamed word are represented by an
                   5125: @dfn{execution token} (@i{xt}). As explained in @ref{Supplying names},
                   5126: the execution token of the last word defined can be produced with
                   5127: @code{lastxt}.
                   5128: 
                   5129: The interpretation semantics of a named word are also represented by an
                   5130: execution token. You can produce the execution token using @code{'} or
                   5131: @code{[']}. A simple example shows the difference between the two:
1.21      crook    5132: 
1.29      crook    5133: @example
                   5134: : greet ( -- )   ." Hello" ;
1.36      anton    5135: : foo ( -- xt )  ['] greet execute ; \ ['] parses greet at compile-time
                   5136: : bar ( -- )     ' execute ; \  '  parses at run-time
1.1       anton    5137: 
1.29      crook    5138: \ the next four lines all do the same thing
1.36      anton    5139: foo
                   5140: bar greet
1.29      crook    5141: greet
                   5142: ' greet EXECUTE
                   5143: @end example
1.1       anton    5144: 
1.29      crook    5145: An execution token occupies one cell.
1.26      crook    5146: @cindex code field address
                   5147: @cindex CFA
1.29      crook    5148: In Gforth, the abstract data type @i{execution token} is implemented
1.26      crook    5149: as a code field address (CFA).
                   5150: @comment TODO note that the standard does not say what it represents..
                   5151: @comment and you cannot necessarily compile it in all Forths (eg native
                   5152: @comment compilers?).
1.1       anton    5153: 
1.29      crook    5154: For literals, use @code{'} in interpreted code and @code{[']} in
                   5155: compiled code. Gforth's @code{'} and @code{[']} behave somewhat
                   5156: unusually by complaining about compile-only words. To get the execution
                   5157: token for a compile-only word @i{name}, use @code{COMP' @i{name} DROP}
                   5158: or @code{[COMP'] @i{name} DROP}.
1.1       anton    5159: 
1.26      crook    5160: @cindex compilation token
1.29      crook    5161: The compilation semantics of a named word are represented by a
                   5162: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
                   5163: @i{xt} is an execution token. The compilation semantics represented by
                   5164: the compilation token can be performed with @code{execute}, which
                   5165: consumes the whole compilation token, with an additional stack effect
                   5166: determined by the represented compilation semantics.
                   5167: 
                   5168: At present, the @i{w} part of a compilation token is an execution token,
                   5169: and the @i{xt} part represents either @code{execute} or
                   5170: @code{compile,}@footnote{Depending upon the compilation semantics of the
                   5171: word. If the word has default compilation semantics, the @i{xt} will
1.36      anton    5172: represent @code{compile,}. Otherwise (e.g., for immediate words), the
                   5173: @i{xt} will represent @code{execute}.}. However, don't rely on that
                   5174: knowledge, unless necessary; future versions of Gforth may introduce
                   5175: unusual compilation tokens (e.g., a compilation token that represents
                   5176: the compilation semantics of a literal).
1.1       anton    5177: 
1.26      crook    5178: You can compile the compilation semantics with @code{postpone,}. I.e.,
1.29      crook    5179: @code{COMP' @i{word} postpone,} is equivalent to @code{postpone
                   5180: @i{word}}.
1.21      crook    5181: 
1.26      crook    5182: @cindex name token
                   5183: @cindex name field address
                   5184: @cindex NFA
1.29      crook    5185: Named words are also represented by the @dfn{name token}, (@i{nt}). In
                   5186: Gforth, the abstract data type @emph{name token} is implemented as a
                   5187: name field address (NFA).
                   5188: 
                   5189: doc-execute
                   5190: doc-compile,
                   5191: doc-[']
                   5192: doc-'
                   5193: doc-[comp']
                   5194: doc-comp'
                   5195: doc-postpone,
1.1       anton    5196: 
1.26      crook    5197: doc-find-name
                   5198: doc-name>int
                   5199: doc-name?int
                   5200: doc-name>comp
                   5201: doc-name>string
1.1       anton    5202: 
1.26      crook    5203: @c -------------------------------------------------------------
                   5204: @node Word Lists, Environmental Queries, Tokens for Words, Words
                   5205: @section Word Lists
                   5206: @cindex word lists
1.32      anton    5207: @cindex header space
1.1       anton    5208: 
1.36      anton    5209: A wordlist is a list of named words; you can add new words and look up
                   5210: words by name (and you can remove words in a restricted way with
                   5211: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
                   5212: 
                   5213: @cindex search order stack
                   5214: The text interpreter searches the wordlists present in the search order
                   5215: (a stack of wordlists), from the top to the bottom.  Within each
                   5216: wordlist, the search starts conceptually at the newest word; i.e., if
                   5217: two words in a wordlist have the same name, the newer word is found.
1.1       anton    5218: 
1.26      crook    5219: @cindex compilation word list
1.36      anton    5220: New words are added to the @dfn{compilation wordlist} (aka current
                   5221: wordlist).
1.1       anton    5222: 
1.36      anton    5223: @cindex wid
                   5224: A word list is identified by a cell-sized word list identifier (@i{wid})
                   5225: in much the same way as a file is identified by a file handle. The
                   5226: numerical value of the wid has no (portable) meaning, and might change
                   5227: from session to session.
1.1       anton    5228: 
1.29      crook    5229: The ANS Forth ``Search order'' word set is intended to provide a set of
                   5230: low-level tools that allow various different schemes to be
1.26      crook    5231: implemented. Gforth provides @code{vocabulary}, a traditional Forth
                   5232: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
                   5233: Standard Forth.
1.1       anton    5234: 
1.27      crook    5235: @comment TODO: locals section refers to here, saying that every word list (aka
                   5236: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.1       anton    5237: 
1.27      crook    5238: @comment the thisone- prefix is used to pick out the true definition of a
                   5239: @comment word from the source files, rather than some alias.
1.26      crook    5240: doc-forth-wordlist
                   5241: doc-definitions
                   5242: doc-get-current
                   5243: doc-set-current
                   5244: doc-get-order
1.27      crook    5245: doc---thisone-set-order
1.26      crook    5246: doc-wordlist
1.30      anton    5247: doc-table
1.36      anton    5248: doc-push-order
                   5249: doc-previous
1.26      crook    5250: doc-also
1.27      crook    5251: doc---thisone-forth
1.26      crook    5252: doc-only
1.27      crook    5253: doc---thisone-order
1.15      anton    5254: 
1.26      crook    5255: doc-find
                   5256: doc-search-wordlist
1.15      anton    5257: 
1.26      crook    5258: doc-words
                   5259: doc-vlist
1.1       anton    5260: 
1.26      crook    5261: doc-mappedwordlist
                   5262: doc-root
                   5263: doc-vocabulary
                   5264: doc-seal
                   5265: doc-vocs
                   5266: doc-current
                   5267: doc-context
1.1       anton    5268: 
1.26      crook    5269: @menu
                   5270: * Why use word lists?::
                   5271: * Word list examples::
                   5272: @end menu
                   5273: 
                   5274: @node Why use word lists?, Word list examples, Word Lists, Word Lists
                   5275: @subsection Why use word lists?
                   5276: @cindex word lists - why use them?
                   5277: 
1.29      crook    5278: Here are some reasons for using multiple word lists:
1.26      crook    5279: 
                   5280: @itemize @bullet
                   5281: @item
1.32      anton    5282: To improve compilation speed by reducing the number of header space
1.26      crook    5283: entries that must be searched. This is achieved by creating a new
                   5284: word list that contains all of the definitions that are used in the
                   5285: definition of a Forth system but which would not usually be used by
                   5286: programs running on that system. That word list would be on the search
                   5287: list when the Forth system was compiled but would be removed from the
                   5288: search list for normal operation. This can be a useful technique for
                   5289: low-performance systems (for example, 8-bit processors in embedded
                   5290: systems) but is unlikely to be necessary in high-performance desktop
                   5291: systems.
                   5292: @item
                   5293: To prevent a set of words from being used outside the context in which
                   5294: they are valid. Two classic examples of this are an integrated editor
                   5295: (all of the edit commands are defined in a separate word list; the
                   5296: search order is set to the editor word list when the editor is invoked;
                   5297: the old search order is restored when the editor is terminated) and an
                   5298: integrated assembler (the op-codes for the machine are defined in a
                   5299: separate word list which is used when a @code{CODE} word is defined).
                   5300: @item
                   5301: To prevent a name-space clash between multiple definitions with the same
                   5302: name. For example, when building a cross-compiler you might have a word
                   5303: @code{IF} that generates conditional code for your target system. By
                   5304: placing this definition in a different word list you can control whether
                   5305: the host system's @code{IF} or the target system's @code{IF} get used in
                   5306: any particular context by controlling the order of the word lists on the
                   5307: search order stack.
                   5308: @end itemize
1.1       anton    5309: 
1.26      crook    5310: @node Word list examples, ,Why use word lists?, Word Lists
                   5311: @subsection Word list examples
                   5312: @cindex word lists - examples
1.1       anton    5313: 
1.26      crook    5314: Here is an example of creating and using a new wordlist using ANS
                   5315: Forth Standard words:
1.1       anton    5316: 
                   5317: @example
1.26      crook    5318: wordlist constant my-new-words-wordlist
                   5319: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
1.21      crook    5320: 
1.26      crook    5321: \ add it to the search order
                   5322: also my-new-words
1.21      crook    5323: 
1.26      crook    5324: \ alternatively, add it to the search order and make it
                   5325: \ the compilation word list
                   5326: also my-new-words definitions
                   5327: \ type "order" to see the problem
1.21      crook    5328: @end example
                   5329: 
1.26      crook    5330: The problem with this example is that @code{order} has no way to
                   5331: associate the name @code{my-new-words} with the wid of the word list (in
                   5332: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   5333: that has no associated name). There is no Standard way of associating a
                   5334: name with a wid.
                   5335: 
                   5336: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   5337: associates a name with a wid:
1.21      crook    5338: 
1.26      crook    5339: @example
                   5340: vocabulary my-new-words
1.21      crook    5341: 
1.26      crook    5342: \ add it to the search order
                   5343: my-new-words
1.21      crook    5344: 
1.26      crook    5345: \ alternatively, add it to the search order and make it
                   5346: \ the compilation word list
                   5347: my-new-words definitions
                   5348: \ type "order" to see that the problem is solved
                   5349: @end example
1.23      crook    5350: 
1.26      crook    5351: @c -------------------------------------------------------------
                   5352: @node Environmental Queries, Files, Word Lists, Words
                   5353: @section Environmental Queries
                   5354: @cindex environmental queries
1.21      crook    5355: 
1.26      crook    5356: ANS Forth introduced the idea of ``environmental queries'' as a way
                   5357: for a program running on a system to determine certain characteristics of the system.
                   5358: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    5359: 
1.32      anton    5360: The Standard requires that the header space used for environmental queries
                   5361: be distinct from the header space used for definitions.
1.21      crook    5362: 
1.26      crook    5363: Typically, environmental queries are supported by creating a set of
1.29      crook    5364: definitions in a word list that is @i{only} used during environmental
1.26      crook    5365: queries; that is what Gforth does. There is no Standard way of adding
                   5366: definitions to the set of recognised environmental queries, but any
                   5367: implementation that supports the loading of optional word sets must have
                   5368: some mechanism for doing this (after loading the word set, the
                   5369: associated environmental query string must return @code{true}). In
                   5370: Gforth, the word list used to honour environmental queries can be
                   5371: manipulated just like any other word list.
1.21      crook    5372: 
1.26      crook    5373: doc-environment?
                   5374: doc-environment-wordlist
1.21      crook    5375: 
1.26      crook    5376: doc-gforth
                   5377: doc-os-class
1.21      crook    5378: 
1.26      crook    5379: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   5380: returning two items on the stack, querying it using @code{environment?}
                   5381: will return an additional item; the @code{true} flag that shows that the
                   5382: string was recognised.
1.21      crook    5383: 
1.26      crook    5384: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    5385: 
1.26      crook    5386: Here are some examples of using environmental queries:
1.21      crook    5387: 
1.26      crook    5388: @example
                   5389: s" address-unit-bits" environment? 0=
                   5390: [IF]
                   5391:      cr .( environmental attribute address-units-bits unknown... ) cr
                   5392: [THEN]
1.21      crook    5393: 
1.26      crook    5394: s" block" environment? [IF] DROP include block.fs [THEN]
1.21      crook    5395: 
1.26      crook    5396: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
1.21      crook    5397: 
1.26      crook    5398: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   5399:                         [ELSE] .( Not Gforth..) [THEN]
                   5400: @end example
1.21      crook    5401: 
                   5402: 
1.26      crook    5403: Here is an example of adding a definition to the environment word list:
1.21      crook    5404: 
1.26      crook    5405: @example
                   5406: get-current environment-wordlist set-current
                   5407: true constant block
                   5408: true constant block-ext
                   5409: set-current
                   5410: @end example
1.21      crook    5411: 
1.26      crook    5412: You can see what definitions are in the environment word list like this:
1.21      crook    5413: 
1.26      crook    5414: @example
                   5415: get-order 1+ environment-wordlist swap set-order words previous
                   5416: @end example
1.21      crook    5417: 
                   5418: 
1.26      crook    5419: @c -------------------------------------------------------------
                   5420: @node Files, Blocks, Environmental Queries, Words
                   5421: @section Files
1.28      crook    5422: @cindex files
                   5423: @cindex I/O - file-handling
1.21      crook    5424: 
1.26      crook    5425: Gforth provides facilities for accessing files that are stored in the
                   5426: host operating system's file-system. Files that are processed by Gforth
                   5427: can be divided into two categories:
1.21      crook    5428: 
1.23      crook    5429: @itemize @bullet
                   5430: @item
1.29      crook    5431: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    5432: @item
1.29      crook    5433: Files that are processed by some other program (@dfn{general files}).
1.26      crook    5434: @end itemize
                   5435: 
                   5436: @menu
                   5437: * Forth source files::
                   5438: * General files::         
                   5439: * Search Paths::                 
                   5440: * Forth Search Paths::    
                   5441: * General Search Paths::        
                   5442: @end menu
                   5443: 
1.21      crook    5444: 
1.26      crook    5445: @c -------------------------------------------------------------
                   5446: @node Forth source files, General files, Files, Files
                   5447: @subsection Forth source files
                   5448: @cindex including files
                   5449: @cindex Forth source files
1.21      crook    5450: 
1.26      crook    5451: The simplest way to interpret the contents of a file is to use one of
                   5452: these two formats:
1.21      crook    5453: 
1.26      crook    5454: @example
                   5455: include mysource.fs
                   5456: s" mysource.fs" included
                   5457: @end example
1.21      crook    5458: 
1.26      crook    5459: Sometimes you want to include a file only if it is not included already
                   5460: (by, say, another source file). In that case, you can use one of these
                   5461: fomats:
1.21      crook    5462: 
1.26      crook    5463: @example
                   5464: require mysource.fs
                   5465: needs mysource.fs
                   5466: s" mysource.fs" required
                   5467: @end example
1.21      crook    5468: 
1.26      crook    5469: @cindex stack effect of included files
                   5470: @cindex including files, stack effect
                   5471: I recommend that you write your source files such that interpreting them
                   5472: does not change the stack. This allows using these files with
                   5473: @code{required} and friends without complications. For example:
1.21      crook    5474: 
1.26      crook    5475: @example
                   5476: 1 require foo.fs drop
                   5477: @end example
1.21      crook    5478: 
1.26      crook    5479: doc-include-file
                   5480: doc-included
1.28      crook    5481: doc-included?
1.26      crook    5482: doc-include
                   5483: doc-required
                   5484: doc-require
                   5485: doc-needs
1.28      crook    5486: doc-init-included-files
1.21      crook    5487: 
1.26      crook    5488: A definition in ANS Forth for @code{required} is provided in
                   5489: @file{compat/required.fs}.
1.21      crook    5490: 
1.26      crook    5491: @c -------------------------------------------------------------
                   5492: @node General files, Search Paths, Forth source files, Files
                   5493: @subsection General files
                   5494: @cindex general files
                   5495: @cindex file-handling
1.21      crook    5496: 
1.26      crook    5497: Files are opened/created by name and type. The following types are
                   5498: recognised:
1.1       anton    5499: 
1.26      crook    5500: doc-r/o
                   5501: doc-r/w
                   5502: doc-w/o
                   5503: doc-bin
1.1       anton    5504: 
1.26      crook    5505: When a file is opened/created, it returns a file identifier,
1.29      crook    5506: @i{wfileid} that is used for all other file commands. All file
                   5507: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    5508: successful operation and an implementation-defined non-zero value in the
                   5509: case of an error.
1.21      crook    5510: 
1.26      crook    5511: doc-open-file
                   5512: doc-create-file
1.21      crook    5513: 
1.26      crook    5514: doc-close-file
                   5515: doc-delete-file
                   5516: doc-rename-file
                   5517: doc-read-file
                   5518: doc-read-line
                   5519: doc-write-file
                   5520: doc-write-line
                   5521: doc-emit-file
                   5522: doc-flush-file
1.21      crook    5523: 
1.26      crook    5524: doc-file-status
                   5525: doc-file-position
                   5526: doc-reposition-file
                   5527: doc-file-size
                   5528: doc-resize-file
1.21      crook    5529: 
1.26      crook    5530: @c ---------------------------------------------------------
                   5531: @node Search Paths, Forth Search Paths, General files, Files
                   5532: @subsection Search Paths
                   5533: @cindex path for @code{included}
                   5534: @cindex file search path
                   5535: @cindex @code{include} search path
                   5536: @cindex search path for files
1.21      crook    5537: 
1.26      crook    5538: If you specify an absolute filename (i.e., a filename starting with
                   5539: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   5540: @samp{C:...})) for @code{included} and friends, that file is included
                   5541: just as you would expect.
1.21      crook    5542: 
1.26      crook    5543: For relative filenames, Gforth uses a search path similar to Forth's
                   5544: search order (@pxref{Word Lists}). It tries to find the given filename
                   5545: in the directories present in the path, and includes the first one it
                   5546: finds. There are separate search paths for Forth source files and
                   5547: general files.
1.21      crook    5548: 
1.26      crook    5549: If the search path contains the directory @file{.} (as it should), this
                   5550: refers to the directory that the present file was @code{included}
                   5551: from. This allows files to include other files relative to their own
                   5552: position (irrespective of the current working directory or the absolute
                   5553: position).  This feature is essential for libraries consisting of
                   5554: several files, where a file may include other files from the library.
                   5555: It corresponds to @code{#include "..."} in C. If the current input
                   5556: source is not a file, @file{.} refers to the directory of the innermost
                   5557: file being included, or, if there is no file being included, to the
                   5558: current working directory.
1.21      crook    5559: 
1.26      crook    5560: Use @file{~+} to refer to the current working directory (as in the
                   5561: @code{bash}).
1.1       anton    5562: 
1.26      crook    5563: If the filename starts with @file{./}, the search path is not searched
                   5564: (just as with absolute filenames), and the @file{.} has the same meaning
                   5565: as described above.
1.1       anton    5566: 
1.26      crook    5567: @c ---------------------------------------------------------
                   5568: @node Forth Search Paths, General Search Paths, Search Paths, Files
                   5569: @subsubsection Forth Search Paths
1.28      crook    5570: @cindex search path control - Forth
1.5       anton    5571: 
1.26      crook    5572: The search path is initialized when you start Gforth (@pxref{Invoking
                   5573: Gforth}). You can display it and change it using these words:
1.5       anton    5574: 
1.26      crook    5575: doc-.fpath
                   5576: doc-fpath+
                   5577: doc-fpath=
                   5578: doc-open-fpath-file
1.5       anton    5579: 
1.26      crook    5580: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    5581: 
1.26      crook    5582: @example
                   5583: fpath= /usr/lib/forth/|./
                   5584: require timer.fs
                   5585: @end example
1.5       anton    5586: 
1.26      crook    5587: @c ---------------------------------------------------------
                   5588: @node General Search Paths,  , Forth Search Paths, Files
                   5589: @subsubsection General Search Paths
                   5590: @cindex search path control - for user applications
1.5       anton    5591: 
1.26      crook    5592: Your application may need to search files in several directories, like
                   5593: @code{included} does. To facilitate this, Gforth allows you to define
                   5594: and use your own search paths, by providing generic equivalents of the
                   5595: Forth search path words:
1.5       anton    5596: 
1.26      crook    5597: doc-.path
                   5598: doc-path+
                   5599: doc-path=
                   5600: doc-open-path-file
1.5       anton    5601: 
1.26      crook    5602: Here's an example of creating a search path:
1.5       anton    5603: 
1.26      crook    5604: @example
                   5605: \ Make a buffer for the path:
                   5606: create mypath   100 chars ,     \ maximum length (is checked)
                   5607:                 0 ,             \ real len
                   5608:                 100 chars allot \ space for path
                   5609: @end example
1.5       anton    5610: 
1.26      crook    5611: @c -------------------------------------------------------------
                   5612: @node Blocks, Other I/O, Files, Words
                   5613: @section Blocks
1.28      crook    5614: @cindex I/O - blocks
                   5615: @cindex blocks
                   5616: 
                   5617: When you run Gforth on a modern desk-top computer, it runs under the
                   5618: control of an operating system which provides certain services.  One of
                   5619: these services is @var{file services}, which allows Forth source code
                   5620: and data to be stored in files and read into Gforth (@pxref{Files}).
                   5621: 
                   5622: Traditionally, Forth has been an important programming language on
                   5623: systems where it has interfaced directly to the underlying hardware with
                   5624: no intervening operating system. Forth provides a mechanism, called
1.29      crook    5625: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    5626: 
                   5627: A block is a 1024-byte data area, which can be used to hold data or
                   5628: Forth source code. No structure is imposed on the contents of the
                   5629: block. A block is identified by its number; blocks are numbered
                   5630: contiguously from 1 to an implementation-defined maximum.
                   5631: 
                   5632: A typical system that used blocks but no operating system might use a
                   5633: single floppy-disk drive for mass storage, with the disks formatted to
                   5634: provide 256-byte sectors. Blocks would be implemented by assigning the
                   5635: first four sectors of the disk to block 1, the second four sectors to
                   5636: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   5637: would not contain any file system information, just the set of blocks.
                   5638: 
1.29      crook    5639: @cindex blocks file
1.28      crook    5640: On systems that do provide file services, blocks are typically
1.29      crook    5641: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    5642: file}.  The size of the blocks file will be an exact multiple of 1024
                   5643: bytes, corresponding to the number of blocks it contains. This is the
                   5644: mechanism that Gforth uses.
                   5645: 
1.29      crook    5646: @cindex @file{blocks.fb}
1.28      crook    5647: Only 1 blocks file can be open at a time. If you use block words without
                   5648: having specified a blocks file, Gforth defaults to the blocks file
                   5649: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
                   5650: locate a blocks file (@pxref{Forth Search Paths}).
                   5651: 
1.29      crook    5652: @cindex block buffers
1.28      crook    5653: When you read and write blocks under program control, Gforth uses a
1.29      crook    5654: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    5655: not used when you use @code{load} to interpret the contents of a block.
                   5656: 
                   5657: The behaviour of the block buffers is directly analagous to that of a
                   5658: cache. Each block buffer has three states:
                   5659: 
                   5660: @itemize @bullet
                   5661: @item
                   5662: Unassigned
                   5663: @item
                   5664: Assigned-clean
                   5665: @item
                   5666: Assigned-dirty
                   5667: @end itemize
                   5668: 
1.29      crook    5669: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    5670: block, the block (specified by its block number) must be assigned to a
                   5671: block buffer.
                   5672: 
                   5673: The assignment of a block to a block buffer is performed by @code{block}
                   5674: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   5675: contents of a block. Use @code{buffer} when you don't care about the
                   5676: existing contents of the block@footnote{The ANS Forth definition of
1.35      anton    5677: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28      crook    5678: with the particular block is already stored in a block buffer due to an
                   5679: earlier @code{block} command, @code{buffer} will return that block
                   5680: buffer and the existing contents of the block will be
                   5681: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29      crook    5682: block buffer for the block.}.
1.28      crook    5683: 
                   5684: Once a block has been assigned to a block buffer, the block buffer state
1.29      crook    5685: becomes @i{assigned-clean}. Data can now be manipulated within the
1.28      crook    5686: block buffer.
                   5687: 
                   5688: When the contents of a block buffer is changed it is necessary,
                   5689: @i{before calling} @code{block} @i{or} @code{buffer} @i{again}, to
                   5690: either abandon the changes (by doing nothing) or commit the changes,
                   5691: using @code{update}. Using @code{update} does not change the blocks
1.29      crook    5692: file; it simply changes a block buffer's state to @i{assigned-dirty}.
1.28      crook    5693: 
1.29      crook    5694: The word @code{flush} causes all @i{assigned-dirty} blocks to be
1.28      crook    5695: written back to the blocks file on disk. Leaving Gforth using @code{bye}
                   5696: also causes a @code{flush} to be performed.
                   5697: 
1.29      crook    5698: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    5699: algorithm to assign a block buffer to a block. That means that any
                   5700: particular block can only be assigned to one specific block buffer,
1.29      crook    5701: called (for the particular operation) the @i{victim buffer}. If the
                   5702: victim buffer is @i{unassigned} or @i{assigned-clean} it can be
                   5703: allocated to the new block immediately. If it is @i{assigned-dirty}
1.28      crook    5704: its current contents must be written out to disk before it can be
                   5705: allocated to the new block.
                   5706: 
                   5707: Although no structure is imposed on the contents of a block, it is
                   5708: traditional to display the contents as 16 lines each of 64 characters.  A
                   5709: block provides a single, continuous stream of input (for example, it
                   5710: acts as a single parse area) -- there are no end-of-line characters
                   5711: within a block, and no end-of-file character at the end of a
                   5712: block. There are two consequences of this:
1.26      crook    5713: 
1.28      crook    5714: @itemize @bullet
                   5715: @item
                   5716: The last character of one line wraps straight into the first character
                   5717: of the following line
                   5718: @item
                   5719: The word @code{\} -- comment to end of line -- requires special
                   5720: treatment; in the context of a block it causes all characters until the
                   5721: end of the current 64-character ``line'' to be ignored.
                   5722: @end itemize
                   5723: 
                   5724: In Gforth, when you use @code{block} with a non-existent block number,
                   5725: the current block file will be extended to the appropriate size and the
                   5726: block buffer will be initialised with spaces.
                   5727: 
1.29      crook    5728: Gforth doesn't encourage the use of blocks; the mechanism is only
                   5729: provided for backward compatibility -- ANS Forth requires blocks to be
                   5730: available when files are.
1.28      crook    5731: 
                   5732: Common techniques that are used when working with blocks include:
                   5733: 
                   5734: @itemize @bullet
                   5735: @item
                   5736: A screen editor that allows you to edit blocks without leaving the Forth
                   5737: environment.
                   5738: @item
                   5739: Shadow screens; where every code block has an associated block
                   5740: containing comments (for example: code in odd block numbers, comments in
                   5741: even block numbers). Typically, the block editor provides a convenient
                   5742: mechanism to toggle between code and comments.
                   5743: @item
                   5744: Load blocks; a single block (typically block 1) contains a number of
                   5745: @code{thru} commands which @code{load} the whole of the application.
                   5746: @end itemize
1.26      crook    5747: 
1.29      crook    5748: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
                   5749: integrated into a Forth programming environment.
1.26      crook    5750: 
                   5751: @comment TODO what about errors on open-blocks?
                   5752: doc-open-blocks
                   5753: doc-use
                   5754: doc-get-block-fid
                   5755: doc-block-position
1.28      crook    5756: 
                   5757: doc-scr
                   5758: doc-list
                   5759: 
                   5760: doc---block-block
                   5761: doc-buffer
                   5762: 
1.26      crook    5763: doc-update
1.28      crook    5764: doc-updated?
1.26      crook    5765: doc-save-buffers
                   5766: doc-empty-buffers
                   5767: doc-empty-buffer
                   5768: doc-flush
1.28      crook    5769: 
1.26      crook    5770: doc-load
                   5771: doc-thru
                   5772: doc-+load
                   5773: doc-+thru
1.35      anton    5774: xdoc--gforth--->
1.26      crook    5775: doc-block-included
                   5776: 
                   5777: @c -------------------------------------------------------------
                   5778: @node Other I/O, Programming Tools, Blocks, Words
                   5779: @section Other I/O
1.28      crook    5780: @cindex I/O - keyboard and display
1.26      crook    5781: 
                   5782: @menu
                   5783: * Simple numeric output::       Predefined formats
                   5784: * Formatted numeric output::    Formatted (pictured) output
                   5785: * String Formats::              How Forth stores strings in memory
                   5786: * Displaying characters and strings:: Other stuff
                   5787: * Input::                       Input
                   5788: @end menu
                   5789: 
                   5790: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   5791: @subsection Simple numeric output
1.28      crook    5792: @cindex numeric output - simple/free-format
1.5       anton    5793: 
1.26      crook    5794: The simplest output functions are those that display numbers from the
                   5795: data or floating-point stacks. Floating-point output is always displayed
                   5796: using base 10. Numbers displayed from the data stack use the value stored
                   5797: in @code{base}.
1.5       anton    5798: 
1.26      crook    5799: doc-.
                   5800: doc-dec.
                   5801: doc-hex.
                   5802: doc-u.
                   5803: doc-.r
                   5804: doc-u.r
                   5805: doc-d.
                   5806: doc-ud.
                   5807: doc-d.r
                   5808: doc-ud.r
                   5809: doc-f.
                   5810: doc-fe.
                   5811: doc-fs.
1.5       anton    5812: 
1.26      crook    5813: Examples of printing the number 1234.5678E23 in the different floating-point output
                   5814: formats are shown below:
1.5       anton    5815: 
                   5816: @example
1.26      crook    5817: f. 123456779999999000000000000.
                   5818: fe. 123.456779999999E24
                   5819: fs. 1.23456779999999E26
1.5       anton    5820: @end example
                   5821: 
                   5822: 
1.26      crook    5823: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   5824: @subsection Formatted numeric output
1.28      crook    5825: @cindex formatted numeric output
1.26      crook    5826: @cindex pictured numeric output
1.28      crook    5827: @cindex numeric output - formatted
1.26      crook    5828: 
1.29      crook    5829: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    5830: output} for formatted printing of integers.  In this technique, digits
                   5831: are extracted from the number (using the current output radix defined by
                   5832: @code{base}), converted to ASCII codes and appended to a string that is
                   5833: built in a scratch-pad area of memory (@pxref{core-idef,
                   5834: Implementation-defined options, Implementation-defined
                   5835: options}). Arbitrary characters can be appended to the string during the
                   5836: extraction process. The completed string is specified by an address
                   5837: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   5838: under program control.
1.5       anton    5839: 
1.26      crook    5840: All of the words described in the previous section for simple numeric
                   5841: output are implemented in Gforth using pictured numeric output.
1.5       anton    5842: 
1.26      crook    5843: Three important things to remember about Pictured Numeric Output:
1.5       anton    5844: 
1.26      crook    5845: @itemize @bullet
                   5846: @item
1.28      crook    5847: It always operates on double-precision numbers; to display a
                   5848: single-precision number, convert it first (@pxref{Double precision} for
                   5849: ways of doing this).
1.26      crook    5850: @item
1.28      crook    5851: It always treats the double-precision number as though it were
                   5852: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    5853: @item
                   5854: The string is built up from right to left; least significant digit first.
                   5855: @end itemize
1.5       anton    5856: 
1.26      crook    5857: doc-<#
                   5858: doc-#
                   5859: doc-#s
                   5860: doc-hold
                   5861: doc-sign
                   5862: doc-#>
1.5       anton    5863: 
1.26      crook    5864: doc-represent
1.5       anton    5865: 
1.26      crook    5866: Here are some examples of using pictured numeric output:
1.5       anton    5867: 
                   5868: @example
1.26      crook    5869: : my-u. ( u -- )
                   5870:   \ Simplest use of pns.. behaves like Standard u. 
                   5871:   0              \ convert to unsigned double
                   5872:   <#             \ start conversion
                   5873:   #s             \ convert all digits
                   5874:   #>             \ complete conversion
                   5875:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    5876: 
1.26      crook    5877: : cents-only ( u -- )
                   5878:   0              \ convert to unsigned double
                   5879:   <#             \ start conversion
                   5880:   # #            \ convert two least-significant digits
                   5881:   #>             \ complete conversion, discard other digits
                   5882:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    5883: 
1.26      crook    5884: : dollars-and-cents ( u -- )
                   5885:   0              \ convert to unsigned double
                   5886:   <#             \ start conversion
                   5887:   # #            \ convert two least-significant digits
                   5888:   [char] . hold  \ insert decimal point
                   5889:   #s             \ convert remaining digits
                   5890:   [char] $ hold  \ append currency symbol
                   5891:   #>             \ complete conversion
                   5892:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    5893: 
1.26      crook    5894: : my-. ( n -- )
                   5895:   \ handling negatives.. behaves like Standard .
                   5896:   s>d            \ convert to signed double
                   5897:   swap over dabs \ leave sign byte followed by unsigned double
                   5898:   <#             \ start conversion
                   5899:   #s             \ convert all digits
                   5900:   rot sign       \ get at sign byte, append "-" if needed
                   5901:   #>             \ complete conversion
                   5902:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    5903: 
1.26      crook    5904: : account. ( n -- )
                   5905:   \ accountants don't like minus signs, they use braces
                   5906:   \ for negative numbers
                   5907:   s>d            \ convert to signed double
                   5908:   swap over dabs \ leave sign byte followed by unsigned double
                   5909:   <#             \ start conversion
                   5910:   2 pick         \ get copy of sign byte
                   5911:   0< IF [char] ) hold THEN \ right-most character of output
                   5912:   #s             \ convert all digits
                   5913:   rot            \ get at sign byte
                   5914:   0< IF [char] ( hold THEN
                   5915:   #>             \ complete conversion
                   5916:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    5917: @end example
                   5918: 
1.26      crook    5919: Here are some examples of using these words:
1.5       anton    5920: 
                   5921: @example
1.26      crook    5922: 1 my-u. 1
                   5923: hex -1 my-u. decimal FFFFFFFF
                   5924: 1 cents-only 01
                   5925: 1234 cents-only 34
                   5926: 2 dollars-and-cents $0.02
                   5927: 1234 dollars-and-cents $12.34
                   5928: 123 my-. 123
                   5929: -123 my. -123
                   5930: 123 account. 123
                   5931: -456 account. (456)
1.5       anton    5932: @end example
                   5933: 
                   5934: 
1.26      crook    5935: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   5936: @subsection String Formats
1.27      crook    5937: @cindex strings - see character strings
                   5938: @cindex character strings - formats
1.28      crook    5939: @cindex I/O - see character strings
1.26      crook    5940: 
1.27      crook    5941: Forth commonly uses two different methods for representing character
                   5942: strings:
1.26      crook    5943: 
                   5944: @itemize @bullet
                   5945: @item
                   5946: @cindex address of counted string
1.29      crook    5947: As a @dfn{counted string}, represented by a @i{c-addr}. The char
                   5948: addressed by @i{c-addr} contains a character-count, @i{n}, of the
                   5949: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    5950: memory.
                   5951: @item
1.29      crook    5952: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
                   5953: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    5954: first byte of the string.
                   5955: @end itemize
                   5956: 
                   5957: ANS Forth encourages the use of the second format when representing
                   5958: strings on the stack, whilst conceeding that the counted string format
                   5959: remains useful as a way of storing strings in memory.
                   5960: 
                   5961: doc-count
                   5962: 
                   5963: @xref{Memory Blocks} for words that move, copy and search
                   5964: for strings. @xref{Displaying characters and strings,} for words that
                   5965: display characters and strings.
                   5966: 
                   5967: 
                   5968: @node Displaying characters and strings, Input, String Formats, Other I/O
                   5969: @subsection Displaying characters and strings
1.27      crook    5970: @cindex characters - compiling and displaying
                   5971: @cindex character strings - compiling and displaying
1.26      crook    5972: 
                   5973: This section starts with a glossary of Forth words and ends with a set
                   5974: of examples.
                   5975: 
                   5976: doc-bl
                   5977: doc-space
                   5978: doc-spaces
                   5979: doc-emit
                   5980: doc-toupper
                   5981: doc-."
                   5982: doc-.(
                   5983: doc-type
                   5984: doc-cr
1.27      crook    5985: @cindex cursor control
1.26      crook    5986: doc-at-xy
                   5987: doc-page
                   5988: doc-s"
                   5989: doc-c"
                   5990: doc-char
                   5991: doc-[char]
                   5992: doc-sliteral
                   5993: 
                   5994: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    5995: 
                   5996: @example
1.26      crook    5997: .( text-1)
                   5998: : my-word
                   5999:   ." text-2" cr
                   6000:   .( text-3)
                   6001: ;
                   6002: 
                   6003: ." text-4"
                   6004: 
                   6005: : my-char
                   6006:   [char] ALPHABET emit
                   6007:   char emit
                   6008: ;
1.5       anton    6009: @end example
                   6010: 
1.26      crook    6011: When you load this code into Gforth, the following output is generated:
1.5       anton    6012: 
1.26      crook    6013: @example
1.30      anton    6014: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26      crook    6015: @end example
1.5       anton    6016: 
1.26      crook    6017: @itemize @bullet
                   6018: @item
                   6019: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   6020: is an immediate word; it behaves in the same way whether it is used inside
                   6021: or outside a colon definition.
                   6022: @item
                   6023: Message @code{text-4} is displayed because of Gforth's added interpretation
                   6024: semantics for @code{."}.
                   6025: @item
1.29      crook    6026: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    6027: performs the compilation semantics for @code{."} within the definition of
                   6028: @code{my-word}.
                   6029: @end itemize
1.5       anton    6030: 
1.26      crook    6031: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    6032: 
1.26      crook    6033: @example
1.30      anton    6034: @kbd{my-word @key{RET}} text-2
1.26      crook    6035:  ok
1.30      anton    6036: @kbd{my-char fred @key{RET}} Af ok
                   6037: @kbd{my-char jim @key{RET}} Aj ok
1.26      crook    6038: @end example
1.5       anton    6039: 
                   6040: @itemize @bullet
                   6041: @item
1.26      crook    6042: Message @code{text-2} is displayed because of the run-time behaviour of
                   6043: @code{."}.
                   6044: @item
                   6045: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   6046: on the stack at run-time. @code{emit} always displays the character
                   6047: when @code{my-char} is executed.
                   6048: @item
                   6049: @code{char} parses a string at run-time and the second @code{emit} displays
                   6050: the first character of the string.
1.5       anton    6051: @item
1.26      crook    6052: If you type @code{see my-char} you can see that @code{[char]} discarded
                   6053: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   6054: definition of @code{my-char}.
1.5       anton    6055: @end itemize
                   6056: 
                   6057: 
                   6058: 
1.26      crook    6059: @node Input, , Displaying characters and strings, Other I/O
                   6060: @subsection Input
                   6061: @cindex input
1.28      crook    6062: @cindex I/O - see input
                   6063: @cindex parsing a string
1.5       anton    6064: 
1.27      crook    6065: @xref{String Formats} for ways of storing character strings in memory.
1.5       anton    6066: 
1.27      crook    6067: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29      crook    6068: @comment then index them
1.27      crook    6069: 
                   6070: doc-key
                   6071: doc-key?
1.26      crook    6072: doc->number
                   6073: doc->float
                   6074: doc-accept
1.27      crook    6075: doc-pad
                   6076: doc-parse
                   6077: doc-word
                   6078: doc-sword
                   6079: doc-refill
                   6080: @comment obsolescent words..
                   6081: doc-convert
1.26      crook    6082: doc-query
                   6083: doc-expect
1.27      crook    6084: doc-span
1.5       anton    6085: 
                   6086: 
                   6087: @c -------------------------------------------------------------
1.26      crook    6088: @node Programming Tools, Assembler and Code Words, Other I/O, Words
                   6089: @section Programming Tools
                   6090: @cindex programming tools
1.12      anton    6091: 
                   6092: @menu
1.26      crook    6093: * Debugging::                   Simple and quick.
                   6094: * Assertions::                  Making your programs self-checking.
                   6095: * Singlestep Debugger::                Executing your program word by word.
1.5       anton    6096: @end menu
                   6097: 
1.26      crook    6098: @node Debugging, Assertions, Programming Tools, Programming Tools
                   6099: @subsection Debugging
                   6100: @cindex debugging
1.5       anton    6101: 
1.26      crook    6102: Languages with a slow edit/compile/link/test development loop tend to
                   6103: require sophisticated tracing/stepping debuggers to facilate
                   6104: productive debugging.
1.5       anton    6105: 
1.26      crook    6106: A much better (faster) way in fast-compiling languages is to add
                   6107: printing code at well-selected places, let the program run, look at
                   6108: the output, see where things went wrong, add more printing code, etc.,
                   6109: until the bug is found.
1.5       anton    6110: 
1.26      crook    6111: The simple debugging aids provided in @file{debugs.fs}
                   6112: are meant to support this style of debugging. In addition, there are
                   6113: words for non-destructively inspecting the stack and memory:
1.5       anton    6114: 
1.26      crook    6115: doc-.s
                   6116: doc-f.s
1.5       anton    6117: 
1.29      crook    6118: There is a word @code{.r} but it does @i{not} display the return
1.26      crook    6119: stack! It is used for formatted numeric output.
1.5       anton    6120: 
1.26      crook    6121: doc-depth
                   6122: doc-fdepth
                   6123: doc-clearstack
                   6124: doc-?
                   6125: doc-dump
1.5       anton    6126: 
1.26      crook    6127: The word @code{~~} prints debugging information (by default the source
                   6128: location and the stack contents). It is easy to insert. If you use Emacs
                   6129: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   6130: query-replace them with nothing). The deferred words
                   6131: @code{printdebugdata} and @code{printdebugline} control the output of
                   6132: @code{~~}. The default source location output format works well with
                   6133: Emacs' compilation mode, so you can step through the program at the
                   6134: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   6135: is that you can step in any direction and you know where the crash has
                   6136: happened or where the strange data has occurred).
1.5       anton    6137: 
1.26      crook    6138: The default actions of @code{~~} clobber the contents of the pictured
                   6139: numeric output string, so you should not use @code{~~}, e.g., between
                   6140: @code{<#} and @code{#>}.
1.5       anton    6141: 
1.26      crook    6142: doc-~~
                   6143: doc-printdebugdata
                   6144: doc-printdebugline
1.5       anton    6145: 
1.26      crook    6146: doc-see
                   6147: doc-marker
1.5       anton    6148: 
1.26      crook    6149: Here's an example of using @code{marker} at the start of a source file
                   6150: that you are debugging; it ensures that you only ever have one copy of
                   6151: the file's definitions compiled at any time:
1.5       anton    6152: 
1.26      crook    6153: @example
                   6154: [IFDEF] my-code
                   6155:     my-code
                   6156: [ENDIF]
1.5       anton    6157: 
1.26      crook    6158: marker my-code
1.28      crook    6159: init-included-files
1.5       anton    6160: 
1.26      crook    6161: \ .. definitions start here
                   6162: \ .
                   6163: \ .
                   6164: \ end
                   6165: @end example
1.5       anton    6166: 
                   6167: 
                   6168: 
1.26      crook    6169: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
                   6170: @subsection Assertions
                   6171: @cindex assertions
1.5       anton    6172: 
1.26      crook    6173: It is a good idea to make your programs self-checking, especially if you
                   6174: make an assumption that may become invalid during maintenance (for
                   6175: example, that a certain field of a data structure is never zero). Gforth
1.29      crook    6176: supports @dfn{assertions} for this purpose. They are used like this:
1.23      crook    6177: 
1.26      crook    6178: @example
1.29      crook    6179: assert( @i{flag} )
1.26      crook    6180: @end example
1.23      crook    6181: 
1.26      crook    6182: The code between @code{assert(} and @code{)} should compute a flag, that
                   6183: should be true if everything is alright and false otherwise. It should
                   6184: not change anything else on the stack. The overall stack effect of the
                   6185: assertion is @code{( -- )}. E.g.
1.23      crook    6186: 
1.26      crook    6187: @example
                   6188: assert( 1 1 + 2 = ) \ what we learn in school
                   6189: assert( dup 0<> ) \ assert that the top of stack is not zero
                   6190: assert( false ) \ this code should not be reached
                   6191: @end example
1.23      crook    6192: 
1.26      crook    6193: The need for assertions is different at different times. During
                   6194: debugging, we want more checking, in production we sometimes care more
                   6195: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   6196: becomes a comment. Depending on the importance of an assertion and the
                   6197: time it takes to check it, you may want to turn off some assertions and
                   6198: keep others turned on. Gforth provides several levels of assertions for
                   6199: this purpose:
1.23      crook    6200: 
1.26      crook    6201: doc-assert0(
                   6202: doc-assert1(
                   6203: doc-assert2(
                   6204: doc-assert3(
                   6205: doc-assert(
                   6206: doc-)
1.23      crook    6207: 
1.26      crook    6208: The variable @code{assert-level} specifies the highest assertions that
                   6209: are turned on. I.e., at the default @code{assert-level} of one,
                   6210: @code{assert0(} and @code{assert1(} assertions perform checking, while
                   6211: @code{assert2(} and @code{assert3(} assertions are treated as comments.
                   6212: 
                   6213: The value of @code{assert-level} is evaluated at compile-time, not at
                   6214: run-time. Therefore you cannot turn assertions on or off at run-time;
                   6215: you have to set the @code{assert-level} appropriately before compiling a
                   6216: piece of code. You can compile different pieces of code at different
                   6217: @code{assert-level}s (e.g., a trusted library at level 1 and
                   6218: newly-written code at level 3).
1.23      crook    6219: 
1.26      crook    6220: doc-assert-level
1.23      crook    6221: 
1.26      crook    6222: If an assertion fails, a message compatible with Emacs' compilation mode
                   6223: is produced and the execution is aborted (currently with @code{ABORT"}.
                   6224: If there is interest, we will introduce a special throw code. But if you
                   6225: intend to @code{catch} a specific condition, using @code{throw} is
                   6226: probably more appropriate than an assertion).
1.23      crook    6227: 
1.26      crook    6228: Definitions in ANS Forth for these assertion words are provided
                   6229: in @file{compat/assert.fs}.
1.23      crook    6230: 
                   6231: 
1.26      crook    6232: @node Singlestep Debugger, , Assertions, Programming Tools
                   6233: @subsection Singlestep Debugger
                   6234: @cindex singlestep Debugger
                   6235: @cindex debugging Singlestep
                   6236: @cindex @code{dbg}
                   6237: @cindex @code{BREAK:}
                   6238: @cindex @code{BREAK"}
1.23      crook    6239: 
1.26      crook    6240: When you create a new word there's often the need to check whether it
                   6241: behaves correctly or not. You can do this by typing @code{dbg
                   6242: badword}. A debug session might look like this:
1.23      crook    6243: 
1.26      crook    6244: @example
                   6245: : badword 0 DO i . LOOP ;  ok
                   6246: 2 dbg badword 
                   6247: : badword  
                   6248: Scanning code...
1.23      crook    6249: 
1.26      crook    6250: Nesting debugger ready!
1.23      crook    6251: 
1.26      crook    6252: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   6253: 400D4740  8049F68 DO             -> [ 0 ] 
                   6254: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   6255: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   6256: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   6257: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   6258: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   6259: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   6260: 400D4758  804B384 ;              ->  ok
                   6261: @end example
1.23      crook    6262: 
1.26      crook    6263: Each line displayed is one step. You always have to hit return to
                   6264: execute the next word that is displayed. If you don't want to execute
                   6265: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   6266: an overview what keys are available:
1.23      crook    6267: 
1.26      crook    6268: @table @i
1.23      crook    6269: 
1.30      anton    6270: @item @key{RET}
1.26      crook    6271: Next; Execute the next word.
1.23      crook    6272: 
1.26      crook    6273: @item n
                   6274: Nest; Single step through next word.
1.5       anton    6275: 
1.26      crook    6276: @item u
                   6277: Unnest; Stop debugging and execute rest of word. If we got to this word
                   6278: with nest, continue debugging with the calling word.
1.5       anton    6279: 
1.26      crook    6280: @item d
                   6281: Done; Stop debugging and execute rest.
1.5       anton    6282: 
1.26      crook    6283: @item s
                   6284: Stop; Abort immediately.
1.5       anton    6285: 
1.26      crook    6286: @end table
1.5       anton    6287: 
1.26      crook    6288: Debugging large application with this mechanism is very difficult, because
                   6289: you have to nest very deeply into the program before the interesting part
                   6290: begins. This takes a lot of time. 
1.5       anton    6291: 
1.26      crook    6292: To do it more directly put a @code{BREAK:} command into your source code.
                   6293: When program execution reaches @code{BREAK:} the single step debugger is
                   6294: invoked and you have all the features described above.
1.23      crook    6295: 
1.26      crook    6296: If you have more than one part to debug it is useful to know where the
                   6297: program has stopped at the moment. You can do this by the 
                   6298: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   6299: string is typed out when the ``breakpoint'' is reached.
                   6300: 
                   6301: doc-dbg
                   6302: doc-BREAK:
                   6303: doc-BREAK"
                   6304: 
                   6305: 
                   6306: @c -------------------------------------------------------------
                   6307: @node Assembler and Code Words, Threading Words, Programming Tools, Words
                   6308: @section Assembler and Code Words
                   6309: @cindex assembler
                   6310: @cindex code words
1.5       anton    6311: 
1.26      crook    6312: Gforth provides some words for defining primitives (words written in
1.29      crook    6313: machine code), and for defining the machine-code equivalent of
1.26      crook    6314: @code{DOES>}-based defining words. However, the machine-independent
                   6315: nature of Gforth poses a few problems: First of all, Gforth runs on
                   6316: several architectures, so it can provide no standard assembler. What's
                   6317: worse is that the register allocation not only depends on the processor,
                   6318: but also on the @code{gcc} version and options used.
1.5       anton    6319: 
1.29      crook    6320: The words that Gforth offers encapsulate some system dependences (e.g.,
                   6321: the header structure), so a system-independent assembler may be used in
1.26      crook    6322: Gforth. If you do not have an assembler, you can compile machine code
1.29      crook    6323: directly with @code{,} and @code{c,}@footnote{This isn't portable,
                   6324: because these words emit stuff in @i{data} space; it works because
                   6325: Gforth has unified code/data spaces. Assembler isn't likely to be
                   6326: portable anyway.}.
1.5       anton    6327: 
1.26      crook    6328: doc-assembler
                   6329: doc-code
                   6330: doc-end-code
                   6331: doc-;code
                   6332: doc-flush-icache
1.5       anton    6333: 
1.26      crook    6334: If @code{flush-icache} does not work correctly, @code{code} words
                   6335: etc. will not work (reliably), either.
1.5       anton    6336: 
1.29      crook    6337: The typical usage of these @code{code} words can be shown most easily by
                   6338: analogy to the equivalent high-level defining words:
                   6339: 
                   6340: @example
                   6341: : foo                                        code foo
                   6342:    <high-level Forth words>                        <assembler>
                   6343: ;                                            end-code
                   6344: 
                   6345: : bar                                        : bar
                   6346:    <high-level Forth words>                     <high-level Forth words>
                   6347:    CREATE                                       CREATE
                   6348:       <high-level Forth words>                     <high-level Forth words>
                   6349:    DOES>                                        ;code
                   6350:       <high-level Forth words>                     <assembler>
                   6351: ;                                            end-code
                   6352: @end example
                   6353: 
1.26      crook    6354: @code{flush-icache} is always present. The other words are rarely used
                   6355: and reside in @code{code.fs}, which is usually not loaded. You can load
                   6356: it with @code{require code.fs}.
1.5       anton    6357: 
1.26      crook    6358: @cindex registers of the inner interpreter
                   6359: In the assembly code you will want to refer to the inner interpreter's
                   6360: registers (e.g., the data stack pointer) and you may want to use other
                   6361: registers for temporary storage. Unfortunately, the register allocation
                   6362: is installation-dependent.
1.5       anton    6363: 
1.26      crook    6364: The easiest solution is to use explicit register declarations
                   6365: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
                   6366: GNU C Manual}) for all of the inner interpreter's registers: You have to
                   6367: compile Gforth with @code{-DFORCE_REG} (configure option
                   6368: @code{--enable-force-reg}) and the appropriate declarations must be
                   6369: present in the @code{machine.h} file (see @code{mips.h} for an example;
                   6370: you can find a full list of all declarable register symbols with
                   6371: @code{grep register engine.c}). If you give explicit registers to all
                   6372: variables that are declared at the beginning of @code{engine()}, you
                   6373: should be able to use the other caller-saved registers for temporary
                   6374: storage. Alternatively, you can use the @code{gcc} option
                   6375: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
                   6376: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
                   6377: (however, this restriction on register allocation may slow Gforth
                   6378: significantly).
1.5       anton    6379: 
1.26      crook    6380: If this solution is not viable (e.g., because @code{gcc} does not allow
                   6381: you to explicitly declare all the registers you need), you have to find
                   6382: out by looking at the code where the inner interpreter's registers
                   6383: reside and which registers can be used for temporary storage. You can
                   6384: get an assembly listing of the engine's code with @code{make engine.s}.
1.5       anton    6385: 
1.26      crook    6386: In any case, it is good practice to abstract your assembly code from the
                   6387: actual register allocation. E.g., if the data stack pointer resides in
                   6388: register @code{$17}, create an alias for this register called @code{sp},
                   6389: and use that in your assembly code.
1.5       anton    6390: 
1.26      crook    6391: @cindex code words, portable
                   6392: Another option for implementing normal and defining words efficiently
                   6393: is to add the desired functionality to the source of Gforth. For normal
                   6394: words you just have to edit @file{primitives} (@pxref{Automatic
                   6395: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
                   6396: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
                   6397: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.5       anton    6398: 
                   6399: 
1.26      crook    6400: @c -------------------------------------------------------------
                   6401: @node Threading Words, Locals, Assembler and Code Words, Words
                   6402: @section Threading Words
                   6403: @cindex threading words
1.5       anton    6404: 
1.26      crook    6405: @cindex code address
                   6406: These words provide access to code addresses and other threading stuff
                   6407: in Gforth (and, possibly, other interpretive Forths). It more or less
                   6408: abstracts away the differences between direct and indirect threading
                   6409: (and, for direct threading, the machine dependences). However, at
                   6410: present this wordset is still incomplete. It is also pretty low-level;
                   6411: some day it will hopefully be made unnecessary by an internals wordset
                   6412: that abstracts implementation details away completely.
1.5       anton    6413: 
1.26      crook    6414: doc-threading-method
                   6415: doc->code-address
                   6416: doc->does-code
                   6417: doc-code-address!
                   6418: doc-does-code!
                   6419: doc-does-handler!
                   6420: doc-/does-handler
1.5       anton    6421: 
1.26      crook    6422: The code addresses produced by various defining words are produced by
                   6423: the following words:
1.5       anton    6424: 
1.26      crook    6425: doc-docol:
                   6426: doc-docon:
                   6427: doc-dovar:
                   6428: doc-douser:
                   6429: doc-dodefer:
                   6430: doc-dofield:
1.5       anton    6431: 
1.26      crook    6432: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
                   6433: with @code{>does-code}. If the word was defined in that way, the value
                   6434: returned is non-zero and identifies the @code{DOES>} used by the
                   6435: defining word.
                   6436: @comment TODO should that be ``identifies the xt of the DOES> ??''
1.5       anton    6437: 
1.26      crook    6438: @c -------------------------------------------------------------
                   6439: @node Locals, Structures, Threading Words, Words
                   6440: @section Locals
                   6441: @cindex locals
1.5       anton    6442: 
1.26      crook    6443: Local variables can make Forth programming more enjoyable and Forth
                   6444: programs easier to read. Unfortunately, the locals of ANS Forth are
                   6445: laden with restrictions. Therefore, we provide not only the ANS Forth
                   6446: locals wordset, but also our own, more powerful locals wordset (we
                   6447: implemented the ANS Forth locals wordset through our locals wordset).
1.5       anton    6448: 
1.26      crook    6449: The ideas in this section have also been published in the paper
                   6450: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
                   6451: at EuroForth '94; it is available at
                   6452: @*@url{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
1.5       anton    6453: 
1.26      crook    6454: @menu
                   6455: * Gforth locals::               
                   6456: * ANS Forth locals::            
                   6457: @end menu
1.5       anton    6458: 
1.26      crook    6459: @node Gforth locals, ANS Forth locals, Locals, Locals
                   6460: @subsection Gforth locals
                   6461: @cindex Gforth locals
                   6462: @cindex locals, Gforth style
1.5       anton    6463: 
1.26      crook    6464: Locals can be defined with
1.5       anton    6465: 
                   6466: @example
1.26      crook    6467: @{ local1 local2 ... -- comment @}
                   6468: @end example
                   6469: or
                   6470: @example
                   6471: @{ local1 local2 ... @}
1.5       anton    6472: @end example
                   6473: 
1.26      crook    6474: E.g.,
1.5       anton    6475: @example
1.26      crook    6476: : max @{ n1 n2 -- n3 @}
                   6477:  n1 n2 > if
                   6478:    n1
                   6479:  else
                   6480:    n2
                   6481:  endif ;
1.5       anton    6482: @end example
                   6483: 
1.26      crook    6484: The similarity of locals definitions with stack comments is intended. A
                   6485: locals definition often replaces the stack comment of a word. The order
                   6486: of the locals corresponds to the order in a stack comment and everything
                   6487: after the @code{--} is really a comment.
1.5       anton    6488: 
1.26      crook    6489: This similarity has one disadvantage: It is too easy to confuse locals
                   6490: declarations with stack comments, causing bugs and making them hard to
                   6491: find. However, this problem can be avoided by appropriate coding
                   6492: conventions: Do not use both notations in the same program. If you do,
                   6493: they should be distinguished using additional means, e.g. by position.
                   6494: 
                   6495: @cindex types of locals
                   6496: @cindex locals types
                   6497: The name of the local may be preceded by a type specifier, e.g.,
                   6498: @code{F:} for a floating point value:
                   6499: 
                   6500: @example
                   6501: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   6502: \ complex multiplication
                   6503:  Ar Br f* Ai Bi f* f-
                   6504:  Ar Bi f* Ai Br f* f+ ;
                   6505: @end example
                   6506: 
                   6507: @cindex flavours of locals
                   6508: @cindex locals flavours
                   6509: @cindex value-flavoured locals
                   6510: @cindex variable-flavoured locals
                   6511: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   6512: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   6513: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   6514: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   6515: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   6516: produces its address (which becomes invalid when the variable's scope is
                   6517: left). E.g., the standard word @code{emit} can be defined in terms of
                   6518: @code{type} like this:
1.5       anton    6519: 
                   6520: @example
1.26      crook    6521: : emit @{ C^ char* -- @}
                   6522:     char* 1 type ;
1.5       anton    6523: @end example
                   6524: 
1.26      crook    6525: @cindex default type of locals
                   6526: @cindex locals, default type
                   6527: A local without type specifier is a @code{W:} local. Both flavours of
                   6528: locals are initialized with values from the data or FP stack.
1.5       anton    6529: 
1.26      crook    6530: Currently there is no way to define locals with user-defined data
                   6531: structures, but we are working on it.
1.5       anton    6532: 
1.26      crook    6533: Gforth allows defining locals everywhere in a colon definition. This
                   6534: poses the following questions:
1.5       anton    6535: 
1.26      crook    6536: @menu
                   6537: * Where are locals visible by name?::  
                   6538: * How long do locals live?::    
                   6539: * Programming Style::           
                   6540: * Implementation::              
                   6541: @end menu
1.5       anton    6542: 
1.26      crook    6543: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   6544: @subsubsection Where are locals visible by name?
                   6545: @cindex locals visibility
                   6546: @cindex visibility of locals
                   6547: @cindex scope of locals
1.5       anton    6548: 
1.26      crook    6549: Basically, the answer is that locals are visible where you would expect
                   6550: it in block-structured languages, and sometimes a little longer. If you
                   6551: want to restrict the scope of a local, enclose its definition in
                   6552: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    6553: 
1.26      crook    6554: doc-scope
                   6555: doc-endscope
1.5       anton    6556: 
1.26      crook    6557: These words behave like control structure words, so you can use them
                   6558: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   6559: arbitrary ways.
1.5       anton    6560: 
1.26      crook    6561: If you want a more exact answer to the visibility question, here's the
                   6562: basic principle: A local is visible in all places that can only be
                   6563: reached through the definition of the local@footnote{In compiler
                   6564: construction terminology, all places dominated by the definition of the
                   6565: local.}. In other words, it is not visible in places that can be reached
                   6566: without going through the definition of the local. E.g., locals defined
                   6567: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   6568: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   6569: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.5       anton    6570: 
1.26      crook    6571: The reasoning behind this solution is: We want to have the locals
                   6572: visible as long as it is meaningful. The user can always make the
                   6573: visibility shorter by using explicit scoping. In a place that can
                   6574: only be reached through the definition of a local, the meaning of a
                   6575: local name is clear. In other places it is not: How is the local
                   6576: initialized at the control flow path that does not contain the
                   6577: definition? Which local is meant, if the same name is defined twice in
                   6578: two independent control flow paths?
1.5       anton    6579: 
1.26      crook    6580: This should be enough detail for nearly all users, so you can skip the
                   6581: rest of this section. If you really must know all the gory details and
                   6582: options, read on.
1.5       anton    6583: 
1.26      crook    6584: In order to implement this rule, the compiler has to know which places
                   6585: are unreachable. It knows this automatically after @code{AHEAD},
                   6586: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   6587: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   6588: compiler that the control flow never reaches that place. If
                   6589: @code{UNREACHABLE} is not used where it could, the only consequence is
                   6590: that the visibility of some locals is more limited than the rule above
                   6591: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   6592: lie to the compiler), buggy code will be produced.
1.5       anton    6593: 
1.26      crook    6594: doc-unreachable
1.5       anton    6595: 
1.26      crook    6596: Another problem with this rule is that at @code{BEGIN}, the compiler
                   6597: does not know which locals will be visible on the incoming
                   6598: back-edge. All problems discussed in the following are due to this
                   6599: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   6600: loops as examples; the discussion also applies to @code{?DO} and other
                   6601: loops). Perhaps the most insidious example is:
1.5       anton    6602: @example
1.26      crook    6603: AHEAD
                   6604: BEGIN
                   6605:   x
                   6606: [ 1 CS-ROLL ] THEN
                   6607:   @{ x @}
                   6608:   ...
                   6609: UNTIL
                   6610: @end example
1.5       anton    6611: 
1.26      crook    6612: This should be legal according to the visibility rule. The use of
                   6613: @code{x} can only be reached through the definition; but that appears
                   6614: textually below the use.
1.5       anton    6615: 
1.26      crook    6616: From this example it is clear that the visibility rules cannot be fully
                   6617: implemented without major headaches. Our implementation treats common
                   6618: cases as advertised and the exceptions are treated in a safe way: The
                   6619: compiler makes a reasonable guess about the locals visible after a
                   6620: @code{BEGIN}; if it is too pessimistic, the
                   6621: user will get a spurious error about the local not being defined; if the
                   6622: compiler is too optimistic, it will notice this later and issue a
                   6623: warning. In the case above the compiler would complain about @code{x}
                   6624: being undefined at its use. You can see from the obscure examples in
                   6625: this section that it takes quite unusual control structures to get the
                   6626: compiler into trouble, and even then it will often do fine.
1.5       anton    6627: 
1.26      crook    6628: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   6629: is that all locals visible before the @code{BEGIN} will also be
                   6630: visible after the @code{BEGIN}. This guess is valid for all loops that
                   6631: are entered only through the @code{BEGIN}, in particular, for normal
                   6632: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   6633: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   6634: compiler. When the branch to the @code{BEGIN} is finally generated by
                   6635: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   6636: warns the user if it was too optimistic:
                   6637: @example
                   6638: IF
                   6639:   @{ x @}
                   6640: BEGIN
                   6641:   \ x ? 
                   6642: [ 1 cs-roll ] THEN
                   6643:   ...
                   6644: UNTIL
1.5       anton    6645: @end example
                   6646: 
1.26      crook    6647: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   6648: optimistically assumes that it lives until the @code{THEN}. It notices
                   6649: this difference when it compiles the @code{UNTIL} and issues a
                   6650: warning. The user can avoid the warning, and make sure that @code{x}
                   6651: is not used in the wrong area by using explicit scoping:
                   6652: @example
                   6653: IF
                   6654:   SCOPE
                   6655:   @{ x @}
                   6656:   ENDSCOPE
                   6657: BEGIN
                   6658: [ 1 cs-roll ] THEN
                   6659:   ...
                   6660: UNTIL
                   6661: @end example
1.5       anton    6662: 
1.26      crook    6663: Since the guess is optimistic, there will be no spurious error messages
                   6664: about undefined locals.
1.5       anton    6665: 
1.26      crook    6666: If the @code{BEGIN} is not reachable from above (e.g., after
                   6667: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   6668: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   6669: defined later. Therefore, the compiler assumes that no locals are
                   6670: visible after the @code{BEGIN}. However, the user can use
                   6671: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   6672: visible at the BEGIN as at the point where the top control-flow stack
                   6673: item was created.
1.5       anton    6674: 
1.26      crook    6675: doc-assume-live
1.5       anton    6676: 
1.26      crook    6677: E.g.,
1.5       anton    6678: @example
1.26      crook    6679: @{ x @}
                   6680: AHEAD
                   6681: ASSUME-LIVE
                   6682: BEGIN
                   6683:   x
                   6684: [ 1 CS-ROLL ] THEN
                   6685:   ...
                   6686: UNTIL
1.5       anton    6687: @end example
                   6688: 
1.26      crook    6689: Other cases where the locals are defined before the @code{BEGIN} can be
                   6690: handled by inserting an appropriate @code{CS-ROLL} before the
                   6691: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   6692: behind the @code{ASSUME-LIVE}).
1.5       anton    6693: 
1.26      crook    6694: Cases where locals are defined after the @code{BEGIN} (but should be
                   6695: visible immediately after the @code{BEGIN}) can only be handled by
                   6696: rearranging the loop. E.g., the ``most insidious'' example above can be
                   6697: arranged into:
1.5       anton    6698: @example
1.26      crook    6699: BEGIN
                   6700:   @{ x @}
                   6701:   ... 0=
                   6702: WHILE
                   6703:   x
                   6704: REPEAT
1.5       anton    6705: @end example
                   6706: 
1.26      crook    6707: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
                   6708: @subsubsection How long do locals live?
                   6709: @cindex locals lifetime
                   6710: @cindex lifetime of locals
1.5       anton    6711: 
1.26      crook    6712: The right answer for the lifetime question would be: A local lives at
                   6713: least as long as it can be accessed. For a value-flavoured local this
                   6714: means: until the end of its visibility. However, a variable-flavoured
                   6715: local could be accessed through its address far beyond its visibility
                   6716: scope. Ultimately, this would mean that such locals would have to be
                   6717: garbage collected. Since this entails un-Forth-like implementation
                   6718: complexities, I adopted the same cowardly solution as some other
                   6719: languages (e.g., C): The local lives only as long as it is visible;
                   6720: afterwards its address is invalid (and programs that access it
                   6721: afterwards are erroneous).
1.5       anton    6722: 
1.26      crook    6723: @node Programming Style, Implementation, How long do locals live?, Gforth locals
                   6724: @subsubsection Programming Style
                   6725: @cindex locals programming style
                   6726: @cindex programming style, locals
1.5       anton    6727: 
1.26      crook    6728: The freedom to define locals anywhere has the potential to change
                   6729: programming styles dramatically. In particular, the need to use the
                   6730: return stack for intermediate storage vanishes. Moreover, all stack
                   6731: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   6732: determined arguments) can be eliminated: If the stack items are in the
                   6733: wrong order, just write a locals definition for all of them; then
                   6734: write the items in the order you want.
1.5       anton    6735: 
1.26      crook    6736: This seems a little far-fetched and eliminating stack manipulations is
                   6737: unlikely to become a conscious programming objective. Still, the number
                   6738: of stack manipulations will be reduced dramatically if local variables
                   6739: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
                   6740: a traditional implementation of @code{max}).
1.5       anton    6741: 
1.26      crook    6742: This shows one potential benefit of locals: making Forth programs more
                   6743: readable. Of course, this benefit will only be realized if the
                   6744: programmers continue to honour the principle of factoring instead of
                   6745: using the added latitude to make the words longer.
1.5       anton    6746: 
1.26      crook    6747: @cindex single-assignment style for locals
                   6748: Using @code{TO} can and should be avoided.  Without @code{TO},
                   6749: every value-flavoured local has only a single assignment and many
                   6750: advantages of functional languages apply to Forth. I.e., programs are
                   6751: easier to analyse, to optimize and to read: It is clear from the
                   6752: definition what the local stands for, it does not turn into something
                   6753: different later.
1.5       anton    6754: 
1.26      crook    6755: E.g., a definition using @code{TO} might look like this:
1.5       anton    6756: @example
1.26      crook    6757: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   6758:  u1 u2 min 0
                   6759:  ?do
                   6760:    addr1 c@@ addr2 c@@ -
                   6761:    ?dup-if
                   6762:      unloop exit
                   6763:    then
                   6764:    addr1 char+ TO addr1
                   6765:    addr2 char+ TO addr2
                   6766:  loop
                   6767:  u1 u2 - ;
1.5       anton    6768: @end example
1.26      crook    6769: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   6770: every loop iteration. @code{strcmp} is a typical example of the
                   6771: readability problems of using @code{TO}. When you start reading
                   6772: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   6773: string. Only near the end of the loop you realize that it is something
                   6774: else.
1.5       anton    6775: 
1.26      crook    6776: This can be avoided by defining two locals at the start of the loop that
                   6777: are initialized with the right value for the current iteration.
1.5       anton    6778: @example
1.26      crook    6779: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   6780:  addr1 addr2
                   6781:  u1 u2 min 0 
                   6782:  ?do @{ s1 s2 @}
                   6783:    s1 c@@ s2 c@@ -
                   6784:    ?dup-if
                   6785:      unloop exit
                   6786:    then
                   6787:    s1 char+ s2 char+
                   6788:  loop
                   6789:  2drop
                   6790:  u1 u2 - ;
1.5       anton    6791: @end example
1.26      crook    6792: Here it is clear from the start that @code{s1} has a different value
                   6793: in every loop iteration.
1.5       anton    6794: 
1.26      crook    6795: @node Implementation,  , Programming Style, Gforth locals
                   6796: @subsubsection Implementation
                   6797: @cindex locals implementation
                   6798: @cindex implementation of locals
1.5       anton    6799: 
1.26      crook    6800: @cindex locals stack
                   6801: Gforth uses an extra locals stack. The most compelling reason for
                   6802: this is that the return stack is not float-aligned; using an extra stack
                   6803: also eliminates the problems and restrictions of using the return stack
                   6804: as locals stack. Like the other stacks, the locals stack grows toward
                   6805: lower addresses. A few primitives allow an efficient implementation:
1.5       anton    6806: 
1.26      crook    6807: doc-@local#
                   6808: doc-f@local#
                   6809: doc-laddr#
                   6810: doc-lp+!#
                   6811: doc-lp!
                   6812: doc->l
                   6813: doc-f>l
1.5       anton    6814: 
1.26      crook    6815: In addition to these primitives, some specializations of these
                   6816: primitives for commonly occurring inline arguments are provided for
                   6817: efficiency reasons, e.g., @code{@@local0} as specialization of
                   6818: @code{@@local#} for the inline argument 0. The following compiling words
                   6819: compile the right specialized version, or the general version, as
                   6820: appropriate:
1.6       pazsan   6821: 
1.26      crook    6822: doc-compile-@local
                   6823: doc-compile-f@local
                   6824: doc-compile-lp+!
1.12      anton    6825: 
1.26      crook    6826: Combinations of conditional branches and @code{lp+!#} like
                   6827: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   6828: is taken) are provided for efficiency and correctness in loops.
1.6       pazsan   6829: 
1.26      crook    6830: A special area in the dictionary space is reserved for keeping the
                   6831: local variable names. @code{@{} switches the dictionary pointer to this
                   6832: area and @code{@}} switches it back and generates the locals
                   6833: initializing code. @code{W:} etc.@ are normal defining words. This
                   6834: special area is cleared at the start of every colon definition.
1.6       pazsan   6835: 
1.26      crook    6836: @cindex word list for defining locals
                   6837: A special feature of Gforth's dictionary is used to implement the
                   6838: definition of locals without type specifiers: every word list (aka
                   6839: vocabulary) has its own methods for searching
                   6840: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   6841: with a special search method: When it is searched for a word, it
                   6842: actually creates that word using @code{W:}. @code{@{} changes the search
                   6843: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   6844: and then the word list for defining locals without type specifiers.
1.12      anton    6845: 
1.26      crook    6846: The lifetime rules support a stack discipline within a colon
                   6847: definition: The lifetime of a local is either nested with other locals
                   6848: lifetimes or it does not overlap them.
1.6       pazsan   6849: 
1.26      crook    6850: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   6851: pointer manipulation is generated. Between control structure words
                   6852: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   6853: is the simplest of the other three control flow words. It has to
                   6854: restore the locals stack depth of the corresponding @code{BEGIN}
                   6855: before branching. The code looks like this:
                   6856: @format
                   6857: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   6858: @code{branch} <begin>
                   6859: @end format
1.6       pazsan   6860: 
1.26      crook    6861: @code{UNTIL} is a little more complicated: If it branches back, it
                   6862: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   6863: the locals stack must not be changed. The compiler generates the
                   6864: following code:
                   6865: @format
                   6866: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   6867: @end format
                   6868: The locals stack pointer is only adjusted if the branch is taken.
1.6       pazsan   6869: 
1.26      crook    6870: @code{THEN} can produce somewhat inefficient code:
                   6871: @format
                   6872: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   6873: <orig target>:
                   6874: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   6875: @end format
                   6876: The second @code{lp+!#} adjusts the locals stack pointer from the
1.29      crook    6877: level at the @i{orig} point to the level after the @code{THEN}. The
1.26      crook    6878: first @code{lp+!#} adjusts the locals stack pointer from the current
                   6879: level to the level at the orig point, so the complete effect is an
                   6880: adjustment from the current level to the right level after the
                   6881: @code{THEN}.
1.6       pazsan   6882: 
1.26      crook    6883: @cindex locals information on the control-flow stack
                   6884: @cindex control-flow stack items, locals information
                   6885: In a conventional Forth implementation a dest control-flow stack entry
                   6886: is just the target address and an orig entry is just the address to be
                   6887: patched. Our locals implementation adds a word list to every orig or dest
                   6888: item. It is the list of locals visible (or assumed visible) at the point
                   6889: described by the entry. Our implementation also adds a tag to identify
                   6890: the kind of entry, in particular to differentiate between live and dead
                   6891: (reachable and unreachable) orig entries.
1.6       pazsan   6892: 
1.26      crook    6893: A few unusual operations have to be performed on locals word lists:
1.6       pazsan   6894: 
1.26      crook    6895: doc-common-list
                   6896: doc-sub-list?
                   6897: doc-list-size
1.6       pazsan   6898: 
1.26      crook    6899: Several features of our locals word list implementation make these
                   6900: operations easy to implement: The locals word lists are organised as
                   6901: linked lists; the tails of these lists are shared, if the lists
                   6902: contain some of the same locals; and the address of a name is greater
                   6903: than the address of the names behind it in the list.
1.6       pazsan   6904: 
1.26      crook    6905: Another important implementation detail is the variable
                   6906: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   6907: determine if they can be reached directly or only through the branch
                   6908: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   6909: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   6910: definition, by @code{BEGIN} and usually by @code{THEN}.
1.6       pazsan   6911: 
1.26      crook    6912: Counted loops are similar to other loops in most respects, but
                   6913: @code{LEAVE} requires special attention: It performs basically the same
                   6914: service as @code{AHEAD}, but it does not create a control-flow stack
                   6915: entry. Therefore the information has to be stored elsewhere;
                   6916: traditionally, the information was stored in the target fields of the
                   6917: branches created by the @code{LEAVE}s, by organizing these fields into a
                   6918: linked list. Unfortunately, this clever trick does not provide enough
                   6919: space for storing our extended control flow information. Therefore, we
                   6920: introduce another stack, the leave stack. It contains the control-flow
                   6921: stack entries for all unresolved @code{LEAVE}s.
1.6       pazsan   6922: 
1.26      crook    6923: Local names are kept until the end of the colon definition, even if
                   6924: they are no longer visible in any control-flow path. In a few cases
                   6925: this may lead to increased space needs for the locals name area, but
                   6926: usually less than reclaiming this space would cost in code size.
1.6       pazsan   6927: 
                   6928: 
1.26      crook    6929: @node ANS Forth locals,  , Gforth locals, Locals
                   6930: @subsection ANS Forth locals
                   6931: @cindex locals, ANS Forth style
1.6       pazsan   6932: 
1.26      crook    6933: The ANS Forth locals wordset does not define a syntax for locals, but
                   6934: words that make it possible to define various syntaxes. One of the
                   6935: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   6936: wordset, i.e.:
1.6       pazsan   6937: 
                   6938: @example
1.26      crook    6939: @{ local1 local2 ... -- comment @}
1.6       pazsan   6940: @end example
1.23      crook    6941: @noindent
1.26      crook    6942: or
1.6       pazsan   6943: @example
1.26      crook    6944: @{ local1 local2 ... @}
1.6       pazsan   6945: @end example
                   6946: 
1.26      crook    6947: The order of the locals corresponds to the order in a stack comment. The
                   6948: restrictions are:
1.6       pazsan   6949: 
                   6950: @itemize @bullet
                   6951: @item
1.26      crook    6952: Locals can only be cell-sized values (no type specifiers are allowed).
1.6       pazsan   6953: @item
1.26      crook    6954: Locals can be defined only outside control structures.
1.6       pazsan   6955: @item
1.26      crook    6956: Locals can interfere with explicit usage of the return stack. For the
                   6957: exact (and long) rules, see the standard. If you don't use return stack
                   6958: accessing words in a definition using locals, you will be all right. The
                   6959: purpose of this rule is to make locals implementation on the return
                   6960: stack easier.
1.6       pazsan   6961: @item
1.26      crook    6962: The whole definition must be in one line.
                   6963: @end itemize
1.6       pazsan   6964: 
1.26      crook    6965: Locals defined in this way behave like @code{VALUE}s (@xref{Simple
                   6966: Defining Words}). I.e., they are initialized from the stack. Using their
                   6967: name produces their value. Their value can be changed using @code{TO}.
1.6       pazsan   6968: 
1.26      crook    6969: Since this syntax is supported by Gforth directly, you need not do
                   6970: anything to use it. If you want to port a program using this syntax to
                   6971: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   6972: syntax on the other system.
1.6       pazsan   6973: 
1.26      crook    6974: Note that a syntax shown in the standard, section A.13 looks
                   6975: similar, but is quite different in having the order of locals
                   6976: reversed. Beware!
1.6       pazsan   6977: 
1.26      crook    6978: The ANS Forth locals wordset itself consists of a word:
1.6       pazsan   6979: 
1.26      crook    6980: doc-(local)
1.6       pazsan   6981: 
1.26      crook    6982: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
                   6983: awful that we strongly recommend not to use it. We have implemented this
                   6984: syntax to make porting to Gforth easy, but do not document it here. The
                   6985: problem with this syntax is that the locals are defined in an order
                   6986: reversed with respect to the standard stack comment notation, making
                   6987: programs harder to read, and easier to misread and miswrite. The only
                   6988: merit of this syntax is that it is easy to implement using the ANS Forth
                   6989: locals wordset.
1.7       pazsan   6990: 
                   6991: 
1.26      crook    6992: @c ----------------------------------------------------------
                   6993: @node Structures, Object-oriented Forth, Locals, Words
                   6994: @section  Structures
                   6995: @cindex structures
                   6996: @cindex records
1.7       pazsan   6997: 
1.26      crook    6998: This section presents the structure package that comes with Gforth. A
                   6999: version of the package implemented in ANS Forth is available in
                   7000: @file{compat/struct.fs}. This package was inspired by a posting on
                   7001: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   7002: possibly John Hayes). A version of this section has been published in
                   7003: ???. Marcel Hendrix provided helpful comments.
1.7       pazsan   7004: 
1.26      crook    7005: @menu
                   7006: * Why explicit structure support?::  
                   7007: * Structure Usage::             
                   7008: * Structure Naming Convention::  
                   7009: * Structure Implementation::    
                   7010: * Structure Glossary::          
                   7011: @end menu
1.7       pazsan   7012: 
1.26      crook    7013: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   7014: @subsection Why explicit structure support?
1.7       pazsan   7015: 
1.26      crook    7016: @cindex address arithmetic for structures
                   7017: @cindex structures using address arithmetic
                   7018: If we want to use a structure containing several fields, we could simply
                   7019: reserve memory for it, and access the fields using address arithmetic
1.32      anton    7020: (@pxref{Address arithmetic}). As an example, consider a structure with
1.26      crook    7021: the following fields
1.7       pazsan   7022: 
1.26      crook    7023: @table @code
                   7024: @item a
                   7025: is a float
                   7026: @item b
                   7027: is a cell
                   7028: @item c
                   7029: is a float
                   7030: @end table
1.7       pazsan   7031: 
1.26      crook    7032: Given the (float-aligned) base address of the structure we get the
                   7033: address of the field
1.13      pazsan   7034: 
1.26      crook    7035: @table @code
                   7036: @item a
                   7037: without doing anything further.
                   7038: @item b
                   7039: with @code{float+}
                   7040: @item c
                   7041: with @code{float+ cell+ faligned}
                   7042: @end table
1.13      pazsan   7043: 
1.26      crook    7044: It is easy to see that this can become quite tiring. 
1.13      pazsan   7045: 
1.26      crook    7046: Moreover, it is not very readable, because seeing a
                   7047: @code{cell+} tells us neither which kind of structure is
                   7048: accessed nor what field is accessed; we have to somehow infer the kind
                   7049: of structure, and then look up in the documentation, which field of
                   7050: that structure corresponds to that offset.
1.13      pazsan   7051: 
1.26      crook    7052: Finally, this kind of address arithmetic also causes maintenance
                   7053: troubles: If you add or delete a field somewhere in the middle of the
                   7054: structure, you have to find and change all computations for the fields
                   7055: afterwards.
1.13      pazsan   7056: 
1.26      crook    7057: So, instead of using @code{cell+} and friends directly, how
                   7058: about storing the offsets in constants:
1.13      pazsan   7059: 
                   7060: @example
1.26      crook    7061: 0 constant a-offset
                   7062: 0 float+ constant b-offset
                   7063: 0 float+ cell+ faligned c-offset
1.13      pazsan   7064: @end example
                   7065: 
1.26      crook    7066: Now we can get the address of field @code{x} with @code{x-offset
                   7067: +}. This is much better in all respects. Of course, you still
                   7068: have to change all later offset definitions if you add a field. You can
                   7069: fix this by declaring the offsets in the following way:
1.13      pazsan   7070: 
                   7071: @example
1.26      crook    7072: 0 constant a-offset
                   7073: a-offset float+ constant b-offset
                   7074: b-offset cell+ faligned constant c-offset
1.13      pazsan   7075: @end example
                   7076: 
1.26      crook    7077: Since we always use the offsets with @code{+}, we could use a defining
                   7078: word @code{cfield} that includes the @code{+} in the action of the
                   7079: defined word:
1.8       pazsan   7080: 
                   7081: @example
1.26      crook    7082: : cfield ( n "name" -- )
                   7083:     create ,
                   7084: does> ( name execution: addr1 -- addr2 )
                   7085:     @@ + ;
1.13      pazsan   7086: 
1.26      crook    7087: 0 cfield a
                   7088: 0 a float+ cfield b
                   7089: 0 b cell+ faligned cfield c
1.13      pazsan   7090: @end example
                   7091: 
1.26      crook    7092: Instead of @code{x-offset +}, we now simply write @code{x}.
                   7093: 
                   7094: The structure field words now can be used quite nicely. However,
                   7095: their definition is still a bit cumbersome: We have to repeat the
                   7096: name, the information about size and alignment is distributed before
                   7097: and after the field definitions etc.  The structure package presented
                   7098: here addresses these problems.
                   7099: 
                   7100: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   7101: @subsection Structure Usage
                   7102: @cindex structure usage
1.13      pazsan   7103: 
1.26      crook    7104: @cindex @code{field} usage
                   7105: @cindex @code{struct} usage
                   7106: @cindex @code{end-struct} usage
                   7107: You can define a structure for a (data-less) linked list with:
1.13      pazsan   7108: @example
1.26      crook    7109: struct
                   7110:     cell% field list-next
                   7111: end-struct list%
1.13      pazsan   7112: @end example
                   7113: 
1.26      crook    7114: With the address of the list node on the stack, you can compute the
                   7115: address of the field that contains the address of the next node with
                   7116: @code{list-next}. E.g., you can determine the length of a list
                   7117: with:
1.13      pazsan   7118: 
                   7119: @example
1.26      crook    7120: : list-length ( list -- n )
                   7121: \ "list" is a pointer to the first element of a linked list
                   7122: \ "n" is the length of the list
                   7123:     0 BEGIN ( list1 n1 )
                   7124:         over
                   7125:     WHILE ( list1 n1 )
                   7126:         1+ swap list-next @@ swap
                   7127:     REPEAT
                   7128:     nip ;
1.13      pazsan   7129: @end example
                   7130: 
1.26      crook    7131: You can reserve memory for a list node in the dictionary with
                   7132: @code{list% %allot}, which leaves the address of the list node on the
                   7133: stack. For the equivalent allocation on the heap you can use @code{list%
                   7134: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   7135: use @code{list% %allocate}). You can get the the size of a list
                   7136: node with @code{list% %size} and its alignment with @code{list%
                   7137: %alignment}.
1.13      pazsan   7138: 
1.26      crook    7139: Note that in ANS Forth the body of a @code{create}d word is
                   7140: @code{aligned} but not necessarily @code{faligned};
                   7141: therefore, if you do a:
1.13      pazsan   7142: @example
1.26      crook    7143: create @emph{name} foo% %allot
1.8       pazsan   7144: @end example
                   7145: 
1.26      crook    7146: @noindent
                   7147: then the memory alloted for @code{foo%} is
                   7148: guaranteed to start at the body of @code{@emph{name}} only if
                   7149: @code{foo%} contains only character, cell and double fields.
1.20      pazsan   7150: 
1.26      crook    7151: @cindex strcutures containing structures
                   7152: You can include a structure @code{foo%} as a field of
                   7153: another structure, like this:
1.20      pazsan   7154: @example
1.26      crook    7155: struct
                   7156: ...
                   7157:     foo% field ...
                   7158: ...
                   7159: end-struct ...
1.20      pazsan   7160: @end example
                   7161: 
1.26      crook    7162: @cindex structure extension
                   7163: @cindex extended records
                   7164: Instead of starting with an empty structure, you can extend an
                   7165: existing structure. E.g., a plain linked list without data, as defined
                   7166: above, is hardly useful; You can extend it to a linked list of integers,
                   7167: like this:@footnote{This feature is also known as @emph{extended
                   7168: records}. It is the main innovation in the Oberon language; in other
                   7169: words, adding this feature to Modula-2 led Wirth to create a new
                   7170: language, write a new compiler etc.  Adding this feature to Forth just
                   7171: required a few lines of code.}
1.20      pazsan   7172: 
                   7173: @example
1.26      crook    7174: list%
                   7175:     cell% field intlist-int
                   7176: end-struct intlist%
1.20      pazsan   7177: @end example
                   7178: 
1.26      crook    7179: @code{intlist%} is a structure with two fields:
                   7180: @code{list-next} and @code{intlist-int}.
1.20      pazsan   7181: 
1.26      crook    7182: @cindex structures containing arrays
                   7183: You can specify an array type containing @emph{n} elements of
                   7184: type @code{foo%} like this:
1.20      pazsan   7185: 
                   7186: @example
1.26      crook    7187: foo% @emph{n} *
1.20      pazsan   7188: @end example
                   7189: 
1.26      crook    7190: You can use this array type in any place where you can use a normal
                   7191: type, e.g., when defining a @code{field}, or with
                   7192: @code{%allot}.
1.20      pazsan   7193: 
1.26      crook    7194: @cindex first field optimization
                   7195: The first field is at the base address of a structure and the word
                   7196: for this field (e.g., @code{list-next}) actually does not change
                   7197: the address on the stack. You may be tempted to leave it away in the
                   7198: interest of run-time and space efficiency. This is not necessary,
                   7199: because the structure package optimizes this case and compiling such
                   7200: words does not generate any code. So, in the interest of readability
                   7201: and maintainability you should include the word for the field when
                   7202: accessing the field.
1.20      pazsan   7203: 
1.26      crook    7204: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   7205: @subsection Structure Naming Convention
                   7206: @cindex structure naming convention
1.20      pazsan   7207: 
1.26      crook    7208: The field names that come to (my) mind are often quite generic, and,
                   7209: if used, would cause frequent name clashes. E.g., many structures
                   7210: probably contain a @code{counter} field. The structure names
                   7211: that come to (my) mind are often also the logical choice for the names
                   7212: of words that create such a structure.
1.20      pazsan   7213: 
1.26      crook    7214: Therefore, I have adopted the following naming conventions: 
1.20      pazsan   7215: 
1.26      crook    7216: @itemize @bullet
                   7217: @cindex field naming convention
                   7218: @item
                   7219: The names of fields are of the form
                   7220: @code{@emph{struct}-@emph{field}}, where
                   7221: @code{@emph{struct}} is the basic name of the structure, and
                   7222: @code{@emph{field}} is the basic name of the field. You can
                   7223: think of field words as converting the (address of the)
                   7224: structure into the (address of the) field.
1.20      pazsan   7225: 
1.26      crook    7226: @cindex structure naming convention
                   7227: @item
                   7228: The names of structures are of the form
                   7229: @code{@emph{struct}%}, where
                   7230: @code{@emph{struct}} is the basic name of the structure.
                   7231: @end itemize
1.20      pazsan   7232: 
1.26      crook    7233: This naming convention does not work that well for fields of extended
                   7234: structures; e.g., the integer list structure has a field
                   7235: @code{intlist-int}, but has @code{list-next}, not
                   7236: @code{intlist-next}.
1.20      pazsan   7237: 
1.26      crook    7238: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   7239: @subsection Structure Implementation
                   7240: @cindex structure implementation
                   7241: @cindex implementation of structures
1.20      pazsan   7242: 
1.26      crook    7243: The central idea in the implementation is to pass the data about the
                   7244: structure being built on the stack, not in some global
                   7245: variable. Everything else falls into place naturally once this design
                   7246: decision is made.
1.20      pazsan   7247: 
1.26      crook    7248: The type description on the stack is of the form @emph{align
                   7249: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   7250: very simple.
1.20      pazsan   7251: 
1.26      crook    7252: @code{field} is a defining word that uses @code{Create}
                   7253: and @code{DOES>}. The body of the field contains the offset
                   7254: of the field, and the normal @code{DOES>} action is simply:
1.20      pazsan   7255: 
                   7256: @example
1.26      crook    7257: @ +
1.20      pazsan   7258: @end example
                   7259: 
1.23      crook    7260: @noindent
1.26      crook    7261: i.e., add the offset to the address, giving the stack effect
1.29      crook    7262: @i{addr1 -- addr2} for a field.
1.20      pazsan   7263: 
1.26      crook    7264: @cindex first field optimization, implementation
                   7265: This simple structure is slightly complicated by the optimization
                   7266: for fields with offset 0, which requires a different
                   7267: @code{DOES>}-part (because we cannot rely on there being
                   7268: something on the stack if such a field is invoked during
                   7269: compilation). Therefore, we put the different @code{DOES>}-parts
                   7270: in separate words, and decide which one to invoke based on the
                   7271: offset. For a zero offset, the field is basically a noop; it is
                   7272: immediate, and therefore no code is generated when it is compiled.
1.20      pazsan   7273: 
1.26      crook    7274: @node Structure Glossary,  , Structure Implementation, Structures
                   7275: @subsection Structure Glossary
                   7276: @cindex structure glossary
1.20      pazsan   7277: 
1.26      crook    7278: doc-%align
                   7279: doc-%alignment
                   7280: doc-%alloc
                   7281: doc-%allocate
                   7282: doc-%allot
                   7283: doc-cell%
                   7284: doc-char%
                   7285: doc-dfloat%
                   7286: doc-double%
                   7287: doc-end-struct
                   7288: doc-field
                   7289: doc-float%
                   7290: doc-naligned
                   7291: doc-sfloat%
                   7292: doc-%size
                   7293: doc-struct
1.23      crook    7294: 
1.26      crook    7295: @c -------------------------------------------------------------
                   7296: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
                   7297: @section Object-oriented Forth
1.20      pazsan   7298: 
1.26      crook    7299: Gforth comes with three packages for object-oriented programming:
                   7300: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   7301: is preloaded, so you have to @code{include} them before use. The most
                   7302: important differences between these packages (and others) are discussed
                   7303: in @ref{Comparison with other object models}. All packages are written
                   7304: in ANS Forth and can be used with any other ANS Forth.
1.20      pazsan   7305: 
1.26      crook    7306: @menu
                   7307: * Why object-oriented programming?::
                   7308: * Object-Oriented Terminology::
                   7309: * Objects::
                   7310: * OOF::
                   7311: * Mini-OOF::
                   7312: * Comparison with other object models::  
                   7313: @end menu
1.20      pazsan   7314: 
1.23      crook    7315: 
1.26      crook    7316: @node Why object-oriented programming?, Object-Oriented Terminology, , Object-oriented Forth
                   7317: @subsubsection Why object-oriented programming?
                   7318: @cindex object-oriented programming motivation
                   7319: @cindex motivation for object-oriented programming
1.23      crook    7320: 
1.26      crook    7321: Often we have to deal with several data structures (@emph{objects}),
                   7322: that have to be treated similarly in some respects, but differently in
                   7323: others. Graphical objects are the textbook example: circles, triangles,
                   7324: dinosaurs, icons, and others, and we may want to add more during program
                   7325: development. We want to apply some operations to any graphical object,
                   7326: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   7327: has to do something different for every kind of object.
                   7328: @comment TODO add some other operations eg perimeter, area
                   7329: @comment and tie in to concrete examples later..
1.23      crook    7330: 
1.26      crook    7331: We could implement @code{draw} as a big @code{CASE}
                   7332: control structure that executes the appropriate code depending on the
                   7333: kind of object to be drawn. This would be not be very elegant, and,
                   7334: moreover, we would have to change @code{draw} every time we add
                   7335: a new kind of graphical object (say, a spaceship).
1.23      crook    7336: 
1.26      crook    7337: What we would rather do is: When defining spaceships, we would tell
                   7338: the system: ``Here's how you @code{draw} a spaceship; you figure
                   7339: out the rest''.
1.23      crook    7340: 
1.26      crook    7341: This is the problem that all systems solve that (rightfully) call
                   7342: themselves object-oriented; the object-oriented packages presented here
                   7343: solve this problem (and not much else).
                   7344: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.23      crook    7345: 
1.26      crook    7346: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
                   7347: @subsubsection Object-Oriented Terminology
                   7348: @cindex object-oriented terminology
                   7349: @cindex terminology for object-oriented programming
1.23      crook    7350: 
1.26      crook    7351: This section is mainly for reference, so you don't have to understand
                   7352: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   7353: short:
1.23      crook    7354: 
1.26      crook    7355: @table @emph
                   7356: @cindex class
                   7357: @item class
                   7358: a data structure definition with some extras.
1.23      crook    7359: 
1.26      crook    7360: @cindex object
                   7361: @item object
                   7362: an instance of the data structure described by the class definition.
1.23      crook    7363: 
1.26      crook    7364: @cindex instance variables
                   7365: @item instance variables
                   7366: fields of the data structure.
1.23      crook    7367: 
1.26      crook    7368: @cindex selector
                   7369: @cindex method selector
                   7370: @cindex virtual function
                   7371: @item selector
                   7372: (or @emph{method selector}) a word (e.g.,
                   7373: @code{draw}) that performs an operation on a variety of data
                   7374: structures (classes). A selector describes @emph{what} operation to
                   7375: perform. In C++ terminology: a (pure) virtual function.
1.23      crook    7376: 
1.26      crook    7377: @cindex method
                   7378: @item method
                   7379: the concrete definition that performs the operation
                   7380: described by the selector for a specific class. A method specifies
                   7381: @emph{how} the operation is performed for a specific class.
1.23      crook    7382: 
1.26      crook    7383: @cindex selector invocation
                   7384: @cindex message send
                   7385: @cindex invoking a selector
                   7386: @item selector invocation
                   7387: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   7388: is used for determining which method is used. In Smalltalk terminology:
                   7389: a message (consisting of the selector and the other arguments) is sent
                   7390: to the object.
1.1       anton    7391: 
1.26      crook    7392: @cindex receiving object
                   7393: @item receiving object
                   7394: the object used for determining the method executed by a selector
                   7395: invocation. In the @file{objects.fs} model, it is the object that is on
                   7396: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   7397: the Smalltalk @emph{message} terminology.)
1.1       anton    7398: 
1.26      crook    7399: @cindex child class
                   7400: @cindex parent class
                   7401: @cindex inheritance
                   7402: @item child class
                   7403: a class that has (@emph{inherits}) all properties (instance variables,
                   7404: selectors, methods) from a @emph{parent class}. In Smalltalk
                   7405: terminology: The subclass inherits from the superclass. In C++
                   7406: terminology: The derived class inherits from the base class.
1.1       anton    7407: 
1.26      crook    7408: @end table
1.21      crook    7409: 
1.26      crook    7410: @c If you wonder about the message sending terminology, it comes from
                   7411: @c a time when each object had it's own task and objects communicated via
                   7412: @c message passing; eventually the Smalltalk developers realized that
                   7413: @c they can do most things through simple (indirect) calls. They kept the
                   7414: @c terminology.
1.1       anton    7415: 
                   7416: 
1.26      crook    7417: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   7418: @subsection The @file{objects.fs} model
                   7419: @cindex objects
                   7420: @cindex object-oriented programming
1.1       anton    7421: 
1.26      crook    7422: @cindex @file{objects.fs}
                   7423: @cindex @file{oof.fs}
1.1       anton    7424: 
1.37      anton    7425: This section describes the @file{objects.fs} package. This material also
                   7426: has been published in @cite{Yet Another Forth Objects Package} by Anton
                   7427: Ertl and appeared in Forth Dimensions 19(2), pages 37--43
                   7428: (@url{http://www.complang.tuwien.ac.at/forth/objects/objects.html}).
1.26      crook    7429: @c McKewan's and Zsoter's packages
1.1       anton    7430: 
1.26      crook    7431: This section assumes that you have read @ref{Structures}.
1.1       anton    7432: 
1.26      crook    7433: The techniques on which this model is based have been used to implement
                   7434: the parser generator, Gray, and have also been used in Gforth for
                   7435: implementing the various flavours of word lists (hashed or not,
                   7436: case-sensitive or not, special-purpose word lists for locals etc.).
1.1       anton    7437: 
                   7438: 
1.26      crook    7439: @menu
                   7440: * Properties of the Objects model::  
                   7441: * Basic Objects Usage::         
1.37      anton    7442: * The Objects base class::      
1.26      crook    7443: * Creating objects::            
                   7444: * Object-Oriented Programming Style::  
                   7445: * Class Binding::               
                   7446: * Method conveniences::         
                   7447: * Classes and Scoping::         
1.37      anton    7448: * Dividing classes::            
1.26      crook    7449: * Object Interfaces::           
                   7450: * Objects Implementation::      
                   7451: * Objects Glossary::            
                   7452: @end menu
1.1       anton    7453: 
1.26      crook    7454: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
                   7455: and Bernd Paysan helped me with the related works section.
1.1       anton    7456: 
1.26      crook    7457: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   7458: @subsubsection Properties of the @file{objects.fs} model
                   7459: @cindex @file{objects.fs} properties
1.1       anton    7460: 
1.26      crook    7461: @itemize @bullet
                   7462: @item
                   7463: It is straightforward to pass objects on the stack. Passing
                   7464: selectors on the stack is a little less convenient, but possible.
1.1       anton    7465: 
1.26      crook    7466: @item
                   7467: Objects are just data structures in memory, and are referenced by their
                   7468: address. You can create words for objects with normal defining words
                   7469: like @code{constant}. Likewise, there is no difference between instance
                   7470: variables that contain objects and those that contain other data.
1.1       anton    7471: 
1.26      crook    7472: @item
                   7473: Late binding is efficient and easy to use.
1.21      crook    7474: 
1.26      crook    7475: @item
                   7476: It avoids parsing, and thus avoids problems with state-smartness
                   7477: and reduced extensibility; for convenience there are a few parsing
                   7478: words, but they have non-parsing counterparts. There are also a few
                   7479: defining words that parse. This is hard to avoid, because all standard
                   7480: defining words parse (except @code{:noname}); however, such
                   7481: words are not as bad as many other parsing words, because they are not
                   7482: state-smart.
1.21      crook    7483: 
1.26      crook    7484: @item
                   7485: It does not try to incorporate everything. It does a few things and does
                   7486: them well (IMO). In particular, this model was not designed to support
                   7487: information hiding (although it has features that may help); you can use
                   7488: a separate package for achieving this.
1.21      crook    7489: 
1.26      crook    7490: @item
                   7491: It is layered; you don't have to learn and use all features to use this
                   7492: model. Only a few features are necessary (@xref{Basic Objects Usage},
                   7493: @xref{The Objects base class}, @xref{Creating objects}.), the others
                   7494: are optional and independent of each other.
1.21      crook    7495: 
1.26      crook    7496: @item
                   7497: An implementation in ANS Forth is available.
1.21      crook    7498: 
1.26      crook    7499: @end itemize
1.21      crook    7500: 
                   7501: 
1.26      crook    7502: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   7503: @subsubsection Basic @file{objects.fs} Usage
                   7504: @cindex basic objects usage
                   7505: @cindex objects, basic usage
1.21      crook    7506: 
1.26      crook    7507: You can define a class for graphical objects like this:
1.21      crook    7508: 
1.26      crook    7509: @cindex @code{class} usage
                   7510: @cindex @code{end-class} usage
                   7511: @cindex @code{selector} usage
                   7512: @example
                   7513: object class \ "object" is the parent class
                   7514:   selector draw ( x y graphical -- )
                   7515: end-class graphical
                   7516: @end example
1.21      crook    7517: 
1.26      crook    7518: This code defines a class @code{graphical} with an
                   7519: operation @code{draw}.  We can perform the operation
                   7520: @code{draw} on any @code{graphical} object, e.g.:
1.21      crook    7521: 
1.26      crook    7522: @example
                   7523: 100 100 t-rex draw
                   7524: @end example
1.21      crook    7525: 
1.26      crook    7526: @noindent
                   7527: where @code{t-rex} is a word (say, a constant) that produces a
                   7528: graphical object.
1.21      crook    7529: 
1.29      crook    7530: @comment TODO add a 2nd operation eg perimeter.. and use for
1.26      crook    7531: @comment a concrete example
1.21      crook    7532: 
1.26      crook    7533: @cindex abstract class
                   7534: How do we create a graphical object? With the present definitions,
                   7535: we cannot create a useful graphical object. The class
                   7536: @code{graphical} describes graphical objects in general, but not
                   7537: any concrete graphical object type (C++ users would call it an
                   7538: @emph{abstract class}); e.g., there is no method for the selector
                   7539: @code{draw} in the class @code{graphical}.
1.21      crook    7540: 
1.26      crook    7541: For concrete graphical objects, we define child classes of the
                   7542: class @code{graphical}, e.g.:
1.21      crook    7543: 
1.26      crook    7544: @cindex @code{overrides} usage
                   7545: @cindex @code{field} usage in class definition
                   7546: @example
                   7547: graphical class \ "graphical" is the parent class
                   7548:   cell% field circle-radius
1.21      crook    7549: 
1.26      crook    7550: :noname ( x y circle -- )
                   7551:   circle-radius @@ draw-circle ;
                   7552: overrides draw
1.21      crook    7553: 
1.26      crook    7554: :noname ( n-radius circle -- )
                   7555:   circle-radius ! ;
                   7556: overrides construct
1.21      crook    7557: 
1.26      crook    7558: end-class circle
1.21      crook    7559: @end example
                   7560: 
1.26      crook    7561: Here we define a class @code{circle} as a child of @code{graphical},
                   7562: with field @code{circle-radius} (which behaves just like a field
                   7563: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   7564: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   7565: defined in @code{object}, the parent class of @code{graphical}).
1.21      crook    7566: 
1.26      crook    7567: Now we can create a circle on the heap (i.e.,
                   7568: @code{allocate}d memory) with:
1.21      crook    7569: 
1.26      crook    7570: @cindex @code{heap-new} usage
1.21      crook    7571: @example
1.26      crook    7572: 50 circle heap-new constant my-circle
                   7573: @end example
1.21      crook    7574: 
1.26      crook    7575: @noindent
                   7576: @code{heap-new} invokes @code{construct}, thus
                   7577: initializing the field @code{circle-radius} with 50. We can draw
                   7578: this new circle at (100,100) with:
1.21      crook    7579: 
1.26      crook    7580: @example
                   7581: 100 100 my-circle draw
1.21      crook    7582: @end example
                   7583: 
1.26      crook    7584: @cindex selector invocation, restrictions
                   7585: @cindex class definition, restrictions
                   7586: Note: You can only invoke a selector if the object on the TOS
                   7587: (the receiving object) belongs to the class where the selector was
                   7588: defined or one of its descendents; e.g., you can invoke
                   7589: @code{draw} only for objects belonging to @code{graphical}
                   7590: or its descendents (e.g., @code{circle}).  Immediately before
                   7591: @code{end-class}, the search order has to be the same as
                   7592: immediately after @code{class}.
1.21      crook    7593: 
1.26      crook    7594: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   7595: @subsubsection The @file{object.fs} base class
                   7596: @cindex @code{object} class
1.21      crook    7597: 
1.26      crook    7598: When you define a class, you have to specify a parent class.  So how do
                   7599: you start defining classes? There is one class available from the start:
                   7600: @code{object}. It is ancestor for all classes and so is the
                   7601: only class that has no parent. It has two selectors: @code{construct}
                   7602: and @code{print}.
1.21      crook    7603: 
1.26      crook    7604: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   7605: @subsubsection Creating objects
                   7606: @cindex creating objects
                   7607: @cindex object creation
                   7608: @cindex object allocation options
1.21      crook    7609: 
1.26      crook    7610: @cindex @code{heap-new} discussion
                   7611: @cindex @code{dict-new} discussion
                   7612: @cindex @code{construct} discussion
                   7613: You can create and initialize an object of a class on the heap with
                   7614: @code{heap-new} ( ... class -- object ) and in the dictionary
                   7615: (allocation with @code{allot}) with @code{dict-new} (
                   7616: ... class -- object ). Both words invoke @code{construct}, which
                   7617: consumes the stack items indicated by "..." above.
1.21      crook    7618: 
1.26      crook    7619: @cindex @code{init-object} discussion
                   7620: @cindex @code{class-inst-size} discussion
                   7621: If you want to allocate memory for an object yourself, you can get its
                   7622: alignment and size with @code{class-inst-size 2@@} ( class --
                   7623: align size ). Once you have memory for an object, you can initialize
                   7624: it with @code{init-object} ( ... class object -- );
                   7625: @code{construct} does only a part of the necessary work.
1.21      crook    7626: 
1.26      crook    7627: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   7628: @subsubsection Object-Oriented Programming Style
                   7629: @cindex object-oriented programming style
1.21      crook    7630: 
1.26      crook    7631: This section is not exhaustive.
1.1       anton    7632: 
1.26      crook    7633: @cindex stack effects of selectors
                   7634: @cindex selectors and stack effects
                   7635: In general, it is a good idea to ensure that all methods for the
                   7636: same selector have the same stack effect: when you invoke a selector,
                   7637: you often have no idea which method will be invoked, so, unless all
                   7638: methods have the same stack effect, you will not know the stack effect
                   7639: of the selector invocation.
1.21      crook    7640: 
1.26      crook    7641: One exception to this rule is methods for the selector
                   7642: @code{construct}. We know which method is invoked, because we
                   7643: specify the class to be constructed at the same place. Actually, I
                   7644: defined @code{construct} as a selector only to give the users a
                   7645: convenient way to specify initialization. The way it is used, a
                   7646: mechanism different from selector invocation would be more natural
                   7647: (but probably would take more code and more space to explain).
1.21      crook    7648: 
1.26      crook    7649: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   7650: @subsubsection Class Binding
                   7651: @cindex class binding
                   7652: @cindex early binding
1.21      crook    7653: 
1.26      crook    7654: @cindex late binding
                   7655: Normal selector invocations determine the method at run-time depending
                   7656: on the class of the receiving object. This run-time selection is called
1.29      crook    7657: @i{late binding}.
1.21      crook    7658: 
1.26      crook    7659: Sometimes it's preferable to invoke a different method. For example,
                   7660: you might want to use the simple method for @code{print}ing
                   7661: @code{object}s instead of the possibly long-winded @code{print} method
                   7662: of the receiver class. You can achieve this by replacing the invocation
                   7663: of @code{print} with:
1.21      crook    7664: 
1.26      crook    7665: @cindex @code{[bind]} usage
                   7666: @example
                   7667: [bind] object print
1.21      crook    7668: @end example
                   7669: 
1.26      crook    7670: @noindent
                   7671: in compiled code or:
1.21      crook    7672: 
1.26      crook    7673: @cindex @code{bind} usage
1.21      crook    7674: @example
1.26      crook    7675: bind object print
1.21      crook    7676: @end example
                   7677: 
1.26      crook    7678: @cindex class binding, alternative to
                   7679: @noindent
                   7680: in interpreted code. Alternatively, you can define the method with a
                   7681: name (e.g., @code{print-object}), and then invoke it through the
                   7682: name. Class binding is just a (often more convenient) way to achieve
                   7683: the same effect; it avoids name clutter and allows you to invoke
                   7684: methods directly without naming them first.
                   7685: 
                   7686: @cindex superclass binding
                   7687: @cindex parent class binding
                   7688: A frequent use of class binding is this: When we define a method
                   7689: for a selector, we often want the method to do what the selector does
                   7690: in the parent class, and a little more. There is a special word for
                   7691: this purpose: @code{[parent]}; @code{[parent]
                   7692: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   7693: selector}}, where @code{@emph{parent}} is the parent
                   7694: class of the current class. E.g., a method definition might look like:
1.21      crook    7695: 
1.26      crook    7696: @cindex @code{[parent]} usage
1.21      crook    7697: @example
1.26      crook    7698: :noname
                   7699:   dup [parent] foo \ do parent's foo on the receiving object
                   7700:   ... \ do some more
                   7701: ; overrides foo
1.21      crook    7702: @end example
                   7703: 
1.26      crook    7704: @cindex class binding as optimization
                   7705: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   7706: March 1997), Andrew McKewan presents class binding as an optimization
                   7707: technique. I recommend not using it for this purpose unless you are in
                   7708: an emergency. Late binding is pretty fast with this model anyway, so the
                   7709: benefit of using class binding is small; the cost of using class binding
                   7710: where it is not appropriate is reduced maintainability.
1.21      crook    7711: 
1.26      crook    7712: While we are at programming style questions: You should bind
                   7713: selectors only to ancestor classes of the receiving object. E.g., say,
                   7714: you know that the receiving object is of class @code{foo} or its
                   7715: descendents; then you should bind only to @code{foo} and its
                   7716: ancestors.
1.21      crook    7717: 
1.26      crook    7718: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   7719: @subsubsection Method conveniences
                   7720: @cindex method conveniences
1.1       anton    7721: 
1.26      crook    7722: In a method you usually access the receiving object pretty often.  If
                   7723: you define the method as a plain colon definition (e.g., with
                   7724: @code{:noname}), you may have to do a lot of stack
                   7725: gymnastics. To avoid this, you can define the method with @code{m:
                   7726: ... ;m}. E.g., you could define the method for
                   7727: @code{draw}ing a @code{circle} with
1.20      pazsan   7728: 
1.26      crook    7729: @cindex @code{this} usage
                   7730: @cindex @code{m:} usage
                   7731: @cindex @code{;m} usage
                   7732: @example
                   7733: m: ( x y circle -- )
                   7734:   ( x y ) this circle-radius @@ draw-circle ;m
                   7735: @end example
1.20      pazsan   7736: 
1.26      crook    7737: @cindex @code{exit} in @code{m: ... ;m}
                   7738: @cindex @code{exitm} discussion
                   7739: @cindex @code{catch} in @code{m: ... ;m}
                   7740: When this method is executed, the receiver object is removed from the
                   7741: stack; you can access it with @code{this} (admittedly, in this
                   7742: example the use of @code{m: ... ;m} offers no advantage). Note
                   7743: that I specify the stack effect for the whole method (i.e. including
                   7744: the receiver object), not just for the code between @code{m:}
                   7745: and @code{;m}. You cannot use @code{exit} in
                   7746: @code{m:...;m}; instead, use
                   7747: @code{exitm}.@footnote{Moreover, for any word that calls
                   7748: @code{catch} and was defined before loading
                   7749: @code{objects.fs}, you have to redefine it like I redefined
                   7750: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.20      pazsan   7751: 
1.26      crook    7752: @cindex @code{inst-var} usage
                   7753: You will frequently use sequences of the form @code{this
                   7754: @emph{field}} (in the example above: @code{this
                   7755: circle-radius}). If you use the field only in this way, you can
                   7756: define it with @code{inst-var} and eliminate the
                   7757: @code{this} before the field name. E.g., the @code{circle}
                   7758: class above could also be defined with:
1.20      pazsan   7759: 
1.26      crook    7760: @example
                   7761: graphical class
                   7762:   cell% inst-var radius
1.20      pazsan   7763: 
1.26      crook    7764: m: ( x y circle -- )
                   7765:   radius @@ draw-circle ;m
                   7766: overrides draw
1.20      pazsan   7767: 
1.26      crook    7768: m: ( n-radius circle -- )
                   7769:   radius ! ;m
                   7770: overrides construct
1.12      anton    7771: 
1.26      crook    7772: end-class circle
                   7773: @end example
1.12      anton    7774: 
1.26      crook    7775: @code{radius} can only be used in @code{circle} and its
                   7776: descendent classes and inside @code{m:...;m}.
1.12      anton    7777: 
1.26      crook    7778: @cindex @code{inst-value} usage
                   7779: You can also define fields with @code{inst-value}, which is
                   7780: to @code{inst-var} what @code{value} is to
                   7781: @code{variable}.  You can change the value of such a field with
                   7782: @code{[to-inst]}.  E.g., we could also define the class
                   7783: @code{circle} like this:
1.12      anton    7784: 
1.26      crook    7785: @example
                   7786: graphical class
                   7787:   inst-value radius
1.12      anton    7788: 
1.26      crook    7789: m: ( x y circle -- )
                   7790:   radius draw-circle ;m
                   7791: overrides draw
1.12      anton    7792: 
1.26      crook    7793: m: ( n-radius circle -- )
                   7794:   [to-inst] radius ;m
                   7795: overrides construct
1.21      crook    7796: 
1.26      crook    7797: end-class circle
1.12      anton    7798: @end example
                   7799: 
1.38    ! anton    7800: Finally, you can define named methods with @code{:m}.  One use of this
        !          7801: feature is the definition of words that occur only in one class and are
        !          7802: not intended to be overridden, but which still need method context
        !          7803: (e.g., for accessing @code{inst-var}s).  Another use is for methods that
        !          7804: would be bound frequently, if defined anonymously.
        !          7805: 
1.12      anton    7806: 
1.37      anton    7807: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
1.26      crook    7808: @subsubsection Classes and Scoping
                   7809: @cindex classes and scoping
                   7810: @cindex scoping and classes
1.12      anton    7811: 
1.26      crook    7812: Inheritance is frequent, unlike structure extension. This exacerbates
                   7813: the problem with the field name convention (@pxref{Structure Naming
                   7814: Convention}): One always has to remember in which class the field was
                   7815: originally defined; changing a part of the class structure would require
                   7816: changes for renaming in otherwise unaffected code.
1.12      anton    7817: 
1.26      crook    7818: @cindex @code{inst-var} visibility
                   7819: @cindex @code{inst-value} visibility
                   7820: To solve this problem, I added a scoping mechanism (which was not in my
                   7821: original charter): A field defined with @code{inst-var} (or
                   7822: @code{inst-value}) is visible only in the class where it is defined and in
                   7823: the descendent classes of this class.  Using such fields only makes
                   7824: sense in @code{m:}-defined methods in these classes anyway.
1.12      anton    7825: 
1.26      crook    7826: This scoping mechanism allows us to use the unadorned field name,
                   7827: because name clashes with unrelated words become much less likely.
1.12      anton    7828: 
1.26      crook    7829: @cindex @code{protected} discussion
                   7830: @cindex @code{private} discussion
                   7831: Once we have this mechanism, we can also use it for controlling the
                   7832: visibility of other words: All words defined after
                   7833: @code{protected} are visible only in the current class and its
                   7834: descendents. @code{public} restores the compilation
                   7835: (i.e. @code{current}) word list that was in effect before. If you
                   7836: have several @code{protected}s without an intervening
                   7837: @code{public} or @code{set-current}, @code{public}
                   7838: will restore the compilation word list in effect before the first of
                   7839: these @code{protected}s.
1.12      anton    7840: 
1.37      anton    7841: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
                   7842: @subsubsection Dividing classes
                   7843: @cindex Dividing classes
                   7844: @cindex @code{methods}...@code{end-methods}
                   7845: 
                   7846: You may want to do the definition of methods separate from the
                   7847: definition of the class, its selectors, fields, and instance variables,
                   7848: i.e., separate the implementation from the definition.  You can do this
                   7849: in the following way:
                   7850: 
                   7851: @example
                   7852: graphical class
                   7853:   inst-value radius
                   7854: end-class circle
                   7855: 
                   7856: ... \ do some other stuff
                   7857: 
                   7858: circle methods \ now we are ready
                   7859: 
                   7860: m: ( x y circle -- )
                   7861:   radius draw-circle ;m
                   7862: overrides draw
                   7863: 
                   7864: m: ( n-radius circle -- )
                   7865:   [to-inst] radius ;m
                   7866: overrides construct
                   7867: 
                   7868: end-methods
                   7869: @end example
                   7870: 
                   7871: You can use several @code{methods}...@code{end-methods} sections.  The
                   7872: only things you can do to the class in these sections are: defining
                   7873: methods, and overriding the class's selectors.  You must not define new
                   7874: selectors or fields.
                   7875: 
                   7876: Note that you often have to override a selector before using it.  In
                   7877: particular, you usually have to override @code{construct} with a new
                   7878: method before you can invoke @code{heap-new} and friends.  E.g., you
                   7879: must not create a circle before the @code{overrides construct} sequence
                   7880: in the example above.
                   7881: 
                   7882: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
1.26      crook    7883: @subsubsection Object Interfaces
                   7884: @cindex object interfaces
                   7885: @cindex interfaces for objects
1.12      anton    7886: 
1.26      crook    7887: In this model you can only call selectors defined in the class of the
                   7888: receiving objects or in one of its ancestors. If you call a selector
                   7889: with a receiving object that is not in one of these classes, the
                   7890: result is undefined; if you are lucky, the program crashes
                   7891: immediately.
1.12      anton    7892: 
1.26      crook    7893: @cindex selectors common to hardly-related classes
                   7894: Now consider the case when you want to have a selector (or several)
                   7895: available in two classes: You would have to add the selector to a
                   7896: common ancestor class, in the worst case to @code{object}. You
                   7897: may not want to do this, e.g., because someone else is responsible for
                   7898: this ancestor class.
1.12      anton    7899: 
1.26      crook    7900: The solution for this problem is interfaces. An interface is a
                   7901: collection of selectors. If a class implements an interface, the
                   7902: selectors become available to the class and its descendents. A class
                   7903: can implement an unlimited number of interfaces. For the problem
                   7904: discussed above, we would define an interface for the selector(s), and
                   7905: both classes would implement the interface.
1.12      anton    7906: 
1.26      crook    7907: As an example, consider an interface @code{storage} for
                   7908: writing objects to disk and getting them back, and a class
                   7909: @code{foo} that implements it. The code would look like this:
1.12      anton    7910: 
1.26      crook    7911: @cindex @code{interface} usage
                   7912: @cindex @code{end-interface} usage
                   7913: @cindex @code{implementation} usage
                   7914: @example
                   7915: interface
                   7916:   selector write ( file object -- )
                   7917:   selector read1 ( file object -- )
                   7918: end-interface storage
1.12      anton    7919: 
1.26      crook    7920: bar class
                   7921:   storage implementation
1.12      anton    7922: 
1.26      crook    7923: ... overrides write
1.37      anton    7924: ... overrides read1
1.26      crook    7925: ...
                   7926: end-class foo
1.12      anton    7927: @end example
                   7928: 
1.26      crook    7929: @noindent
1.29      crook    7930: (I would add a word @code{read} @i{( file -- object )} that uses
1.26      crook    7931: @code{read1} internally, but that's beyond the point illustrated
                   7932: here.)
1.12      anton    7933: 
1.26      crook    7934: Note that you cannot use @code{protected} in an interface; and
                   7935: of course you cannot define fields.
1.12      anton    7936: 
1.26      crook    7937: In the Neon model, all selectors are available for all classes;
                   7938: therefore it does not need interfaces. The price you pay in this model
                   7939: is slower late binding, and therefore, added complexity to avoid late
                   7940: binding.
1.12      anton    7941: 
1.26      crook    7942: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   7943: @subsubsection @file{objects.fs} Implementation
                   7944: @cindex @file{objects.fs} implementation
1.12      anton    7945: 
1.26      crook    7946: @cindex @code{object-map} discussion
                   7947: An object is a piece of memory, like one of the data structures
                   7948: described with @code{struct...end-struct}. It has a field
                   7949: @code{object-map} that points to the method map for the object's
                   7950: class.
1.12      anton    7951: 
1.26      crook    7952: @cindex method map
                   7953: @cindex virtual function table
                   7954: The @emph{method map}@footnote{This is Self terminology; in C++
                   7955: terminology: virtual function table.} is an array that contains the
1.29      crook    7956: execution tokens (@i{xt}s) of the methods for the object's class. Each
1.26      crook    7957: selector contains an offset into a method map.
1.12      anton    7958: 
1.26      crook    7959: @cindex @code{selector} implementation, class
                   7960: @code{selector} is a defining word that uses
                   7961: @code{CREATE} and @code{DOES>}. The body of the
                   7962: selector contains the offset; the @code{does>} action for a
                   7963: class selector is, basically:
1.21      crook    7964: 
1.26      crook    7965: @example
                   7966: ( object addr ) @@ over object-map @@ + @@ execute
                   7967: @end example
1.12      anton    7968: 
1.26      crook    7969: Since @code{object-map} is the first field of the object, it
                   7970: does not generate any code. As you can see, calling a selector has a
                   7971: small, constant cost.
1.12      anton    7972: 
1.26      crook    7973: @cindex @code{current-interface} discussion
                   7974: @cindex class implementation and representation
                   7975: A class is basically a @code{struct} combined with a method
                   7976: map. During the class definition the alignment and size of the class
                   7977: are passed on the stack, just as with @code{struct}s, so
                   7978: @code{field} can also be used for defining class
                   7979: fields. However, passing more items on the stack would be
                   7980: inconvenient, so @code{class} builds a data structure in memory,
                   7981: which is accessed through the variable
                   7982: @code{current-interface}. After its definition is complete, the
                   7983: class is represented on the stack by a pointer (e.g., as parameter for
                   7984: a child class definition).
1.1       anton    7985: 
1.26      crook    7986: A new class starts off with the alignment and size of its parent,
                   7987: and a copy of the parent's method map. Defining new fields extends the
                   7988: size and alignment; likewise, defining new selectors extends the
1.29      crook    7989: method map. @code{overrides} just stores a new @i{xt} in the method
1.26      crook    7990: map at the offset given by the selector.
1.20      pazsan   7991: 
1.26      crook    7992: @cindex class binding, implementation
1.29      crook    7993: Class binding just gets the @i{xt} at the offset given by the selector
1.26      crook    7994: from the class's method map and @code{compile,}s (in the case of
                   7995: @code{[bind]}) it.
1.21      crook    7996: 
1.26      crook    7997: @cindex @code{this} implementation
                   7998: @cindex @code{catch} and @code{this}
                   7999: @cindex @code{this} and @code{catch}
                   8000: I implemented @code{this} as a @code{value}. At the
                   8001: start of an @code{m:...;m} method the old @code{this} is
                   8002: stored to the return stack and restored at the end; and the object on
                   8003: the TOS is stored @code{TO this}. This technique has one
                   8004: disadvantage: If the user does not leave the method via
                   8005: @code{;m}, but via @code{throw} or @code{exit},
                   8006: @code{this} is not restored (and @code{exit} may
                   8007: crash). To deal with the @code{throw} problem, I have redefined
                   8008: @code{catch} to save and restore @code{this}; the same
                   8009: should be done with any word that can catch an exception. As for
                   8010: @code{exit}, I simply forbid it (as a replacement, there is
                   8011: @code{exitm}).
1.21      crook    8012: 
1.26      crook    8013: @cindex @code{inst-var} implementation
                   8014: @code{inst-var} is just the same as @code{field}, with
                   8015: a different @code{DOES>} action:
                   8016: @example
                   8017: @@ this +
                   8018: @end example
                   8019: Similar for @code{inst-value}.
1.21      crook    8020: 
1.26      crook    8021: @cindex class scoping implementation
                   8022: Each class also has a word list that contains the words defined with
                   8023: @code{inst-var} and @code{inst-value}, and its protected
                   8024: words. It also has a pointer to its parent. @code{class} pushes
                   8025: the word lists of the class and all its ancestors onto the search order stack,
                   8026: and @code{end-class} drops them.
1.21      crook    8027: 
1.26      crook    8028: @cindex interface implementation
                   8029: An interface is like a class without fields, parent and protected
                   8030: words; i.e., it just has a method map. If a class implements an
                   8031: interface, its method map contains a pointer to the method map of the
                   8032: interface. The positive offsets in the map are reserved for class
                   8033: methods, therefore interface map pointers have negative
                   8034: offsets. Interfaces have offsets that are unique throughout the
                   8035: system, unlike class selectors, whose offsets are only unique for the
                   8036: classes where the selector is available (invokable).
1.21      crook    8037: 
1.26      crook    8038: This structure means that interface selectors have to perform one
                   8039: indirection more than class selectors to find their method. Their body
                   8040: contains the interface map pointer offset in the class method map, and
                   8041: the method offset in the interface method map. The
                   8042: @code{does>} action for an interface selector is, basically:
1.21      crook    8043: 
                   8044: @example
1.26      crook    8045: ( object selector-body )
                   8046: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   8047: swap object-map @@ + @@ ( object selector-body map )
                   8048: swap selector-offset @@ + @@ execute
1.21      crook    8049: @end example
                   8050: 
1.26      crook    8051: where @code{object-map} and @code{selector-offset} are
                   8052: first fields and generate no code.
                   8053: 
                   8054: As a concrete example, consider the following code:
1.21      crook    8055: 
1.26      crook    8056: @example
                   8057: interface
                   8058:   selector if1sel1
                   8059:   selector if1sel2
                   8060: end-interface if1
1.21      crook    8061: 
1.26      crook    8062: object class
                   8063:   if1 implementation
                   8064:   selector cl1sel1
                   8065:   cell% inst-var cl1iv1
1.21      crook    8066: 
1.26      crook    8067: ' m1 overrides construct
                   8068: ' m2 overrides if1sel1
                   8069: ' m3 overrides if1sel2
                   8070: ' m4 overrides cl1sel2
                   8071: end-class cl1
1.21      crook    8072: 
1.26      crook    8073: create obj1 object dict-new drop
                   8074: create obj2 cl1    dict-new drop
                   8075: @end example
1.21      crook    8076: 
1.26      crook    8077: The data structure created by this code (including the data structure
                   8078: for @code{object}) is shown in the <a
                   8079: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
1.29      crook    8080: @comment TODO add this diagram..
1.21      crook    8081: 
1.26      crook    8082: @node Objects Glossary,  , Objects Implementation, Objects
                   8083: @subsubsection @file{objects.fs} Glossary
                   8084: @cindex @file{objects.fs} Glossary
1.21      crook    8085: 
1.26      crook    8086: doc---objects-bind
                   8087: doc---objects-<bind>
                   8088: doc---objects-bind'
                   8089: doc---objects-[bind]
                   8090: doc---objects-class
                   8091: doc---objects-class->map
                   8092: doc---objects-class-inst-size
                   8093: doc---objects-class-override!
                   8094: doc---objects-construct
                   8095: doc---objects-current'
                   8096: doc---objects-[current]
                   8097: doc---objects-current-interface
                   8098: doc---objects-dict-new
                   8099: doc---objects-drop-order
                   8100: doc---objects-end-class
                   8101: doc---objects-end-class-noname
                   8102: doc---objects-end-interface
                   8103: doc---objects-end-interface-noname
1.37      anton    8104: doc---objects-end-methods
1.26      crook    8105: doc---objects-exitm
                   8106: doc---objects-heap-new
                   8107: doc---objects-implementation
                   8108: doc---objects-init-object
                   8109: doc---objects-inst-value
                   8110: doc---objects-inst-var
                   8111: doc---objects-interface
1.38    ! anton    8112: doc---objects-m:
        !          8113: doc---objects-:m
1.26      crook    8114: doc---objects-;m
                   8115: doc---objects-method
1.37      anton    8116: doc---objects-methods
1.26      crook    8117: doc---objects-object
                   8118: doc---objects-overrides
                   8119: doc---objects-[parent]
                   8120: doc---objects-print
                   8121: doc---objects-protected
                   8122: doc---objects-public
                   8123: doc---objects-push-order
                   8124: doc---objects-selector
                   8125: doc---objects-this
                   8126: doc---objects-<to-inst>
                   8127: doc---objects-[to-inst]
                   8128: doc---objects-to-this
                   8129: doc---objects-xt-new
1.21      crook    8130: 
1.26      crook    8131: @c -------------------------------------------------------------
                   8132: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   8133: @subsection The @file{oof.fs} model
                   8134: @cindex oof
                   8135: @cindex object-oriented programming
1.21      crook    8136: 
1.26      crook    8137: @cindex @file{objects.fs}
                   8138: @cindex @file{oof.fs}
1.21      crook    8139: 
1.26      crook    8140: This section describes the @file{oof.fs} package.
1.21      crook    8141: 
1.26      crook    8142: The package described in this section has been used in bigFORTH since 1991, and
                   8143: used for two large applications: a chromatographic system used to
                   8144: create new medicaments, and a graphic user interface library (MINOS).
1.21      crook    8145: 
1.26      crook    8146: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   8147: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   8148: 10(2), 1994.
1.21      crook    8149: 
1.26      crook    8150: @menu
                   8151: * Properties of the OOF model::
                   8152: * Basic OOF Usage::
                   8153: * The OOF base class::
                   8154: * Class Declaration::
                   8155: * Class Implementation::
                   8156: @end menu
1.21      crook    8157: 
1.26      crook    8158: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   8159: @subsubsection Properties of the @file{oof.fs} model
                   8160: @cindex @file{oof.fs} properties
1.21      crook    8161: 
1.26      crook    8162: @itemize @bullet
                   8163: @item
                   8164: This model combines object oriented programming with information
                   8165: hiding. It helps you writing large application, where scoping is
                   8166: necessary, because it provides class-oriented scoping.
1.21      crook    8167: 
1.26      crook    8168: @item
                   8169: Named objects, object pointers, and object arrays can be created,
                   8170: selector invocation uses the ``object selector'' syntax. Selector invocation
                   8171: to objects and/or selectors on the stack is a bit less convenient, but
                   8172: possible.
1.21      crook    8173: 
1.26      crook    8174: @item
                   8175: Selector invocation and instance variable usage of the active object is
                   8176: straightforward, since both make use of the active object.
1.21      crook    8177: 
1.26      crook    8178: @item
                   8179: Late binding is efficient and easy to use.
1.21      crook    8180: 
1.26      crook    8181: @item
                   8182: State-smart objects parse selectors. However, extensibility is provided
                   8183: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.21      crook    8184: 
                   8185: @item
1.26      crook    8186: An implementation in ANS Forth is available.
                   8187: 
1.21      crook    8188: @end itemize
                   8189: 
                   8190: 
1.26      crook    8191: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   8192: @subsubsection Basic @file{oof.fs} Usage
                   8193: @cindex @file{oof.fs} usage
                   8194: 
                   8195: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.21      crook    8196: 
1.26      crook    8197: You can define a class for graphical objects like this:
1.21      crook    8198: 
1.26      crook    8199: @cindex @code{class} usage
                   8200: @cindex @code{class;} usage
                   8201: @cindex @code{method} usage
                   8202: @example
                   8203: object class graphical \ "object" is the parent class
                   8204:   method draw ( x y graphical -- )
                   8205: class;
                   8206: @end example
1.21      crook    8207: 
1.26      crook    8208: This code defines a class @code{graphical} with an
                   8209: operation @code{draw}.  We can perform the operation
                   8210: @code{draw} on any @code{graphical} object, e.g.:
1.21      crook    8211: 
1.26      crook    8212: @example
                   8213: 100 100 t-rex draw
                   8214: @end example
1.21      crook    8215: 
1.26      crook    8216: @noindent
                   8217: where @code{t-rex} is an object or object pointer, created with e.g.
                   8218: @code{graphical : t-rex}.
1.21      crook    8219: 
1.26      crook    8220: @cindex abstract class
                   8221: How do we create a graphical object? With the present definitions,
                   8222: we cannot create a useful graphical object. The class
                   8223: @code{graphical} describes graphical objects in general, but not
                   8224: any concrete graphical object type (C++ users would call it an
                   8225: @emph{abstract class}); e.g., there is no method for the selector
                   8226: @code{draw} in the class @code{graphical}.
1.21      crook    8227: 
1.26      crook    8228: For concrete graphical objects, we define child classes of the
                   8229: class @code{graphical}, e.g.:
1.21      crook    8230: 
                   8231: @example
1.26      crook    8232: graphical class circle \ "graphical" is the parent class
                   8233:   cell var circle-radius
                   8234: how:
                   8235:   : draw ( x y -- )
                   8236:     circle-radius @@ draw-circle ;
                   8237: 
                   8238:   : init ( n-radius -- (
                   8239:     circle-radius ! ;
                   8240: class;
                   8241: @end example
                   8242: 
                   8243: Here we define a class @code{circle} as a child of @code{graphical},
                   8244: with a field @code{circle-radius}; it defines new methods for the
                   8245: selectors @code{draw} and @code{init} (@code{init} is defined in
                   8246: @code{object}, the parent class of @code{graphical}).
1.21      crook    8247: 
1.26      crook    8248: Now we can create a circle in the dictionary with:
1.21      crook    8249: 
1.26      crook    8250: @example
                   8251: 50 circle : my-circle
1.21      crook    8252: @end example
                   8253: 
1.26      crook    8254: @noindent
                   8255: @code{:} invokes @code{init}, thus initializing the field
                   8256: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   8257: with:
1.21      crook    8258: 
                   8259: @example
1.26      crook    8260: 100 100 my-circle draw
1.21      crook    8261: @end example
                   8262: 
1.26      crook    8263: @cindex selector invocation, restrictions
                   8264: @cindex class definition, restrictions
                   8265: Note: You can only invoke a selector if the receiving object belongs to
                   8266: the class where the selector was defined or one of its descendents;
                   8267: e.g., you can invoke @code{draw} only for objects belonging to
                   8268: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   8269: mechanism will check if you try to invoke a selector that is not
                   8270: defined in this class hierarchy, so you'll get an error at compilation
                   8271: time.
                   8272: 
                   8273: 
                   8274: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   8275: @subsubsection The @file{oof.fs} base class
                   8276: @cindex @file{oof.fs} base class
                   8277: 
                   8278: When you define a class, you have to specify a parent class.  So how do
                   8279: you start defining classes? There is one class available from the start:
                   8280: @code{object}. You have to use it as ancestor for all classes. It is the
                   8281: only class that has no parent. Classes are also objects, except that
                   8282: they don't have instance variables; class manipulation such as
                   8283: inheritance or changing definitions of a class is handled through
                   8284: selectors of the class @code{object}.
                   8285: 
                   8286: @code{object} provides a number of selectors:
                   8287: 
1.21      crook    8288: @itemize @bullet
                   8289: @item
1.26      crook    8290: @code{class} for subclassing, @code{definitions} to add definitions
                   8291: later on, and @code{class?} to get type informations (is the class a
                   8292: subclass of the class passed on the stack?).
                   8293: doc---object-class
                   8294: doc---object-definitions
                   8295: doc---object-class?
                   8296: 
1.21      crook    8297: @item
1.26      crook    8298: @code{init} and @code{dispose} as constructor and destructor of the
                   8299: object. @code{init} is invocated after the object's memory is allocated,
                   8300: while @code{dispose} also handles deallocation. Thus if you redefine
                   8301: @code{dispose}, you have to call the parent's dispose with @code{super
                   8302: dispose}, too.
                   8303: doc---object-init
                   8304: doc---object-dispose
                   8305: 
1.21      crook    8306: @item
1.26      crook    8307: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   8308: @code{[]} to create named and unnamed objects and object arrays or
                   8309: object pointers.
                   8310: doc---object-new
                   8311: doc---object-new[]
                   8312: doc---object-:
                   8313: doc---object-ptr
                   8314: doc---object-asptr
                   8315: doc---object-[]
1.21      crook    8316: 
1.26      crook    8317: @item
                   8318: @code{::} and @code{super} for explicit scoping. You should use explicit
                   8319: scoping only for super classes or classes with the same set of instance
                   8320: variables. Explicitly-scoped selectors use early binding.
                   8321: doc---object-::
                   8322: doc---object-super
1.21      crook    8323: 
1.26      crook    8324: @item
                   8325: @code{self} to get the address of the object
                   8326: doc---object-self
1.21      crook    8327: 
                   8328: @item
1.26      crook    8329: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   8330: pointers and instance defers.
                   8331: doc---object-bind
                   8332: doc---object-bound
                   8333: doc---object-link
                   8334: doc---object-is
                   8335: 
1.21      crook    8336: @item
1.26      crook    8337: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   8338: form the stack, and @code{postpone} to generate selector invocation code.
                   8339: doc---object-'
                   8340: doc---object-postpone
                   8341: 
1.21      crook    8342: @item
1.26      crook    8343: @code{with} and @code{endwith} to select the active object from the
                   8344: stack, and enable its scope. Using @code{with} and @code{endwith}
                   8345: also allows you to create code using selector @code{postpone} without being
                   8346: trapped by the state-smart objects.
                   8347: doc---object-with
                   8348: doc---object-endwith
                   8349: 
1.21      crook    8350: @end itemize
                   8351: 
1.26      crook    8352: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   8353: @subsubsection Class Declaration
                   8354: @cindex class declaration
                   8355: 
                   8356: @itemize @bullet
                   8357: @item
                   8358: Instance variables
                   8359: doc---oof-var
1.21      crook    8360: 
1.26      crook    8361: @item
                   8362: Object pointers
                   8363: doc---oof-ptr
                   8364: doc---oof-asptr
1.21      crook    8365: 
1.26      crook    8366: @item
                   8367: Instance defers
                   8368: doc---oof-defer
1.21      crook    8369: 
1.26      crook    8370: @item
                   8371: Method selectors
                   8372: doc---oof-early
                   8373: doc---oof-method
1.21      crook    8374: 
1.26      crook    8375: @item
                   8376: Class-wide variables
                   8377: doc---oof-static
1.21      crook    8378: 
1.26      crook    8379: @item
                   8380: End declaration
                   8381: doc---oof-how:
                   8382: doc---oof-class;
1.21      crook    8383: 
1.26      crook    8384: @end itemize
1.21      crook    8385: 
1.26      crook    8386: @c -------------------------------------------------------------
                   8387: @node Class Implementation,  , Class Declaration, OOF
                   8388: @subsubsection Class Implementation
                   8389: @cindex class implementation
1.21      crook    8390: 
1.26      crook    8391: @c -------------------------------------------------------------
                   8392: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   8393: @subsection The @file{mini-oof.fs} model
                   8394: @cindex mini-oof
1.1       anton    8395: 
1.26      crook    8396: Gforth's third object oriented Forth package is a 12-liner. It uses a
                   8397: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
                   8398: and reduces to the bare minimum of features. This is based on a posting
                   8399: of Bernd Paysan in comp.arch.
1.1       anton    8400: 
                   8401: @menu
1.26      crook    8402: * Basic Mini-OOF Usage::
                   8403: * Mini-OOF Example::
                   8404: * Mini-OOF Implementation::
1.1       anton    8405: @end menu
                   8406: 
1.26      crook    8407: @c -------------------------------------------------------------
                   8408: @node Basic Mini-OOF Usage, Mini-OOF Example, , Mini-OOF
                   8409: @subsubsection Basic @file{mini-oof.fs} Usage
                   8410: @cindex mini-oof usage
1.1       anton    8411: 
1.28      crook    8412: There is a base class (@code{class}, which allocates one cell for the
                   8413: object pointer) plus seven other words: to define a method, a variable,
                   8414: a class; to end a class, to resolve binding, to allocate an object and
                   8415: to compile a class method.
1.26      crook    8416: @comment TODO better description of the last one
1.1       anton    8417: 
1.26      crook    8418: doc-object
                   8419: doc-method
                   8420: doc-var
                   8421: doc-class
                   8422: doc-end-class
                   8423: doc-defines
                   8424: doc-new
                   8425: doc-::
1.1       anton    8426: 
1.21      crook    8427: 
1.26      crook    8428: @c -------------------------------------------------------------
                   8429: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   8430: @subsubsection Mini-OOF Example
                   8431: @cindex mini-oof example
1.21      crook    8432: 
1.26      crook    8433: A short example shows how to use this package. This example, in slightly
                   8434: extended form, is supplied as @file{moof-exm.fs}
1.29      crook    8435: @comment TODO could flesh this out with some comments from the Forthwrite article
1.21      crook    8436: 
1.26      crook    8437: @example
                   8438: object class
                   8439:   method init
                   8440:   method draw
                   8441: end-class graphical
                   8442: @end example
1.21      crook    8443: 
1.26      crook    8444: This code defines a class @code{graphical} with an
                   8445: operation @code{draw}.  We can perform the operation
                   8446: @code{draw} on any @code{graphical} object, e.g.:
1.1       anton    8447: 
1.26      crook    8448: @example
                   8449: 100 100 t-rex draw
                   8450: @end example
1.1       anton    8451: 
1.26      crook    8452: where @code{t-rex} is an object or object pointer, created with e.g.
                   8453: @code{graphical new Constant t-rex}.
1.1       anton    8454: 
1.26      crook    8455: For concrete graphical objects, we define child classes of the
                   8456: class @code{graphical}, e.g.:
1.21      crook    8457: 
                   8458: @example
1.26      crook    8459: graphical class
                   8460:   cell var circle-radius
                   8461: end-class circle \ "graphical" is the parent class
1.21      crook    8462: 
1.26      crook    8463: :noname ( x y -- )
                   8464:   circle-radius @@ draw-circle ; circle defines draw
                   8465: :noname ( r -- )
                   8466:   circle-radius ! ; circle defines init
1.21      crook    8467: @end example
                   8468: 
1.26      crook    8469: There is no implicit init method, so we have to define one. The creation
                   8470: code of the object now has to call init explicitely.
1.21      crook    8471: 
1.26      crook    8472: @example
                   8473: circle new Constant my-circle
                   8474: 50 my-circle init
                   8475: @end example
1.21      crook    8476: 
1.26      crook    8477: It is also possible to add a function to create named objects with
                   8478: automatic call of @code{init}, given that all objects have @code{init}
                   8479: on the same place:
1.1       anton    8480: 
                   8481: @example
1.26      crook    8482: : new: ( .. o "name" -- )
                   8483:     new dup Constant init ;
                   8484: 80 circle new: large-circle
1.1       anton    8485: @end example
                   8486: 
1.26      crook    8487: We can draw this new circle at (100,100) with:
1.1       anton    8488: 
                   8489: @example
1.26      crook    8490: 100 100 my-circle draw
1.1       anton    8491: @end example
                   8492: 
1.26      crook    8493: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
                   8494: @subsubsection @file{mini-oof.fs} Implementation
1.1       anton    8495: 
1.26      crook    8496: Object-oriented systems with late binding typically use a
                   8497: ``vtable''-approach: the first variable in each object is a pointer to a
                   8498: table, which contains the methods as function pointers. The vtable
                   8499: may also contain other information.
1.1       anton    8500: 
1.26      crook    8501: So first, let's declare methods:
1.1       anton    8502: 
1.26      crook    8503: @example
                   8504: : method ( m v -- m' v ) Create  over , swap cell+ swap
                   8505:   DOES> ( ... o -- ... ) @ over @ + @ execute ;
                   8506: @end example
1.1       anton    8507: 
1.26      crook    8508: During method declaration, the number of methods and instance
                   8509: variables is on the stack (in address units). @code{method} creates
                   8510: one method and increments the method number. To execute a method, it
                   8511: takes the object, fetches the vtable pointer, adds the offset, and
1.29      crook    8512: executes the @i{xt} stored there. Each method takes the object it is
1.26      crook    8513: invoked from as top of stack parameter. The method itself should
                   8514: consume that object.
1.1       anton    8515: 
1.26      crook    8516: Now, we also have to declare instance variables
1.21      crook    8517: 
1.26      crook    8518: @example
                   8519: : var ( m v size -- m v' ) Create  over , +
                   8520:   DOES> ( o -- addr ) @ + ;
                   8521: @end example
1.21      crook    8522: 
1.26      crook    8523: As before, a word is created with the current offset. Instance
                   8524: variables can have different sizes (cells, floats, doubles, chars), so
                   8525: all we do is take the size and add it to the offset. If your machine
                   8526: has alignment restrictions, put the proper @code{aligned} or
                   8527: @code{faligned} before the variable, to adjust the variable
                   8528: offset. That's why it is on the top of stack.
1.2       jwilke   8529: 
1.26      crook    8530: We need a starting point (the base object) and some syntactic sugar:
1.21      crook    8531: 
1.26      crook    8532: @example
                   8533: Create object  1 cells , 2 cells ,
                   8534: : class ( class -- class methods vars ) dup 2@ ;
                   8535: @end example
1.21      crook    8536: 
1.26      crook    8537: For inheritance, the vtable of the parent object has to be
                   8538: copied when a new, derived class is declared. This gives all the
                   8539: methods of the parent class, which can be overridden, though.
1.21      crook    8540: 
1.2       jwilke   8541: @example
1.26      crook    8542: : end-class  ( class methods vars -- )
                   8543:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   8544:   cell+ dup cell+ r> rot @ 2 cells /string move ;
                   8545: @end example
                   8546: 
                   8547: The first line creates the vtable, initialized with
                   8548: @code{noop}s. The second line is the inheritance mechanism, it
                   8549: copies the xts from the parent vtable.
1.2       jwilke   8550: 
1.26      crook    8551: We still have no way to define new methods, let's do that now:
1.2       jwilke   8552: 
1.26      crook    8553: @example
                   8554: : defines ( xt class -- ) ' >body @ + ! ;
1.2       jwilke   8555: @end example
                   8556: 
1.26      crook    8557: To allocate a new object, we need a word, too:
1.2       jwilke   8558: 
1.26      crook    8559: @example
                   8560: : new ( class -- o )  here over @ allot swap over ! ;
                   8561: @end example
1.2       jwilke   8562: 
1.26      crook    8563: Sometimes derived classes want to access the method of the
                   8564: parent object. There are two ways to achieve this with Mini-OOF:
                   8565: first, you could use named words, and second, you could look up the
                   8566: vtable of the parent object.
1.2       jwilke   8567: 
1.26      crook    8568: @example
                   8569: : :: ( class "name" -- ) ' >body @ + @ compile, ;
                   8570: @end example
1.2       jwilke   8571: 
                   8572: 
1.26      crook    8573: Nothing can be more confusing than a good example, so here is
                   8574: one. First let's declare a text object (called
                   8575: @code{button}), that stores text and position:
1.2       jwilke   8576: 
1.26      crook    8577: @example
                   8578: object class
                   8579:   cell var text
                   8580:   cell var len
                   8581:   cell var x
                   8582:   cell var y
                   8583:   method init
                   8584:   method draw
                   8585: end-class button
                   8586: @end example
1.2       jwilke   8587: 
1.26      crook    8588: @noindent
                   8589: Now, implement the two methods, @code{draw} and @code{init}:
1.2       jwilke   8590: 
1.26      crook    8591: @example
                   8592: :noname ( o -- )
                   8593:  >r r@ x @ r@ y @ at-xy  r@ text @ r> len @ type ;
                   8594:  button defines draw
                   8595: :noname ( addr u o -- )
                   8596:  >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
                   8597:  button defines init
                   8598: @end example
1.2       jwilke   8599: 
1.26      crook    8600: @noindent
                   8601: To demonstrate inheritance, we define a class @code{bold-button}, with no
                   8602: new data and no new methods:
1.2       jwilke   8603: 
1.26      crook    8604: @example
                   8605: button class
                   8606: end-class bold-button
1.1       anton    8607: 
1.26      crook    8608: : bold   27 emit ." [1m" ;
                   8609: : normal 27 emit ." [0m" ;
                   8610: @end example
1.1       anton    8611: 
1.26      crook    8612: @noindent
                   8613: The class @code{bold-button} has a different draw method to
                   8614: @code{button}, but the new method is defined in terms of the draw method
                   8615: for @code{button}:
1.1       anton    8616: 
1.26      crook    8617: @example
                   8618: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   8619: @end example
1.1       anton    8620: 
1.26      crook    8621: @noindent
                   8622: Finally, create two objects and apply methods:
1.1       anton    8623: 
1.26      crook    8624: @example
                   8625: button new Constant foo
                   8626: s" thin foo" foo init
                   8627: page
                   8628: foo draw
                   8629: bold-button new Constant bar
                   8630: s" fat bar" bar init
                   8631: 1 bar y !
                   8632: bar draw
                   8633: @end example
1.1       anton    8634: 
                   8635: 
1.26      crook    8636: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
                   8637: @subsubsection Comparison with other object models
                   8638: @cindex comparison of object models
                   8639: @cindex object models, comparison
1.1       anton    8640: 
1.26      crook    8641: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   8642: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   8643: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   8644: relation of the object models described here to two well-known and two
                   8645: closely-related (by the use of method maps) models.
1.1       anton    8646: 
1.26      crook    8647: @cindex Neon model
                   8648: The most popular model currently seems to be the Neon model (see
                   8649: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   8650: 1997) by Andrew McKewan) but this model has a number of limitations
                   8651: @footnote{A longer version of this critique can be
                   8652: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   8653: Dimensions, May 1997) by Anton Ertl.}:
1.1       anton    8654: 
1.26      crook    8655: @itemize @bullet
                   8656: @item
                   8657: It uses a @code{@emph{selector
                   8658: object}} syntax, which makes it unnatural to pass objects on the
                   8659: stack.
1.1       anton    8660: 
1.26      crook    8661: @item
                   8662: It requires that the selector parses the input stream (at
                   8663: compile time); this leads to reduced extensibility and to bugs that are+
                   8664: hard to find.
1.1       anton    8665: 
1.26      crook    8666: @item
                   8667: It allows using every selector to every object;
                   8668: this eliminates the need for classes, but makes it harder to create
                   8669: efficient implementations. 
                   8670: @end itemize
1.1       anton    8671: 
1.26      crook    8672: @cindex Pountain's object-oriented model
                   8673: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   8674: Press, London, 1987) by Dick Pountain. However, it is not really about
                   8675: object-oriented programming, because it hardly deals with late
                   8676: binding. Instead, it focuses on features like information hiding and
                   8677: overloading that are characteristic of modular languages like Ada (83).
1.1       anton    8678: 
1.26      crook    8679: @cindex Zsoter's object-oriented model
                   8680: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1) 1996, pages 31-35)
                   8681: Andras Zsoter describes a model that makes heavy use of an active object
                   8682: (like @code{this} in @file{objects.fs}): The active object is not only
                   8683: used for accessing all fields, but also specifies the receiving object
                   8684: of every selector invocation; you have to change the active object
                   8685: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
                   8686: changes more or less implicitly at @code{m: ... ;m}. Such a change at
                   8687: the method entry point is unnecessary with the Zsoter's model, because
                   8688: the receiving object is the active object already. On the other hand, the explicit
                   8689: change is absolutely necessary in that model, because otherwise no one
                   8690: could ever change the active object. An ANS Forth implementation of this
                   8691: model is available at @url{http://www.forth.org/fig/oopf.html}.
1.1       anton    8692: 
1.26      crook    8693: @cindex @file{oof.fs}, differences to other models
                   8694: The @file{oof.fs} model combines information hiding and overloading
                   8695: resolution (by keeping names in various word lists) with object-oriented
                   8696: programming. It sets the active object implicitly on method entry, but
                   8697: also allows explicit changing (with @code{>o...o>} or with
                   8698: @code{with...endwith}). It uses parsing and state-smart objects and
                   8699: classes for resolving overloading and for early binding: the object or
                   8700: class parses the selector and determines the method from this. If the
                   8701: selector is not parsed by an object or class, it performs a call to the
                   8702: selector for the active object (late binding), like Zsoter's model.
                   8703: Fields are always accessed through the active object. The big
                   8704: disadvantage of this model is the parsing and the state-smartness, which
                   8705: reduces extensibility and increases the opportunities for subtle bugs;
                   8706: essentially, you are only safe if you never tick or @code{postpone} an
                   8707: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.1       anton    8708: 
1.26      crook    8709: @cindex @file{mini-oof.fs}, differences to other models
                   8710: The @file{mini-oof.fs} model is quite similar to a very stripped-down version of
                   8711: the @file{objects.fs} model, but syntactically it is a mixture of the @file{objects.fs} and
                   8712: @file{oof.fs} models.
1.1       anton    8713: 
1.26      crook    8714: @c -------------------------------------------------------------
                   8715: @node Passing Commands to the OS, Miscellaneous Words, Object-oriented Forth, Words
1.21      crook    8716: @section Passing Commands to the Operating System
                   8717: @cindex operating system - passing commands
                   8718: @cindex shell commands
                   8719: 
                   8720: Gforth allows you to pass an arbitrary string to the host operating
                   8721: system shell (if such a thing exists) for execution.
                   8722: 
                   8723: doc-sh
                   8724: doc-system
                   8725: doc-$?
1.23      crook    8726: doc-getenv
1.21      crook    8727: 
1.26      crook    8728: @c -------------------------------------------------------------
1.21      crook    8729: @node Miscellaneous Words,  , Passing Commands to the OS, Words
                   8730: @section Miscellaneous Words
                   8731: @cindex miscellaneous words
                   8732: 
1.29      crook    8733: @comment TODO find homes for these
                   8734: 
1.26      crook    8735: These section lists the ANS Forth words that are not documented
1.21      crook    8736: elsewhere in this manual. Ultimately, they all need proper homes.
                   8737: 
                   8738: doc-ms
                   8739: doc-time&date
1.27      crook    8740: 
1.21      crook    8741: doc-[compile]
                   8742: 
1.26      crook    8743: The following ANS Forth words are not currently supported by Gforth 
1.27      crook    8744: (@pxref{ANS conformance}):
1.21      crook    8745: 
                   8746: @code{EDITOR} 
                   8747: @code{EKEY} 
                   8748: @code{EKEY>CHAR} 
                   8749: @code{EKEY?} 
                   8750: @code{EMIT?} 
                   8751: @code{FORGET} 
                   8752: 
1.24      anton    8753: @c ******************************************************************
                   8754: @node Error messages, Tools, Words, Top
                   8755: @chapter Error messages
                   8756: @cindex error messages
                   8757: @cindex backtrace
                   8758: 
                   8759: A typical Gforth error message looks like this:
                   8760: 
                   8761: @example
                   8762: in file included from :-1
                   8763: in file included from ./yyy.fs:1
                   8764: ./xxx.fs:4: Invalid memory address
                   8765: bar
                   8766: ^^^
1.25      anton    8767: $400E664C @@
                   8768: $400E6664 foo
1.24      anton    8769: @end example
                   8770: 
                   8771: The message identifying the error is @code{Invalid memory address}.  The
                   8772: error happened when text-interpreting line 4 of the file
                   8773: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
                   8774: word on the line where the error happened, is pointed out (with
                   8775: @code{^^^}).
                   8776: 
                   8777: The file containing the error was included in line 1 of @file{./yyy.fs},
                   8778: and @file{yyy.fs} was included from a non-file (in this case, by giving
                   8779: @file{yyy.fs} as command-line parameter to Gforth).
                   8780: 
                   8781: At the end of the error message you find a return stack dump that can be
                   8782: interpreted as a backtrace (possibly empty). On top you find the top of
                   8783: the return stack when the @code{throw} happened, and at the bottom you
                   8784: find the return stack entry just above the return stack of the topmost
                   8785: text interpreter.
                   8786: 
                   8787: To the right of most return stack entries you see a guess for the word
                   8788: that pushed that return stack entry as its return address. This gives a
                   8789: backtrace. In our case we see that @code{bar} called @code{foo}, and
                   8790: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
                   8791: address} exception).
                   8792: 
                   8793: Note that the backtrace is not perfect: We don't know which return stack
                   8794: entries are return addresses (so we may get false positives); and in
                   8795: some cases (e.g., for @code{abort"}) we cannot determine from the return
                   8796: address the word that pushed the return address, so for some return
                   8797: addresses you see no names in the return stack dump.
1.25      anton    8798: 
                   8799: @cindex @code{catch} and backtraces
                   8800: The return stack dump represents the return stack at the time when a
                   8801: specific @code{throw} was executed.  In programs that make use of
                   8802: @code{catch}, it is not necessarily clear which @code{throw} should be
                   8803: used for the return stack dump (e.g., consider one @code{throw} that
                   8804: indicates an error, which is caught, and during recovery another error
                   8805: happens; which @code{throw} should be used for the stack dump).  Gforth
                   8806: presents the return stack dump for the first @code{throw} after the last
                   8807: executed (not returned-to) @code{catch}; this works well in the usual
                   8808: case.
                   8809: 
                   8810: @cindex @code{gforth-fast} and backtraces
                   8811: @cindex @code{gforth-fast}, difference from @code{gforth}
                   8812: @cindex backtraces with @code{gforth-fast}
                   8813: @cindex return stack dump with @code{gforth-fast}
                   8814: @code{gforth} is able to do a return stack dump for throws generated
                   8815: from primitives (e.g., invalid memory address, stack empty etc.);
                   8816: @code{gforth-fast} is only able to do a return stack dump from a
                   8817: directly called @code{throw} (including @code{abort} etc.).  This is the
1.30      anton    8818: only difference (apart from a speed factor of between 1.15 (K6-2) and
                   8819: 1.6 (21164A)) between @code{gforth} and @code{gforth-fast}.  Given an
                   8820: exception caused by a primitive in @code{gforth-fast}, you will
                   8821: typically see no return stack dump at all; however, if the exception is
                   8822: caught by @code{catch} (e.g., for restoring some state), and then
                   8823: @code{throw}n again, the return stack dump will be for the first such
                   8824: @code{throw}.
1.2       jwilke   8825: 
1.5       anton    8826: @c ******************************************************************
1.24      anton    8827: @node Tools, ANS conformance, Error messages, Top
1.1       anton    8828: @chapter Tools
                   8829: 
                   8830: @menu
                   8831: * ANS Report::                  Report the words used, sorted by wordset.
                   8832: @end menu
                   8833: 
                   8834: See also @ref{Emacs and Gforth}.
                   8835: 
                   8836: @node ANS Report,  , Tools, Tools
                   8837: @section @file{ans-report.fs}: Report the words used, sorted by wordset
                   8838: @cindex @file{ans-report.fs}
                   8839: @cindex report the words used in your program
                   8840: @cindex words used in your program
                   8841: 
                   8842: If you want to label a Forth program as ANS Forth Program, you must
                   8843: document which wordsets the program uses; for extension wordsets, it is
                   8844: helpful to list the words the program requires from these wordsets
                   8845: (because Forth systems are allowed to provide only some words of them).
                   8846: 
                   8847: The @file{ans-report.fs} tool makes it easy for you to determine which
                   8848: words from which wordset and which non-ANS words your application
                   8849: uses. You simply have to include @file{ans-report.fs} before loading the
                   8850: program you want to check. After loading your program, you can get the
                   8851: report with @code{print-ans-report}. A typical use is to run this as
                   8852: batch job like this:
                   8853: @example
                   8854: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
                   8855: @end example
                   8856: 
                   8857: The output looks like this (for @file{compat/control.fs}):
                   8858: @example
                   8859: The program uses the following words
                   8860: from CORE :
                   8861: : POSTPONE THEN ; immediate ?dup IF 0= 
                   8862: from BLOCK-EXT :
                   8863: \ 
                   8864: from FILE :
                   8865: ( 
                   8866: @end example
                   8867: 
                   8868: @subsection Caveats
                   8869: 
                   8870: Note that @file{ans-report.fs} just checks which words are used, not whether
                   8871: they are used in an ANS Forth conforming way!
                   8872: 
                   8873: Some words are defined in several wordsets in the
                   8874: standard. @file{ans-report.fs} reports them for only one of the
                   8875: wordsets, and not necessarily the one you expect. It depends on usage
                   8876: which wordset is the right one to specify. E.g., if you only use the
                   8877: compilation semantics of @code{S"}, it is a Core word; if you also use
                   8878: its interpretation semantics, it is a File word.
                   8879: 
                   8880: @c ******************************************************************
                   8881: @node ANS conformance, Model, Tools, Top
                   8882: @chapter ANS conformance
                   8883: @cindex ANS conformance of Gforth
                   8884: 
                   8885: To the best of our knowledge, Gforth is an
                   8886: 
                   8887: ANS Forth System
                   8888: @itemize @bullet
                   8889: @item providing the Core Extensions word set
                   8890: @item providing the Block word set
                   8891: @item providing the Block Extensions word set
                   8892: @item providing the Double-Number word set
                   8893: @item providing the Double-Number Extensions word set
                   8894: @item providing the Exception word set
                   8895: @item providing the Exception Extensions word set
                   8896: @item providing the Facility word set
                   8897: @item providing @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
                   8898: @item providing the File Access word set
                   8899: @item providing the File Access Extensions word set
                   8900: @item providing the Floating-Point word set
                   8901: @item providing the Floating-Point Extensions word set
                   8902: @item providing the Locals word set
                   8903: @item providing the Locals Extensions word set
                   8904: @item providing the Memory-Allocation word set
                   8905: @item providing the Memory-Allocation Extensions word set (that one's easy)
                   8906: @item providing the Programming-Tools word set
                   8907: @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
                   8908: @item providing the Search-Order word set
                   8909: @item providing the Search-Order Extensions word set
                   8910: @item providing the String word set
                   8911: @item providing the String Extensions word set (another easy one)
                   8912: @end itemize
                   8913: 
                   8914: @cindex system documentation
                   8915: In addition, ANS Forth systems are required to document certain
                   8916: implementation choices. This chapter tries to meet these
                   8917: requirements. In many cases it gives a way to ask the system for the
                   8918: information instead of providing the information directly, in
                   8919: particular, if the information depends on the processor, the operating
                   8920: system or the installation options chosen, or if they are likely to
                   8921: change during the maintenance of Gforth.
                   8922: 
                   8923: @comment The framework for the rest has been taken from pfe.
                   8924: 
                   8925: @menu
                   8926: * The Core Words::              
                   8927: * The optional Block word set::  
                   8928: * The optional Double Number word set::  
                   8929: * The optional Exception word set::  
                   8930: * The optional Facility word set::  
                   8931: * The optional File-Access word set::  
                   8932: * The optional Floating-Point word set::  
                   8933: * The optional Locals word set::  
                   8934: * The optional Memory-Allocation word set::  
                   8935: * The optional Programming-Tools word set::  
                   8936: * The optional Search-Order word set::  
                   8937: @end menu
                   8938: 
                   8939: 
                   8940: @c =====================================================================
                   8941: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
                   8942: @comment  node-name,  next,  previous,  up
                   8943: @section The Core Words
                   8944: @c =====================================================================
                   8945: @cindex core words, system documentation
                   8946: @cindex system documentation, core words
                   8947: 
                   8948: @menu
                   8949: * core-idef::                   Implementation Defined Options                   
                   8950: * core-ambcond::                Ambiguous Conditions                
                   8951: * core-other::                  Other System Documentation                  
                   8952: @end menu
                   8953: 
                   8954: @c ---------------------------------------------------------------------
                   8955: @node core-idef, core-ambcond, The Core Words, The Core Words
                   8956: @subsection Implementation Defined Options
                   8957: @c ---------------------------------------------------------------------
                   8958: @cindex core words, implementation-defined options
                   8959: @cindex implementation-defined options, core words
                   8960: 
                   8961: 
                   8962: @table @i
                   8963: @item (Cell) aligned addresses:
                   8964: @cindex cell-aligned addresses
                   8965: @cindex aligned addresses
                   8966: processor-dependent. Gforth's alignment words perform natural alignment
                   8967: (e.g., an address aligned for a datum of size 8 is divisible by
                   8968: 8). Unaligned accesses usually result in a @code{-23 THROW}.
                   8969: 
                   8970: @item @code{EMIT} and non-graphic characters:
                   8971: @cindex @code{EMIT} and non-graphic characters
                   8972: @cindex non-graphic characters and @code{EMIT}
                   8973: The character is output using the C library function (actually, macro)
                   8974: @code{putc}.
                   8975: 
                   8976: @item character editing of @code{ACCEPT} and @code{EXPECT}:
                   8977: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
                   8978: @cindex editing in @code{ACCEPT} and @code{EXPECT}
                   8979: @cindex @code{ACCEPT}, editing
                   8980: @cindex @code{EXPECT}, editing
                   8981: This is modeled on the GNU readline library (@pxref{Readline
                   8982: Interaction, , Command Line Editing, readline, The GNU Readline
                   8983: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
                   8984: producing a full word completion every time you type it (instead of
1.28      crook    8985: producing the common prefix of all completions). @xref{Command-line editing}.
1.1       anton    8986: 
                   8987: @item character set:
                   8988: @cindex character set
                   8989: The character set of your computer and display device. Gforth is
                   8990: 8-bit-clean (but some other component in your system may make trouble).
                   8991: 
                   8992: @item Character-aligned address requirements:
                   8993: @cindex character-aligned address requirements
                   8994: installation-dependent. Currently a character is represented by a C
                   8995: @code{unsigned char}; in the future we might switch to @code{wchar_t}
                   8996: (Comments on that requested).
                   8997: 
                   8998: @item character-set extensions and matching of names:
                   8999: @cindex character-set extensions and matching of names
1.26      crook    9000: @cindex case-sensitivity for name lookup
                   9001: @cindex name lookup, case-sensitivity
                   9002: @cindex locale and case-sensitivity
1.21      crook    9003: Any character except the ASCII NUL character can be used in a
1.1       anton    9004: name. Matching is case-insensitive (except in @code{TABLE}s). The
                   9005: matching is performed using the C function @code{strncasecmp}, whose
                   9006: function is probably influenced by the locale. E.g., the @code{C} locale
                   9007: does not know about accents and umlauts, so they are matched
                   9008: case-sensitively in that locale. For portability reasons it is best to
                   9009: write programs such that they work in the @code{C} locale. Then one can
                   9010: use libraries written by a Polish programmer (who might use words
                   9011: containing ISO Latin-2 encoded characters) and by a French programmer
                   9012: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
                   9013: funny results for some of the words (which ones, depends on the font you
                   9014: are using)). Also, the locale you prefer may not be available in other
                   9015: operating systems. Hopefully, Unicode will solve these problems one day.
                   9016: 
                   9017: @item conditions under which control characters match a space delimiter:
                   9018: @cindex space delimiters
                   9019: @cindex control characters as delimiters
                   9020: If @code{WORD} is called with the space character as a delimiter, all
                   9021: white-space characters (as identified by the C macro @code{isspace()})
                   9022: are delimiters. @code{PARSE}, on the other hand, treats space like other
                   9023: delimiters. @code{PARSE-WORD} treats space like @code{WORD}, but behaves
                   9024: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
                   9025: interpreter (aka text interpreter) by default, treats all white-space
                   9026: characters as delimiters.
                   9027: 
1.26      crook    9028: @item format of the control-flow stack:
                   9029: @cindex control-flow stack, format
                   9030: The data stack is used as control-flow stack. The size of a control-flow
1.1       anton    9031: stack item in cells is given by the constant @code{cs-item-size}. At the
                   9032: time of this writing, an item consists of a (pointer to a) locals list
                   9033: (third), an address in the code (second), and a tag for identifying the
                   9034: item (TOS). The following tags are used: @code{defstart},
                   9035: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
                   9036: @code{scopestart}.
                   9037: 
                   9038: @item conversion of digits > 35
                   9039: @cindex digits > 35
                   9040: The characters @code{[\]^_'} are the digits with the decimal value
                   9041: 36@minus{}41. There is no way to input many of the larger digits.
                   9042: 
                   9043: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
                   9044: @cindex @code{EXPECT}, display after end of input
                   9045: @cindex @code{ACCEPT}, display after end of input
                   9046: The cursor is moved to the end of the entered string. If the input is
                   9047: terminated using the @kbd{Return} key, a space is typed.
                   9048: 
                   9049: @item exception abort sequence of @code{ABORT"}:
                   9050: @cindex exception abort sequence of @code{ABORT"}
                   9051: @cindex @code{ABORT"}, exception abort sequence
                   9052: The error string is stored into the variable @code{"error} and a
                   9053: @code{-2 throw} is performed.
                   9054: 
                   9055: @item input line terminator:
                   9056: @cindex input line terminator
                   9057: @cindex line terminator on input
1.26      crook    9058: @cindex newline character on input
1.1       anton    9059: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
                   9060: lines. One of these characters is typically produced when you type the
                   9061: @kbd{Enter} or @kbd{Return} key.
                   9062: 
                   9063: @item maximum size of a counted string:
                   9064: @cindex maximum size of a counted string
                   9065: @cindex counted string, maximum size
                   9066: @code{s" /counted-string" environment? drop .}. Currently 255 characters
                   9067: on all ports, but this may change.
                   9068: 
                   9069: @item maximum size of a parsed string:
                   9070: @cindex maximum size of a parsed string
                   9071: @cindex parsed string, maximum size
                   9072: Given by the constant @code{/line}. Currently 255 characters.
                   9073: 
                   9074: @item maximum size of a definition name, in characters:
                   9075: @cindex maximum size of a definition name, in characters
                   9076: @cindex name, maximum length
                   9077: 31
                   9078: 
                   9079: @item maximum string length for @code{ENVIRONMENT?}, in characters:
                   9080: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
                   9081: @cindex @code{ENVIRONMENT?} string length, maximum
                   9082: 31
                   9083: 
                   9084: @item method of selecting the user input device:
                   9085: @cindex user input device, method of selecting
                   9086: The user input device is the standard input. There is currently no way to
                   9087: change it from within Gforth. However, the input can typically be
                   9088: redirected in the command line that starts Gforth.
                   9089: 
                   9090: @item method of selecting the user output device:
                   9091: @cindex user output device, method of selecting
                   9092: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10      anton    9093: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
                   9094: output when the user output device is a terminal, otherwise the output
                   9095: is buffered.
1.1       anton    9096: 
                   9097: @item methods of dictionary compilation:
                   9098: What are we expected to document here?
                   9099: 
                   9100: @item number of bits in one address unit:
                   9101: @cindex number of bits in one address unit
                   9102: @cindex address unit, size in bits
                   9103: @code{s" address-units-bits" environment? drop .}. 8 in all current
                   9104: ports.
                   9105: 
                   9106: @item number representation and arithmetic:
                   9107: @cindex number representation and arithmetic
                   9108: Processor-dependent. Binary two's complement on all current ports.
                   9109: 
                   9110: @item ranges for integer types:
                   9111: @cindex ranges for integer types
                   9112: @cindex integer types, ranges
                   9113: Installation-dependent. Make environmental queries for @code{MAX-N},
                   9114: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
                   9115: unsigned (and positive) types is 0. The lower bound for signed types on
                   9116: two's complement and one's complement machines machines can be computed
                   9117: by adding 1 to the upper bound.
                   9118: 
                   9119: @item read-only data space regions:
                   9120: @cindex read-only data space regions
                   9121: @cindex data-space, read-only regions
                   9122: The whole Forth data space is writable.
                   9123: 
                   9124: @item size of buffer at @code{WORD}:
                   9125: @cindex size of buffer at @code{WORD}
                   9126: @cindex @code{WORD} buffer size
                   9127: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   9128: shared with the pictured numeric output string. If overwriting
                   9129: @code{PAD} is acceptable, it is as large as the remaining dictionary
                   9130: space, although only as much can be sensibly used as fits in a counted
                   9131: string.
                   9132: 
                   9133: @item size of one cell in address units:
                   9134: @cindex cell size
                   9135: @code{1 cells .}.
                   9136: 
                   9137: @item size of one character in address units:
                   9138: @cindex char size
                   9139: @code{1 chars .}. 1 on all current ports.
                   9140: 
                   9141: @item size of the keyboard terminal buffer:
                   9142: @cindex size of the keyboard terminal buffer
                   9143: @cindex terminal buffer, size
                   9144: Varies. You can determine the size at a specific time using @code{lp@@
                   9145: tib - .}. It is shared with the locals stack and TIBs of files that
                   9146: include the current file. You can change the amount of space for TIBs
                   9147: and locals stack at Gforth startup with the command line option
                   9148: @code{-l}.
                   9149: 
                   9150: @item size of the pictured numeric output buffer:
                   9151: @cindex size of the pictured numeric output buffer
                   9152: @cindex pictured numeric output buffer, size
                   9153: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   9154: shared with @code{WORD}.
                   9155: 
                   9156: @item size of the scratch area returned by @code{PAD}:
                   9157: @cindex size of the scratch area returned by @code{PAD}
                   9158: @cindex @code{PAD} size
                   9159: The remainder of dictionary space. @code{unused pad here - - .}.
                   9160: 
                   9161: @item system case-sensitivity characteristics:
                   9162: @cindex case-sensitivity characteristics
1.26      crook    9163: Dictionary searches are case-insensitive (except in
1.1       anton    9164: @code{TABLE}s). However, as explained above under @i{character-set
                   9165: extensions}, the matching for non-ASCII characters is determined by the
                   9166: locale you are using. In the default @code{C} locale all non-ASCII
                   9167: characters are matched case-sensitively.
                   9168: 
                   9169: @item system prompt:
                   9170: @cindex system prompt
                   9171: @cindex prompt
                   9172: @code{ ok} in interpret state, @code{ compiled} in compile state.
                   9173: 
                   9174: @item division rounding:
                   9175: @cindex division rounding
                   9176: installation dependent. @code{s" floored" environment? drop .}. We leave
                   9177: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
                   9178: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
                   9179: 
                   9180: @item values of @code{STATE} when true:
                   9181: @cindex @code{STATE} values
                   9182: -1.
                   9183: 
                   9184: @item values returned after arithmetic overflow:
                   9185: On two's complement machines, arithmetic is performed modulo
                   9186: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   9187: arithmetic (with appropriate mapping for signed types). Division by zero
                   9188: typically results in a @code{-55 throw} (Floating-point unidentified
                   9189: fault), although a @code{-10 throw} (divide by zero) would be more
                   9190: appropriate.
                   9191: 
                   9192: @item whether the current definition can be found after @t{DOES>}:
                   9193: @cindex @t{DOES>}, visibility of current definition
                   9194: No.
                   9195: 
                   9196: @end table
                   9197: 
                   9198: @c ---------------------------------------------------------------------
                   9199: @node core-ambcond, core-other, core-idef, The Core Words
                   9200: @subsection Ambiguous conditions
                   9201: @c ---------------------------------------------------------------------
                   9202: @cindex core words, ambiguous conditions
                   9203: @cindex ambiguous conditions, core words
                   9204: 
                   9205: @table @i
                   9206: 
                   9207: @item a name is neither a word nor a number:
                   9208: @cindex name not found
1.26      crook    9209: @cindex undefined word
1.1       anton    9210: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
                   9211: preserves the data and FP stack, so you don't lose more work than
                   9212: necessary.
                   9213: 
                   9214: @item a definition name exceeds the maximum length allowed:
1.26      crook    9215: @cindex word name too long
1.1       anton    9216: @code{-19 throw} (Word name too long)
                   9217: 
                   9218: @item addressing a region not inside the various data spaces of the forth system:
                   9219: @cindex Invalid memory address
1.32      anton    9220: The stacks, code space and header space are accessible. Machine code space is
1.1       anton    9221: typically readable. Accessing other addresses gives results dependent on
                   9222: the operating system. On decent systems: @code{-9 throw} (Invalid memory
                   9223: address).
                   9224: 
                   9225: @item argument type incompatible with parameter:
1.26      crook    9226: @cindex argument type mismatch
1.1       anton    9227: This is usually not caught. Some words perform checks, e.g., the control
                   9228: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
                   9229: mismatch).
                   9230: 
                   9231: @item attempting to obtain the execution token of a word with undefined execution semantics:
                   9232: @cindex Interpreting a compile-only word, for @code{'} etc.
                   9233: @cindex execution token of words with undefined execution semantics
                   9234: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
                   9235: get an execution token for @code{compile-only-error} (which performs a
                   9236: @code{-14 throw} when executed).
                   9237: 
                   9238: @item dividing by zero:
                   9239: @cindex dividing by zero
                   9240: @cindex floating point unidentified fault, integer division
1.24      anton    9241: On better platforms, this produces a @code{-10 throw} (Division by
                   9242: zero); on other systems, this typically results in a @code{-55 throw}
                   9243: (Floating-point unidentified fault).
1.1       anton    9244: 
                   9245: @item insufficient data stack or return stack space:
                   9246: @cindex insufficient data stack or return stack space
                   9247: @cindex stack overflow
1.26      crook    9248: @cindex address alignment exception, stack overflow
1.1       anton    9249: @cindex Invalid memory address, stack overflow
                   9250: Depending on the operating system, the installation, and the invocation
                   9251: of Gforth, this is either checked by the memory management hardware, or
1.24      anton    9252: it is not checked. If it is checked, you typically get a @code{-3 throw}
                   9253: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
                   9254: throw} (Invalid memory address) (depending on the platform and how you
                   9255: achieved the overflow) as soon as the overflow happens. If it is not
                   9256: checked, overflows typically result in mysterious illegal memory
                   9257: accesses, producing @code{-9 throw} (Invalid memory address) or
                   9258: @code{-23 throw} (Address alignment exception); they might also destroy
                   9259: the internal data structure of @code{ALLOCATE} and friends, resulting in
                   9260: various errors in these words.
1.1       anton    9261: 
                   9262: @item insufficient space for loop control parameters:
                   9263: @cindex insufficient space for loop control parameters
                   9264: like other return stack overflows.
                   9265: 
                   9266: @item insufficient space in the dictionary:
                   9267: @cindex insufficient space in the dictionary
                   9268: @cindex dictionary overflow
1.12      anton    9269: If you try to allot (either directly with @code{allot}, or indirectly
                   9270: with @code{,}, @code{create} etc.) more memory than available in the
                   9271: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
                   9272: to access memory beyond the end of the dictionary, the results are
                   9273: similar to stack overflows.
1.1       anton    9274: 
                   9275: @item interpreting a word with undefined interpretation semantics:
                   9276: @cindex interpreting a word with undefined interpretation semantics
                   9277: @cindex Interpreting a compile-only word
                   9278: For some words, we have defined interpretation semantics. For the
                   9279: others: @code{-14 throw} (Interpreting a compile-only word).
                   9280: 
                   9281: @item modifying the contents of the input buffer or a string literal:
                   9282: @cindex modifying the contents of the input buffer or a string literal
                   9283: These are located in writable memory and can be modified.
                   9284: 
                   9285: @item overflow of the pictured numeric output string:
                   9286: @cindex overflow of the pictured numeric output string
                   9287: @cindex pictured numeric output string, overflow
1.24      anton    9288: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1       anton    9289: 
                   9290: @item parsed string overflow:
                   9291: @cindex parsed string overflow
                   9292: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
                   9293: 
                   9294: @item producing a result out of range:
                   9295: @cindex result out of range
                   9296: On two's complement machines, arithmetic is performed modulo
                   9297: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   9298: arithmetic (with appropriate mapping for signed types). Division by zero
1.24      anton    9299: typically results in a @code{-10 throw} (divide by zero) or @code{-55
                   9300: throw} (floating point unidentified fault). @code{convert} and
                   9301: @code{>number} currently overflow silently.
1.1       anton    9302: 
                   9303: @item reading from an empty data or return stack:
                   9304: @cindex stack empty
                   9305: @cindex stack underflow
1.24      anton    9306: @cindex return stack underflow
1.1       anton    9307: The data stack is checked by the outer (aka text) interpreter after
                   9308: every word executed. If it has underflowed, a @code{-4 throw} (Stack
                   9309: underflow) is performed. Apart from that, stacks may be checked or not,
1.24      anton    9310: depending on operating system, installation, and invocation. If they are
                   9311: caught by a check, they typically result in @code{-4 throw} (Stack
                   9312: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
                   9313: (Invalid memory address), depending on the platform and which stack
                   9314: underflows and by how much. Note that even if the system uses checking
                   9315: (through the MMU), your program may have to underflow by a significant
                   9316: number of stack items to trigger the reaction (the reason for this is
                   9317: that the MMU, and therefore the checking, works with a page-size
                   9318: granularity).  If there is no checking, the symptoms resulting from an
                   9319: underflow are similar to those from an overflow.  Unbalanced return
                   9320: stack errors result in a variaty of symptoms, including @code{-9 throw}
                   9321: (Invalid memory address) and Illegal Instruction (typically @code{-260
                   9322: throw}).
1.1       anton    9323: 
                   9324: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
                   9325: @cindex unexpected end of the input buffer
                   9326: @cindex zero-length string as a name
                   9327: @cindex Attempt to use zero-length string as a name
                   9328: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
                   9329: use zero-length string as a name). Words like @code{'} probably will not
                   9330: find what they search. Note that it is possible to create zero-length
                   9331: names with @code{nextname} (should it not?).
                   9332: 
                   9333: @item @code{>IN} greater than input buffer:
                   9334: @cindex @code{>IN} greater than input buffer
                   9335: The next invocation of a parsing word returns a string with length 0.
                   9336: 
                   9337: @item @code{RECURSE} appears after @code{DOES>}:
                   9338: @cindex @code{RECURSE} appears after @code{DOES>}
                   9339: Compiles a recursive call to the defining word, not to the defined word.
                   9340: 
                   9341: @item argument input source different than current input source for @code{RESTORE-INPUT}:
                   9342: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26      crook    9343: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1       anton    9344: @cindex @code{RESTORE-INPUT}, Argument type mismatch
                   9345: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
                   9346: the end of the file was reached), its source-id may be
                   9347: reused. Therefore, restoring an input source specification referencing a
                   9348: closed file may lead to unpredictable results instead of a @code{-12
                   9349: THROW}.
                   9350: 
                   9351: In the future, Gforth may be able to restore input source specifications
                   9352: from other than the current input source.
                   9353: 
                   9354: @item data space containing definitions gets de-allocated:
                   9355: @cindex data space containing definitions gets de-allocated
                   9356: Deallocation with @code{allot} is not checked. This typically results in
                   9357: memory access faults or execution of illegal instructions.
                   9358: 
                   9359: @item data space read/write with incorrect alignment:
                   9360: @cindex data space read/write with incorrect alignment
                   9361: @cindex alignment faults
1.26      crook    9362: @cindex address alignment exception
1.1       anton    9363: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12      anton    9364: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1       anton    9365: alignment turned on, incorrect alignment results in a @code{-9 throw}
                   9366: (Invalid memory address). There are reportedly some processors with
1.12      anton    9367: alignment restrictions that do not report violations.
1.1       anton    9368: 
                   9369: @item data space pointer not properly aligned, @code{,}, @code{C,}:
                   9370: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
                   9371: Like other alignment errors.
                   9372: 
                   9373: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
                   9374: Like other stack underflows.
                   9375: 
                   9376: @item loop control parameters not available:
                   9377: @cindex loop control parameters not available
                   9378: Not checked. The counted loop words simply assume that the top of return
                   9379: stack items are loop control parameters and behave accordingly.
                   9380: 
                   9381: @item most recent definition does not have a name (@code{IMMEDIATE}):
                   9382: @cindex most recent definition does not have a name (@code{IMMEDIATE})
                   9383: @cindex last word was headerless
                   9384: @code{abort" last word was headerless"}.
                   9385: 
                   9386: @item name not defined by @code{VALUE} used by @code{TO}:
                   9387: @cindex name not defined by @code{VALUE} used by @code{TO}
                   9388: @cindex @code{TO} on non-@code{VALUE}s
                   9389: @cindex Invalid name argument, @code{TO}
                   9390: @code{-32 throw} (Invalid name argument) (unless name is a local or was
                   9391: defined by @code{CONSTANT}; in the latter case it just changes the constant).
                   9392: 
                   9393: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
                   9394: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26      crook    9395: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1       anton    9396: @code{-13 throw} (Undefined word)
                   9397: 
                   9398: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
                   9399: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
                   9400: Gforth behaves as if they were of the same type. I.e., you can predict
                   9401: the behaviour by interpreting all parameters as, e.g., signed.
                   9402: 
                   9403: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
                   9404: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
                   9405: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
                   9406: compilation semantics of @code{TO}.
                   9407: 
                   9408: @item String longer than a counted string returned by @code{WORD}:
1.26      crook    9409: @cindex string longer than a counted string returned by @code{WORD}
1.1       anton    9410: @cindex @code{WORD}, string overflow
                   9411: Not checked. The string will be ok, but the count will, of course,
                   9412: contain only the least significant bits of the length.
                   9413: 
                   9414: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
                   9415: @cindex @code{LSHIFT}, large shift counts
                   9416: @cindex @code{RSHIFT}, large shift counts
                   9417: Processor-dependent. Typical behaviours are returning 0 and using only
                   9418: the low bits of the shift count.
                   9419: 
                   9420: @item word not defined via @code{CREATE}:
                   9421: @cindex @code{>BODY} of non-@code{CREATE}d words
                   9422: @code{>BODY} produces the PFA of the word no matter how it was defined.
                   9423: 
                   9424: @cindex @code{DOES>} of non-@code{CREATE}d words
                   9425: @code{DOES>} changes the execution semantics of the last defined word no
                   9426: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
                   9427: @code{CREATE , DOES>}.
                   9428: 
                   9429: @item words improperly used outside @code{<#} and @code{#>}:
                   9430: Not checked. As usual, you can expect memory faults.
                   9431: 
                   9432: @end table
                   9433: 
                   9434: 
                   9435: @c ---------------------------------------------------------------------
                   9436: @node core-other,  , core-ambcond, The Core Words
                   9437: @subsection Other system documentation
                   9438: @c ---------------------------------------------------------------------
                   9439: @cindex other system documentation, core words
                   9440: @cindex core words, other system documentation
                   9441: 
                   9442: @table @i
                   9443: @item nonstandard words using @code{PAD}:
                   9444: @cindex @code{PAD} use by nonstandard words
                   9445: None.
                   9446: 
                   9447: @item operator's terminal facilities available:
                   9448: @cindex operator's terminal facilities available
                   9449: After processing the command line, Gforth goes into interactive mode,
                   9450: and you can give commands to Gforth interactively. The actual facilities
                   9451: available depend on how you invoke Gforth.
                   9452: 
                   9453: @item program data space available:
                   9454: @cindex program data space available
                   9455: @cindex data space available
                   9456: @code{UNUSED .} gives the remaining dictionary space. The total
                   9457: dictionary space can be specified with the @code{-m} switch
                   9458: (@pxref{Invoking Gforth}) when Gforth starts up.
                   9459: 
                   9460: @item return stack space available:
                   9461: @cindex return stack space available
                   9462: You can compute the total return stack space in cells with
                   9463: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
                   9464: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
                   9465: 
                   9466: @item stack space available:
                   9467: @cindex stack space available
                   9468: You can compute the total data stack space in cells with
                   9469: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
                   9470: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
                   9471: 
                   9472: @item system dictionary space required, in address units:
                   9473: @cindex system dictionary space required, in address units
                   9474: Type @code{here forthstart - .} after startup. At the time of this
                   9475: writing, this gives 80080 (bytes) on a 32-bit system.
                   9476: @end table
                   9477: 
                   9478: 
                   9479: @c =====================================================================
                   9480: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
                   9481: @section The optional Block word set
                   9482: @c =====================================================================
                   9483: @cindex system documentation, block words
                   9484: @cindex block words, system documentation
                   9485: 
                   9486: @menu
                   9487: * block-idef::                  Implementation Defined Options
                   9488: * block-ambcond::               Ambiguous Conditions               
                   9489: * block-other::                 Other System Documentation                 
                   9490: @end menu
                   9491: 
                   9492: 
                   9493: @c ---------------------------------------------------------------------
                   9494: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
                   9495: @subsection Implementation Defined Options
                   9496: @c ---------------------------------------------------------------------
                   9497: @cindex implementation-defined options, block words
                   9498: @cindex block words, implementation-defined options
                   9499: 
                   9500: @table @i
                   9501: @item the format for display by @code{LIST}:
                   9502: @cindex @code{LIST} display format
                   9503: First the screen number is displayed, then 16 lines of 64 characters,
                   9504: each line preceded by the line number.
                   9505: 
                   9506: @item the length of a line affected by @code{\}:
                   9507: @cindex length of a line affected by @code{\}
                   9508: @cindex @code{\}, line length in blocks
                   9509: 64 characters.
                   9510: @end table
                   9511: 
                   9512: 
                   9513: @c ---------------------------------------------------------------------
                   9514: @node block-ambcond, block-other, block-idef, The optional Block word set
                   9515: @subsection Ambiguous conditions
                   9516: @c ---------------------------------------------------------------------
                   9517: @cindex block words, ambiguous conditions
                   9518: @cindex ambiguous conditions, block words
                   9519: 
                   9520: @table @i
                   9521: @item correct block read was not possible:
                   9522: @cindex block read not possible
                   9523: Typically results in a @code{throw} of some OS-derived value (between
                   9524: -512 and -2048). If the blocks file was just not long enough, blanks are
                   9525: supplied for the missing portion.
                   9526: 
                   9527: @item I/O exception in block transfer:
                   9528: @cindex I/O exception in block transfer
                   9529: @cindex block transfer, I/O exception
                   9530: Typically results in a @code{throw} of some OS-derived value (between
                   9531: -512 and -2048).
                   9532: 
                   9533: @item invalid block number:
                   9534: @cindex invalid block number
                   9535: @cindex block number invalid
                   9536: @code{-35 throw} (Invalid block number)
                   9537: 
                   9538: @item a program directly alters the contents of @code{BLK}:
                   9539: @cindex @code{BLK}, altering @code{BLK}
                   9540: The input stream is switched to that other block, at the same
                   9541: position. If the storing to @code{BLK} happens when interpreting
                   9542: non-block input, the system will get quite confused when the block ends.
                   9543: 
                   9544: @item no current block buffer for @code{UPDATE}:
                   9545: @cindex @code{UPDATE}, no current block buffer
                   9546: @code{UPDATE} has no effect.
                   9547: 
                   9548: @end table
                   9549: 
                   9550: @c ---------------------------------------------------------------------
                   9551: @node block-other,  , block-ambcond, The optional Block word set
                   9552: @subsection Other system documentation
                   9553: @c ---------------------------------------------------------------------
                   9554: @cindex other system documentation, block words
                   9555: @cindex block words, other system documentation
                   9556: 
                   9557: @table @i
                   9558: @item any restrictions a multiprogramming system places on the use of buffer addresses:
                   9559: No restrictions (yet).
                   9560: 
                   9561: @item the number of blocks available for source and data:
                   9562: depends on your disk space.
                   9563: 
                   9564: @end table
                   9565: 
                   9566: 
                   9567: @c =====================================================================
                   9568: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
                   9569: @section The optional Double Number word set
                   9570: @c =====================================================================
                   9571: @cindex system documentation, double words
                   9572: @cindex double words, system documentation
                   9573: 
                   9574: @menu
                   9575: * double-ambcond::              Ambiguous Conditions              
                   9576: @end menu
                   9577: 
                   9578: 
                   9579: @c ---------------------------------------------------------------------
                   9580: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
                   9581: @subsection Ambiguous conditions
                   9582: @c ---------------------------------------------------------------------
                   9583: @cindex double words, ambiguous conditions
                   9584: @cindex ambiguous conditions, double words
                   9585: 
                   9586: @table @i
1.29      crook    9587: @item @i{d} outside of range of @i{n} in @code{D>S}:
                   9588: @cindex @code{D>S}, @i{d} out of range of @i{n} 
                   9589: The least significant cell of @i{d} is produced.
1.1       anton    9590: 
                   9591: @end table
                   9592: 
                   9593: 
                   9594: @c =====================================================================
                   9595: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
                   9596: @section The optional Exception word set
                   9597: @c =====================================================================
                   9598: @cindex system documentation, exception words
                   9599: @cindex exception words, system documentation
                   9600: 
                   9601: @menu
                   9602: * exception-idef::              Implementation Defined Options              
                   9603: @end menu
                   9604: 
                   9605: 
                   9606: @c ---------------------------------------------------------------------
                   9607: @node exception-idef,  , The optional Exception word set, The optional Exception word set
                   9608: @subsection Implementation Defined Options
                   9609: @c ---------------------------------------------------------------------
                   9610: @cindex implementation-defined options, exception words
                   9611: @cindex exception words, implementation-defined options
                   9612: 
                   9613: @table @i
                   9614: @item @code{THROW}-codes used in the system:
                   9615: @cindex @code{THROW}-codes used in the system
                   9616: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29      crook    9617: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1       anton    9618: codes -512@minus{}-2047 are used for OS errors (for file and memory
                   9619: allocation operations). The mapping from OS error numbers to throw codes
                   9620: is -512@minus{}@code{errno}. One side effect of this mapping is that
                   9621: undefined OS errors produce a message with a strange number; e.g.,
                   9622: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
                   9623: @end table
                   9624: 
                   9625: @c =====================================================================
                   9626: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
                   9627: @section The optional Facility word set
                   9628: @c =====================================================================
                   9629: @cindex system documentation, facility words
                   9630: @cindex facility words, system documentation
                   9631: 
                   9632: @menu
                   9633: * facility-idef::               Implementation Defined Options               
                   9634: * facility-ambcond::            Ambiguous Conditions            
                   9635: @end menu
                   9636: 
                   9637: 
                   9638: @c ---------------------------------------------------------------------
                   9639: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
                   9640: @subsection Implementation Defined Options
                   9641: @c ---------------------------------------------------------------------
                   9642: @cindex implementation-defined options, facility words
                   9643: @cindex facility words, implementation-defined options
                   9644: 
                   9645: @table @i
                   9646: @item encoding of keyboard events (@code{EKEY}):
                   9647: @cindex keyboard events, encoding in @code{EKEY}
                   9648: @cindex @code{EKEY}, encoding of keyboard events
                   9649: Not yet implemented.
                   9650: 
                   9651: @item duration of a system clock tick:
                   9652: @cindex duration of a system clock tick
                   9653: @cindex clock tick duration
                   9654: System dependent. With respect to @code{MS}, the time is specified in
                   9655: microseconds. How well the OS and the hardware implement this, is
                   9656: another question.
                   9657: 
                   9658: @item repeatability to be expected from the execution of @code{MS}:
                   9659: @cindex repeatability to be expected from the execution of @code{MS}
                   9660: @cindex @code{MS}, repeatability to be expected
                   9661: System dependent. On Unix, a lot depends on load. If the system is
                   9662: lightly loaded, and the delay is short enough that Gforth does not get
                   9663: swapped out, the performance should be acceptable. Under MS-DOS and
                   9664: other single-tasking systems, it should be good.
                   9665: 
                   9666: @end table
                   9667: 
                   9668: 
                   9669: @c ---------------------------------------------------------------------
                   9670: @node facility-ambcond,  , facility-idef, The optional Facility word set
                   9671: @subsection Ambiguous conditions
                   9672: @c ---------------------------------------------------------------------
                   9673: @cindex facility words, ambiguous conditions
                   9674: @cindex ambiguous conditions, facility words
                   9675: 
                   9676: @table @i
                   9677: @item @code{AT-XY} can't be performed on user output device:
                   9678: @cindex @code{AT-XY} can't be performed on user output device
                   9679: Largely terminal dependent. No range checks are done on the arguments.
                   9680: No errors are reported. You may see some garbage appearing, you may see
                   9681: simply nothing happen.
                   9682: 
                   9683: @end table
                   9684: 
                   9685: 
                   9686: @c =====================================================================
                   9687: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
                   9688: @section The optional File-Access word set
                   9689: @c =====================================================================
                   9690: @cindex system documentation, file words
                   9691: @cindex file words, system documentation
                   9692: 
                   9693: @menu
                   9694: * file-idef::                   Implementation Defined Options
                   9695: * file-ambcond::                Ambiguous Conditions                
                   9696: @end menu
                   9697: 
                   9698: @c ---------------------------------------------------------------------
                   9699: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
                   9700: @subsection Implementation Defined Options
                   9701: @c ---------------------------------------------------------------------
                   9702: @cindex implementation-defined options, file words
                   9703: @cindex file words, implementation-defined options
                   9704: 
                   9705: @table @i
                   9706: @item file access methods used:
                   9707: @cindex file access methods used
                   9708: @code{R/O}, @code{R/W} and @code{BIN} work as you would
                   9709: expect. @code{W/O} translates into the C file opening mode @code{w} (or
                   9710: @code{wb}): The file is cleared, if it exists, and created, if it does
                   9711: not (with both @code{open-file} and @code{create-file}).  Under Unix
                   9712: @code{create-file} creates a file with 666 permissions modified by your
                   9713: umask.
                   9714: 
                   9715: @item file exceptions:
                   9716: @cindex file exceptions
                   9717: The file words do not raise exceptions (except, perhaps, memory access
                   9718: faults when you pass illegal addresses or file-ids).
                   9719: 
                   9720: @item file line terminator:
                   9721: @cindex file line terminator
                   9722: System-dependent. Gforth uses C's newline character as line
                   9723: terminator. What the actual character code(s) of this are is
                   9724: system-dependent.
                   9725: 
                   9726: @item file name format:
                   9727: @cindex file name format
                   9728: System dependent. Gforth just uses the file name format of your OS.
                   9729: 
                   9730: @item information returned by @code{FILE-STATUS}:
                   9731: @cindex @code{FILE-STATUS}, returned information
                   9732: @code{FILE-STATUS} returns the most powerful file access mode allowed
                   9733: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
                   9734: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
                   9735: along with the returned mode.
                   9736: 
                   9737: @item input file state after an exception when including source:
                   9738: @cindex exception when including source
                   9739: All files that are left via the exception are closed.
                   9740: 
1.29      crook    9741: @item @i{ior} values and meaning:
                   9742: @cindex @i{ior} values and meaning
                   9743: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    9744: intended as throw codes. They typically are in the range
                   9745: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    9746: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    9747: 
                   9748: @item maximum depth of file input nesting:
                   9749: @cindex maximum depth of file input nesting
                   9750: @cindex file input nesting, maximum depth
                   9751: limited by the amount of return stack, locals/TIB stack, and the number
                   9752: of open files available. This should not give you troubles.
                   9753: 
                   9754: @item maximum size of input line:
                   9755: @cindex maximum size of input line
                   9756: @cindex input line size, maximum
                   9757: @code{/line}. Currently 255.
                   9758: 
                   9759: @item methods of mapping block ranges to files:
                   9760: @cindex mapping block ranges to files
                   9761: @cindex files containing blocks
                   9762: @cindex blocks in files
                   9763: By default, blocks are accessed in the file @file{blocks.fb} in the
                   9764: current working directory. The file can be switched with @code{USE}.
                   9765: 
                   9766: @item number of string buffers provided by @code{S"}:
                   9767: @cindex @code{S"}, number of string buffers
                   9768: 1
                   9769: 
                   9770: @item size of string buffer used by @code{S"}:
                   9771: @cindex @code{S"}, size of string buffer
                   9772: @code{/line}. currently 255.
                   9773: 
                   9774: @end table
                   9775: 
                   9776: @c ---------------------------------------------------------------------
                   9777: @node file-ambcond,  , file-idef, The optional File-Access word set
                   9778: @subsection Ambiguous conditions
                   9779: @c ---------------------------------------------------------------------
                   9780: @cindex file words, ambiguous conditions
                   9781: @cindex ambiguous conditions, file words
                   9782: 
                   9783: @table @i
                   9784: @item attempting to position a file outside its boundaries:
                   9785: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
                   9786: @code{REPOSITION-FILE} is performed as usual: Afterwards,
                   9787: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
                   9788: 
                   9789: @item attempting to read from file positions not yet written:
                   9790: @cindex reading from file positions not yet written
                   9791: End-of-file, i.e., zero characters are read and no error is reported.
                   9792: 
1.29      crook    9793: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
                   9794: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
1.1       anton    9795: An appropriate exception may be thrown, but a memory fault or other
                   9796: problem is more probable.
                   9797: 
1.29      crook    9798: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
                   9799: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
                   9800: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
                   9801: The @i{ior} produced by the operation, that discovered the problem, is
1.1       anton    9802: thrown.
                   9803: 
                   9804: @item named file cannot be opened (@code{INCLUDED}):
                   9805: @cindex @code{INCLUDED}, named file cannot be opened
1.29      crook    9806: The @i{ior} produced by @code{open-file} is thrown.
1.1       anton    9807: 
                   9808: @item requesting an unmapped block number:
                   9809: @cindex unmapped block numbers
                   9810: There are no unmapped legal block numbers. On some operating systems,
                   9811: writing a block with a large number may overflow the file system and
                   9812: have an error message as consequence.
                   9813: 
                   9814: @item using @code{source-id} when @code{blk} is non-zero:
                   9815: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
                   9816: @code{source-id} performs its function. Typically it will give the id of
                   9817: the source which loaded the block. (Better ideas?)
                   9818: 
                   9819: @end table
                   9820: 
                   9821: 
                   9822: @c =====================================================================
                   9823: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
                   9824: @section The optional Floating-Point word set
                   9825: @c =====================================================================
                   9826: @cindex system documentation, floating-point words
                   9827: @cindex floating-point words, system documentation
                   9828: 
                   9829: @menu
                   9830: * floating-idef::               Implementation Defined Options
                   9831: * floating-ambcond::            Ambiguous Conditions            
                   9832: @end menu
                   9833: 
                   9834: 
                   9835: @c ---------------------------------------------------------------------
                   9836: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
                   9837: @subsection Implementation Defined Options
                   9838: @c ---------------------------------------------------------------------
                   9839: @cindex implementation-defined options, floating-point words
                   9840: @cindex floating-point words, implementation-defined options
                   9841: 
                   9842: @table @i
                   9843: @item format and range of floating point numbers:
                   9844: @cindex format and range of floating point numbers
                   9845: @cindex floating point numbers, format and range
                   9846: System-dependent; the @code{double} type of C.
                   9847: 
1.29      crook    9848: @item results of @code{REPRESENT} when @i{float} is out of range:
                   9849: @cindex  @code{REPRESENT}, results when @i{float} is out of range
1.1       anton    9850: System dependent; @code{REPRESENT} is implemented using the C library
                   9851: function @code{ecvt()} and inherits its behaviour in this respect.
                   9852: 
                   9853: @item rounding or truncation of floating-point numbers:
                   9854: @cindex rounding of floating-point numbers
                   9855: @cindex truncation of floating-point numbers
                   9856: @cindex floating-point numbers, rounding or truncation
                   9857: System dependent; the rounding behaviour is inherited from the hosting C
                   9858: compiler. IEEE-FP-based (i.e., most) systems by default round to
                   9859: nearest, and break ties by rounding to even (i.e., such that the last
                   9860: bit of the mantissa is 0).
                   9861: 
                   9862: @item size of floating-point stack:
                   9863: @cindex floating-point stack size
                   9864: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
                   9865: the floating-point stack (in floats). You can specify this on startup
                   9866: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
                   9867: 
                   9868: @item width of floating-point stack:
                   9869: @cindex floating-point stack width 
                   9870: @code{1 floats}.
                   9871: 
                   9872: @end table
                   9873: 
                   9874: 
                   9875: @c ---------------------------------------------------------------------
                   9876: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
                   9877: @subsection Ambiguous conditions
                   9878: @c ---------------------------------------------------------------------
                   9879: @cindex floating-point words, ambiguous conditions
                   9880: @cindex ambiguous conditions, floating-point words
                   9881: 
                   9882: @table @i
                   9883: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
                   9884: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
                   9885: System-dependent. Typically results in a @code{-23 THROW} like other
                   9886: alignment violations.
                   9887: 
                   9888: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
                   9889: @cindex @code{f@@} used with an address that is not float aligned
                   9890: @cindex @code{f!} used with an address that is not float aligned
                   9891: System-dependent. Typically results in a @code{-23 THROW} like other
                   9892: alignment violations.
                   9893: 
                   9894: @item floating-point result out of range:
                   9895: @cindex floating-point result out of range
                   9896: System-dependent. Can result in a @code{-55 THROW} (Floating-point
                   9897: unidentified fault), or can produce a special value representing, e.g.,
                   9898: Infinity.
                   9899: 
                   9900: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
                   9901: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
                   9902: System-dependent. Typically results in an alignment fault like other
                   9903: alignment violations.
                   9904: 
1.35      anton    9905: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
                   9906: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1       anton    9907: The floating-point number is converted into decimal nonetheless.
                   9908: 
                   9909: @item Both arguments are equal to zero (@code{FATAN2}):
                   9910: @cindex @code{FATAN2}, both arguments are equal to zero
                   9911: System-dependent. @code{FATAN2} is implemented using the C library
                   9912: function @code{atan2()}.
                   9913: 
1.29      crook    9914: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
                   9915: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
                   9916: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1       anton    9917: because of small errors and the tan will be a very large (or very small)
                   9918: but finite number.
                   9919: 
1.29      crook    9920: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
                   9921: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1       anton    9922: The result is rounded to the nearest float.
                   9923: 
                   9924: @item dividing by zero:
                   9925: @cindex dividing by zero, floating-point
                   9926: @cindex floating-point dividing by zero
                   9927: @cindex floating-point unidentified fault, FP divide-by-zero
                   9928: @code{-55 throw} (Floating-point unidentified fault)
                   9929: 
                   9930: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
                   9931: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
                   9932: System dependent. On IEEE-FP based systems the number is converted into
                   9933: an infinity.
                   9934: 
1.29      crook    9935: @item @i{float}<1 (@code{FACOSH}):
                   9936: @cindex @code{FACOSH}, @i{float}<1
1.1       anton    9937: @cindex floating-point unidentified fault, @code{FACOSH}
                   9938: @code{-55 throw} (Floating-point unidentified fault)
                   9939: 
1.29      crook    9940: @item @i{float}=<-1 (@code{FLNP1}):
                   9941: @cindex @code{FLNP1}, @i{float}=<-1
1.1       anton    9942: @cindex floating-point unidentified fault, @code{FLNP1}
                   9943: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29      crook    9944: negative infinity is typically produced for @i{float}=-1.
1.1       anton    9945: 
1.29      crook    9946: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
                   9947: @cindex @code{FLN}, @i{float}=<0
                   9948: @cindex @code{FLOG}, @i{float}=<0
1.1       anton    9949: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
                   9950: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29      crook    9951: negative infinity is typically produced for @i{float}=0.
1.1       anton    9952: 
1.29      crook    9953: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
                   9954: @cindex @code{FASINH}, @i{float}<0
                   9955: @cindex @code{FSQRT}, @i{float}<0
1.1       anton    9956: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
                   9957: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
                   9958: produces values for these inputs on my Linux box (Bug in the C library?)
                   9959: 
1.29      crook    9960: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
                   9961: @cindex @code{FACOS}, |@i{float}|>1
                   9962: @cindex @code{FASIN}, |@i{float}|>1
                   9963: @cindex @code{FATANH}, |@i{float}|>1
1.1       anton    9964: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
                   9965: @code{-55 throw} (Floating-point unidentified fault).
                   9966: 
1.29      crook    9967: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
                   9968: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1       anton    9969: @cindex floating-point unidentified fault, @code{F>D}
                   9970: @code{-55 throw} (Floating-point unidentified fault).
                   9971: 
                   9972: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
                   9973: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
                   9974: This does not happen.
                   9975: @end table
                   9976: 
                   9977: @c =====================================================================
                   9978: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
                   9979: @section The optional Locals word set
                   9980: @c =====================================================================
                   9981: @cindex system documentation, locals words
                   9982: @cindex locals words, system documentation
                   9983: 
                   9984: @menu
                   9985: * locals-idef::                 Implementation Defined Options                 
                   9986: * locals-ambcond::              Ambiguous Conditions              
                   9987: @end menu
                   9988: 
                   9989: 
                   9990: @c ---------------------------------------------------------------------
                   9991: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
                   9992: @subsection Implementation Defined Options
                   9993: @c ---------------------------------------------------------------------
                   9994: @cindex implementation-defined options, locals words
                   9995: @cindex locals words, implementation-defined options
                   9996: 
                   9997: @table @i
                   9998: @item maximum number of locals in a definition:
                   9999: @cindex maximum number of locals in a definition
                   10000: @cindex locals, maximum number in a definition
                   10001: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
                   10002: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
                   10003: characters. The number of locals in a definition is bounded by the size
                   10004: of locals-buffer, which contains the names of the locals.
                   10005: 
                   10006: @end table
                   10007: 
                   10008: 
                   10009: @c ---------------------------------------------------------------------
                   10010: @node locals-ambcond,  , locals-idef, The optional Locals word set
                   10011: @subsection Ambiguous conditions
                   10012: @c ---------------------------------------------------------------------
                   10013: @cindex locals words, ambiguous conditions
                   10014: @cindex ambiguous conditions, locals words
                   10015: 
                   10016: @table @i
                   10017: @item executing a named local in interpretation state:
                   10018: @cindex local in interpretation state
                   10019: @cindex Interpreting a compile-only word, for a local
                   10020: Locals have no interpretation semantics. If you try to perform the
                   10021: interpretation semantics, you will get a @code{-14 throw} somewhere
                   10022: (Interpreting a compile-only word). If you perform the compilation
                   10023: semantics, the locals access will be compiled (irrespective of state).
                   10024: 
1.29      crook    10025: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1       anton    10026: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
                   10027: @cindex @code{TO} on non-@code{VALUE}s and non-locals
                   10028: @cindex Invalid name argument, @code{TO}
                   10029: @code{-32 throw} (Invalid name argument)
                   10030: 
                   10031: @end table
                   10032: 
                   10033: 
                   10034: @c =====================================================================
                   10035: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
                   10036: @section The optional Memory-Allocation word set
                   10037: @c =====================================================================
                   10038: @cindex system documentation, memory-allocation words
                   10039: @cindex memory-allocation words, system documentation
                   10040: 
                   10041: @menu
                   10042: * memory-idef::                 Implementation Defined Options                 
                   10043: @end menu
                   10044: 
                   10045: 
                   10046: @c ---------------------------------------------------------------------
                   10047: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
                   10048: @subsection Implementation Defined Options
                   10049: @c ---------------------------------------------------------------------
                   10050: @cindex implementation-defined options, memory-allocation words
                   10051: @cindex memory-allocation words, implementation-defined options
                   10052: 
                   10053: @table @i
1.29      crook    10054: @item values and meaning of @i{ior}:
                   10055: @cindex  @i{ior} values and meaning
                   10056: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    10057: intended as throw codes. They typically are in the range
                   10058: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    10059: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    10060: 
                   10061: @end table
                   10062: 
                   10063: @c =====================================================================
                   10064: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
                   10065: @section The optional Programming-Tools word set
                   10066: @c =====================================================================
                   10067: @cindex system documentation, programming-tools words
                   10068: @cindex programming-tools words, system documentation
                   10069: 
                   10070: @menu
                   10071: * programming-idef::            Implementation Defined Options            
                   10072: * programming-ambcond::         Ambiguous Conditions         
                   10073: @end menu
                   10074: 
                   10075: 
                   10076: @c ---------------------------------------------------------------------
                   10077: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
                   10078: @subsection Implementation Defined Options
                   10079: @c ---------------------------------------------------------------------
                   10080: @cindex implementation-defined options, programming-tools words
                   10081: @cindex programming-tools words, implementation-defined options
                   10082: 
                   10083: @table @i
                   10084: @item ending sequence for input following @code{;CODE} and @code{CODE}:
                   10085: @cindex @code{;CODE} ending sequence
                   10086: @cindex @code{CODE} ending sequence
                   10087: @code{END-CODE}
                   10088: 
                   10089: @item manner of processing input following @code{;CODE} and @code{CODE}:
                   10090: @cindex @code{;CODE}, processing input
                   10091: @cindex @code{CODE}, processing input
                   10092: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
                   10093: the input is processed by the text interpreter, (starting) in interpret
                   10094: state.
                   10095: 
                   10096: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
                   10097: @cindex @code{ASSEMBLER}, search order capability
                   10098: The ANS Forth search order word set.
                   10099: 
                   10100: @item source and format of display by @code{SEE}:
                   10101: @cindex @code{SEE}, source and format of output
                   10102: The source for @code{see} is the intermediate code used by the inner
                   10103: interpreter.  The current @code{see} tries to output Forth source code
                   10104: as well as possible.
                   10105: 
                   10106: @end table
                   10107: 
                   10108: @c ---------------------------------------------------------------------
                   10109: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
                   10110: @subsection Ambiguous conditions
                   10111: @c ---------------------------------------------------------------------
                   10112: @cindex programming-tools words, ambiguous conditions
                   10113: @cindex ambiguous conditions, programming-tools words
                   10114: 
                   10115: @table @i
                   10116: 
1.21      crook    10117: @item deleting the compilation word list (@code{FORGET}):
                   10118: @cindex @code{FORGET}, deleting the compilation word list
1.1       anton    10119: Not implemented (yet).
                   10120: 
1.29      crook    10121: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
                   10122: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
                   10123: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1       anton    10124: @cindex control-flow stack underflow
                   10125: This typically results in an @code{abort"} with a descriptive error
                   10126: message (may change into a @code{-22 throw} (Control structure mismatch)
                   10127: in the future). You may also get a memory access error. If you are
                   10128: unlucky, this ambiguous condition is not caught.
                   10129: 
1.29      crook    10130: @item @i{name} can't be found (@code{FORGET}):
                   10131: @cindex @code{FORGET}, @i{name} can't be found
1.1       anton    10132: Not implemented (yet).
                   10133: 
1.29      crook    10134: @item @i{name} not defined via @code{CREATE}:
                   10135: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1       anton    10136: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
                   10137: the execution semantics of the last defined word no matter how it was
                   10138: defined.
                   10139: 
                   10140: @item @code{POSTPONE} applied to @code{[IF]}:
                   10141: @cindex @code{POSTPONE} applied to @code{[IF]}
                   10142: @cindex @code{[IF]} and @code{POSTPONE}
                   10143: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
                   10144: equivalent to @code{[IF]}.
                   10145: 
                   10146: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
                   10147: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
                   10148: Continue in the same state of conditional compilation in the next outer
                   10149: input source. Currently there is no warning to the user about this.
                   10150: 
                   10151: @item removing a needed definition (@code{FORGET}):
                   10152: @cindex @code{FORGET}, removing a needed definition
                   10153: Not implemented (yet).
                   10154: 
                   10155: @end table
                   10156: 
                   10157: 
                   10158: @c =====================================================================
                   10159: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
                   10160: @section The optional Search-Order word set
                   10161: @c =====================================================================
                   10162: @cindex system documentation, search-order words
                   10163: @cindex search-order words, system documentation
                   10164: 
                   10165: @menu
                   10166: * search-idef::                 Implementation Defined Options                 
                   10167: * search-ambcond::              Ambiguous Conditions              
                   10168: @end menu
                   10169: 
                   10170: 
                   10171: @c ---------------------------------------------------------------------
                   10172: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
                   10173: @subsection Implementation Defined Options
                   10174: @c ---------------------------------------------------------------------
                   10175: @cindex implementation-defined options, search-order words
                   10176: @cindex search-order words, implementation-defined options
                   10177: 
                   10178: @table @i
                   10179: @item maximum number of word lists in search order:
                   10180: @cindex maximum number of word lists in search order
                   10181: @cindex search order, maximum depth
                   10182: @code{s" wordlists" environment? drop .}. Currently 16.
                   10183: 
                   10184: @item minimum search order:
                   10185: @cindex minimum search order
                   10186: @cindex search order, minimum
                   10187: @code{root root}.
                   10188: 
                   10189: @end table
                   10190: 
                   10191: @c ---------------------------------------------------------------------
                   10192: @node search-ambcond,  , search-idef, The optional Search-Order word set
                   10193: @subsection Ambiguous conditions
                   10194: @c ---------------------------------------------------------------------
                   10195: @cindex search-order words, ambiguous conditions
                   10196: @cindex ambiguous conditions, search-order words
                   10197: 
                   10198: @table @i
1.21      crook    10199: @item changing the compilation word list (during compilation):
                   10200: @cindex changing the compilation word list (during compilation)
                   10201: @cindex compilation word list, change before definition ends
                   10202: The word is entered into the word list that was the compilation word list
1.1       anton    10203: at the start of the definition. Any changes to the name field (e.g.,
                   10204: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
                   10205: are applied to the latest defined word (as reported by @code{last} or
1.21      crook    10206: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1       anton    10207: 
                   10208: @item search order empty (@code{previous}):
                   10209: @cindex @code{previous}, search order empty
1.26      crook    10210: @cindex vocstack empty, @code{previous}
1.1       anton    10211: @code{abort" Vocstack empty"}.
                   10212: 
                   10213: @item too many word lists in search order (@code{also}):
                   10214: @cindex @code{also}, too many word lists in search order
1.26      crook    10215: @cindex vocstack full, @code{also}
1.1       anton    10216: @code{abort" Vocstack full"}.
                   10217: 
                   10218: @end table
                   10219: 
                   10220: @c ***************************************************************
                   10221: @node Model, Integrating Gforth, ANS conformance, Top
                   10222: @chapter Model
                   10223: 
                   10224: This chapter has yet to be written. It will contain information, on
                   10225: which internal structures you can rely.
                   10226: 
                   10227: @c ***************************************************************
                   10228: @node Integrating Gforth, Emacs and Gforth, Model, Top
                   10229: @chapter Integrating Gforth into C programs
                   10230: 
                   10231: This is not yet implemented.
                   10232: 
                   10233: Several people like to use Forth as scripting language for applications
                   10234: that are otherwise written in C, C++, or some other language.
                   10235: 
                   10236: The Forth system ATLAST provides facilities for embedding it into
                   10237: applications; unfortunately it has several disadvantages: most
                   10238: importantly, it is not based on ANS Forth, and it is apparently dead
                   10239: (i.e., not developed further and not supported). The facilities
1.21      crook    10240: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1       anton    10241: making the switch should not be hard.
                   10242: 
                   10243: We also tried to design the interface such that it can easily be
                   10244: implemented by other Forth systems, so that we may one day arrive at a
                   10245: standardized interface. Such a standard interface would allow you to
                   10246: replace the Forth system without having to rewrite C code.
                   10247: 
                   10248: You embed the Gforth interpreter by linking with the library
                   10249: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
                   10250: global symbols in this library that belong to the interface, have the
                   10251: prefix @code{forth_}. (Global symbols that are used internally have the
                   10252: prefix @code{gforth_}).
                   10253: 
                   10254: You can include the declarations of Forth types and the functions and
                   10255: variables of the interface with @code{#include <forth.h>}.
                   10256: 
                   10257: Types.
                   10258: 
                   10259: Variables.
                   10260: 
                   10261: Data and FP Stack pointer. Area sizes.
                   10262: 
                   10263: functions.
                   10264: 
                   10265: forth_init(imagefile)
                   10266: forth_evaluate(string) exceptions?
                   10267: forth_goto(address) (or forth_execute(xt)?)
                   10268: forth_continue() (a corountining mechanism)
                   10269: 
                   10270: Adding primitives.
                   10271: 
                   10272: No checking.
                   10273: 
                   10274: Signals?
                   10275: 
                   10276: Accessing the Stacks
                   10277: 
1.26      crook    10278: @c ******************************************************************
1.1       anton    10279: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
                   10280: @chapter Emacs and Gforth
                   10281: @cindex Emacs and Gforth
                   10282: 
                   10283: @cindex @file{gforth.el}
                   10284: @cindex @file{forth.el}
                   10285: @cindex Rydqvist, Goran
                   10286: @cindex comment editing commands
                   10287: @cindex @code{\}, editing with Emacs
                   10288: @cindex debug tracer editing commands
                   10289: @cindex @code{~~}, removal with Emacs
                   10290: @cindex Forth mode in Emacs
                   10291: Gforth comes with @file{gforth.el}, an improved version of
                   10292: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26      crook    10293: improvements are:
                   10294: 
                   10295: @itemize @bullet
                   10296: @item
                   10297: A better (but still not perfect) handling of indentation.
                   10298: @item
                   10299: Comment paragraph filling (@kbd{M-q})
                   10300: @item
                   10301: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
                   10302: @item
                   10303: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
                   10304: @end itemize
                   10305: 
                   10306: I left the stuff I do not use alone, even though some of it only makes
                   10307: sense for TILE. To get a description of these features, enter Forth mode
                   10308: and type @kbd{C-h m}.
1.1       anton    10309: 
                   10310: @cindex source location of error or debugging output in Emacs
                   10311: @cindex error output, finding the source location in Emacs
                   10312: @cindex debugging output, finding the source location in Emacs
                   10313: In addition, Gforth supports Emacs quite well: The source code locations
                   10314: given in error messages, debugging output (from @code{~~}) and failed
                   10315: assertion messages are in the right format for Emacs' compilation mode
                   10316: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
                   10317: Manual}) so the source location corresponding to an error or other
                   10318: message is only a few keystrokes away (@kbd{C-x `} for the next error,
                   10319: @kbd{C-c C-c} for the error under the cursor).
                   10320: 
                   10321: @cindex @file{TAGS} file
                   10322: @cindex @file{etags.fs}
                   10323: @cindex viewing the source of a word in Emacs
1.26      crook    10324: Also, if you @code{include} @file{etags.fs}, a new @file{TAGS} file will
                   10325: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1       anton    10326: contains the definitions of all words defined afterwards. You can then
                   10327: find the source for a word using @kbd{M-.}. Note that emacs can use
                   10328: several tags files at the same time (e.g., one for the Gforth sources
                   10329: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
                   10330: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
                   10331: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
                   10332: @file{/usr/local/share/gforth/0.2.0/TAGS}).
                   10333: 
                   10334: @cindex @file{.emacs}
                   10335: To get all these benefits, add the following lines to your @file{.emacs}
                   10336: file:
                   10337: 
                   10338: @example
                   10339: (autoload 'forth-mode "gforth.el")
                   10340: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
                   10341: @end example
                   10342: 
1.26      crook    10343: @c ******************************************************************
1.1       anton    10344: @node Image Files, Engine, Emacs and Gforth, Top
                   10345: @chapter Image Files
1.26      crook    10346: @cindex image file
                   10347: @cindex @file{.fi} files
1.1       anton    10348: @cindex precompiled Forth code
                   10349: @cindex dictionary in persistent form
                   10350: @cindex persistent form of dictionary
                   10351: 
                   10352: An image file is a file containing an image of the Forth dictionary,
                   10353: i.e., compiled Forth code and data residing in the dictionary.  By
                   10354: convention, we use the extension @code{.fi} for image files.
                   10355: 
                   10356: @menu
1.18      anton    10357: * Image Licensing Issues::      Distribution terms for images.
                   10358: * Image File Background::       Why have image files?
1.29      crook    10359: * Non-Relocatable Image Files::   don't always work.
1.18      anton    10360: * Data-Relocatable Image Files::  are better.
1.29      crook    10361: * Fully Relocatable Image Files:: better yet.
1.18      anton    10362: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.29      crook    10363: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.18      anton    10364: * Modifying the Startup Sequence::  and turnkey applications.
1.1       anton    10365: @end menu
                   10366: 
1.18      anton    10367: @node Image Licensing Issues, Image File Background, Image Files, Image Files
                   10368: @section Image Licensing Issues
                   10369: @cindex license for images
                   10370: @cindex image license
                   10371: 
                   10372: An image created with @code{gforthmi} (@pxref{gforthmi}) or
                   10373: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
                   10374: original image; i.e., according to copyright law it is a derived work of
                   10375: the original image.
                   10376: 
                   10377: Since Gforth is distributed under the GNU GPL, the newly created image
                   10378: falls under the GNU GPL, too. In particular, this means that if you
                   10379: distribute the image, you have to make all of the sources for the image
                   10380: available, including those you wrote.  For details see @ref{License, ,
                   10381: GNU General Public License (Section 3)}.
                   10382: 
                   10383: If you create an image with @code{cross} (@pxref{cross.fs}), the image
                   10384: contains only code compiled from the sources you gave it; if none of
                   10385: these sources is under the GPL, the terms discussed above do not apply
                   10386: to the image. However, if your image needs an engine (a gforth binary)
                   10387: that is under the GPL, you should make sure that you distribute both in
                   10388: a way that is at most a @emph{mere aggregation}, if you don't want the
                   10389: terms of the GPL to apply to the image.
                   10390: 
                   10391: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1       anton    10392: @section Image File Background
                   10393: @cindex image file background
                   10394: 
                   10395: Our Forth system consists not only of primitives, but also of
                   10396: definitions written in Forth. Since the Forth compiler itself belongs to
                   10397: those definitions, it is not possible to start the system with the
                   10398: primitives and the Forth source alone. Therefore we provide the Forth
1.26      crook    10399: code as an image file in nearly executable form. When Gforth starts up,
                   10400: a C routine loads the image file into memory, optionally relocates the
                   10401: addresses, then sets up the memory (stacks etc.) according to
                   10402: information in the image file, and (finally) starts executing Forth
                   10403: code.
1.1       anton    10404: 
                   10405: The image file variants represent different compromises between the
                   10406: goals of making it easy to generate image files and making them
                   10407: portable.
                   10408: 
                   10409: @cindex relocation at run-time
1.26      crook    10410: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1       anton    10411: run-time. This avoids many of the complications discussed below (image
                   10412: files are data relocatable without further ado), but costs performance
                   10413: (one addition per memory access).
                   10414: 
                   10415: @cindex relocation at load-time
1.26      crook    10416: By contrast, the Gforth loader performs relocation at image load time. The
                   10417: loader also has to replace tokens that represent primitive calls with the
1.1       anton    10418: appropriate code-field addresses (or code addresses in the case of
                   10419: direct threading).
                   10420: 
                   10421: There are three kinds of image files, with different degrees of
                   10422: relocatability: non-relocatable, data-relocatable, and fully relocatable
                   10423: image files.
                   10424: 
                   10425: @cindex image file loader
                   10426: @cindex relocating loader
                   10427: @cindex loader for image files
                   10428: These image file variants have several restrictions in common; they are
                   10429: caused by the design of the image file loader:
                   10430: 
                   10431: @itemize @bullet
                   10432: @item
                   10433: There is only one segment; in particular, this means, that an image file
                   10434: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26      crook    10435: them). The contents of the stacks are not represented, either.
1.1       anton    10436: 
                   10437: @item
                   10438: The only kinds of relocation supported are: adding the same offset to
                   10439: all cells that represent data addresses; and replacing special tokens
                   10440: with code addresses or with pieces of machine code.
                   10441: 
                   10442: If any complex computations involving addresses are performed, the
                   10443: results cannot be represented in the image file. Several applications that
                   10444: use such computations come to mind:
                   10445: @itemize @minus
                   10446: @item
                   10447: Hashing addresses (or data structures which contain addresses) for table
                   10448: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
                   10449: purpose, you will have no problem, because the hash tables are
                   10450: recomputed automatically when the system is started. If you use your own
                   10451: hash tables, you will have to do something similar.
                   10452: 
                   10453: @item
                   10454: There's a cute implementation of doubly-linked lists that uses
                   10455: @code{XOR}ed addresses. You could represent such lists as singly-linked
                   10456: in the image file, and restore the doubly-linked representation on
                   10457: startup.@footnote{In my opinion, though, you should think thrice before
                   10458: using a doubly-linked list (whatever implementation).}
                   10459: 
                   10460: @item
                   10461: The code addresses of run-time routines like @code{docol:} cannot be
                   10462: represented in the image file (because their tokens would be replaced by
                   10463: machine code in direct threaded implementations). As a workaround,
                   10464: compute these addresses at run-time with @code{>code-address} from the
                   10465: executions tokens of appropriate words (see the definitions of
                   10466: @code{docol:} and friends in @file{kernel.fs}).
                   10467: 
                   10468: @item
                   10469: On many architectures addresses are represented in machine code in some
                   10470: shifted or mangled form. You cannot put @code{CODE} words that contain
                   10471: absolute addresses in this form in a relocatable image file. Workarounds
                   10472: are representing the address in some relative form (e.g., relative to
                   10473: the CFA, which is present in some register), or loading the address from
                   10474: a place where it is stored in a non-mangled form.
                   10475: @end itemize
                   10476: @end itemize
                   10477: 
                   10478: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
                   10479: @section Non-Relocatable Image Files
                   10480: @cindex non-relocatable image files
1.26      crook    10481: @cindex image file, non-relocatable
1.1       anton    10482: 
                   10483: These files are simple memory dumps of the dictionary. They are specific
                   10484: to the executable (i.e., @file{gforth} file) they were created
                   10485: with. What's worse, they are specific to the place on which the
                   10486: dictionary resided when the image was created. Now, there is no
                   10487: guarantee that the dictionary will reside at the same place the next
                   10488: time you start Gforth, so there's no guarantee that a non-relocatable
                   10489: image will work the next time (Gforth will complain instead of crashing,
                   10490: though).
                   10491: 
                   10492: You can create a non-relocatable image file with
                   10493: 
                   10494: doc-savesystem
                   10495: 
                   10496: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
                   10497: @section Data-Relocatable Image Files
                   10498: @cindex data-relocatable image files
1.26      crook    10499: @cindex image file, data-relocatable
1.1       anton    10500: 
                   10501: These files contain relocatable data addresses, but fixed code addresses
                   10502: (instead of tokens). They are specific to the executable (i.e.,
                   10503: @file{gforth} file) they were created with. For direct threading on some
                   10504: architectures (e.g., the i386), data-relocatable images do not work. You
                   10505: get a data-relocatable image, if you use @file{gforthmi} with a
                   10506: Gforth binary that is not doubly indirect threaded (@pxref{Fully
                   10507: Relocatable Image Files}).
                   10508: 
                   10509: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
                   10510: @section Fully Relocatable Image Files
                   10511: @cindex fully relocatable image files
1.26      crook    10512: @cindex image file, fully relocatable
1.1       anton    10513: 
                   10514: @cindex @file{kern*.fi}, relocatability
                   10515: @cindex @file{gforth.fi}, relocatability
                   10516: These image files have relocatable data addresses, and tokens for code
                   10517: addresses. They can be used with different binaries (e.g., with and
                   10518: without debugging) on the same machine, and even across machines with
                   10519: the same data formats (byte order, cell size, floating point
                   10520: format). However, they are usually specific to the version of Gforth
                   10521: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
                   10522: are fully relocatable.
                   10523: 
                   10524: There are two ways to create a fully relocatable image file:
                   10525: 
                   10526: @menu
1.29      crook    10527: * gforthmi::                    The normal way
1.1       anton    10528: * cross.fs::                    The hard way
                   10529: @end menu
                   10530: 
                   10531: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
                   10532: @subsection @file{gforthmi}
                   10533: @cindex @file{comp-i.fs}
                   10534: @cindex @file{gforthmi}
                   10535: 
                   10536: You will usually use @file{gforthmi}. If you want to create an
1.29      crook    10537: image @i{file} that contains everything you would load by invoking
                   10538: Gforth with @code{gforth @i{options}}, you simply say:
1.1       anton    10539: @example
1.29      crook    10540: gforthmi @i{file} @i{options}
1.1       anton    10541: @end example
                   10542: 
                   10543: E.g., if you want to create an image @file{asm.fi} that has the file
                   10544: @file{asm.fs} loaded in addition to the usual stuff, you could do it
                   10545: like this:
                   10546: 
                   10547: @example
                   10548: gforthmi asm.fi asm.fs
                   10549: @end example
                   10550: 
1.27      crook    10551: @file{gforthmi} is implemented as a sh script and works like this: It
                   10552: produces two non-relocatable images for different addresses and then
                   10553: compares them. Its output reflects this: first you see the output (if
                   10554: any) of the two Gforth invocations that produce the nonrelocatable image
                   10555: files, then you see the output of the comparing program: It displays the
                   10556: offset used for data addresses and the offset used for code addresses;
1.1       anton    10557: moreover, for each cell that cannot be represented correctly in the
                   10558: image files, it displays a line like the following one:
                   10559: 
                   10560: @example
                   10561:      78DC         BFFFFA50         BFFFFA40
                   10562: @end example
                   10563: 
                   10564: This means that at offset $78dc from @code{forthstart}, one input image
                   10565: contains $bffffa50, and the other contains $bffffa40. Since these cells
                   10566: cannot be represented correctly in the output image, you should examine
                   10567: these places in the dictionary and verify that these cells are dead
                   10568: (i.e., not read before they are written).
                   10569: 
1.27      crook    10570: If you type @file{gforthmi} with no arguments, it prints some usage
                   10571: instructions.
                   10572: 
1.1       anton    10573: @cindex @code{savesystem} during @file{gforthmi}
                   10574: @cindex @code{bye} during @file{gforthmi}
                   10575: @cindex doubly indirect threaded code
                   10576: @cindex environment variable @code{GFORTHD}
                   10577: @cindex @code{GFORTHD} environment variable
                   10578: @cindex @code{gforth-ditc}
1.29      crook    10579: There are a few wrinkles: After processing the passed @i{options}, the
1.1       anton    10580: words @code{savesystem} and @code{bye} must be visible. A special doubly
                   10581: indirect threaded version of the @file{gforth} executable is used for
                   10582: creating the nonrelocatable images; you can pass the exact filename of
                   10583: this executable through the environment variable @code{GFORTHD}
                   10584: (default: @file{gforth-ditc}); if you pass a version that is not doubly
                   10585: indirect threaded, you will not get a fully relocatable image, but a
1.27      crook    10586: data-relocatable image (because there is no code address offset). The
                   10587: normal @file{gforth} executable is used for creating the relocatable
                   10588: image; you can pass the exact filename of this executable through the
                   10589: environment variable @code{GFORTH}.
1.1       anton    10590: 
                   10591: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
                   10592: @subsection @file{cross.fs}
                   10593: @cindex @file{cross.fs}
                   10594: @cindex cross-compiler
                   10595: @cindex metacompiler
                   10596: 
                   10597: You can also use @code{cross}, a batch compiler that accepts a Forth-like
                   10598: programming language. This @code{cross} language has to be documented
                   10599: yet.
                   10600: 
                   10601: @cindex target compiler
                   10602: @code{cross} also allows you to create image files for machines with
                   10603: different data sizes and data formats than the one used for generating
                   10604: the image file. You can also use it to create an application image that
                   10605: does not contain a Forth compiler. These features are bought with
                   10606: restrictions and inconveniences in programming. E.g., addresses have to
                   10607: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
                   10608: order to make the code relocatable.
                   10609: 
                   10610: 
                   10611: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
                   10612: @section Stack and Dictionary Sizes
                   10613: @cindex image file, stack and dictionary sizes
                   10614: @cindex dictionary size default
                   10615: @cindex stack size default
                   10616: 
                   10617: If you invoke Gforth with a command line flag for the size
                   10618: (@pxref{Invoking Gforth}), the size you specify is stored in the
                   10619: dictionary. If you save the dictionary with @code{savesystem} or create
                   10620: an image with @file{gforthmi}, this size will become the default
                   10621: for the resulting image file. E.g., the following will create a
1.21      crook    10622: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1       anton    10623: 
                   10624: @example
                   10625: gforthmi gforth.fi -m 1M
                   10626: @end example
                   10627: 
                   10628: In other words, if you want to set the default size for the dictionary
                   10629: and the stacks of an image, just invoke @file{gforthmi} with the
                   10630: appropriate options when creating the image.
                   10631: 
                   10632: @cindex stack size, cache-friendly
                   10633: Note: For cache-friendly behaviour (i.e., good performance), you should
                   10634: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
                   10635: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
                   10636: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
                   10637: 
                   10638: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
                   10639: @section Running Image Files
                   10640: @cindex running image files
                   10641: @cindex invoking image files
                   10642: @cindex image file invocation
                   10643: 
                   10644: @cindex -i, invoke image file
                   10645: @cindex --image file, invoke image file
1.29      crook    10646: You can invoke Gforth with an image file @i{image} instead of the
1.1       anton    10647: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
                   10648: @example
1.29      crook    10649: gforth -i @i{image}
1.1       anton    10650: @end example
                   10651: 
                   10652: @cindex executable image file
1.26      crook    10653: @cindex image file, executable
1.1       anton    10654: If your operating system supports starting scripts with a line of the
                   10655: form @code{#! ...}, you just have to type the image file name to start
                   10656: Gforth with this image file (note that the file extension @code{.fi} is
1.29      crook    10657: just a convention). I.e., to run Gforth with the image file @i{image},
                   10658: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27      crook    10659: This works because every @code{.fi} file starts with a line of this
                   10660: format:
                   10661: 
                   10662: @example
                   10663: #! /usr/local/bin/gforth-0.4.0 -i
                   10664: @end example
                   10665: 
                   10666: The file and pathname for the Gforth engine specified on this line is
                   10667: the specific Gforth executable that it was built against; i.e. the value
                   10668: of the environment variable @code{GFORTH} at the time that
                   10669: @file{gforthmi} was executed.
1.1       anton    10670: 
1.27      crook    10671: You can make use of the same shell capability to make a Forth source
                   10672: file into an executable. For example, if you place this text in a file:
1.26      crook    10673: 
                   10674: @example
                   10675: #! /usr/local/bin/gforth
                   10676: 
                   10677: ." Hello, world" CR
                   10678: bye
                   10679: @end example
                   10680: 
                   10681: @noindent
1.27      crook    10682: and then make the file executable (chmod +x in Unix), you can run it
1.26      crook    10683: directly from the command line. The sequence @code{#!} is used in two
                   10684: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29      crook    10685: system@footnote{The Unix kernel actually recognises two types of files:
                   10686: executable files and files of data, where the data is processed by an
                   10687: interpreter that is specified on the ``interpreter line'' -- the first
                   10688: line of the file, starting with the sequence #!. There may be a small
                   10689: limit (e.g., 32) on the number of characters that may be specified on
                   10690: the interpreter line.} secondly it is treated as a comment character by
                   10691: Gforth. Because of the second usage, a space is required between
                   10692: @code{#!} and the path to the executable.
1.27      crook    10693: 
                   10694: The disadvantage of this latter technique, compared with using
                   10695: @file{gforthmi}, is that it is slower; the Forth source code is compiled
                   10696: on-the-fly, each time the program is invoked.
                   10697: 
1.26      crook    10698: @comment TODO describe the #! magic with reference to the Power Tools book.
                   10699: 
1.1       anton    10700: doc-#!
                   10701: 
                   10702: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
                   10703: @section Modifying the Startup Sequence
                   10704: @cindex startup sequence for image file
                   10705: @cindex image file initialization sequence
                   10706: @cindex initialization sequence of image file
                   10707: 
                   10708: You can add your own initialization to the startup sequence through the
1.26      crook    10709: deferred word @code{'cold}. @code{'cold} is invoked just before the
                   10710: image-specific command line processing (by default, loading files and
                   10711: evaluating (@code{-e}) strings) starts.
1.1       anton    10712: 
                   10713: A sequence for adding your initialization usually looks like this:
                   10714: 
                   10715: @example
                   10716: :noname
                   10717:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
                   10718:     ... \ your stuff
                   10719: ; IS 'cold
                   10720: @end example
                   10721: 
                   10722: @cindex turnkey image files
1.26      crook    10723: @cindex image file, turnkey applications
1.1       anton    10724: You can make a turnkey image by letting @code{'cold} execute a word
                   10725: (your turnkey application) that never returns; instead, it exits Gforth
                   10726: via @code{bye} or @code{throw}.
                   10727: 
                   10728: @cindex command-line arguments, access
                   10729: @cindex arguments on the command line, access
                   10730: You can access the (image-specific) command-line arguments through the
1.26      crook    10731: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1       anton    10732: access to @code{argv}.
                   10733: 
1.26      crook    10734: If @code{'cold} exits normally, Gforth processes the command-line
                   10735: arguments as files to be loaded and strings to be evaluated.  Therefore,
                   10736: @code{'cold} should remove the arguments it has used in this case.
                   10737: 
                   10738: doc-'cold
1.1       anton    10739: doc-argc
                   10740: doc-argv
                   10741: doc-arg
                   10742: 
                   10743: 
                   10744: @c ******************************************************************
1.13      pazsan   10745: @node Engine, Binding to System Library, Image Files, Top
1.1       anton    10746: @chapter Engine
                   10747: @cindex engine
                   10748: @cindex virtual machine
                   10749: 
1.26      crook    10750: Reading this chapter is not necessary for programming with Gforth. It
1.1       anton    10751: may be helpful for finding your way in the Gforth sources.
                   10752: 
                   10753: The ideas in this section have also been published in the papers
                   10754: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
                   10755: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
                   10756: Ertl, presented at EuroForth '93; the latter is available at
                   10757: @*@url{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
                   10758: 
                   10759: @menu
                   10760: * Portability::                 
                   10761: * Threading::                   
                   10762: * Primitives::                  
                   10763: * Performance::                 
                   10764: @end menu
                   10765: 
                   10766: @node Portability, Threading, Engine, Engine
                   10767: @section Portability
                   10768: @cindex engine portability
                   10769: 
1.26      crook    10770: An important goal of the Gforth Project is availability across a wide
                   10771: range of personal machines. fig-Forth, and, to a lesser extent, F83,
                   10772: achieved this goal by manually coding the engine in assembly language
                   10773: for several then-popular processors. This approach is very
                   10774: labor-intensive and the results are short-lived due to progress in
                   10775: computer architecture.
1.1       anton    10776: 
                   10777: @cindex C, using C for the engine
                   10778: Others have avoided this problem by coding in C, e.g., Mitch Bradley
                   10779: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
                   10780: particularly popular for UNIX-based Forths due to the large variety of
                   10781: architectures of UNIX machines. Unfortunately an implementation in C
                   10782: does not mix well with the goals of efficiency and with using
                   10783: traditional techniques: Indirect or direct threading cannot be expressed
                   10784: in C, and switch threading, the fastest technique available in C, is
                   10785: significantly slower. Another problem with C is that it is very
                   10786: cumbersome to express double integer arithmetic.
                   10787: 
                   10788: @cindex GNU C for the engine
                   10789: @cindex long long
                   10790: Fortunately, there is a portable language that does not have these
                   10791: limitations: GNU C, the version of C processed by the GNU C compiler
                   10792: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
                   10793: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
                   10794: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
                   10795: threading possible, its @code{long long} type (@pxref{Long Long, ,
                   10796: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
                   10797: double numbers@footnote{Unfortunately, long longs are not implemented
                   10798: properly on all machines (e.g., on alpha-osf1, long longs are only 64
                   10799: bits, the same size as longs (and pointers), but they should be twice as
1.4       anton    10800: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1       anton    10801: C Manual}). So, we had to implement doubles in C after all. Still, on
                   10802: most machines we can use long longs and achieve better performance than
                   10803: with the emulation package.}. GNU C is available for free on all
                   10804: important (and many unimportant) UNIX machines, VMS, 80386s running
                   10805: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
                   10806: on all these machines.
                   10807: 
                   10808: Writing in a portable language has the reputation of producing code that
                   10809: is slower than assembly. For our Forth engine we repeatedly looked at
                   10810: the code produced by the compiler and eliminated most compiler-induced
                   10811: inefficiencies by appropriate changes in the source code.
                   10812: 
                   10813: @cindex explicit register declarations
                   10814: @cindex --enable-force-reg, configuration flag
                   10815: @cindex -DFORCE_REG
                   10816: However, register allocation cannot be portably influenced by the
                   10817: programmer, leading to some inefficiencies on register-starved
                   10818: machines. We use explicit register declarations (@pxref{Explicit Reg
                   10819: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
                   10820: improve the speed on some machines. They are turned on by using the
                   10821: configuration flag @code{--enable-force-reg} (@code{gcc} switch
                   10822: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
                   10823: machine, but also on the compiler version: On some machines some
                   10824: compiler versions produce incorrect code when certain explicit register
                   10825: declarations are used. So by default @code{-DFORCE_REG} is not used.
                   10826: 
                   10827: @node Threading, Primitives, Portability, Engine
                   10828: @section Threading
                   10829: @cindex inner interpreter implementation
                   10830: @cindex threaded code implementation
                   10831: 
                   10832: @cindex labels as values
                   10833: GNU C's labels as values extension (available since @code{gcc-2.0},
                   10834: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29      crook    10835: makes it possible to take the address of @i{label} by writing
                   10836: @code{&&@i{label}}.  This address can then be used in a statement like
                   10837: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1       anton    10838: @code{goto x}.
                   10839: 
1.26      crook    10840: @cindex @code{NEXT}, indirect threaded
1.1       anton    10841: @cindex indirect threaded inner interpreter
                   10842: @cindex inner interpreter, indirect threaded
1.26      crook    10843: With this feature an indirect threaded @code{NEXT} looks like:
1.1       anton    10844: @example
                   10845: cfa = *ip++;
                   10846: ca = *cfa;
                   10847: goto *ca;
                   10848: @end example
                   10849: @cindex instruction pointer
                   10850: For those unfamiliar with the names: @code{ip} is the Forth instruction
                   10851: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
                   10852: execution token and points to the code field of the next word to be
                   10853: executed; The @code{ca} (code address) fetched from there points to some
                   10854: executable code, e.g., a primitive or the colon definition handler
                   10855: @code{docol}.
                   10856: 
1.26      crook    10857: @cindex @code{NEXT}, direct threaded
1.1       anton    10858: @cindex direct threaded inner interpreter
                   10859: @cindex inner interpreter, direct threaded
                   10860: Direct threading is even simpler:
                   10861: @example
                   10862: ca = *ip++;
                   10863: goto *ca;
                   10864: @end example
                   10865: 
                   10866: Of course we have packaged the whole thing neatly in macros called
1.26      crook    10867: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1       anton    10868: 
                   10869: @menu
                   10870: * Scheduling::                  
                   10871: * Direct or Indirect Threaded?::  
                   10872: * DOES>::                       
                   10873: @end menu
                   10874: 
                   10875: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
                   10876: @subsection Scheduling
                   10877: @cindex inner interpreter optimization
                   10878: 
                   10879: There is a little complication: Pipelined and superscalar processors,
                   10880: i.e., RISC and some modern CISC machines can process independent
                   10881: instructions while waiting for the results of an instruction. The
                   10882: compiler usually reorders (schedules) the instructions in a way that
                   10883: achieves good usage of these delay slots. However, on our first tries
                   10884: the compiler did not do well on scheduling primitives. E.g., for
                   10885: @code{+} implemented as
                   10886: @example
                   10887: n=sp[0]+sp[1];
                   10888: sp++;
                   10889: sp[0]=n;
                   10890: NEXT;
                   10891: @end example
1.26      crook    10892: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
1.1       anton    10893: scheduling. After a little thought the problem becomes clear: The
1.21      crook    10894: compiler cannot know that @code{sp} and @code{ip} point to different
                   10895: addresses (and the version of @code{gcc} we used would not know it even
                   10896: if it was possible), so it could not move the load of the cfa above the
                   10897: store to the TOS. Indeed the pointers could be the same, if code on or
                   10898: very near the top of stack were executed. In the interest of speed we
                   10899: chose to forbid this probably unused ``feature'' and helped the compiler
1.26      crook    10900: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
1.21      crook    10901: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1       anton    10902: @example
                   10903: n=sp[0]+sp[1];
                   10904: sp++;
                   10905: NEXT_P1;
                   10906: sp[0]=n;
                   10907: NEXT_P2;
                   10908: @end example
                   10909: This can be scheduled optimally by the compiler.
                   10910: 
                   10911: This division can be turned off with the switch @code{-DCISC_NEXT}. This
                   10912: switch is on by default on machines that do not profit from scheduling
                   10913: (e.g., the 80386), in order to preserve registers.
                   10914: 
                   10915: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
                   10916: @subsection Direct or Indirect Threaded?
                   10917: @cindex threading, direct or indirect?
                   10918: 
                   10919: @cindex -DDIRECT_THREADED
                   10920: Both! After packaging the nasty details in macro definitions we
                   10921: realized that we could switch between direct and indirect threading by
                   10922: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
                   10923: defining a few machine-specific macros for the direct-threading case.
                   10924: On the Forth level we also offer access words that hide the
                   10925: differences between the threading methods (@pxref{Threading Words}).
                   10926: 
                   10927: Indirect threading is implemented completely machine-independently.
                   10928: Direct threading needs routines for creating jumps to the executable
1.21      crook    10929: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
                   10930: machine-dependent, but they do not amount to many source lines. Therefore,
                   10931: even porting direct threading to a new machine requires little effort.
1.1       anton    10932: 
                   10933: @cindex --enable-indirect-threaded, configuration flag
                   10934: @cindex --enable-direct-threaded, configuration flag
                   10935: The default threading method is machine-dependent. You can enforce a
                   10936: specific threading method when building Gforth with the configuration
                   10937: flag @code{--enable-direct-threaded} or
                   10938: @code{--enable-indirect-threaded}. Note that direct threading is not
                   10939: supported on all machines.
                   10940: 
                   10941: @node DOES>,  , Direct or Indirect Threaded?, Threading
                   10942: @subsection DOES>
                   10943: @cindex @code{DOES>} implementation
                   10944: 
1.26      crook    10945: @cindex @code{dodoes} routine
                   10946: @cindex @code{DOES>}-code
1.1       anton    10947: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
                   10948: the chunk of code executed by every word defined by a
                   10949: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
                   10950: the Forth code to be executed, i.e. the code after the
1.26      crook    10951: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1       anton    10952: 
1.21      crook    10953: In fig-Forth the code field points directly to the @code{dodoes} and the
1.26      crook    10954: @code{DOES>}code address is stored in the cell after the code address (i.e. at
1.29      crook    10955: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1       anton    10956: the Forth-79 and all later standards, because in fig-Forth this address
                   10957: lies in the body (which is illegal in these standards). However, by
                   10958: making the code field larger for all words this solution becomes legal
                   10959: again. We use this approach for the indirect threaded version and for
                   10960: direct threading on some machines. Leaving a cell unused in most words
                   10961: is a bit wasteful, but on the machines we are targeting this is hardly a
                   10962: problem. The other reason for having a code field size of two cells is
                   10963: to avoid having different image files for direct and indirect threaded
                   10964: systems (direct threaded systems require two-cell code fields on many
                   10965: machines).
                   10966: 
1.26      crook    10967: @cindex @code{DOES>}-handler
1.1       anton    10968: The other approach is that the code field points or jumps to the cell
1.26      crook    10969: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
                   10970: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
                   10971: @code{DOES>}-code address by computing the code address, i.e., the address of
1.1       anton    10972: the jump to dodoes, and add the length of that jump field. A variant of
                   10973: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
                   10974: return address (which can be found in the return register on RISCs) is
1.26      crook    10975: the @code{DOES>}-code address. Since the two cells available in the code field
1.1       anton    10976: are used up by the jump to the code address in direct threading on many
                   10977: architectures, we use this approach for direct threading on these
                   10978: architectures. We did not want to add another cell to the code field.
                   10979: 
                   10980: @node Primitives, Performance, Threading, Engine
                   10981: @section Primitives
                   10982: @cindex primitives, implementation
                   10983: @cindex virtual machine instructions, implementation
                   10984: 
                   10985: @menu
                   10986: * Automatic Generation::        
                   10987: * TOS Optimization::            
                   10988: * Produced code::               
                   10989: @end menu
                   10990: 
                   10991: @node Automatic Generation, TOS Optimization, Primitives, Primitives
                   10992: @subsection Automatic Generation
                   10993: @cindex primitives, automatic generation
                   10994: 
                   10995: @cindex @file{prims2x.fs}
                   10996: Since the primitives are implemented in a portable language, there is no
                   10997: longer any need to minimize the number of primitives. On the contrary,
                   10998: having many primitives has an advantage: speed. In order to reduce the
                   10999: number of errors in primitives and to make programming them easier, we
                   11000: provide a tool, the primitive generator (@file{prims2x.fs}), that
                   11001: automatically generates most (and sometimes all) of the C code for a
                   11002: primitive from the stack effect notation.  The source for a primitive
                   11003: has the following form:
                   11004: 
                   11005: @cindex primitive source format
                   11006: @format
1.29      crook    11007: @i{Forth-name} @i{stack-effect}        @i{category}    [@i{pronounc.}]
                   11008: [@code{""}@i{glossary entry}@code{""}]
                   11009: @i{C code}
1.1       anton    11010: [@code{:}
1.29      crook    11011: @i{Forth code}]
1.1       anton    11012: @end format
                   11013: 
                   11014: The items in brackets are optional. The category and glossary fields
                   11015: are there for generating the documentation, the Forth code is there
                   11016: for manual implementations on machines without GNU C. E.g., the source
                   11017: for the primitive @code{+} is:
                   11018: @example
                   11019: +    n1 n2 -- n    core    plus
                   11020: n = n1+n2;
                   11021: @end example
                   11022: 
                   11023: This looks like a specification, but in fact @code{n = n1+n2} is C
                   11024: code. Our primitive generation tool extracts a lot of information from
                   11025: the stack effect notations@footnote{We use a one-stack notation, even
                   11026: though we have separate data and floating-point stacks; The separate
                   11027: notation can be generated easily from the unified notation.}: The number
                   11028: of items popped from and pushed on the stack, their type, and by what
                   11029: name they are referred to in the C code. It then generates a C code
                   11030: prelude and postlude for each primitive. The final C code for @code{+}
                   11031: looks like this:
                   11032: 
                   11033: @example
                   11034: I_plus:        /* + ( n1 n2 -- n ) */  /* label, stack effect */
                   11035: /*  */                          /* documentation */
                   11036: @{
                   11037: DEF_CA                          /* definition of variable ca (indirect threading) */
                   11038: Cell n1;                        /* definitions of variables */
                   11039: Cell n2;
                   11040: Cell n;
                   11041: n1 = (Cell) sp[1];              /* input */
                   11042: n2 = (Cell) TOS;
                   11043: sp += 1;                        /* stack adjustment */
                   11044: NAME("+")                       /* debugging output (with -DDEBUG) */
                   11045: @{
                   11046: n = n1+n2;                      /* C code taken from the source */
                   11047: @}
                   11048: NEXT_P1;                        /* NEXT part 1 */
                   11049: TOS = (Cell)n;                  /* output */
                   11050: NEXT_P2;                        /* NEXT part 2 */
                   11051: @}
                   11052: @end example
                   11053: 
                   11054: This looks long and inefficient, but the GNU C compiler optimizes quite
                   11055: well and produces optimal code for @code{+} on, e.g., the R3000 and the
                   11056: HP RISC machines: Defining the @code{n}s does not produce any code, and
                   11057: using them as intermediate storage also adds no cost.
                   11058: 
1.26      crook    11059: There are also other optimizations that are not illustrated by this
                   11060: example: assignments between simple variables are usually for free (copy
1.1       anton    11061: propagation). If one of the stack items is not used by the primitive
                   11062: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
                   11063: (dead code elimination). On the other hand, there are some things that
                   11064: the compiler does not do, therefore they are performed by
                   11065: @file{prims2x.fs}: The compiler does not optimize code away that stores
                   11066: a stack item to the place where it just came from (e.g., @code{over}).
                   11067: 
                   11068: While programming a primitive is usually easy, there are a few cases
                   11069: where the programmer has to take the actions of the generator into
                   11070: account, most notably @code{?dup}, but also words that do not (always)
1.26      crook    11071: fall through to @code{NEXT}.
1.1       anton    11072: 
                   11073: @node TOS Optimization, Produced code, Automatic Generation, Primitives
                   11074: @subsection TOS Optimization
                   11075: @cindex TOS optimization for primitives
                   11076: @cindex primitives, keeping the TOS in a register
                   11077: 
                   11078: An important optimization for stack machine emulators, e.g., Forth
                   11079: engines, is keeping  one or more of the top stack items in
1.29      crook    11080: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
                   11081: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1       anton    11082: @itemize @bullet
                   11083: @item
1.29      crook    11084: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1       anton    11085: due to fewer loads from and stores to the stack.
1.29      crook    11086: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
                   11087: @i{y<n}, due to additional moves between registers.
1.1       anton    11088: @end itemize
                   11089: 
                   11090: @cindex -DUSE_TOS
                   11091: @cindex -DUSE_NO_TOS
                   11092: In particular, keeping one item in a register is never a disadvantage,
                   11093: if there are enough registers. Keeping two items in registers is a
                   11094: disadvantage for frequent words like @code{?branch}, constants,
                   11095: variables, literals and @code{i}. Therefore our generator only produces
                   11096: code that keeps zero or one items in registers. The generated C code
                   11097: covers both cases; the selection between these alternatives is made at
                   11098: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
                   11099: code for @code{+} is just a simple variable name in the one-item case,
                   11100: otherwise it is a macro that expands into @code{sp[0]}. Note that the
                   11101: GNU C compiler tries to keep simple variables like @code{TOS} in
                   11102: registers, and it usually succeeds, if there are enough registers.
                   11103: 
                   11104: @cindex -DUSE_FTOS
                   11105: @cindex -DUSE_NO_FTOS
                   11106: The primitive generator performs the TOS optimization for the
                   11107: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
                   11108: operations the benefit of this optimization is even larger:
                   11109: floating-point operations take quite long on most processors, but can be
                   11110: performed in parallel with other operations as long as their results are
                   11111: not used. If the FP-TOS is kept in a register, this works. If
                   11112: it is kept on the stack, i.e., in memory, the store into memory has to
                   11113: wait for the result of the floating-point operation, lengthening the
                   11114: execution time of the primitive considerably.
                   11115: 
                   11116: The TOS optimization makes the automatic generation of primitives a
                   11117: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
                   11118: @code{TOS} is not sufficient. There are some special cases to
                   11119: consider:
                   11120: @itemize @bullet
                   11121: @item In the case of @code{dup ( w -- w w )} the generator must not
                   11122: eliminate the store to the original location of the item on the stack,
                   11123: if the TOS optimization is turned on.
                   11124: @item Primitives with stack effects of the form @code{--}
1.29      crook    11125: @i{out1}...@i{outy} must store the TOS to the stack at the start.
                   11126: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1       anton    11127: must load the TOS from the stack at the end. But for the null stack
                   11128: effect @code{--} no stores or loads should be generated.
                   11129: @end itemize
                   11130: 
                   11131: @node Produced code,  , TOS Optimization, Primitives
                   11132: @subsection Produced code
                   11133: @cindex primitives, assembly code listing
                   11134: 
                   11135: @cindex @file{engine.s}
                   11136: To see what assembly code is produced for the primitives on your machine
                   11137: with your compiler and your flag settings, type @code{make engine.s} and
                   11138: look at the resulting file @file{engine.s}.
                   11139: 
                   11140: @node  Performance,  , Primitives, Engine
                   11141: @section Performance
                   11142: @cindex performance of some Forth interpreters
                   11143: @cindex engine performance
                   11144: @cindex benchmarking Forth systems
                   11145: @cindex Gforth performance
                   11146: 
                   11147: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
                   11148: impossible to write a significantly faster engine.
                   11149: 
                   11150: On register-starved machines like the 386 architecture processors
                   11151: improvements are possible, because @code{gcc} does not utilize the
                   11152: registers as well as a human, even with explicit register declarations;
                   11153: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
                   11154: and hand-tuned it for the 486; this system is 1.19 times faster on the
                   11155: Sieve benchmark on a 486DX2/66 than Gforth compiled with
                   11156: @code{gcc-2.6.3} with @code{-DFORCE_REG}.
                   11157: 
                   11158: @cindex Win32Forth performance
                   11159: @cindex NT Forth performance
                   11160: @cindex eforth performance
                   11161: @cindex ThisForth performance
                   11162: @cindex PFE performance
                   11163: @cindex TILE performance
                   11164: However, this potential advantage of assembly language implementations
                   11165: is not necessarily realized in complete Forth systems: We compared
                   11166: Gforth (direct threaded, compiled with @code{gcc-2.6.3} and
                   11167: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
                   11168: 1994) and Eforth (with and without peephole (aka pinhole) optimization
                   11169: of the threaded code); all these systems were written in assembly
                   11170: language. We also compared Gforth with three systems written in C:
                   11171: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
                   11172: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21      crook    11173: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
                   11174: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1       anton    11175: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
                   11176: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
                   11177: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
                   11178: 486DX2/66 with similar memory performance under Windows NT. Marcel
                   11179: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
                   11180: added the peephole optimizer, ran the benchmarks and reported the
                   11181: results.
                   11182:  
                   11183: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
                   11184: matrix multiplication come from the Stanford integer benchmarks and have
                   11185: been translated into Forth by Martin Fraeman; we used the versions
                   11186: included in the TILE Forth package, but with bigger data set sizes; and
                   11187: a recursive Fibonacci number computation for benchmarking calling
                   11188: performance. The following table shows the time taken for the benchmarks
                   11189: scaled by the time taken by Gforth (in other words, it shows the speedup
                   11190: factor that Gforth achieved over the other systems).
                   11191: 
                   11192: @example
                   11193: relative      Win32-    NT       eforth       This-
                   11194:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
                   11195: sieve     1.00  1.39  1.14   1.39  0.85  1.58  3.18  8.58
                   11196: bubble    1.00  1.31  1.41   1.48  0.88  1.50        3.88
                   11197: matmul    1.00  1.47  1.35   1.46  0.74  1.58        4.09
                   11198: fib       1.00  1.52  1.34   1.22  0.86  1.74  2.99  4.30
                   11199: @end example
                   11200: 
1.26      crook    11201: You may be quite surprised by the good performance of Gforth when
                   11202: compared with systems written in assembly language. One important reason
                   11203: for the disappointing performance of these other systems is probably
                   11204: that they are not written optimally for the 486 (e.g., they use the
                   11205: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
                   11206: but costly method for relocating the Forth image: like @code{cforth}, it
                   11207: computes the actual addresses at run time, resulting in two address
                   11208: computations per @code{NEXT} (@pxref{Image File Background}).
                   11209: 
                   11210: Only Eforth with the peephole optimizer has a performance that is
                   11211: comparable to Gforth. The speedups achieved with peephole optimization
                   11212: of threaded code are quite remarkable. Adding a peephole optimizer to
                   11213: Gforth should cause similar speedups.
1.1       anton    11214: 
                   11215: The speedup of Gforth over PFE, ThisForth and TILE can be easily
                   11216: explained with the self-imposed restriction of the latter systems to
                   11217: standard C, which makes efficient threading impossible (however, the
1.4       anton    11218: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1       anton    11219: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
                   11220: Moreover, current C compilers have a hard time optimizing other aspects
                   11221: of the ThisForth and the TILE source.
                   11222: 
1.26      crook    11223: The performance of Gforth on 386 architecture processors varies widely
                   11224: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
                   11225: allocate any of the virtual machine registers into real machine
                   11226: registers by itself and would not work correctly with explicit register
                   11227: declarations, giving a 1.3 times slower engine (on a 486DX2/66 running
                   11228: the Sieve) than the one measured above.
1.1       anton    11229: 
1.26      crook    11230: Note that there have been several releases of Win32Forth since the
                   11231: release presented here, so the results presented above may have little
1.1       anton    11232: predictive value for the performance of Win32Forth today.
                   11233: 
                   11234: @cindex @file{Benchres}
                   11235: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
                   11236: Maierhofer (presented at EuroForth '95), an indirect threaded version of
                   11237: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
                   11238: version of Gforth is 2%@minus{}8% slower on a 486 than the direct
                   11239: threaded version used here. The paper available at
                   11240: @*@url{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
                   11241: it also contains numbers for some native code systems. You can find a
                   11242: newer version of these measurements at
                   11243: @url{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
                   11244: find numbers for Gforth on various machines in @file{Benchres}.
                   11245: 
1.26      crook    11246: @c ******************************************************************
1.13      pazsan   11247: @node Binding to System Library, Cross Compiler, Engine, Top
1.14      pazsan   11248: @chapter Binding to System Library
1.13      pazsan   11249: 
                   11250: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14      pazsan   11251: @chapter Cross Compiler
1.13      pazsan   11252: 
                   11253: Cross Compiler
                   11254: 
                   11255: @menu
                   11256: * Using the Cross Compiler::
                   11257: * How the Cross Compiler Works::
                   11258: @end menu
                   11259: 
1.21      crook    11260: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14      pazsan   11261: @section Using the Cross Compiler
1.13      pazsan   11262: 
1.21      crook    11263: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14      pazsan   11264: @section How the Cross Compiler Works
1.13      pazsan   11265: 
                   11266: @node Bugs, Origin, Cross Compiler, Top
1.21      crook    11267: @appendix Bugs
1.1       anton    11268: @cindex bug reporting
                   11269: 
1.21      crook    11270: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1       anton    11271: 
                   11272: If you find a bug, please send a bug report to
1.33      anton    11273: @email{bug-gforth@@gnu.org}. A bug report should include this
1.21      crook    11274: information:
                   11275: 
                   11276: @itemize @bullet
                   11277: @item
                   11278: The Gforth version used (it is announced at the start of an
                   11279: interactive Gforth session).
                   11280: @item
                   11281: The machine and operating system (on Unix
                   11282: systems @code{uname -a} will report this information).
                   11283: @item
                   11284: The installation options (send the file @file{config.status}).
                   11285: @item
                   11286: A complete list of changes (if any) you (or your installer) have made to the
                   11287: Gforth sources.
                   11288: @item
                   11289: A program (or a sequence of keyboard commands) that reproduces the bug.
                   11290: @item
                   11291: A description of what you think constitutes the buggy behaviour.
                   11292: @end itemize
1.1       anton    11293: 
                   11294: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
                   11295: to Report Bugs, gcc.info, GNU C Manual}.
                   11296: 
                   11297: 
1.21      crook    11298: @node Origin, Forth-related information, Bugs, Top
                   11299: @appendix Authors and Ancestors of Gforth
1.1       anton    11300: 
                   11301: @section Authors and Contributors
                   11302: @cindex authors of Gforth
                   11303: @cindex contributors to Gforth
                   11304: 
                   11305: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
                   11306: Ertl. The third major author was Jens Wilke.  Lennart Benschop (who was
                   11307: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
                   11308: with their continuous feedback. Lennart Benshop contributed
                   11309: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
                   11310: support for calling C libraries. Helpful comments also came from Paul
                   11311: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.12      anton    11312: Wavrik, Barrie Stott, Marc de Groot, and Jorge Acerada. Since the
                   11313: release of Gforth-0.2.1 there were also helpful comments from many
                   11314: others; thank you all, sorry for not listing you here (but digging
1.23      crook    11315: through my mailbox to extract your names is on my to-do list). Since the
                   11316: release of Gforth-0.4.0 Neal Crook worked on the manual.
1.1       anton    11317: 
                   11318: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
                   11319: and autoconf, among others), and to the creators of the Internet: Gforth
1.21      crook    11320: was developed across the Internet, and its authors did not meet
1.20      pazsan   11321: physically for the first 4 years of development.
1.1       anton    11322: 
                   11323: @section Pedigree
1.26      crook    11324: @cindex pedigree of Gforth
1.1       anton    11325: 
1.20      pazsan   11326: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1       anton    11327: Dirk Zoller) will cross-fertilize each other. Of course, a significant
                   11328: part of the design of Gforth was prescribed by ANS Forth.
                   11329: 
1.20      pazsan   11330: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1       anton    11331: 32 bit native code version of VolksForth for the Atari ST, written
                   11332: mostly by Dietrich Weineck.
                   11333: 
                   11334: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
                   11335: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
                   11336: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
                   11337: 
                   11338: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
                   11339: Forth-83 standard. !! Pedigree? When?
                   11340: 
                   11341: A team led by Bill Ragsdale implemented fig-Forth on many processors in
                   11342: 1979. Robert Selzer and Bill Ragsdale developed the original
                   11343: implementation of fig-Forth for the 6502 based on microForth.
                   11344: 
                   11345: The principal architect of microForth was Dean Sanderson. microForth was
                   11346: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
                   11347: the 1802, and subsequently implemented on the 8080, the 6800 and the
                   11348: Z80.
                   11349: 
                   11350: All earlier Forth systems were custom-made, usually by Charles Moore,
                   11351: who discovered (as he puts it) Forth during the late 60s. The first full
                   11352: Forth existed in 1971.
                   11353: 
                   11354: A part of the information in this section comes from @cite{The Evolution
                   11355: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
                   11356: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
                   11357: Notices 28(3), 1993.  You can find more historical and genealogical
                   11358: information about Forth there.
                   11359: 
1.21      crook    11360: @node Forth-related information, Word Index, Origin, Top
                   11361: @appendix Other Forth-related information
                   11362: @cindex Forth-related information
                   11363: 
                   11364: @menu
                   11365: * Internet resources::
                   11366: * Books::
                   11367: * The Forth Interest Group::
                   11368: * Conferences::
                   11369: @end menu
                   11370: 
                   11371: 
                   11372: @node Internet resources, Books, Forth-related information, Forth-related information
                   11373: @section Internet resources
1.26      crook    11374: @cindex internet resources
1.21      crook    11375: 
                   11376: @cindex comp.lang.forth
                   11377: @cindex frequently asked questions
                   11378: There is an active newsgroup (comp.lang.forth) discussing Forth and
                   11379: Forth-related issues. A frequently-asked-questions (FAQ) list
                   11380: is posted to the newsgroup regulary, and archived at these sites:
                   11381: 
                   11382: @itemize @bullet
                   11383: @item
                   11384: @url{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
                   11385: @item
                   11386: @url{ftp://ftp.forth.org/pub/Forth/FAQ/}
                   11387: @end itemize
                   11388: 
                   11389: The FAQ list should be considered mandatory reading before posting to
                   11390: the newsgroup.
                   11391: 
                   11392: Here are some other web sites holding Forth-related material:
                   11393: 
                   11394: @itemize @bullet
                   11395: @item
                   11396: @url{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
                   11397: @item
                   11398: @url{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
                   11399: @item
                   11400: @url{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
                   11401: @item
                   11402: @url{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
                   11403: Research page, including links to the Journal of Forth Application and
                   11404: Research (JFAR) and a searchable Forth bibliography.
                   11405: @end itemize
                   11406: 
                   11407: 
                   11408: @node Books, The Forth Interest Group, Internet resources, Forth-related information
                   11409: @section Books
1.26      crook    11410: @cindex books on Forth
1.21      crook    11411: 
                   11412: As the Standard is relatively new, there are not many books out yet. It
                   11413: is not recommended to learn Forth by using Gforth and a book that is not
                   11414: written for ANS Forth, as you will not know your mistakes from the
                   11415: deviations of the book. However, books based on the Forth-83 standard
                   11416: should be ok, because ANS Forth is primarily an extension of Forth-83.
                   11417: 
                   11418: @cindex standard document for ANS Forth
                   11419: @cindex ANS Forth document
                   11420: The definite reference if you want to write ANS Forth programs is, of
1.26      crook    11421: course, the ANS Forth document. It is available in printed form from the
1.21      crook    11422: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
                   11423: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
                   11424: $200. You can also get it from Global Engineering Documents (Tel.: USA
                   11425: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
                   11426: 
                   11427: @cite{dpANS6}, the last draft of the standard, which was then submitted
                   11428: to ANSI for publication is available electronically and for free in some
                   11429: MS Word format, and it has been converted to HTML
                   11430: (@url{http://www.taygeta.com/forth/dpans.html}; this is my favourite
                   11431: format); this HTML version also includes the answers to Requests for
                   11432: Interpretation (RFIs). Some pointers to these versions can be found
                   11433: through @*@url{http://www.complang.tuwien.ac.at/projects/forth.html}.
                   11434: 
1.26      crook    11435: @cindex introductory book on Forth
                   11436: @cindex book on Forth, introductory
1.21      crook    11437: @cindex Woehr, Jack: @cite{Forth: The New Model}
                   11438: @cindex @cite{Forth: The new model} (book)
                   11439: @cite{Forth: The New Model} by Jack Woehr (Prentice-Hall, 1993) is an
                   11440: introductory book based on a draft version of the standard. It does not
                   11441: cover the whole standard. It also contains interesting background
                   11442: information (Jack Woehr was in the ANS Forth Technical Committee). It is
                   11443: not appropriate for complete newbies, but programmers experienced in
                   11444: other languages should find it ok.
                   11445: 
                   11446: @cindex Conklin, Edward K., and Elizabeth Rather: @cite{Forth Programmer's Handbook}
                   11447: @cindex Rather, Elizabeth and Edward K. Conklin: @cite{Forth Programmer's Handbook}
                   11448: @cindex @cite{Forth Programmer's Handbook} (book)
                   11449: @cite{Forth Programmer's Handbook} by Edward K. Conklin, Elizabeth
                   11450: D. Rather and the technical staff of Forth, Inc. (Forth, Inc., 1997;
                   11451: ISBN 0-9662156-0-5) contains little introductory material. The majority
                   11452: of the book is similar to @ref{Words}, but the book covers most of the
                   11453: standard words and some non-standard words (whereas this manual is
                   11454: quite incomplete). In addition, the book contains a chapter on
                   11455: programming style. The major drawback of this book is that it usually
                   11456: does not identify what is standard and what is specific to the Forth
                   11457: system described in the book (probably one of Forth, Inc.'s systems).
                   11458: Fortunately, many of the non-standard programming practices described in
                   11459: the book work in Gforth, too.  Still, this drawback makes the book
                   11460: hardly more useful than a pre-ANS book.
                   11461: 
                   11462: @node The Forth Interest Group, Conferences, Books, Forth-related information
                   11463: @section The Forth Interest Group
                   11464: @cindex Forth interest group (FIG)
                   11465: 
                   11466: The Forth Interest Group (FIG) is a world-wide, non-profit,
1.26      crook    11467: member-supported organisation. It publishes a regular magazine,
                   11468: @var{FORTH Dimensions}, and offers other benefits of membership. You can
                   11469: contact the FIG through their office email address:
                   11470: @email{office@@forth.org} or by visiting their web site at
                   11471: @url{http://www.forth.org/}. This web site also includes links to FIG
                   11472: chapters in other countries and American cities
1.21      crook    11473: (@url{http://www.forth.org/chapters.html}).
                   11474: 
                   11475: @node Conferences, , The Forth Interest Group, Forth-related information
                   11476: @section Conferences
                   11477: @cindex Conferences
                   11478: 
                   11479: There are several regular conferences related to Forth. They are all
1.26      crook    11480: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
                   11481: news group:
1.21      crook    11482: 
                   11483: @itemize @bullet
                   11484: @item
                   11485: FORML -- the Forth modification laboratory convenes every year near
                   11486: Monterey, California.
                   11487: @item
                   11488: The Rochester Forth Conference -- an annual conference traditionally
                   11489: held in Rochester, New York.
                   11490: @item
                   11491: EuroForth -- this European conference takes place annually.
                   11492: @end itemize
                   11493: 
                   11494: 
                   11495: @node Word Index, Concept Index, Forth-related information, Top
1.1       anton    11496: @unnumbered Word Index
                   11497: 
1.26      crook    11498: This index is a list of Forth words that have ``glossary'' entries
                   11499: within this manual. Each word is listed with its stack effect and
                   11500: wordset.
1.1       anton    11501: 
                   11502: @printindex fn
                   11503: 
                   11504: @node Concept Index,  , Word Index, Top
                   11505: @unnumbered Concept and Word Index
                   11506: 
1.26      crook    11507: Not all entries listed in this index are present verbatim in the
                   11508: text. This index also duplicates, in abbreviated form, all of the words
                   11509: listed in the Word Index (only the names are listed for the words here).
1.1       anton    11510: 
                   11511: @printindex cp
                   11512: 
                   11513: @contents
                   11514: @bye
                   11515: 

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